<commit_before>'use strict';

angular.module('emuwebApp')
	.directive('correctiontool', function () {
		return {
			restrict: 'A',
			link: function (scope, element, atts) {

				var curMouseSample;
				var dragStartSample;
				var dragEndSample;

				var canvas = element[0];
				var ctx = canvas.getContext('2d');
				// var elem = element[0];
				var tr, col, sRaSt;
				var trackName;

				/////////////////////////////
				// observe attribute
				atts.$observe('ssffTrackname', function (val) {
					if (val) {
						trackName = val;
					}
				});

				/////////////////////////////
				// Bindings
				element.bind('mousedown', function (event) {
					dragStartSample = Math.round(scope.dhs.getX(event) * scope.vs.getPCMpp(event) + scope.vs.curViewPort.sS);
					dragEndSample = dragStartSample;
					scope.vs.select(dragStartSample, dragStartSample);
					scope.$apply();
				});

				element.bind('mousemove', function (event) {
					switch (event.which) {
					case 0:
						if (!scope.vs.getdragBarActive()) {
							// perform mouse tracking
							var mouseX = scope.dhs.getX(event);
							scope.vs.curMousePosSample = Math.round(scope.vs.curViewPort.sS + mouseX / element[0].width * (scope.vs.curViewPort.eS - scope.vs.curViewPort.sS));

							ctx.clearRect(0, 0, canvas.width, canvas.height);
							// draw crossHairs
							if (scope.cps.vals.restrictions.drawCrossHairs) {
								scope.dhs.drawCrossHairs(ctx, event, scope.vs.spectroSettings.rangeFrom, scope.vs.spectroSettings.rangeTo, 'Hz');
							}
							// draw moving boundary line if moving
							scope.dhs.drawMovingBoundaryLine(ctx);

							// draw current viewport selected
							scope.dhs.drawCurViewPortSelected(ctx, false);

							// draw min max vals and name of track
							scope.dhs.drawMinMaxAndName(ctx, '', scope.vs.spectroSettings.rangeFrom, scope.vs.spectroSettings.rangeTo, 2);

							if (scope.vs.curCorrectionToolNr !== undefined && !scope.vs.getdragBarActive() && !$.isEmptyObject(scope.cps.getAssignment(trackName))) {
								// var col = scope.ssffds.data[0].Columns[0];
								if (tr === undefined) {
									tr = scope.cps.getSsffTrackConfig('FORMANTS');
									col = scope.ssffds.getColumnOfTrack(tr.name, tr.columnName);
									sRaSt = scope.ssffds.getSampleRateAndStartTimeOfTrack(tr.name);
								}

								var startTimeVP = scope.vs.getViewPortStartTime();
								var endTimeVP = scope.vs.getViewPortEndTime();

								var colStartSampleNr = Math.round(startTimeVP * sRaSt.sampleRate + sRaSt.startTime);
								var colEndSampleNr = Math.round(endTimeVP * sRaSt.sampleRate + sRaSt.startTime);
								var nrOfSamples = colEndSampleNr - colStartSampleNr;
								var curSampleArrs = col.values.slice(colStartSampleNr, colStartSampleNr + nrOfSamples);

								// console.log(colStartSampleNr)

								var curMouseTime = startTimeVP + (scope.dhs.getX(event) / event.originalEvent.srcElement.width) * (endTimeVP - startTimeVP);
								var curMouseSample = Math.round((curMouseTime + sRaSt.startTime) * sRaSt.sampleRate) - 1; //-1 for in view correction

								var curMouseSampleTime = (1 / sRaSt.sampleRate * curMouseSample) + sRaSt.startTime;

								if (curMouseSample - colStartSampleNr < 0 || curMouseSample - colStartSampleNr >= curSampleArrs.length) {
									console.log('early return');
									return;
								}

								scope.vs.curPreselColumnSample = curMouseSample - colStartSampleNr;

								var x = (curMouseSampleTime - startTimeVP) / (endTimeVP - startTimeVP) * canvas.width;
								var y = canvas.height - curSampleArrs[scope.vs.curPreselColumnSample][scope.vs.curCorrectionToolNr - 1] / (scope.vs.spectroSettings.rangeTo - scope.vs.spectroSettings.rangeFrom) * canvas.height;

								// draw sample
								ctx.strokeStyle = '#0DC5FF';
								ctx.fillStyle = 'white';
								ctx.beginPath();
								ctx.arc(x, y - 1, 2, 0, 2 * Math.PI, false);
								ctx.closePath();
								ctx.stroke();
								ctx.fill();

								if (event.shiftKey) {
									var oldValue = angular.copy(curSampleArrs[scope.vs.curPreselColumnSample][scope.vs.curCorrectionToolNr - 1]);
									var newValue = scope.vs.spectroSettings.rangeTo - scope.dhs.getY(event) / event.originalEvent.srcElement.height * scope.vs.spectroSettings.rangeTo; // SIC only using rangeTo

									curSampleArrs[scope.vs.curPreselColumnSample][scope.vs.curCorrectionToolNr - 1] = scope.vs.spectroSettings.rangeTo - scope.dhs.getY(event) / event.originalEvent.srcElement.height * scope.vs.spectroSettings.rangeTo;
									var updateObj = scope.hists.updateCurChangeObj({
										'type': 'SSFF',
										'trackName': tr.name,
										'sampleBlockIdx': colStartSampleNr + scope.vs.curPreselColumnSample,
										'sampleIdx': scope.vs.curCorrectionToolNr - 1,
										'oldValue': oldValue,
										'newValue': newValue
									});

									//draw updateObj as overlay
									for (var key in updateObj) {
										curMouseSampleTime = (1 / sRaSt.sampleRate * updateObj[key].sampleBlockIdx) + sRaSt.startTime;
										x = (curMouseSampleTime - startTimeVP) / (endTimeVP - startTimeVP) * canvas.width;
										y = canvas.height - updateObj[key].newValue / (scope.vs.spectroSettings.rangeTo - scope.vs.spectroSettings.rangeFrom) * canvas.height;

										// draw sample
										ctx.strokeStyle = 'red';
										ctx.fillStyle = 'red';
										// ctx.lineWidth = 4;
										ctx.beginPath();
										ctx.arc(x, y - 1, 2, 0, 2 * Math.PI, false);
										ctx.closePath();
										ctx.stroke();
										ctx.fill();
									}

								}
							}
						}
						break;
					case 1:
						if (!scope.vs.getdragBarActive()) {
							setSelectDrag(event);
						}
						break;
					}
					scope.$apply();
				});

				element.bind('mouseup', function (event) {
					if (!scope.vs.getdragBarActive()) {
						setSelectDrag(event);
					}
				});

				function setSelectDrag(event) {
					curMouseSample = Math.round(scope.dhs.getX(event) * scope.vs.getPCMpp(event) + scope.vs.curViewPort.sS);
					if (curMouseSample > dragStartSample) {
						dragEndSample = curMouseSample;
						scope.vs.select(dragStartSample, dragEndSample);
					} else {
						dragStartSample = curMouseSample;
						scope.vs.select(dragStartSample, dragEndSample);
					}
					scope.$apply();
				}
			}
		};
	});<commit_msg>correction tool now pre-checking if ssff<commit_after>'use strict';

angular.module('emuwebApp')
	.directive('correctiontool', function () {
		return {
			restrict: 'A',
			link: function (scope, element, atts) {

				var curMouseSample;
				var dragStartSample;
				var dragEndSample;

				var canvas = element[0];
				var ctx = canvas.getContext('2d');
				// var elem = element[0];
				var tr, col, sRaSt;
				var trackName;

				/////////////////////////////
				// observe attribute
				atts.$observe('ssffTrackname', function (val) {
					if (val) {
						trackName = val;
					}
				});

				/////////////////////////////
				// Bindings
				element.bind('mousedown', function (event) {
					dragStartSample = Math.round(scope.dhs.getX(event) * scope.vs.getPCMpp(event) + scope.vs.curViewPort.sS);
					dragEndSample = dragStartSample;
					scope.vs.select(dragStartSample, dragStartSample);
					scope.$apply();
				});

				element.bind('mousemove', function (event) {
					switch (event.which) {
					case 0:
						if (!$.isEmptyObject(scope.ssffds.data)) {
							if (scope.ssffds.data.length !== 0) {

								if (!scope.vs.getdragBarActive()) {
									// perform mouse tracking
									var mouseX = scope.dhs.getX(event);
									scope.vs.curMousePosSample = Math.round(scope.vs.curViewPort.sS + mouseX / element[0].width * (scope.vs.curViewPort.eS - scope.vs.curViewPort.sS));

									ctx.clearRect(0, 0, canvas.width, canvas.height);
									// draw crossHairs
									if (scope.cps.vals.restrictions.drawCrossHairs) {
										scope.dhs.drawCrossHairs(ctx, event, scope.vs.spectroSettings.rangeFrom, scope.vs.spectroSettings.rangeTo, 'Hz');
									}
									// draw moving boundary line if moving
									scope.dhs.drawMovingBoundaryLine(ctx);

									// draw current viewport selected
									scope.dhs.drawCurViewPortSelected(ctx, false);

									// draw min max vals and name of track
									scope.dhs.drawMinMaxAndName(ctx, '', scope.vs.spectroSettings.rangeFrom, scope.vs.spectroSettings.rangeTo, 2);

									if (scope.vs.curCorrectionToolNr !== undefined && !scope.vs.getdragBarActive() && !$.isEmptyObject(scope.cps.getAssignment(trackName))) {
										// var col = scope.ssffds.data[0].Columns[0];
										if (tr === undefined) {
											tr = scope.cps.getSsffTrackConfig('FORMANTS');
											col = scope.ssffds.getColumnOfTrack(tr.name, tr.columnName);
											sRaSt = scope.ssffds.getSampleRateAndStartTimeOfTrack(tr.name);
										}

										var startTimeVP = scope.vs.getViewPortStartTime();
										var endTimeVP = scope.vs.getViewPortEndTime();

										var colStartSampleNr = Math.round(startTimeVP * sRaSt.sampleRate + sRaSt.startTime);
										var colEndSampleNr = Math.round(endTimeVP * sRaSt.sampleRate + sRaSt.startTime);
										var nrOfSamples = colEndSampleNr - colStartSampleNr;
										var curSampleArrs = col.values.slice(colStartSampleNr, colStartSampleNr + nrOfSamples);

										// console.log(colStartSampleNr)

										var curMouseTime = startTimeVP + (scope.dhs.getX(event) / event.originalEvent.srcElement.width) * (endTimeVP - startTimeVP);
										var curMouseSample = Math.round((curMouseTime + sRaSt.startTime) * sRaSt.sampleRate) - 1; //-1 for in view correction

										var curMouseSampleTime = (1 / sRaSt.sampleRate * curMouseSample) + sRaSt.startTime;

										if (curMouseSample - colStartSampleNr < 0 || curMouseSample - colStartSampleNr >= curSampleArrs.length) {
											console.log('early return');
											return;
										}

										scope.vs.curPreselColumnSample = curMouseSample - colStartSampleNr;

										var x = (curMouseSampleTime - startTimeVP) / (endTimeVP - startTimeVP) * canvas.width;
										var y = canvas.height - curSampleArrs[scope.vs.curPreselColumnSample][scope.vs.curCorrectionToolNr - 1] / (scope.vs.spectroSettings.rangeTo - scope.vs.spectroSettings.rangeFrom) * canvas.height;

										// draw sample
										ctx.strokeStyle = '#0DC5FF';
										ctx.fillStyle = 'white';
										ctx.beginPath();
										ctx.arc(x, y - 1, 2, 0, 2 * Math.PI, false);
										ctx.closePath();
										ctx.stroke();
										ctx.fill();

										if (event.shiftKey) {
											var oldValue = angular.copy(curSampleArrs[scope.vs.curPreselColumnSample][scope.vs.curCorrectionToolNr - 1]);
											var newValue = scope.vs.spectroSettings.rangeTo - scope.dhs.getY(event) / event.originalEvent.srcElement.height * scope.vs.spectroSettings.rangeTo; // SIC only using rangeTo

											curSampleArrs[scope.vs.curPreselColumnSample][scope.vs.curCorrectionToolNr - 1] = scope.vs.spectroSettings.rangeTo - scope.dhs.getY(event) / event.originalEvent.srcElement.height * scope.vs.spectroSettings.rangeTo;
											var updateObj = scope.hists.updateCurChangeObj({
												'type': 'SSFF',
												'trackName': tr.name,
												'sampleBlockIdx': colStartSampleNr + scope.vs.curPreselColumnSample,
												'sampleIdx': scope.vs.curCorrectionToolNr - 1,
												'oldValue': oldValue,
												'newValue': newValue
											});

											//draw updateObj as overlay
											for (var key in updateObj) {
												curMouseSampleTime = (1 / sRaSt.sampleRate * updateObj[key].sampleBlockIdx) + sRaSt.startTime;
												x = (curMouseSampleTime - startTimeVP) / (endTimeVP - startTimeVP) * canvas.width;
												y = canvas.height - updateObj[key].newValue / (scope.vs.spectroSettings.rangeTo - scope.vs.spectroSettings.rangeFrom) * canvas.height;

												// draw sample
												ctx.strokeStyle = 'red';
												ctx.fillStyle = 'red';
												// ctx.lineWidth = 4;
												ctx.beginPath();
												ctx.arc(x, y - 1, 2, 0, 2 * Math.PI, false);
												ctx.closePath();
												ctx.stroke();
												ctx.fill();
											}

										}
									}
								}
							}
						}
						break;
					case 1:
						if (!scope.vs.getdragBarActive()) {
							setSelectDrag(event);
						}
						break;
					}
					scope.$apply();
				});

				element.bind('mouseup', function (event) {
					if (!scope.vs.getdragBarActive()) {
						setSelectDrag(event);
					}
				});

				function setSelectDrag(event) {
					curMouseSample = Math.round(scope.dhs.getX(event) * scope.vs.getPCMpp(event) + scope.vs.curViewPort.sS);
					if (curMouseSample > dragStartSample) {
						dragEndSample = curMouseSample;
						scope.vs.select(dragStartSample, dragEndSample);
					} else {
						dragStartSample = curMouseSample;
						scope.vs.select(dragStartSample, dragEndSample);
					}
					scope.$apply();
				}
			}
		};
	});<|endoftext|>


<commit_before>import Conductor from 'conductor';
import ajax from 'glazier/utils/ajax';

/* Diagram: http://www.websequencediagrams.com/cgi-bin/cdraw?lz=Y2FyZCAtPiBjb25zdW1lcjogcmVxdWVzdDogYWpheChvcHRzKQoAFgggLT4gc2VydmljZQATFm5vdGUgcmlnaHQgb2YAIQoALQcgYXVnbWVudHMAVwUgXG5vcHRpb25zIHdpdGggQVBJIGhvc3RcbmFuZCBBdXRob3JpemF0aW9uIGhlYWRlcgoAQAgtPiBhcGkuZ2l0aHViLmNvbTogaHR0cACBNAgKAA8OAIEpDQAhB3Nwb25zZQBFDACBdgxzb2x2ZSBvciByZWplY3RcbncvAIEtBgAwCQCCBgxjYXJkABAm&s=roundgreen
   Put the following into websequencediagrams.com to regenerate:

    card -> consumer: request: ajax(opts)
    consumer -> service: request: ajax(opts)
    note right of service: service augments ajax \noptions with API host\nand Authorization header
    service -> api.github.com: http request
    api.github.com -> service: http response
    service -> consumer: resolve or reject\nw/ ajax response
    consumer -> card: resolve or reject\nw/ ajax response
*/

var AuthenticatedGithubApiService = Conductor.Oasis.Service.extend({

  accessToken: function(){
    return this.userController.get('accessToken');
  },
  /*
    @public

    @property requests
    @type Object
  */
  requests: {

    /*
      @public

      @method ajax
      @param ajaxOpts {Object}
    */
    ajax: function(ajaxOpts) {
      var accessToken = this.accessToken();

      if (!accessToken) {
        throw new Error('no github acccess token');
      }

      if (!ajaxOpts.data) {
        ajaxOpts.data = {};
      }

      var url = 'https://api.github.com' + ajaxOpts.url;
      ajaxOpts.beforeSend = function(xhr) {
        xhr.setRequestHeader('Authorization', "token " + accessToken);
      };

      return ajax(url, ajaxOpts).
        then(null, failureResultFromJqXhr);
    }
  }
});

function failureResultFromJqXhr(jqXhr){
  var parsedError = {
    responseText: jqXhr.responseText,
    status: jqXhr.status,
    rawHeaders: jqXhr.getAllResponseHeaders()
  };

  throw parsedError;
}

export default AuthenticatedGithubApiService;
<commit_msg>Now that RSVP.resolve is used, we get a single array on ajax failure instead of three arguments,<commit_after>import Conductor from 'conductor';
import ajax from 'glazier/utils/ajax';

/* Diagram: http://www.websequencediagrams.com/cgi-bin/cdraw?lz=Y2FyZCAtPiBjb25zdW1lcjogcmVxdWVzdDogYWpheChvcHRzKQoAFgggLT4gc2VydmljZQATFm5vdGUgcmlnaHQgb2YAIQoALQcgYXVnbWVudHMAVwUgXG5vcHRpb25zIHdpdGggQVBJIGhvc3RcbmFuZCBBdXRob3JpemF0aW9uIGhlYWRlcgoAQAgtPiBhcGkuZ2l0aHViLmNvbTogaHR0cACBNAgKAA8OAIEpDQAhB3Nwb25zZQBFDACBdgxzb2x2ZSBvciByZWplY3RcbncvAIEtBgAwCQCCBgxjYXJkABAm&s=roundgreen
   Put the following into websequencediagrams.com to regenerate:

    card -> consumer: request: ajax(opts)
    consumer -> service: request: ajax(opts)
    note right of service: service augments ajax \noptions with API host\nand Authorization header
    service -> api.github.com: http request
    api.github.com -> service: http response
    service -> consumer: resolve or reject\nw/ ajax response
    consumer -> card: resolve or reject\nw/ ajax response
*/

var AuthenticatedGithubApiService = Conductor.Oasis.Service.extend({

  accessToken: function(){
    return this.userController.get('accessToken');
  },
  /*
    @public

    @property requests
    @type Object
  */
  requests: {

    /*
      @public

      @method ajax
      @param ajaxOpts {Object}
    */
    ajax: function(ajaxOpts) {
      var accessToken = this.accessToken();

      if (!accessToken) {
        throw new Error('no github acccess token');
      }

      if (!ajaxOpts.data) {
        ajaxOpts.data = {};
      }

      var url = 'https://api.github.com' + ajaxOpts.url;
      ajaxOpts.beforeSend = function(xhr) {
        xhr.setRequestHeader('Authorization', "token " + accessToken);
      };

      return ajax(url, ajaxOpts).
        then(null, failureResultFromJqXhr);
    }
  }
});

function failureResultFromJqXhr(failureTriple){
  var jqXhr = failureTriple[0],
      parsedError = {
        responseText: jqXhr.responseText,
        status: jqXhr.status,
        rawHeaders: jqXhr.getAllResponseHeaders()
      };

  throw parsedError;
}

export default AuthenticatedGithubApiService;
<|endoftext|>


<commit_before>/*
 * Copyright 2019 EPAM Systems
 *
 * 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.
 */

import { defineMessages } from 'react-intl';

export const COMMON_LOCALE_KEYS = defineMessages({
  DELETE: {
    id: 'Common.delete',
    defaultMessage: 'Delete',
  },
  CANCEL: {
    id: 'Common.cancel',
    defaultMessage: 'Cancel',
  },
  CLOSE: {
    id: 'Common.close',
    defaultMessage: 'Close',
  },
  UPDATE: {
    id: 'Common.update',
    defaultMessage: 'Update',
  },
  SAVE: {
    id: 'Common.save',
    defaultMessage: 'Save',
  },
  CONFIRM: {
    id: 'Common.confirm',
    defaultMessage: 'Confirm',
  },
  SEND: {
    id: 'Common.send',
    defaultMessage: 'Send',
  },
  FINISH: {
    id: 'Common.finish',
    defaultMessage: 'Finish',
  },
  MOVE: {
    id: 'Common.move',
    defaultMessage: 'Move',
  },
  SUBMIT: {
    id: 'Common.submit',
    defaultMessage: 'Submit',
  },
  MERGE: {
    id: 'Common.merge',
    defaultMessage: 'Merge',
  },
  INVITE: {
    id: 'Common.invite',
    defaultMessage: 'Invite',
  },
  OK: {
    id: 'Common.ok',
    defaultMessage: 'Ok',
  },
  DISABLE: {
    id: 'Common.disable',
    defaultMessage: 'Disable',
  },
  ENABLE: {
    id: 'Common.enable',
    defaultMessage: 'Enable',
  },
  CLOSE_MODAL_WARNING: {
    id: 'Common.closeModalWarning',
    defaultMessage: 'You have to save changes or cancel them before closing the window',
  },
  DISCARD: {
    id: 'Common.discard',
    defaultMessage: 'Discard',
  },
  EDIT: {
    id: 'Common.edit',
    defaultMessage: 'Edit',
  },
  CLONE: {
    id: 'Common.clone',
    defaultMessage: 'Clone',
  },
  COMPARE: {
    id: 'Common.compare',
    defaultMessage: 'Compare',
  },
  ADD: {
    id: 'Common.add',
    defaultMessage: 'Add',
  },
  NO_RESULTS: {
    id: 'Common.noResults',
    defaultMessage: 'No results found',
  },
  RESET: {
    id: 'Common.reset',
    defaultMessage: 'Reset',
  },
  SEARCH: {
    id: 'Common.search',
    defaultMessage: 'Search',
  },
  UNINSTALL: {
    id: 'Common.uninstall',
    defaultMessage: 'Uninstall',
  },
  LOGIN: {
    id: 'Common.login',
    defaultMessage: 'Login',
  },
  MOVE_TO_DEBUG: {
    id: 'Common.moveToDebug',
    defaultMessage: 'Move to debug',
  },
  MOVE_TO_ALL_LAUNCHES: {
    id: 'Common.moveToAllLaunches',
    defaultMessage: 'Move to all launches',
  },
  FORCE_FINISH: {
    id: 'Common.forceFinish',
    defaultMessage: 'Force finish',
  },
  ERROR: {
    id: 'Common.error',
    defaultMessage: 'Error',
  },
  BACK: {
    id: 'Common.back',
    defaultMessage: 'Back',
  },
  ACTIONS: {
    id: 'Common.actions',
    defaultMessage: 'Actions',
  },
  EDIT_ITEMS: {
    id: 'Common.editItems',
    defaultMessage: 'Edit items',
  },
  PROCEED_VALID_ITEMS: {
    id: 'Common.proceedValidItems',
    defaultMessage: 'Proceed Valid Items',
  },
  DOWNLOAD: {
    id: 'Common.download',
    defaultMessage: 'Download',
  },
  OPEN_IN_NEW_TAB: {
    id: 'Common.openInNewTab',
    defaultMessage: 'Open in new tab',
  },
});
<commit_msg>EPMRPP-79570 || Page crash when user enters more than 2048 symbols in STEP description<commit_after>/*
 * Copyright 2019 EPAM Systems
 *
 * 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.
 */

import { defineMessages } from 'react-intl';

export const COMMON_LOCALE_KEYS = defineMessages({
  DELETE: {
    id: 'Common.delete',
    defaultMessage: 'Delete',
  },
  CANCEL: {
    id: 'Common.cancel',
    defaultMessage: 'Cancel',
  },
  CLOSE: {
    id: 'Common.close',
    defaultMessage: 'Close',
  },
  UPDATE: {
    id: 'Common.update',
    defaultMessage: 'Update',
  },
  SAVE: {
    id: 'Common.save',
    defaultMessage: 'Save',
  },
  CONFIRM: {
    id: 'Common.confirm',
    defaultMessage: 'Confirm',
  },
  SEND: {
    id: 'Common.send',
    defaultMessage: 'Send',
  },
  FINISH: {
    id: 'Common.finish',
    defaultMessage: 'Finish',
  },
  MOVE: {
    id: 'Common.move',
    defaultMessage: 'Move',
  },
  SUBMIT: {
    id: 'Common.submit',
    defaultMessage: 'Submit',
  },
  MERGE: {
    id: 'Common.merge',
    defaultMessage: 'Merge',
  },
  INVITE: {
    id: 'Common.invite',
    defaultMessage: 'Invite',
  },
  OK: {
    id: 'Common.ok',
    defaultMessage: 'Ok',
  },
  DISABLE: {
    id: 'Common.disable',
    defaultMessage: 'Disable',
  },
  ENABLE: {
    id: 'Common.enable',
    defaultMessage: 'Enable',
  },
  CLOSE_MODAL_WARNING: {
    id: 'Common.closeModalWarning',
    defaultMessage: 'You have to save changes or cancel them before closing the window',
  },
  DISCARD: {
    id: 'Common.discard',
    defaultMessage: 'Discard',
  },
  EDIT: {
    id: 'Common.edit',
    defaultMessage: 'Edit',
  },
  CLONE: {
    id: 'Common.clone',
    defaultMessage: 'Clone',
  },
  COMPARE: {
    id: 'Common.compare',
    defaultMessage: 'Compare',
  },
  ADD: {
    id: 'Common.add',
    defaultMessage: 'Add',
  },
  NO_RESULTS: {
    id: 'Common.noResults',
    defaultMessage: 'No results found',
  },
  RESET: {
    id: 'Common.reset',
    defaultMessage: 'Reset',
  },
  SEARCH: {
    id: 'Common.search',
    defaultMessage: 'Search',
  },
  UNINSTALL: {
    id: 'Common.uninstall',
    defaultMessage: 'Uninstall',
  },
  LOGIN: {
    id: 'Common.login',
    defaultMessage: 'Login',
  },
  MOVE_TO_DEBUG: {
    id: 'Common.moveToDebug',
    defaultMessage: 'Move to debug',
  },
  MOVE_TO_ALL_LAUNCHES: {
    id: 'Common.moveToAllLaunches',
    defaultMessage: 'Move to all launches',
  },
  FORCE_FINISH: {
    id: 'Common.forceFinish',
    defaultMessage: 'Force finish',
  },
  ERROR: {
    id: 'Common.error',
    defaultMessage: 'Error',
  },
  BACK: {
    id: 'Common.back',
    defaultMessage: 'Back',
  },
  ACTIONS: {
    id: 'Common.actions',
    defaultMessage: 'Actions',
  },
  EDIT_ITEMS: {
    id: 'Common.editItems',
    defaultMessage: 'Edit items',
  },
  PROCEED_VALID_ITEMS: {
    id: 'Common.proceedValidItems',
    defaultMessage: 'Proceed Valid Items',
  },
  DOWNLOAD: {
    id: 'Common.download',
    defaultMessage: 'Download',
  },
  OPEN_IN_NEW_TAB: {
    id: 'Common.openInNewTab',
    defaultMessage: 'Open in new tab',
  },
  changesWarning: {
    id: 'Common.changesWarning',
    defaultMessage: 'Field is invalid or changes were not saved',
  },
});
<|endoftext|>


<commit_before>// @flow

import React, { Component, Fragment, createRef } from 'react';
import get from 'lodash/get';
import { Scrollbars } from 'react-custom-scrollbars';
import { Grid, ScrollSync } from 'react-virtualized';
import isMobile from 'ismobilejs';

import CellRender from '../Cell';
import StyledCell from './StyledCell';
import IdField from './IdField';
import Flex from '../Flex';

import { META_FIELDS } from '../../utils/mappings';
import { MODES } from '../../constants';
import colors from '../theme/colors';

const OVERSCAN_COUNT = 3;
const HEIGHT_BUFFER = 32;

const ID_WIDTH = isMobile.any ? 120 : 250;

const isMetaField = field => META_FIELDS.indexOf(field) > -1;

type Props = {
	visibleColumns: string[],
	mode: string,
	mappings: any,
	nestedVisibleColumns: string[],
	isShowingNestedColumns: boolean,
	data: any,
	onCellChange: (...any) => void,
	height: number,
	width: number,
	headerRef: any,
};

class DataGrid extends Component<Props> {
	dataGridRef = createRef();

	dataScrollRef = createRef();

	componentDidUpdate() {
		const { headerRef } = this.props;
		if (
			headerRef &&
			headerRef.current &&
			headerRef.current.scrollLeft > 0
		) {
			// $FlowFixMe
			this.dataScrollRef.current.scrollLeft(headerRef.current.scrollLeft);
		}
	}

	handleScroll = ({ target }: any) => {
		const { scrollTop, scrollLeft } = target;
		const { headerRef } = this.props;

		if (headerRef && headerRef.current) {
			headerRef.current.scrollLeft = scrollLeft;
		}
		// $FlowFixMe
		this.dataGridRef.current.handleScrollEvent({
			scrollTop,
			scrollLeft,
		});
	};

	_renderLeftSideCell = ({ key, rowIndex, style }: any) => {
		const { data, mode } = this.props;

		return (
			<StyledCell
				style={style}
				mode={mode}
				key={key}
				css={{ width: '100%', background: colors.tableHead }}
			>
				<IdField
					rowIndex={rowIndex}
					data={data}
					value={data[rowIndex]._id}
				/>
			</StyledCell>
		);
	};

	_renderDataCell = ({ columnIndex, key, rowIndex, style }: any) => {
		const {
			nestedVisibleColumns,
			visibleColumns,
			isShowingNestedColumns,
			onCellChange,
			mappings,
			data,
			mode,
		} = this.props;
		const columns = isShowingNestedColumns
			? nestedVisibleColumns
			: visibleColumns;
		const mapProp = isShowingNestedColumns
			? 'nestedProperties'
			: 'properties';
		const column = columns[columnIndex];
		return isMetaField(column) ? (
			<div style={style} key={key}>
				{get(data[rowIndex], column)}
			</div>
		) : (
			<div
				style={{
					...style,
					borderRight: '0.5px solid #e8e8e8',
					borderBottom: '1px solid #e8e8e8',
					fontSize: '12px',
					padding: '10px',
				}}
				key={key}
			>
				<CellRender
					row={rowIndex}
					column={column}
					mode={mode}
					onChange={value => onCellChange(rowIndex, column, value)}
					mapping={mappings[mapProp][column]}
					shouldAutoFocus
					style={style}
				>
					{get(data[rowIndex], column)}
				</CellRender>
			</div>
		);
	};

	render() {
		const {
			mode,
			data,
			height,
			width,
			isShowingNestedColumns,
			nestedVisibleColumns,
			visibleColumns,
		} = this.props;
		const columns = isShowingNestedColumns
			? nestedVisibleColumns
			: visibleColumns;

		return (
			<Fragment>
				<ScrollSync>
					{({ onScroll, scrollTop }) => (
						<Flex wrap="nowrap">
							<Grid
								overscanColumnCount={0}
								overscanRowCount={OVERSCAN_COUNT}
								cellRenderer={this._renderLeftSideCell}
								columnWidth={ID_WIDTH}
								columnCount={1}
								height={height - HEIGHT_BUFFER}
								rowHeight={mode === MODES.EDIT ? 45 : 30}
								css={{
									zIndex: '101 !important',
									left: 0,
									position: 'absolute',
									backgroundColor: colors.tableHead,
									outline: 0,
									overflow: 'hidden !important',
								}}
								rowCount={data.length}
								scrollTop={scrollTop}
								width={ID_WIDTH}
							/>
							<Scrollbars
								ref={this.dataScrollRef}
								onScroll={this.handleScroll}
								style={{
									height: height - HEIGHT_BUFFER,
									width: width - ID_WIDTH,
								}}
							>
								<Grid
									overscanColumnCount={OVERSCAN_COUNT}
									overscanRowCount={OVERSCAN_COUNT}
									cellRenderer={this._renderDataCell}
									columnWidth={200}
									columnCount={columns.length}
									height={height - HEIGHT_BUFFER}
									rowHeight={mode === MODES.EDIT ? 45 : 30}
									rowCount={data.length}
									onScroll={onScroll}
									width={width - ID_WIDTH}
									style={{
										outline: 0,
										overflowX: false,
										overflowY: false,
									}}
									ref={this.dataGridRef}
								/>
							</Scrollbars>
						</Flex>
					)}
				</ScrollSync>
			</Fragment>
		);
	}
}

export default DataGrid;
<commit_msg>Fix meta fields styles<commit_after>// @flow

import React, { Component, Fragment, createRef } from 'react';
import get from 'lodash/get';
import { Scrollbars } from 'react-custom-scrollbars';
import { Grid, ScrollSync } from 'react-virtualized';
import isMobile from 'ismobilejs';

import CellRender from '../Cell';
import StyledCell from './StyledCell';
import IdField from './IdField';
import Flex from '../Flex';

import { META_FIELDS } from '../../utils/mappings';
import { MODES } from '../../constants';
import colors from '../theme/colors';

const OVERSCAN_COUNT = 3;
const HEIGHT_BUFFER = 32;
const CELL_STYLE = {
	borderRight: '0.5px solid #e8e8e8',
	borderBottom: '1px solid #e8e8e8',
	fontSize: '12px',
	padding: '10px',
};

const ID_WIDTH = isMobile.any ? 120 : 250;

const isMetaField = field => META_FIELDS.indexOf(field) > -1;

type Props = {
	visibleColumns: string[],
	mode: string,
	mappings: any,
	nestedVisibleColumns: string[],
	isShowingNestedColumns: boolean,
	data: any,
	onCellChange: (...any) => void,
	height: number,
	width: number,
	headerRef: any,
};

class DataGrid extends Component<Props> {
	dataGridRef = createRef();

	dataScrollRef = createRef();

	componentDidUpdate() {
		const { headerRef } = this.props;
		if (
			headerRef &&
			headerRef.current &&
			headerRef.current.scrollLeft > 0
		) {
			// $FlowFixMe
			this.dataScrollRef.current.scrollLeft(headerRef.current.scrollLeft);
		}
	}

	handleScroll = ({ target }: any) => {
		const { scrollTop, scrollLeft } = target;
		const { headerRef } = this.props;

		if (headerRef && headerRef.current) {
			headerRef.current.scrollLeft = scrollLeft;
		}
		// $FlowFixMe
		this.dataGridRef.current.handleScrollEvent({
			scrollTop,
			scrollLeft,
		});
	};

	_renderLeftSideCell = ({ key, rowIndex, style }: any) => {
		const { data, mode } = this.props;

		return (
			<StyledCell
				style={style}
				mode={mode}
				key={key}
				css={{ width: '100%', background: colors.tableHead }}
			>
				<IdField
					rowIndex={rowIndex}
					data={data}
					value={data[rowIndex]._id}
				/>
			</StyledCell>
		);
	};

	_renderDataCell = ({ columnIndex, key, rowIndex, style }: any) => {
		const {
			nestedVisibleColumns,
			visibleColumns,
			isShowingNestedColumns,
			onCellChange,
			mappings,
			data,
			mode,
		} = this.props;
		const columns = isShowingNestedColumns
			? nestedVisibleColumns
			: visibleColumns;
		const mapProp = isShowingNestedColumns
			? 'nestedProperties'
			: 'properties';
		const column = columns[columnIndex];
		return isMetaField(column) ? (
			<div
				style={{
					...style,
					...CELL_STYLE,
				}}
				key={key}
			>
				{get(data[rowIndex], column)}
			</div>
		) : (
			<div
				style={{
					...style,
					...CELL_STYLE,
				}}
				key={key}
			>
				<CellRender
					row={rowIndex}
					column={column}
					mode={mode}
					onChange={value => onCellChange(rowIndex, column, value)}
					mapping={mappings[mapProp][column]}
					shouldAutoFocus
					style={style}
				>
					{get(data[rowIndex], column)}
				</CellRender>
			</div>
		);
	};

	render() {
		const {
			mode,
			data,
			height,
			width,
			isShowingNestedColumns,
			nestedVisibleColumns,
			visibleColumns,
		} = this.props;
		const columns = isShowingNestedColumns
			? nestedVisibleColumns
			: visibleColumns;

		return (
			<Fragment>
				<ScrollSync>
					{({ onScroll, scrollTop }) => (
						<Flex wrap="nowrap">
							<Grid
								overscanColumnCount={0}
								overscanRowCount={OVERSCAN_COUNT}
								cellRenderer={this._renderLeftSideCell}
								columnWidth={ID_WIDTH}
								columnCount={1}
								height={height - HEIGHT_BUFFER}
								rowHeight={mode === MODES.EDIT ? 45 : 30}
								css={{
									zIndex: '101 !important',
									left: 0,
									position: 'absolute',
									backgroundColor: colors.tableHead,
									outline: 0,
									overflow: 'hidden !important',
								}}
								rowCount={data.length}
								scrollTop={scrollTop}
								width={ID_WIDTH}
							/>
							<Scrollbars
								ref={this.dataScrollRef}
								onScroll={this.handleScroll}
								style={{
									height: height - HEIGHT_BUFFER,
									width: width - ID_WIDTH,
								}}
							>
								<Grid
									overscanColumnCount={OVERSCAN_COUNT}
									overscanRowCount={OVERSCAN_COUNT}
									cellRenderer={this._renderDataCell}
									columnWidth={200}
									columnCount={columns.length}
									height={height - HEIGHT_BUFFER}
									rowHeight={mode === MODES.EDIT ? 45 : 30}
									rowCount={data.length}
									onScroll={onScroll}
									width={width - ID_WIDTH}
									style={{
										outline: 0,
										overflowX: false,
										overflowY: false,
									}}
									ref={this.dataGridRef}
								/>
							</Scrollbars>
						</Flex>
					)}
				</ScrollSync>
			</Fragment>
		);
	}
}

export default DataGrid;
<|endoftext|>


<commit_before>/*!
 * Copyright 2002 - 2016 Webdetails, a Pentaho company. All rights reserved.
 *
 * This software was developed by Webdetails and is provided under the terms
 * of the Mozilla Public License, Version 2.0, or any later version. You may not use
 * this file except in compliance with the license. If you need a copy of the license,
 * please go to http://mozilla.org/MPL/2.0/. The Initial Developer is Webdetails.
 *
 * Software distributed under the Mozilla Public License is distributed on an "AS IS"
 * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. Please refer to
 * the license for the specific language governing your rights and limitations.
 */

define([
  '../queries/CdaQuery.ext',
  '../components/XactionComponent.ext',
  './Dashboard.ext',
  './Dashboard',
  '../Logger',
  '../lib/jquery',
  'css!./Dashboard.legacy.css'
], function(CdaQueryExt, XactionComponentExt, DashboardExt, Dashboard, Logger, $) {

  /**
   * @class cdf.dashboard.Dashboard.legacy
   * @amd cdf/dashboard/Dashboard.legacy
   * @classdesc A class representing an extension to the Dashboard class for handling legacy calls.
   *            The methods here handle calling xactions and other legacy related actions.
   *            All the methods in this class are deprecated.
   * @deprecated
   * @ignore
   */
  Dashboard.implement(/** @lends cdf.dashboard.Dashboard# */{

    /**
     * Calls a xaction.
     *
     * @param {Object} obj        DOM object where the response from the xaction should be written.
     * @param {string} solution   The solution folder.
     * @param {string} path       Path to the xaction. Can be the full path, in which case you don't need the solution and action.
     * @param {string} action     The xaction name.
     * @param {Object} parameters Parameter object to send to the xaction.
     * @param {function} callback Callback function to call when the xaction responds.
     * @return {*} The xaction result.
     *
     * @deprecated
     */
    callPentahoAction: function(obj, solution, path, action, parameters, callback) {
      var myself = this;

      // Encapsulate pentahoAction call
      // Dashboards.log("Calling pentahoAction for " + obj.type + " " + obj.name + "; Is it visible?: " + obj.visible);
      if(typeof callback == 'function') {
        return myself.pentahoAction(solution, path, action, parameters, function(json) {
          callback(myself.parseXActionResult(obj, json));
        });
      } else {
        return myself.parseXActionResult(obj, myself.pentahoAction(solution, path, action, parameters, callback));
      }
    },

    /**
     * Calls an arbitrary URL expecting the result content type to be xml.
     *
     * @param {string} url    The URL to call.
     * @param {Object} params The parameters object.
     * @param {function} func Callback function.
     * @return {*} The parsed invocation result if no callback was supplied. Otherwise, null.
     * @see cdf.dashboard.Dashboard#executeAjax
     *
     * @deprecated
     */
    urlAction: function(url, params, func) {
      return this.executeAjax('xml', url, params, func);
    },

    /**
     * Executes an Ajax request. If no `func` callback is provided it executes asynchronously
     * and returns a jQuery XMLHttpRequest ({@link http://api.jquery.com/jQuery.ajax/#jqXHR|jqXHR})
     * object. Otherwise, it executes {@link http://api.jquery.com/jquery.ajax/|jQuery.ajax} synchronously and
     * returns the result of the HTTP request.
     *
     * @param {string}   returnType The expected return type.
     * @param {string}   url        The URL to call.
     * @param {Object}   params     The parameters object.
     * @param {function} func       Callback function.
     * @return {*} If no `func` callback is provided it returns a jqXHR object.
     *             Otherwise, it returns the result of the HTTP request.
     *
     * @deprecated
     */
    executeAjax: function(returnType, url, params, func) {
      var myself = this;
      // execute a url
      if(typeof func == "function") {
        // async
        return $.ajax({
          url: url,
          type: "POST",
          traditional: true,
          dataType: returnType,
          async: true,
          data: params,
          complete: function(XMLHttpRequest, textStatus) {
            /* CDF-271 jQuery 1.9.1 bug #13388 */
            if(typeof XMLHttpRequest.responseXML == "undefined") {
              func($.parseXML(XMLHttpRequest.responseText));
            } else {
              func(XMLHttpRequest.responseXML);
            }
          },
          error: function(XMLHttpRequest, textStatus, errorThrown) {
            Logger.error("Found error: " + XMLHttpRequest + " - " + textStatus + ", Error: " + errorThrown);
          }
        });
      }

      // Sync
      var result = $.ajax({
        url: url,
        type: "POST",
        dataType: returnType,
        async: false,
        data: params,
        error: function(XMLHttpRequest, textStatus, errorThrown) {
          Logger.error("Found error: " + XMLHttpRequest + " - " + textStatus + ", Error: " + errorThrown);
        }
      });

      if(returnType == 'xml') {
        /* CDF-271 jQuery 1.9.1 bug #13388 */
        if(typeof result.responseXML == "undefined") {
          return $.parseXML(result.responseText);
        } else {
          return result.responseXML;
        }
      } else {
        return result.responseText;
      }
    },

    /**
     * Another way to call an xaction.
     *
     * @param {string}   solution Solution folder.
     * @param {string}   path     Path to the xaction. Can be the full path, in which case you don't need the solution and action.
     * @param {string}   action   The xaction name.
     * @param {Object}   params   Parameter object to send to the xaction.
     * @param {function} func     Callback function to call when the xaction responds.
     * @return {*} The xaction result.
     *
     * @deprecated
     */
    pentahoAction: function(solution, path, action, params, func) {
      return this.pentahoServiceAction('ServiceAction', 'xml', solution, path, action, params, func);
    },

    /**
     * Calls an xaction.
     *
     * @param {string}   serviceMethod Dom object where the response from the xaction should be written.
     * @param {string}   returntype    Expected return type of the response.
     * @param {string}   solution      Solution folder.
     * @param {string}   path          Path to the xaction. Can be the full path, in which case you don't need the solution and action
     * @param {string}   action        The xaction name.
     * @param {Object}   params        Parameter object to send to the xaction.
     * @param {function} func          Callback function to call when the xaction responds.
     * @return {*} The xaction result.
     *
     * @deprecated
     */
    pentahoServiceAction: function(serviceMethod, returntype, solution, path, action, params, func) {
      // execute an Action Sequence on the server

      var arr = DashboardExt.getServiceAction(serviceMethod, solution, path, action);
      var url = arr.url;
      delete arr.url;

      $.each(params,function(i, val) {
        arr[val[0]] = val[1];
      });
      return this.executeAjax(returntype, url, arr, func);
    },

    /**
     * Legacy identifier of the HTML div element used for showing errors.
     *
     * @type {string}
     * @default
     *
     * @deprecated
     */
    CDF_ERROR_DIV: 'cdfErrorDiv',

    /**
     * Creates an empty HTML div element, with identifier
     * {@link cdf.dashboard.Dashboard#CDF_ERROR_DIV|CDF_ERROR_DIV} for showing error messages.
     *
     * @deprecated
     */
    createAndCleanErrorDiv: function() {
      if($("#" + this.CDF_ERROR_DIV).length == 0) {
        $("body").append("

");
      }
      $("#" + this.CDF_ERROR_DIV).empty();
    },

    /**
     * Creates an empty HTML div element for showing error messages.
     *
     * @deprecated
     */
    showErrorTooltip: function() {
      $(function() {
        if($.tooltip) {
          $(".cdf_error").tooltip({
            delay: 0,
            track: true,
            fade: 250,
            showBody: " -- "
          });
        }
      });
    },

    /**
     * Parses the xaction result.
     *
     * @private
     * @param {Object} obj  DOM object where the response will be written to.
     * @param {string} html HTML string containing the xaction result.
     *
     * @deprecated
     */
    parseXActionResult: function(obj, html) {

      var jXML = $(html);
      var error = jXML.find("SOAP-ENV\\:Fault");
      if(error.length == 0) {
        return jXML;
      }

      // error found. Parsing it
      var errorMessage = "Error executing component " + obj.name;
      var errorDetails = new Array();
      errorDetails[0] = " Error details for component execution " + obj.name + " -- ";
      errorDetails[1] = error.find("SOAP-ENV\\:faultstring").find("SOAP-ENV\\:Text:eq(0)").text();
      error.find("SOAP-ENV\\:Detail").find("message").each(function() {
        errorDetails.push($(this).text())
      });
      if(errorDetails.length > 8) {
        errorDetails = errorDetails.slice(0, 7);
        errorDetails.push("...");
      }
      //
      // TODO errorDetails in title: is this right?
      var out = "

	" + errorMessage + "

";

      // if this is a hidden component, we'll place this in the error div
      if(obj.visible == false) {
        $("#" + this.CDF_ERROR_DIV).append("
" + out);
      } else{
        $('#' + obj.htmlObject).html(out);
      }

      return null;
    },

    /**
     * Sets a setting in the server.
     *
     * @param {string} name   Name of the setting.
     * @param {Object} object Value for the setting.
     *
     * @deprecated
     */
    setSettingsValue: function(name, object) {

      var data = {
        method: "set",
        key: name,
        value: JSON.stringify(object)
      };
      $.post(DashboardExt.getSettings("set", null), data, function() {});
    },

    /**
     * Gets a setting value from the server.
     *
     * @param {string}   key   Key to the setting.
     * @param {function} value Callback function.
     *
     * @deprecated
     */
    getSettingsValue: function(key, value) {

      $.ajax({
        type: 'GET',
        dataType: "json",
        url: DashboardExt.getSettings("get", key),
        data: args,
        async: true,
        xhrFields: {
          withCredentials: true
        }
      }).done(typeof value == 'function' ? value : function(json) {
        value = json;
      });
    },

    /**
     * Fetches data from the server according to a Chart Definition object.
     * This method is deprecated, a {@link cdf.dashboard.Query|Query} instance should be used instead.
     *
     * @param {Object}   cd       Chart definition object.
     * @param {Object}   params   Parameter object.
     * @param {function} callback Callback to be called with results.
     *
     * @deprecated
     */
    fetchData: function(cd, params, callback) {
      Logger.warn('Dashboard fetchData() is deprecated. Use Query objects instead');
      // Detect and handle CDA data sources
      if(cd != undefined && cd.dataAccessId != undefined) {
        for(var param in params) {
          cd['param' + params[param][0]] = this.getParameterValue(params[param][1]);
        }

        $.post(
          CdaQueryExt.getDoQuery(),
          cd,
          function(json) {
            callback(json);
          },
          'json'
        ).error(this.handleServerError);
      }
      // When we're not working with a CDA data source, we default to using jtable to fetch the data...
      else if(cd != undefined) {

        var xactionFile = (cd.queryType == 'cda') ? "jtable-cda.xaction" : "jtable.xaction";

        $.post(
          XactionComponentExt.getCdfXaction("pentaho-cdf/actions", xactionFile),
          cd,
          function(result) {
            callback(result.values);
          },
          'json'
        );
      }
      // ... or just call the callback when no valid definition is passed
      else {
        callback([]);
      }
    }
  });
});
<commit_msg>[CDF-846] Increase documentation for Dashboard.legacy<commit_after>/*!
 * Copyright 2002 - 2016 Webdetails, a Pentaho company. All rights reserved.
 *
 * This software was developed by Webdetails and is provided under the terms
 * of the Mozilla Public License, Version 2.0, or any later version. You may not use
 * this file except in compliance with the license. If you need a copy of the license,
 * please go to http://mozilla.org/MPL/2.0/. The Initial Developer is Webdetails.
 *
 * Software distributed under the Mozilla Public License is distributed on an "AS IS"
 * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. Please refer to
 * the license for the specific language governing your rights and limitations.
 */

define([
  '../queries/CdaQuery.ext',
  '../components/XactionComponent.ext',
  './Dashboard.ext',
  './Dashboard',
  '../Logger',
  '../lib/jquery',
  'css!./Dashboard.legacy.css'
], function(CdaQueryExt, XactionComponentExt, DashboardExt, Dashboard, Logger, $) {

  /**
   * @class cdf.dashboard.Dashboard.legacy
   * @amd cdf/dashboard/Dashboard.legacy
   * @classdesc A class representing an extension to the Dashboard class for handling legacy calls.
   *            The methods here handle calling xactions and other legacy related actions.
   *            All the methods in this class are deprecated.
   * @deprecated
   * @ignore
   */
  Dashboard.implement(/** @lends cdf.dashboard.Dashboard# */{

    /**
     * @summary Calls a xaction.
     * @description Calls a xaction.
     *
     * @param {Object} obj        DOM object where the response from the xaction should be written.
     * @param {string} solution   The solution folder.
     * @param {string} path       Path to the xaction. Can be the full path, in which case you don't need the solution and action.
     * @param {string} action     The xaction name.
     * @param {Object} parameters Parameter object to send to the xaction.
     * @param {function} callback Callback function to call when the xaction responds.
     * @return {*} The xaction result.
     *
     * @deprecated
     */
    callPentahoAction: function(obj, solution, path, action, parameters, callback) {
      var myself = this;

      // Encapsulate pentahoAction call
      // Dashboards.log("Calling pentahoAction for " + obj.type + " " + obj.name + "; Is it visible?: " + obj.visible);
      if(typeof callback == 'function') {
        return myself.pentahoAction(solution, path, action, parameters, function(json) {
          callback(myself.parseXActionResult(obj, json));
        });
      } else {
        return myself.parseXActionResult(obj, myself.pentahoAction(solution, path, action, parameters, callback));
      }
    },

    /**
     * @summary Calls an arbitrary URL expecting the result content type to be xml.
     * @description Calls an arbitrary URL expecting the result content type to be xml.
     *
     * @param {string} url    The URL to call.
     * @param {Object} params The parameters object.
     * @param {function} func Callback function.
     * @return {*} The parsed invocation result if no callback was supplied. Otherwise, null.
     * @see cdf.dashboard.Dashboard#executeAjax
     *
     * @deprecated
     */
    urlAction: function(url, params, func) {
      return this.executeAjax('xml', url, params, func);
    },

    /**
     * @summary Executes an Ajax request.
     * @description Executes an Ajax request. If no `func` callback is provided it executes asynchronously
     *              and returns a jQuery XMLHttpRequest ({@link http://api.jquery.com/jQuery.ajax/#jqXHR|jqXHR})
     *              object. Otherwise, it executes {@link http://api.jquery.com/jquery.ajax/|jQuery.ajax} synchronously and
     *              returns the result of the HTTP request.
     *
     * @param {string}   returnType The expected return type.
     * @param {string}   url        The URL to call.
     * @param {Object}   params     The parameters object.
     * @param {function} func       Callback function.
     * @return {*} If no `func` callback is provided it returns a jqXHR object.
     *             Otherwise, it returns the result of the HTTP request.
     *
     * @deprecated
     */
    executeAjax: function(returnType, url, params, func) {
      var myself = this;
      // execute a url
      if(typeof func == "function") {
        // async
        return $.ajax({
          url: url,
          type: "POST",
          traditional: true,
          dataType: returnType,
          async: true,
          data: params,
          complete: function(XMLHttpRequest, textStatus) {
            /* CDF-271 jQuery 1.9.1 bug #13388 */
            if(typeof XMLHttpRequest.responseXML == "undefined") {
              func($.parseXML(XMLHttpRequest.responseText));
            } else {
              func(XMLHttpRequest.responseXML);
            }
          },
          error: function(XMLHttpRequest, textStatus, errorThrown) {
            Logger.error("Found error: " + XMLHttpRequest + " - " + textStatus + ", Error: " + errorThrown);
          }
        });
      }

      // Sync
      var result = $.ajax({
        url: url,
        type: "POST",
        dataType: returnType,
        async: false,
        data: params,
        error: function(XMLHttpRequest, textStatus, errorThrown) {
          Logger.error("Found error: " + XMLHttpRequest + " - " + textStatus + ", Error: " + errorThrown);
        }
      });

      if(returnType == 'xml') {
        /* CDF-271 jQuery 1.9.1 bug #13388 */
        if(typeof result.responseXML == "undefined") {
          return $.parseXML(result.responseText);
        } else {
          return result.responseXML;
        }
      } else {
        return result.responseText;
      }
    },

    /**
     * @summary Another way to call a xaction.
     * @description Another way to call a xaction.
     *
     * @param {string}   solution Solution folder.
     * @param {string}   path     Path to the xaction. Can be the full path, in which case you don't need the solution and action.
     * @param {string}   action   The xaction name.
     * @param {Object}   params   Parameter object to send to the xaction.
     * @param {function} func     Callback function to call when the xaction responds.
     * @return {*} The xaction result.
     *
     * @deprecated
     */
    pentahoAction: function(solution, path, action, params, func) {
      return this.pentahoServiceAction('ServiceAction', 'xml', solution, path, action, params, func);
    },

    /**
     * @summary Calls a xaction.
     * @description Calls a xaction.
     *
     * @param {string}   serviceMethod Dom object where the response from the xaction should be written.
     * @param {string}   returntype    Expected return type of the response.
     * @param {string}   solution      Solution folder.
     * @param {string}   path          Path to the xaction. Can be the full path, in which case you don't need the solution and action
     * @param {string}   action        The xaction name.
     * @param {Object}   params        Parameter object to send to the xaction.
     * @param {function} func          Callback function to call when the xaction responds.
     * @return {*} The xaction result.
     *
     * @deprecated
     */
    pentahoServiceAction: function(serviceMethod, returntype, solution, path, action, params, func) {
      // execute an Action Sequence on the server

      var arr = DashboardExt.getServiceAction(serviceMethod, solution, path, action);
      var url = arr.url;
      delete arr.url;

      $.each(params,function(i, val) {
        arr[val[0]] = val[1];
      });
      return this.executeAjax(returntype, url, arr, func);
    },

    /**
     * @summary Legacy identifier of the HTML div element used for showing errors.
     * @description Legacy identifier of the HTML div element used for showing errors.
     *
     * @type {string}
     * @default
     *
     * @deprecated
     */
    CDF_ERROR_DIV: 'cdfErrorDiv',

    /**
     * @summary Creates an empty HTML div element for showing errors.
     * @description Creates an empty HTML div element, with identifier
     * {@link cdf.dashboard.Dashboard#CDF_ERROR_DIV|CDF_ERROR_DIV} for showing error messages.
     *
     * @deprecated
     */
    createAndCleanErrorDiv: function() {
      if($("#" + this.CDF_ERROR_DIV).length == 0) {
        $("body").append("

");
      }
      $("#" + this.CDF_ERROR_DIV).empty();
    },

    /**
     * @summary Creates a tooltip for showing errors.
     * @description Creates an empty HTML div element for showing error messages.
     *
     * @deprecated
     */
    showErrorTooltip: function() {
      $(function() {
        if($.tooltip) {
          $(".cdf_error").tooltip({
            delay: 0,
            track: true,
            fade: 250,
            showBody: " -- "
          });
        }
      });
    },

    /**
     * @summary Parses the xaction result.
     * @description Parses the xaction result.
     *
     * @private
     * @param {Object} obj  DOM object where the response will be written to.
     * @param {string} html HTML string containing the xaction result.
     *
     * @deprecated
     */
    parseXActionResult: function(obj, html) {

      var jXML = $(html);
      var error = jXML.find("SOAP-ENV\\:Fault");
      if(error.length == 0) {
        return jXML;
      }

      // error found. Parsing it
      var errorMessage = "Error executing component " + obj.name;
      var errorDetails = new Array();
      errorDetails[0] = " Error details for component execution " + obj.name + " -- ";
      errorDetails[1] = error.find("SOAP-ENV\\:faultstring").find("SOAP-ENV\\:Text:eq(0)").text();
      error.find("SOAP-ENV\\:Detail").find("message").each(function() {
        errorDetails.push($(this).text())
      });
      if(errorDetails.length > 8) {
        errorDetails = errorDetails.slice(0, 7);
        errorDetails.push("...");
      }
      //
      // TODO errorDetails in title: is this right?
      var out = "

	" + errorMessage + "

";

      // if this is a hidden component, we'll place this in the error div
      if(obj.visible == false) {
        $("#" + this.CDF_ERROR_DIV).append("
" + out);
      } else{
        $('#' + obj.htmlObject).html(out);
      }

      return null;
    },

    /**
     * @summary Sets a setting in the server.
     * @description Sets a setting in the server.
     *
     * @param {string} name   Name of the setting.
     * @param {Object} object Value for the setting.
     *
     * @deprecated
     */
    setSettingsValue: function(name, object) {

      var data = {
        method: "set",
        key: name,
        value: JSON.stringify(object)
      };
      $.post(DashboardExt.getSettings("set", null), data, function() {});
    },

    /**
     * @summary Gets a setting value from the server.
     * @description Gets a setting value from the server.
     *
     * @param {string}   key   Key to the setting.
     * @param {function} value Callback function.
     *
     * @deprecated
     */
    getSettingsValue: function(key, value) {

      $.ajax({
        type: 'GET',
        dataType: "json",
        url: DashboardExt.getSettings("get", key),
        data: args,
        async: true,
        xhrFields: {
          withCredentials: true
        }
      }).done(typeof value == 'function' ? value : function(json) {
        value = json;
      });
    },

    /**
     * @summary Fetches data from the server according to a Chart Definition `object`.
     * @description Fetches data from the server according to a Chart Definition `object`.
     *              This method is deprecated, a {@link cdf.dashboard.Query|Query}
     *              instance should be used instead.
     *
     * @param {Object}   cd       Chart definition object.
     * @param {Object}   params   Parameter object.
     * @param {function} callback Callback to be called with results.
     *
     * @deprecated
     */
    fetchData: function(cd, params, callback) {
      Logger.warn('Dashboard fetchData() is deprecated. Use Query objects instead');
      // Detect and handle CDA data sources
      if(cd != undefined && cd.dataAccessId != undefined) {
        for(var param in params) {
          cd['param' + params[param][0]] = this.getParameterValue(params[param][1]);
        }

        $.post(
          CdaQueryExt.getDoQuery(),
          cd,
          function(json) {
            callback(json);
          },
          'json'
        ).error(this.handleServerError);
      }
      // When we're not working with a CDA data source, we default to using jtable to fetch the data...
      else if(cd != undefined) {

        var xactionFile = (cd.queryType == 'cda') ? "jtable-cda.xaction" : "jtable.xaction";

        $.post(
          XactionComponentExt.getCdfXaction("pentaho-cdf/actions", xactionFile),
          cd,
          function(result) {
            callback(result.values);
          },
          'json'
        );
      }
      // ... or just call the callback when no valid definition is passed
      else {
        callback([]);
      }
    }
  });
});
<|endoftext|>


<commit_before>"use strict";
var Benchmark = Benchmark || {};

Benchmark.MongoClient = require('mongodb').MongoClient;

Benchmark.MongoInterface = function(){
  var client = Benchmark.MongoClient
    , defaultCollectionName = 'documents'
    , insert = function(obj){
      client.connect("mongodb://localhost/documents", function(err, db) {
        if(err){
          return console.dir(err);
        }
        var collection = db.collection(defaultCollectionName);
        collection.insert(obj, {w:1}, function(err, result){
          if(err){
            return err;
          }
          return result;
        });
      });
    }
    , get = function(){

    }
    , remove = function(){

    };

  return{
    insert: insert,
    get: get,
    remove: remove
  };
};<commit_msg>Mongo driver<commit_after>"use strict";

var MongoClient = require('mongodb').MongoClient;

var MongoInterface = (function () {
  var interfaceName = 'mongo'
    , client = MongoClient
    , connectionURL = "mongodb://192.168.1.113/documents"
    , defaultCollectionName = 'documents'
    , insert = function (obj, callback) {
      client.connect(connectionURL, function (err, db) {
        if (err) {
          return console.dir(err);
        }
        var collection = db.collection(defaultCollectionName);
        collection.insert(obj, {w: 1}, function (err, result) {
          db.close();
          callback(err, result);
        });
      });
    }
    , get = function (id, callback) {
      client.connect(connectionURL, function (err, db) {
        if (err) {
          return console.dir(err);
        }
        var collection = db.collection(defaultCollectionName);
        collection.find({"_id": id}, function (err, results) {
          callback(err, results);
        });
      });
    }
    , getInsertId = function(obj){
      return obj.result[0]._id;
    }
    , remove = function () {

    };

  return{
    insert: insert,
    get: get,
    remove: remove,
    name: interfaceName,
    getInsertId: getInsertId
  };
}());

module.exports = MongoInterface;<|endoftext|>


<commit_before>/**
 * Copyright 2017 Google Inc. All rights reserved.
 *
 * 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.
 */

const {helper} = require('./helper');
const {FrameManager} = require('./FrameManager');

class NavigatorWatcher {
  /**
   * @param {!FrameManager} frameManager
   * @param {!Puppeteer.Frame} frame
   * @param {!Object=} options
   */
  constructor(frameManager, frame, options = {}) {
    console.assert(options.networkIdleTimeout === undefined, 'ERROR: networkIdleTimeout option is no longer supported.');
    console.assert(options.networkIdleInflight === undefined, 'ERROR: networkIdleInflight option is no longer supported.');
    console.assert(options.waitUntil !== 'networkidle', 'ERROR: "networkidle" option is no longer supported. Use "networkidle2" instead');
    let waitUntil = ['load'];
    if (Array.isArray(options.waitUntil))
      waitUntil = options.waitUntil.slice();
    else if (typeof options.waitUntil === 'string')
      waitUntil = [options.waitUntil];
    this._expectedLifecycle = waitUntil.map(value => {
      const protocolEvent = puppeteerToProtocolLifecycle[value];
      console.assert(protocolEvent, 'Unknown value for options.waitUntil: ' + value);
      return protocolEvent;
    });

    this._frameManager = frameManager;
    this._frame = frame;
    this._initialLoaderId = frame._loaderId;
    this._timeout = typeof options.timeout === 'number' ? options.timeout : 30000;
    this._eventListeners = [
      helper.addEventListener(this._frameManager, FrameManager.Events.LifecycleEvent, this._checkLifecycleComplete.bind(this)),
      helper.addEventListener(this._frameManager, FrameManager.Events.FrameDetached, this._checkLifecycleComplete.bind(this))
    ];

    const lifecycleCompletePromise = new Promise(fulfill => {
      this._lifecycleCompleteCallback = fulfill;
    });
    this._navigationPromise = Promise.race([
      this._createTimeoutPromise(),
      lifecycleCompletePromise
    ]).then(error => {
      this._cleanup();
      return error;
    });
  }

  /**
   * @return {?Promise<?Error>}
   */
  _createTimeoutPromise() {
    if (!this._timeout)
      return new Promise(() => {});
    const errorMessage = 'Navigation Timeout Exceeded: ' + this._timeout + 'ms exceeded';
    return new Promise(fulfill => this._maximumTimer = setTimeout(fulfill, this._timeout))
        .then(() => new Error(errorMessage));
  }

  /**
   * @return {!Promise<?Error>}
   */
  async navigationPromise() {
    return this._navigationPromise;
  }

  _checkLifecycleComplete() {
    // We expect navigation to commit.
    if (this._frame._loaderId === this._initialLoaderId)
      return;
    if (!checkLifecycle(this._frame, this._expectedLifecycle))
      return;
    this._lifecycleCompleteCallback();

    /**
     * @param {!Puppeteer.Frame} frame
     * @param {!Array<string>} expectedLifecycle
     * @return {boolean}
     */
    function checkLifecycle(frame, expectedLifecycle) {
      for (const event of expectedLifecycle) {
        if (!frame._lifecycleEvents.has(event))
          return false;
      }
      for (const child of frame.childFrames()) {
        if (!checkLifecycle(child, expectedLifecycle))
          return false;
      }
      return true;
    }
  }

  cancel() {
    this._cleanup();
  }

  _cleanup() {
    helper.removeEventListeners(this._eventListeners);
    this._lifecycleCompleteCallback(new Error('Navigation failed'));
    clearTimeout(this._maximumTimer);
  }
}

const puppeteerToProtocolLifecycle = {
  'load': 'load',
  'domcontentloaded': 'DOMContentLoaded',
  'networkidle0': 'networkIdle',
  'networkidle2': 'networkAlmostIdle',
};

module.exports = NavigatorWatcher;
<commit_msg>chore(NavigationWatcher): correct closure annotation (#1658)<commit_after>/**
 * Copyright 2017 Google Inc. All rights reserved.
 *
 * 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.
 */

const {helper} = require('./helper');
const {FrameManager} = require('./FrameManager');

class NavigatorWatcher {
  /**
   * @param {!FrameManager} frameManager
   * @param {!Puppeteer.Frame} frame
   * @param {!Object=} options
   */
  constructor(frameManager, frame, options = {}) {
    console.assert(options.networkIdleTimeout === undefined, 'ERROR: networkIdleTimeout option is no longer supported.');
    console.assert(options.networkIdleInflight === undefined, 'ERROR: networkIdleInflight option is no longer supported.');
    console.assert(options.waitUntil !== 'networkidle', 'ERROR: "networkidle" option is no longer supported. Use "networkidle2" instead');
    let waitUntil = ['load'];
    if (Array.isArray(options.waitUntil))
      waitUntil = options.waitUntil.slice();
    else if (typeof options.waitUntil === 'string')
      waitUntil = [options.waitUntil];
    this._expectedLifecycle = waitUntil.map(value => {
      const protocolEvent = puppeteerToProtocolLifecycle[value];
      console.assert(protocolEvent, 'Unknown value for options.waitUntil: ' + value);
      return protocolEvent;
    });

    this._frameManager = frameManager;
    this._frame = frame;
    this._initialLoaderId = frame._loaderId;
    this._timeout = typeof options.timeout === 'number' ? options.timeout : 30000;
    this._eventListeners = [
      helper.addEventListener(this._frameManager, FrameManager.Events.LifecycleEvent, this._checkLifecycleComplete.bind(this)),
      helper.addEventListener(this._frameManager, FrameManager.Events.FrameDetached, this._checkLifecycleComplete.bind(this))
    ];

    const lifecycleCompletePromise = new Promise(fulfill => {
      this._lifecycleCompleteCallback = fulfill;
    });
    this._navigationPromise = Promise.race([
      this._createTimeoutPromise(),
      lifecycleCompletePromise
    ]).then(error => {
      this._cleanup();
      return error;
    });
  }

  /**
   * @return {!Promise<?Error>}
   */
  _createTimeoutPromise() {
    if (!this._timeout)
      return new Promise(() => {});
    const errorMessage = 'Navigation Timeout Exceeded: ' + this._timeout + 'ms exceeded';
    return new Promise(fulfill => this._maximumTimer = setTimeout(fulfill, this._timeout))
        .then(() => new Error(errorMessage));
  }

  /**
   * @return {!Promise<?Error>}
   */
  async navigationPromise() {
    return this._navigationPromise;
  }

  _checkLifecycleComplete() {
    // We expect navigation to commit.
    if (this._frame._loaderId === this._initialLoaderId)
      return;
    if (!checkLifecycle(this._frame, this._expectedLifecycle))
      return;
    this._lifecycleCompleteCallback();

    /**
     * @param {!Puppeteer.Frame} frame
     * @param {!Array<string>} expectedLifecycle
     * @return {boolean}
     */
    function checkLifecycle(frame, expectedLifecycle) {
      for (const event of expectedLifecycle) {
        if (!frame._lifecycleEvents.has(event))
          return false;
      }
      for (const child of frame.childFrames()) {
        if (!checkLifecycle(child, expectedLifecycle))
          return false;
      }
      return true;
    }
  }

  cancel() {
    this._cleanup();
  }

  _cleanup() {
    helper.removeEventListeners(this._eventListeners);
    this._lifecycleCompleteCallback(new Error('Navigation failed'));
    clearTimeout(this._maximumTimer);
  }
}

const puppeteerToProtocolLifecycle = {
  'load': 'load',
  'domcontentloaded': 'DOMContentLoaded',
  'networkidle0': 'networkIdle',
  'networkidle2': 'networkAlmostIdle',
};

module.exports = NavigatorWatcher;
<|endoftext|>


<commit_before>/* Copyright (c) 2006 MetaCarta, Inc., published under the BSD license.
 * See http://svn.openlayers.org/trunk/openlayers/license.txt for the full
 * text of the license. */
/**
 * @class
 */
OpenLayers.Layer = Class.create();
OpenLayers.Layer.prototype = {

    /** @type String */
    id: null,

    /** @type String */
    name: null,

    /** @type DOMElement */
    div: null,

    /** This variable is set when the layer is added to the map, via the
     *  accessor function setMap()
     *
     * @type OpenLayers.Map */
    map: null,

    /** Whether or not the layer is a base layer. This should be set
     *   individually by all subclasses.
     *   Default is false
     *
     * @type Boolean
     */
    isBaseLayer: false,

    /** asserts whether or not the layer's images have an alpha channel
     *
     * @type boolean */
    alpha: false,

  // OPTIONS

    /** @type Array */
    options: null,

    /** @type String */
    projection: null,

    /** @type OpenLayers.Bounds */
    maxExtent: null,

    /** @type float */
    maxResolution: null,

    /** @type int */
    minZoomLevel: null,

    /** @type int */
    maxZoomLevel: null,

    /** @type float */
    minScale: null,

    /** @type float */
    maxScale: null,

    /** @type String */
    units: null,

    /**
     * @constructor
     *
     * @param {String} name
     * @param {Object} options Hashtable of extra options to tag onto the layer
     */
    initialize: function(name, options) {
        if (arguments.length > 0) {

            //store a copy of the custom options for later cloning
            this.options = Object.extend(new Object(), options);

            //add options to layer
            Object.extend(this, this.options);

            this.name = name;

            //generate unique id based on name
            this.id = OpenLayers.Util.createUniqueID("Layer_");

            if (this.div == null) {
                this.div = OpenLayers.Util.createDiv();
                this.div.style.width = "100%";
                this.div.style.height = "100%";
            }
        }
    },

    /**
     * Destroy is a destructor: this is to alleviate cyclic references which
     * the Javascript garbage cleaner can not take care of on its own.
     */
    destroy: function() {
        if (this.map != null) {
            this.map.removeLayer(this);
        }
        this.map = null;
        this.name = null;
        this.div = null;
        this.options = null;
    },

   /**
    * @returns An exact clone of this OpenLayers.Layer
    * @type OpenLayers.Layer
    */
    clone: function (obj) {

        if (obj == null) {
            obj = new OpenLayers.Layer(this.name, this.options);
        }

        // catch any randomly tagged-on properties
        obj = OpenLayers.Util.applyDefaults(obj, this);

        // a cloned layer should never have its map property set
        //  because it has not been added to a map yet.
        obj.map = null;

        return obj;
    },

    /**
     * @param {String} newName
     */
    setName: function(newName) {
        this.name = newName;
        // assuming a map has been assigned, trigger changelayer
        if (this.map != null)
            this.map.events.triggerEvent("changelayer");
    },

   /**
    * @param {Object} newOptions
    */
    addOptions: function (newOptions) {

        // update our copy for clone
        Object.extend(this.options, newOptions);

        // add new options to this
        Object.extend(this, this.options);
    },

    /**
     * @param {OpenLayers.Bounds} bound
     * @param {Boolean} zoomChanged tells when zoom has changed, as layers
     *                   have to do some init work in that case.
     * @param {Boolean} minor
     */
    moveTo:function(bounds, zoomChanged, minor) {
        //this function can be implemented by subclasses.
    },

    /**
     */
    reproject:function() {
        //this function can be implemented by subclasses.
    },

    /** Set the map property for the layer. This is done through an accessor
     *   so that subclasses can override this and take special action once
     *   they have their map variable set.
     *
     * @param {OpenLayers.Map} map
     */
    setMap: function(map) {
        this.map = map;

        var properties = new Array(
          'projection', 'minExtent', 'maxExtent',
          'minScale', 'maxScale',
          'maxResolution', 'minResolution',
          'minZoomLevel', 'maxZoomLevel', 'units',
          'scales', 'resolutions'

        );
        for(var i=0; i < properties.length; i++) {
            if (this[properties[i]] == null) {
                this[properties[i]] = this.map[properties[i]];
            }
        }
    },

    /**
    * @returns Whether or not the layer is visible
    * @type Boolean
    */
    getVisibility: function() {
        return (this.div.style.display != "none");
    },

    /**
     * @param {Boolean} visible
     * @param {Boolean} noEvent
     */
    setVisibility: function(visible, noEvent) {
        if (visible != this.getVisibility()) {
            this.div.style.display = (visible) ? "block" : "none";
            if ((visible) && (this.map != null)) {
                var extent = this.map.getExtent();
                if (extent != null) {
                    this.moveTo(this.map.getExtent());
                }
            }
            if ((this.map != null) &&
                ((noEvent == null) || (noEvent == false))) {
                this.map.events.triggerEvent("changelayer");
            }
        }
    },

  /********************************************************/
  /*                                                      */
  /*                 Layer Options                        */
  /*                                                      */
  /*    Accessor functions to Layer Options parameters    */
  /*                                                      */
  /********************************************************/

    /**
     * @type String
     */
    getProjection: function() {
        return this.projection;
    },

    /**
     * @type OpenLayers.Bounds
     */
    getMaxExtent: function() {
        return this.maxExtent;
    },

    /**
     * @type float
     */
    getMaxResolution: function() {
        return this.maxResolution;
    },

    /**
     * @returns The minimum zoom level that can be reached in this layer
     * @type int
     */
    getMinZoomLevel: function() {
        return this.minZoomLevel;
    },

    /**
     * @returns The maximum zoom level that can be reached in this layer
     * @type int
     */
    getMaxZoomLevel: function() {
        return this.maxZoomLevel;
    },

  /********************************************************/
  /*                                                      */
  /*                 Baselayer Functions                  */
  /*                                                      */
  /*    The following functions must all be implemented   */
  /*                  by all base layers                  */
  /*                                                      */
  /********************************************************/

    /**
     * @returns Degrees per Pixel
     * @type float
     */
    getResolution: function() {
        var viewSize = this.map.getSize();
        var extent = this.map.getExtent();
        return Math.max( extent.getWidth()  / viewSize.w,
                         extent.getHeight() / viewSize.h );
    },

    /** Calculates using px-> lonlat translation functions on tl and br
     *   corners of viewport
     *
     * @returns A Bounds object which represents the lon/lat bounds of the
     *          current viewPort.
     * @type OpenLayers.Bounds
     */
    getExtent: function () {
        var extent = null;

        var size = this.map.getSize();

        var tlPx = new OpenLayers.Pixel(0,0);
        var tlLL = this.getLonLatFromViewPortPx(tlPx);

        var brPx = new OpenLayers.Pixel(size.w, size.h);
        var brLL = this.getLonLatFromViewPortPx(brPx);

        if ((tlLL != null) && (brLL != null)) {
            extent = new OpenLayers.Bounds(tlLL.lon,
                                       brLL.lat,
                                       brLL.lon,
                                       tlLL.lat);
        }

        return extent;
    },

    /**
    * @param {OpenLayers.Pixel} viewPortPx
    *
    * @returns An OpenLayers.LonLat which is the passed-in view port
    *          OpenLayers.Pixel, translated into lon/lat by the layer
    * @type OpenLayers.LonLat
    */
    getLonLatFromViewPortPx: function (viewPortPx) {
        var size = this.map.getSize();
        var center = this.map.getCenter();        //map center lon/lat
        var res  = this.map.getResolution();

        var delta_x = viewPortPx.x - (size.w / 2);
        var delta_y = viewPortPx.y - (size.h / 2);

        return new OpenLayers.LonLat(center.lon + delta_x * res ,
                                     center.lat - delta_y * res);
    },

    /**
    * @param {OpenLayers.LonLat} lonlat
    *
    * @returns An OpenLayers.Pixel which is the passed-in OpenLayers.LonLat,
    *          translated into view port pixels
    * @type OpenLayers.Pixel
    */
    getViewPortPxFromLonLat: function (lonlat) {
        var resolution = this.map.getResolution();
        var extent = this.map.getExtent();
        return new OpenLayers.Pixel(
                       Math.round(1/resolution * (lonlat.lon - extent.left)),
                       Math.round(1/resolution * (extent.top - lonlat.lat))
                       );
    },

    /**
    * @param {OpenLayers.Bounds} bounds
    *
    * @return {int}
    */
    getZoomForExtent: function (bounds) {
        // this should be implemented by subclasses
    },

    /** @final @type String */
    CLASS_NAME: "OpenLayers.Layer"
};
<commit_msg>useless comment<commit_after>/* Copyright (c) 2006 MetaCarta, Inc., published under the BSD license.
 * See http://svn.openlayers.org/trunk/openlayers/license.txt for the full
 * text of the license. */
/**
 * @class
 */
OpenLayers.Layer = Class.create();
OpenLayers.Layer.prototype = {

    /** @type String */
    id: null,

    /** @type String */
    name: null,

    /** @type DOMElement */
    div: null,

    /** This variable is set when the layer is added to the map, via the
     *  accessor function setMap()
     *
     * @type OpenLayers.Map */
    map: null,

    /** Whether or not the layer is a base layer. This should be set
     *   individually by all subclasses.
     *   Default is false
     *
     * @type Boolean
     */
    isBaseLayer: false,

    /** asserts whether or not the layer's images have an alpha channel
     *
     * @type boolean */
    alpha: false,

  // OPTIONS

    /** @type Array */
    options: null,

    /** @type String */
    projection: null,

    /** @type OpenLayers.Bounds */
    maxExtent: null,

    /** @type float */
    maxResolution: null,

    /** @type int */
    minZoomLevel: null,

    /** @type int */
    maxZoomLevel: null,

    /** @type float */
    minScale: null,

    /** @type float */
    maxScale: null,

    /** @type String */
    units: null,

    /**
     * @constructor
     *
     * @param {String} name
     * @param {Object} options Hashtable of extra options to tag onto the layer
     */
    initialize: function(name, options) {
        if (arguments.length > 0) {

            //store a copy of the custom options for later cloning
            this.options = Object.extend(new Object(), options);

            //add options to layer
            Object.extend(this, this.options);

            this.name = name;

            //generate unique id based on name
            this.id = OpenLayers.Util.createUniqueID("Layer_");

            if (this.div == null) {
                this.div = OpenLayers.Util.createDiv();
                this.div.style.width = "100%";
                this.div.style.height = "100%";
            }
        }
    },

    /**
     * Destroy is a destructor: this is to alleviate cyclic references which
     * the Javascript garbage cleaner can not take care of on its own.
     */
    destroy: function() {
        if (this.map != null) {
            this.map.removeLayer(this);
        }
        this.map = null;
        this.name = null;
        this.div = null;
        this.options = null;
    },

   /**
    * @returns An exact clone of this OpenLayers.Layer
    * @type OpenLayers.Layer
    */
    clone: function (obj) {

        if (obj == null) {
            obj = new OpenLayers.Layer(this.name, this.options);
        }

        // catch any randomly tagged-on properties
        obj = OpenLayers.Util.applyDefaults(obj, this);

        // a cloned layer should never have its map property set
        //  because it has not been added to a map yet.
        obj.map = null;

        return obj;
    },

    /**
     * @param {String} newName
     */
    setName: function(newName) {
        this.name = newName;
        if (this.map != null)
            this.map.events.triggerEvent("changelayer");
    },

   /**
    * @param {Object} newOptions
    */
    addOptions: function (newOptions) {

        // update our copy for clone
        Object.extend(this.options, newOptions);

        // add new options to this
        Object.extend(this, this.options);
    },

    /**
     * @param {OpenLayers.Bounds} bound
     * @param {Boolean} zoomChanged tells when zoom has changed, as layers
     *                   have to do some init work in that case.
     * @param {Boolean} minor
     */
    moveTo:function(bounds, zoomChanged, minor) {
        //this function can be implemented by subclasses.
    },

    /**
     */
    reproject:function() {
        //this function can be implemented by subclasses.
    },

    /** Set the map property for the layer. This is done through an accessor
     *   so that subclasses can override this and take special action once
     *   they have their map variable set.
     *
     * @param {OpenLayers.Map} map
     */
    setMap: function(map) {
        this.map = map;

        var properties = new Array(
          'projection', 'minExtent', 'maxExtent',
          'minScale', 'maxScale',
          'maxResolution', 'minResolution',
          'minZoomLevel', 'maxZoomLevel', 'units',
          'scales', 'resolutions'

        );
        for(var i=0; i < properties.length; i++) {
            if (this[properties[i]] == null) {
                this[properties[i]] = this.map[properties[i]];
            }
        }
    },

    /**
    * @returns Whether or not the layer is visible
    * @type Boolean
    */
    getVisibility: function() {
        return (this.div.style.display != "none");
    },

    /**
     * @param {Boolean} visible
     * @param {Boolean} noEvent
     */
    setVisibility: function(visible, noEvent) {
        if (visible != this.getVisibility()) {
            this.div.style.display = (visible) ? "block" : "none";
            if ((visible) && (this.map != null)) {
                var extent = this.map.getExtent();
                if (extent != null) {
                    this.moveTo(this.map.getExtent());
                }
            }
            if ((this.map != null) &&
                ((noEvent == null) || (noEvent == false))) {
                this.map.events.triggerEvent("changelayer");
            }
        }
    },

  /********************************************************/
  /*                                                      */
  /*                 Layer Options                        */
  /*                                                      */
  /*    Accessor functions to Layer Options parameters    */
  /*                                                      */
  /********************************************************/

    /**
     * @type String
     */
    getProjection: function() {
        return this.projection;
    },

    /**
     * @type OpenLayers.Bounds
     */
    getMaxExtent: function() {
        return this.maxExtent;
    },

    /**
     * @type float
     */
    getMaxResolution: function() {
        return this.maxResolution;
    },

    /**
     * @returns The minimum zoom level that can be reached in this layer
     * @type int
     */
    getMinZoomLevel: function() {
        return this.minZoomLevel;
    },

    /**
     * @returns The maximum zoom level that can be reached in this layer
     * @type int
     */
    getMaxZoomLevel: function() {
        return this.maxZoomLevel;
    },

  /********************************************************/
  /*                                                      */
  /*                 Baselayer Functions                  */
  /*                                                      */
  /*    The following functions must all be implemented   */
  /*                  by all base layers                  */
  /*                                                      */
  /********************************************************/

    /**
     * @returns Degrees per Pixel
     * @type float
     */
    getResolution: function() {
        var viewSize = this.map.getSize();
        var extent = this.map.getExtent();
        return Math.max( extent.getWidth()  / viewSize.w,
                         extent.getHeight() / viewSize.h );
    },

    /** Calculates using px-> lonlat translation functions on tl and br
     *   corners of viewport
     *
     * @returns A Bounds object which represents the lon/lat bounds of the
     *          current viewPort.
     * @type OpenLayers.Bounds
     */
    getExtent: function () {
        var extent = null;

        var size = this.map.getSize();

        var tlPx = new OpenLayers.Pixel(0,0);
        var tlLL = this.getLonLatFromViewPortPx(tlPx);

        var brPx = new OpenLayers.Pixel(size.w, size.h);
        var brLL = this.getLonLatFromViewPortPx(brPx);

        if ((tlLL != null) && (brLL != null)) {
            extent = new OpenLayers.Bounds(tlLL.lon,
                                       brLL.lat,
                                       brLL.lon,
                                       tlLL.lat);
        }

        return extent;
    },

    /**
    * @param {OpenLayers.Pixel} viewPortPx
    *
    * @returns An OpenLayers.LonLat which is the passed-in view port
    *          OpenLayers.Pixel, translated into lon/lat by the layer
    * @type OpenLayers.LonLat
    */
    getLonLatFromViewPortPx: function (viewPortPx) {
        var size = this.map.getSize();
        var center = this.map.getCenter();        //map center lon/lat
        var res  = this.map.getResolution();

        var delta_x = viewPortPx.x - (size.w / 2);
        var delta_y = viewPortPx.y - (size.h / 2);

        return new OpenLayers.LonLat(center.lon + delta_x * res ,
                                     center.lat - delta_y * res);
    },

    /**
    * @param {OpenLayers.LonLat} lonlat
    *
    * @returns An OpenLayers.Pixel which is the passed-in OpenLayers.LonLat,
    *          translated into view port pixels
    * @type OpenLayers.Pixel
    */
    getViewPortPxFromLonLat: function (lonlat) {
        var resolution = this.map.getResolution();
        var extent = this.map.getExtent();
        return new OpenLayers.Pixel(
                       Math.round(1/resolution * (lonlat.lon - extent.left)),
                       Math.round(1/resolution * (extent.top - lonlat.lat))
                       );
    },

    /**
    * @param {OpenLayers.Bounds} bounds
    *
    * @return {int}
    */
    getZoomForExtent: function (bounds) {
        // this should be implemented by subclasses
    },

    /** @final @type String */
    CLASS_NAME: "OpenLayers.Layer"
};
<|endoftext|>


<commit_before>// Porcess generated lib files.
// Like adding js extension in the import statement.

const { transformImport } = require('./transformImport');
const globby = require('globby');
const path = require('path');
const fs = require('fs');
const chalk = require('chalk');
const rollup = require('rollup');
const nodeResolve = require('@rollup/plugin-node-resolve').default;

function addJsExtension(moduleName) {
    // Ignore 'tslib'
    if (!(moduleName.startsWith('.'))) {
        return moduleName;
    }
    if (moduleName.endsWith('.ts')) {
        // Replace ts with js
        return moduleName.replace(/\.ts$/, '.js');
    }
    else if (moduleName.endsWith('.js')) {
        return moduleName;
    }
    else {
        return moduleName + '.js'
    }
}

async function transform() {
    const libFiles = await globby(path.join(__dirname, '../lib/**/*.js'));

    for (let file of libFiles) {
        const code = fs.readFileSync(file, 'utf-8');
        fs.writeFileSync(file, transformImport(code, addJsExtension), 'utf-8');
    }

    // Transform index;
    const indexFile = path.join(__dirname, '../index.js');
    fs.writeFileSync(
        indexFile,
        transformImport(
            fs.readFileSync(indexFile, 'utf-8'),
            (mduleName) => addJsExtension(mduleName).replace('./src', './lib')
        )
    )
}

async function testLibBundling() {

}

transform().then(() => {
    console.log(chalk.green('Added .js extensions.'));
    console.log(chalk.gray('Start testing generated libs...'));
    return testLibBundling();
}).then(() => {
    return rollup.rollup({
        input: path.resolve(__dirname, '../index.js'),
        plugins: [nodeResolve()]
    });
}).then(() => {
    console.log(chalk.green('Libs can be bundled!'));
});<commit_msg>chore: fix globby in windows<commit_after>// Porcess generated lib files.
// Like adding js extension in the import statement.

const { transformImport } = require('./transformImport');
const globby = require('globby');
const path = require('path');
const fs = require('fs');
const chalk = require('chalk');
const rollup = require('rollup');
const nodeResolve = require('@rollup/plugin-node-resolve').default;

function addJsExtension(moduleName) {
    // Ignore 'tslib'
    if (!(moduleName.startsWith('.'))) {
        return moduleName;
    }
    if (moduleName.endsWith('.ts')) {
        // Replace ts with js
        return moduleName.replace(/\.ts$/, '.js');
    }
    else if (moduleName.endsWith('.js')) {
        return moduleName;
    }
    else {
        return moduleName + '.js'
    }
}

async function transform() {
    const libFiles = await globby([
        '**/*.js'
    ], {
        cwd: path.join(__dirname, '../lib'),
        absolute: true
    });

    if (libFiles.length === 0) {
        throw new Error('No lib files found.')
    }

    for (let file of libFiles) {
        const code = fs.readFileSync(file, 'utf-8');
        fs.writeFileSync(file, transformImport(code, addJsExtension), 'utf-8');
    }

    // Transform index;
    const indexFile = path.join(__dirname, '../index.js');
    fs.writeFileSync(
        indexFile,
        transformImport(
            fs.readFileSync(indexFile, 'utf-8'),
            (mduleName) => addJsExtension(mduleName).replace('./src', './lib')
        )
    )
}

async function testLibBundling() {

}

transform().then(() => {
    console.log(chalk.green('Added .js extensions.'));
    console.log(chalk.gray('Start testing generated libs...'));
    return testLibBundling();
}).then(() => {
    return rollup.rollup({
        input: path.resolve(__dirname, '../index.js'),
        plugins: [nodeResolve()]
    });
}).then(() => {
    console.log(chalk.green('Libs can be bundled!'));
});<|endoftext|>


<commit_before>'use strict'

const tables = [
  'FormCBM',
  'FormCiconia',
  'FormBirds',
  'FormHerptiles',
  'FormMammals',
  'FormInvertebrates',
  'FormPlants'
]

module.exports = {
  up: async function (queryInterface, Sequelize) {
    await Promise.all(tables.map(async (table) => {
      await queryInterface.addColumn(table, 'geolocationAccuracy', Sequelize.FLOAT)
    }))
  },

  down: async function (queryInterface, Sequelize) {
    await Promise.all(tables.map(async (table) => {
      await queryInterface.removeColumn(table, 'geolocationAccuracy')
    }))
  }
}
<commit_msg>fixup! Add geolocation accuracy in common model<commit_after>'use strict'

const tables = [
  'FormCBM',
  'FormCiconia',
  'FormBirds',
  'FormHerps',
  'FormHerptiles',
  'FormMammals',
  'FormInvertebrates',
  'FormPlants'
]

module.exports = {
  up: async function (queryInterface, Sequelize) {
    await Promise.all(tables.map(async (table) => {
      await queryInterface.addColumn(table, 'geolocationAccuracy', Sequelize.FLOAT)
    }))
  },

  down: async function (queryInterface, Sequelize) {
    await Promise.all(tables.map(async (table) => {
      await queryInterface.removeColumn(table, 'geolocationAccuracy')
    }))
  }
}
<|endoftext|>


<commit_before>var globs = require("../config/globs.js");
var paths = require("../config/paths.js");
var tslintReporter = require("../reporters/tslint-msbuild.js");

var gulp = require("gulp");
var tsc = require("gulp-typescript");
var tslint = require("gulp-tslint");
var negate = require("../utils/negate.js");

module.exports = function (component) {
    return function () {

        var sources = [paths[component] ? paths[component] + globs.allDTS : paths.sources, negate(globs.allDTS)];
        if (!component) {
            sources.push(paths.tests);
        }

        return gulp.src(sources)
            .pipe(tslint())
            .pipe(tslint.report(tslintReporter.MSBuild));
    };
};
<commit_msg>fixed lint task<commit_after>var globs = require("../config/globs.js");
var paths = require("../config/paths.js");
var tslintReporter = require("../reporters/tslint-msbuild.js");

var gulp = require("gulp");
var tsc = require("gulp-typescript");
var tslint = require("gulp-tslint");
var negate = require("../utils/negate.js");

module.exports = function (component) {
    return function () {
        return gulp.src(getSources(component))
            .pipe(tslint())
            .pipe(tslint.report(tslintReporter.MSBuild));
    };
};

function getSources(component) {

    var sources = [negate(globs.allDTS)];

    if (paths[component]) {
        sources.push(paths[component] + globs.allTS);
    }
    else if (component === "test") {
        sources.push(paths.tests);
    }
    else {
        sources.push(paths.sources, paths.tests);
    }

    return sources;
}
<|endoftext|>