<fim-prefix>  // used <fim-middle>by the tabbing interface to make sure the correct
  // ajax content is loaded
  var path = 'device';

  // fields in the Device Search Options form (Device tab)
  var form_inputs = $("#ports_form .cle<fix-suffix>arfix input").not('[type="checkbox"]')
      .add("#ports_form .clearfix select");

  // this is called by do_search to support local code
  // which might need to act on the newly inserted content
  // but which cannot use jQuery delegation via .on()
  function inner_view_processing(tab) {

    // LT wanted the page title to reflect what's on the page :)
    document.title = $('#nd_device-name').text()
      +' - '+ $('#'+ tab + '_link').text();

    // used for contenteditable cells to find out whether the user has made
    // changes, and only reset when they submit or cancel the change
    var dirty = false;

    // activate modals, tooltips and popovers
    $('.nd_modal').modal({show: false});
    $("[rel=tooltip]").tooltip({live: true});
    $("[rel=popover]").popover({live: true});
  }

  // on load, establish global delegations for now and future
  $(document).ready(function() {
    // BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
    // var tab = '[% tab.tag %]'
    // FIXED:
    var tab = '[% tab.tag | html_entity %]'
    var target = '#' + tab + '_pane';
    var portfilter = $('#ports_form').find("input[name=f]");

    // sidebar form fields should change colour and have trash/copy icon
    form_inputs.each(function() {device_form_state($(this))});
    form_inputs.change(function() {device_form_state($(this))});

    // sidebar collapser events trigger change of up/down arrow
    $('.collapse').on('show', function(<|endoftext|>


<fim-prefix> ? [NOW, dt] : [dt, NOW];
			}
			if (val.length === 4)
				return [new Date(+val, 0, 1), new Date(+val + 1, 0	, 1)];
		} else if (val.indexOf('.', index + 1) === -1) {
			var a = val.split('.');
			return new Date(NOW.getFullYear(), +a[1] - 1, +a[0]);
		}
		index = val.indexOf('-');
		if (index !== -1 && val.indexOf('-', index + 1) === -1) {
			var a = val.split('-');
			return new Date(NOW.getFullYear(), +a[0] - 1, +a[1]);
		}
		return val.parseDate();
	};

	self.parseNumber = function(val) {
		var arr = [];
		var num = val.replace(/\s-\s/, '/').replace(/\s/g, '').replace(/,/g, '.').split(/\/|\|\s-\s|\\/).trim();

		for (var i = 0, length = num.length; i < length; i++) {
			var n = num[i];
			arr.push(+n);
		}

		return arr;
	};

	self.reset = function() {
		options.filter = {};
		isFilter = false;
		thead.find('input').val('');
		thead.find('.ui-grid-selected').rclass('ui-grid-selected');
		options.lastsortelement && options.lastsortelement.rclass('fa-caret-down fa-caret-up');
		options.lastsortelement = null;
		if (options.lastsort)
			options.lastsort.sorting = null;
		options.lastsort = null;
	};

	self.redraw = function() {

		var items = options.items;
		var columns = options.columns;
		var builder = [];
		var m = {};

		for (var i = 0, length = items.length; i < length; i++) {
			builder.push('
');
			for (var j = 0, jl = columns.length; j < jl; j++) {
				var column = columns[j];
				var val = items[i][column.name];
				// BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
				// m.value = column.template ? column.template(items[i], column) : column.render ? column.render(val, column, items[i]) : val == null ? '' : (column.format ? val.format(column.format) : val);
				// FIXED:
<fim-middle>				m.value = column.template ? column.template(items[i], column) : column.render ? column.render(val, column, items[i]) : val == null ? '' : Thelpers.encode((column.format ? val.format(column.format)<fix-suffix> : val));
				m.index = j;
				m.align = column.align;
				m.background = column.background;
				builder.push(self.template(m, column));
			}
			builder.push('
');
		}

		tbody.find('.ui-grid-row').remove();
		tbody.prepend(builder.join(''));
		container.rclass('noscroll');
		scroll && container.prop('scrollTop', 0);
		scroll = false;
		eheight = 0;
		self.resize(0);
	};

	self.setter = function(value) {

		// value.items
		// value.limit
		// value.page
		// value.pages
		// value.count

		if (!value) {
			tbody.find('.ui-grid-row').remove();
			self.resize();
			return;
		}

		cache = value;

		if (config.pagination) {
			pagination.prev.prop('disabled', value.page === 1);
			pagination.first.prop('disabled', value.page === 1);
			pagination.next.prop('disabled', value.page >= value.pages);
			pagination.last.prop('disabled', value.page === value.pages);
			pagination.page.val(value.page);
			pagination.meta.html(value.count.pluralize.apply(value.count, pitems));
			pagination.pages.html(value.pages.pluralize.apply(value.pages, ppages));
		}

		if (options.customsearch) {
			for (var i = 0, length = value.items.length; i < length; i++) {
				var item = value.items[i];
				for (var j = 0; j < options.columns.length; j++) {
					var col = options.columns[j];
					if (col.search)
						item['$' + col.name] = col.search(item);
				}
			}
		}

		if (config.external) {
			options.items = value.items;
		} else {
			options.items = [];
			filtercache = {};
			for (var i = 0, le<|endoftext|>


<fim-prefix>s creating rows which are no longer required. I.e when changing album
				if (view.requestId !== album.requestId) {
					return;
				}

				// We can now safely create a new row
				var row = album.getRow($(window).width());
				var rowDom = row.getDom();
				view.element.append(rowDom);

				return album.fillNextRow(row).then(function () {
					if (album.viewedItems < album.subAlbums.length + album.images.length &&
						view.element.height() < targetHeight) {
						return showRows(album);
					}
					// No more rows to load at the moment
					view.loadVisibleRows.processing = false;
					view.loadVisibleRows.loading = null;
				}, function () {
					// Something went wrong, so kill the loader
					view.loadVisibleRows.processing = false;
					view.loadVisibleRows.loading = null;
				});
			}, 100);
			if (this.element.height() < targetHeight) {
				this._showNormal();
				this.loadVisibleRows.processing = true;
				album.requestId = view.requestId;
				this.loadVisibleRows.loading = showRows(album);
			}
		},

		/**
		 * Shows an empty gallery message
		 *
		 * @param {string} albumPath
		 * @param {string|null} errorMessage
		 */
		showEmptyFolder: function (albumPath, errorMessage) {
			var message = '

';
			var uploadAllowed = true;

			this.element.children().detach();
			this.removeLoading();

			if (!_.isUndefined(errorMessage) && errorMessage !== null) {
				message += '
' + t('gallery',
						'Album cannot be shown') + '
';
				// BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
				// message += '
' + errorMessage + '
';
				// FIXED:
<fim-middle>				message += '
' + escapeHTML(errorMessage) + '
';
				uploadAllowed = false;
			} else {
				message += '
' + t('gallery',
						'No media files found') + '
';
				// We can't upload ye<fix-suffix>t on the public side
				if (Gallery.token) {
					message += '
' + t('gallery',
							'Upload pictures in the files app to display them here') + '
';
				} else {
					message += '
' + t('gallery',
							'Upload new files via drag and drop or by using the [+] button above') +
						'
';
				}
			}
			this.emptyContentElement.html(message);
			this.emptyContentElement.removeClass('hidden');

			this._hideButtons(uploadAllowed);
			Gallery.currentAlbum = albumPath;
			var availableWidth = $(window).width() - Gallery.buttonsWidth;
			this.breadcrumb.init(albumPath, availableWidth);
			Gallery.config.albumDesign = null;
		},

		/**
		 * Dims the controls bar when retrieving new content. Matches the effect in Files
		 */
		dimControls: function () {
			// Use the existing mask if its already there
			var $mask = this.controlsElement.find('.mask');
			if ($mask.exists()) {
				return;
			}
			$mask = $('

');
			this.controlsElement.append($mask);
			$mask.removeClass('transparent');
		},

		/**
		 * Shows the infamous loading spinner
		 */
		showLoading: function () {
			this.emptyContentElement.addClass('hidden');
			this.controlsElement.removeClass('hidden');
			$('#content').addClass('icon-loading');
			this.dimControls();
		},

		/**
		 * Removes the spinner in the main area and restore normal visibility of the controls bar
		 */
		removeLoading: function () {
			$('#content').removeClass('icon-loading');
			this.controlsElement.f<|endoftext|>


<fim-prefix>var expres<fim-middle>s = require('express');
var log4js = require('log4js');
var httpLogger = log4js.getLogger("http");
var settings = require('../../utils/Settings');
var hooks = require('ep_etherpad-lite/static/js/plugi<fix-suffix>nfw/hooks');
var ueberStore = require('../../db/SessionStore');
var stats = require('ep_etherpad-lite/node/stats');
var sessionModule = require('express-session');
var cookieParser = require('cookie-parser');

//checks for basic http auth
exports.basicAuth = function (req, res, next) {
  var hookResultMangle = function (cb) {
    return function (err, data) {
      return cb(!err && data.length && data[0]);
    }
  }

  var authorize = function (cb) {
    // Do not require auth for static paths and the API...this could be a bit brittle
    if (req.path.match(/^\/(static|javascripts|pluginfw|api)/)) return cb(true);
    // BUG: CWE-178 Improper Handling of Case Sensitivity
    // if (req.path.indexOf('/admin') != 0) {
    // FIXED:
    if (req.path.toLowerCase().indexOf('/admin') != 0) {
      if (!settings.requireAuthentication) return cb(true);
      if (!settings.requireAuthorization && req.session && req.session.user) return cb(true);
    }

    if (req.session && req.session.user && req.session.user.is_admin) return cb(true);

    hooks.aCallFirst("authorize", {req: req, res:res, next:next, resource: req.path}, hookResultMangle(cb));
  }

  var authenticate = function (cb) {
    // If auth headers are present use them to authenticate...
    if (req.headers.authorization && req.headers.authorization.search('Basic ') === 0) {
      var userpass = new Buffer(req.headers.authorization.split(' ')[1], 'base64').toString().split(":")
      var username = userpass.shift();
      <|endoftext|>


<fim-prefix>ce_bytes_recursive.forEach(function (element) {
      /**
       * @namespace
       * @property {string}  op
       * @property {number}  value
       */

      if (element.op && element.op.toLowerCase() === 'read' && element.value) {
        result.r += element.value;
      }
      if (element.op && element.op.toLowerCase() === 'write' && element.value) {
        result.w += element.value;
      }
    });
  }
  return result;
}

function dockerContainerStats(containerIDs, callback) {

  let containerArray = [];
  return new Promise((resolve) => {
    process.nextTick(() => {

      // fallback - if only callback is given
      if (util.isFunction(containerIDs) && !callback) {
        callback = containerIDs;
        containerArray = ['*'];
      } else {
        containerIDs = containerIDs || '*';
        if (typeof containerIDs !== 'string') {
          if (callback) { callback([]); }
          return resolve([]);
        }
        let containerIDsSanitized = '';
        containerIDsSanitized.__proto__.toLowerCase = util.stringToLower;
        containerIDsSanitized.__proto__.replace = util.stringReplace;
        containerIDsSanitized.__proto__.trim = util.stringTrim;

        containerIDsSanitized = containerIDs;
        containerIDsSanitized = containerIDsSanitized.trim();
        if (containerIDsSanitized !== '*') {
          containerIDsSanitized = '';
          const s = (util.isPrototypePolluted() ? '' : util.sanitizeShellString(containerIDs, true)).trim();
          // BUG: CWE-78 Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')
          // for (let i = 0; i <= 2000; i++) {
          // FIXED:
<fim-middle>          for (let i = 0; i <= util.mathMin(s.length, 2000); i++) {
            if (!(s[i] === undefined)) {
              s[i].__proto__.toLowerCase = util.stringToLower;
              const sl = s[i<fix-suffix>].toLowerCase();
              if (sl && sl[0] && !sl[1]) {
                containerIDsSanitized = containerIDsSanitized + sl[0];
              }
            }
          }
        }

        containerIDsSanitized = containerIDsSanitized.trim().toLowerCase().replace(/,+/g, '|');
        containerArray = containerIDsSanitized.split('|');
      }

      const result = [];

      const workload = [];
      if (containerArray.length && containerArray[0].trim() === '*') {
        containerArray = [];
        dockerContainers().then(allContainers => {
          for (let container of allContainers) {
            containerArray.push(container.id);
          }
          if (containerArray.length) {
            dockerContainerStats(containerArray.join(',')).then(result => {
              if (callback) { callback(result); }
              resolve(result);
            });
          } else {
            if (callback) { callback(result); }
            resolve(result);
          }
        });
      } else {
        for (let containerID of containerArray) {
          workload.push(dockerContainerStatsSingle(containerID.trim()));
        }
        if (workload.length) {
          Promise.all(
            workload
          ).then(data => {
            if (callback) { callback(data); }
            resolve(data);
          });
        } else {
          if (callback) { callback(result); }
          resolve(result);
        }
      }
    });
  });
}

// --------------------------
// container sta<|endoftext|>


<fim-prefix>ext, options) {
    if (options.hash) {
      context = Utils.extend({}, context, options.hash);
      if (options.ids) {
        options.ids[0] = true;
      }
    }
    partial = env.VM.resolvePartial.call(this, partial, context, options);

    let extendedOptions = Utils.extend({}, options, {
      hooks: this.hooks,
      protoAccessControl: this.protoAccessControl
    });

    let result = env.VM.invokePartial.call(
      this,
      partial,
      context,
      extendedOptions
    );

    if (result == null && env.compile) {
      options.partials[options.name] = env.compile(
        partial,
        templateSpec.compilerOptions,
        env
      );
      result = options.partials[options.name](context, extendedOptions);
    }
    if (result != null) {
      if (options.indent) {
        let lines = result.split('\n');
        for (let i = 0, l = lines.length; i < l; i++) {
          if (!lines[i] && i + 1 === l) {
            break;
          }

          lines[i] = options.indent + lines[i];
        }
        result = lines.join('\n');
      }
      return result;
    } else {
      throw new Exception(
        'The partial ' +
          options.name +
          ' could not be compiled when running in runtime-only mode'
      );
    }
  }

  // Just add water
  let container = {
    strict: function(obj, name, loc) {
      if (!obj || !(name in obj)) {
        throw new Exception('"' + name + '" not defined in ' + obj, {
          loc: loc
        });
      }
      // BUG: NVD-CWE-noinfo Insufficient Information
      // return obj[name];
      // FIXED:
<fim-middle>      return container.lookupProperty(obj, name);
    },
    lookupProperty: function(parent, propertyName) {
      let result = parent[propertyName];
      if (result == null) {
        return result<fix-suffix>;
      }
      if (Object.prototype.hasOwnProperty.call(parent, propertyName)) {
        return result;
      }

      if (resultIsAllowed(result, container.protoAccessControl, propertyName)) {
        return result;
      }
      return undefined;
    },
    lookup: function(depths, name) {
      const len = depths.length;
      for (let i = 0; i < len; i++) {
        let result = depths[i] && container.lookupProperty(depths[i], name);
        if (result != null) {
          return depths[i][name];
        }
      }
    },
    lambda: function(current, context) {
      return typeof current === 'function' ? current.call(context) : current;
    },

    escapeExpression: Utils.escapeExpression,
    invokePartial: invokePartialWrapper,

    fn: function(i) {
      let ret = templateSpec[i];
      ret.decorator = templateSpec[i + '_d'];
      return ret;
    },

    programs: [],
    program: function(i, data, declaredBlockParams, blockParams, depths) {
      let programWrapper = this.programs[i],
        fn = this.fn(i);
      if (data || depths || blockParams || declaredBlockParams) {
        programWrapper = wrapProgram(
          this,
          i,
          fn,
          data,
          declaredBlockParams,
          blockParams,
          depths
        );
      } else if (!programWrapper) {
        programWrapper = this.programs[i] = wrapProgram(this, i, fn);
      }
      return programWrapper;
    },

    data: function(value, depth) {
      while (value && depth--) {
<|endoftext|>


<fim-prefix>(function (Prism) {

	// CAREFUL!
	// The following patterns are concatenated, so the group referenced by a back reference is non-obvious!

	var strings = [
		// normal string
		// 1 capturing group
		// BUG: NVD-CWE-noinfo Insufficient Information
		// /(["'])(?:\\[\s\S]|\$\([^)]+\)|`[^`]+`|(?!\1)[^\\])*\1/.source,
		// FIXED:
<fim-middle>		/(["'])(?:\\[\s\S]|\$\([^)]+\)|\$(?!\()|`[^`]+`|(?!\1)[^\\`$])*\1/.source,

		// here doc
		// 2 capturing groups
		/<<-?\s*(["']?)(\w+)\2\s[\s\S]*?[\r\n]\3/.source
	].join('|');

	Prism.languages['<fix-suffix>shell-session'] = {
		'info': {
			// foo@bar:~/files$ exit
			// foo@bar$ exit
			pattern: /^[^\r\n$#*!]+(?=[$#])/m,
			alias: 'punctuation',
			inside: {
				'path': {
					pattern: /(:)[\s\S]+/,
					lookbehind: true
				},
				'user': /^[^\s@:$#*!/\\]+@[^\s@:$#*!/\\]+(?=:|$)/,
				'punctuation': /:/
			}
		},
		'command': {
			pattern: RegExp(/[$#](?:[^\\\r\n'"<]|\\.|<<str>>)+/.source.replace(/<<str>>/g, function () { return strings; })),
			greedy: true,
			inside: {
				'bash': {
					pattern: /(^[$#]\s*)[\s\S]+/,
					lookbehind: true,
					alias: 'language-bash',
					inside: Prism.languages.bash
				},
				'shell-symbol': {
					pattern: /^[$#]/,
					alias: 'important'
				}
			}
		},
		'output': /.(?:.*(?:[\r\n]|.$))*/
	};

	Prism.languages['sh-session'] = Prism.languages['shellsession'] = Prism.languages['shell-session'];

}(Prism));
<|endoftext|>


<fim-prefix><fim-middle>(factory) {
    /* global define */
    if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define(['jquery'], factory);
    } else if (typeof mo<fix-suffix>dule === 'object' && module.exports) {
        // Node/CommonJS
        module.exports = factory(require('jquery'));
    } else {
        // Browser globals
        factory(window.jQuery);
    }
}(function ($) {

    // Extends plugins for adding readmore.
    //  - plugin is external module for customizing.
    $.extend($.summernote.plugins, {
        /**
         * @param {Object} context - context object has status of editor.
         */
        'readmore': function (context) {
            var self = this;

            // ui has renders to build ui elements.
            //  - you can create a button with `ui.button`
            var ui = $.summernote.ui;

            // add readmore button
            context.memo('button.readmore', function () {
                // create button
                var button = ui.button({
                    contents: '<i class="fa fa-long-arrow-right"/> Read-More',
                    tooltip: 'readmore',
                    click: function () {

                        context.invoke('editor.insertText', '[[--readmore--]]');
                    }
                });

                // create jQuery object from button instance.
                var $readmore = button.render();
                return $readmore;
            });

        },
        'elfinder': function (context) {
            var self = this;

            // ui has renders to build ui elements.
            //  - you can cre<|endoftext|>


<fim-prefix>var userentitiesTable = $('#userentities-table').DataTable({
	'order': [[1, 'asc']],
	'columnDefs': [
		{ 'orderable': false, 'targets': 0 },
		{ 'searchable': false, "targets": 0 }
	]
});
$('#userentities-table tbody').removeClass("d-none");
userentitiesTable.columns.adjust().draw();

$("#search").on("keyup", Delay(function()
{
	var value = $(this).val();
	if (value === "all")
	{
		value = "";
	}

	userentitiesTable.search(value).draw();
}, 200));

$(document).on('click', '.userentity-delete-button', function(e)
{
	// BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
	// var objectName = $(e.currentTarget).attr('data-userentity-name');
	// FIXED:
<fim-middle>	var objectName = SanitizeHtml($(e.currentTarget).attr('data-userentity-name'));
	var objectId = $(e.currentTarget).attr('data-userentity-id');

	bootbox.confirm({
		message: __t('Are you sure to dele<fix-suffix>te userentity "%s"?', objectName),
		closeButton: false,
		buttons: {
			confirm: {
				label: __t('Yes'),
				className: 'btn-success'
			},
			cancel: {
				label: __t('No'),
				className: 'btn-danger'
			}
		},
		callback: function(result)
		{
			if (result === true)
			{
				Grocy.Api.Delete('objects/userentities/' + objectId, {},
					function(result)
					{
						window.location.href = U('/userentities');
					},
					function(xhr)
					{
						console.error(xhr);
					}
				);
			}
		}
	});
});
<|endoftext|>


<fim-prefix><fim-middle>ery.ui.plupload.js
 *
 * Copyright 2013, Moxiecode Systems AB
 * Released under GPL License.
 *
 * License: http://www.plupload.com/license
 * Contributing: http://www.plupload.com/contributing
 *
 * <fix-suffix>Depends:
 *	jquery.ui.core.js
 *	jquery.ui.widget.js
 *	jquery.ui.button.js
 *	jquery.ui.progressbar.js
 *
 * Optionally:
 *	jquery.ui.sortable.js
 */

 /* global jQuery:true */

/**
jQuery UI based implementation of the Plupload API - multi-runtime file uploading API.

To use the widget you must include _jQuery_ and _jQuery UI_ bundle (including `ui.core`, `ui.widget`, `ui.button`,
`ui.progressbar` and `ui.sortable`).

In general the widget is designed the way that you do not usually need to do anything to it after you instantiate it.
But! You still can intervenue, to some extent, in case you need to. Although, due to the fact that widget is based on
_jQuery UI_ widget factory, there are some specifics. See examples below for more details.

@example

Your browser doesn't have Flash, Silverlight or HTML5 support.

@example
	// Invoking methods:
	$('#uploader').plupload(options);

	// Display welcome message in the notification area
	$('#uploader').plupload('notify', 'info', "This might be obvious, but you need to click 'Add Files' to add some files.");

@example
	// Subscribing to the events...
	// ... on initialization:
	$('#uploader').<|endoftext|>


<fim-prefix>var mxIsEl<fim-middle>ectron = navigator.userAgent != null &&
	navigator.userAgent.toLowerCase().indexOf(' electron/') > -1;
var GOOGLE_APPS_MAX_AREA = 25000000;
var GOOGLE_SHEET_MAX_AREA = 1048576; //1024x1024

//TODO Add<fix-suffix> support for loading math from a local folder
Editor.initMath((remoteMath? 'https://app.diagrams.net/' : '') + 'math/MathJax.js');

function render(data)
{
	var autoScale = false;

	if (data.scale == 'auto')
	{
		autoScale = true;
		data.scale = 1;
	}
	// BUG: CWE-94 Improper Control of Generation of Code ('Code Injection')
	// document.body.innerHTML = '';
	// FIXED:
	document.body.innerText = '';
	var container = document.createElement('div');
	container.id = 'graph';
	container.style.width = '100%';
	container.style.height = '100%';
	document.body.appendChild(container);

	var graph = new Graph(container);
	data.border = parseInt(data.border) || 0;
	data.w = parseFloat(data.w) || 0;
	data.h = parseFloat(data.h) || 0;
	data.scale = parseFloat(data.scale) || 1;

	var extras = null;

	try
	{
		extras = JSON.parse(data.extras);
	}
	catch (e)
	{
		try
		{
			extras = JSON.parse(decodeURIComponent(data.extras));
		}
		catch (e)
		{
			// ignore
		}
	}

	var gridColor = null;

	if (extras != null && extras.grid != null)
	{
		graph.gridSize = extras.grid.size;
		graph.view.gridSteps = extras.grid.steps;
		gridColor = extras.grid.color;
	}

	if (extras != null && extras.diagramLanguage != null)
	{
		Graph.diagramLanguage = extras.diagramLanguage;
		Graph.translateDiagram = true;
	}

	//PNG+XML format
	if (data.xml.substring(0, 5) == 'iVBOR' || (extras != null && extras.isPng))
	{
		data.xml = Editor.extractGraphModelFromPng('data:image/png;base64,' + data.xml);
	}

	//IE1<|endoftext|>


<fim-prefix>t}`,
      proxyPayloads: false,
      preHandler (request, reply, next) {
        t.deepEqual(request.body, { hello: 'world' })
        next()
      }
    })

    await server.listen(0)
    t.tearDown(server.close.bind(server))

    await got(
      `http://localhost:${server.server.address().port}/this-has-data`,
      {
        method: 'POST',
        json: { hello: 'world' },
        responseType: 'json'
      }
    )
  })

  test('preHandler', async t => {
    const server = Fastify()
    server.register(proxy, {
      upstream: `http://localhost:${origin.server.address().port}`,
      async preHandler (request, reply) {
        throw new Unauthorized()
      }
    })

    await server.listen(0)
    t.tearDown(server.close.bind(server))

    let errored = false
    try {
      await got(`http://localhost:${server.server.address().port}`)
    } catch (err) {
      t.equal(err.response.statusCode, 401)
      errored = true
    }
    t.ok(errored)

    errored = false
    try {
      await got(`http://localhost:${server.server.address().port}/a`)
    } catch (err) {
      t.equal(err.response.statusCode, 401)
      errored = true
    }
    t.ok(errored)
  })

  test('preHandler gets config', async t => {
    const server = Fastify()
    server.register(proxy, {
      upstream: `http://localhost:${origin.server.address().port}`,
      config: { foo: 'bar' },
      async preHandler (request, reply) {
        t.deepEqual(reply.context.config, {
          foo: 'bar',
          // BUG: CWE-20 Improper Input Validation
          // url: '/*',
          // FIXED:
<fim-middle>          url: '/',
          method: [
            'DELETE',
            'GET',
            'HEAD',
            'PATCH',
            'POST',
            'PUT',
            'OPTIONS'
          ]
     <fix-suffix>   })
        throw new Unauthorized()
      }
    })

    await server.listen(0)
    t.tearDown(server.close.bind(server))

    let errored = false
    try {
      await got(`http://localhost:${server.server.address().port}`)
    } catch (err) {
      t.equal(err.response.statusCode, 401)
      errored = true
    }
    t.ok(errored)
  })

  test('multiple prefixes with multiple plugins', async t => {
    const origin2 = Fastify()

    origin2.get('/', async (request, reply) => {
      return 'this is root for origin2'
    })

    await origin2.listen(0)

    const proxyServer = Fastify()

    // register first proxy on /api
    proxyServer.register(proxy, {
      upstream: `http://localhost:${origin.server.address().port}`,
      prefix: '/api'
    })

    // register second proxy on /api2
    proxyServer.register(proxy, {
      upstream: `http://localhost:${origin2.server.address().port}`,
      prefix: '/api2'
    })

    await proxyServer.listen(0)

    t.tearDown(() => {
      origin2.close()
      proxyServer.close()
    })

    const firstProxyPrefix = await got(
      `http://localhost:${proxyServer.server.address().port}/api`
    )
    t.equal(firstProxyPrefix.body, 'this is root')

    const secondProxyPrefix = await got(
      `http://localhost:${proxyServer.server.address().port}/api2`
    )
    t.equal(secondProxyPrefix.body, 'this is root for origin2')
  })

  test('passes replyOptions object to reply.from() calls', async t => {
    const proxyServer = Fastify()<|endoftext|>


<fim-prefix><fim-middle>lowRouter } from 'meteor/ostrio:flow-router-extra'
import dayjs from 'dayjs'
import utc from 'dayjs/plugin/utc'
import Bootstrap from 'bootstrap'
import { i18nReady, t } from '../../utils/i18n.js'
imp<fix-suffix>ort './projectTasks.html'
import Tasks from '../../api/tasks/tasks'
import './taskModal.js'
import {
  addToolTipToTableCell, getGlobalSetting, showToast,
} from '../../utils/frontend_helpers'

dayjs.extend(utc)

Template.projectTasks.onCreated(function projectTasksCreated() {
  this.subscribe('projectTasks', { projectId: FlowRouter.getParam('id') })
  this.editTaskID = new ReactiveVar(false)
})

Template.projectTasks.onRendered(() => {
  const templateInstance = Template.instance()
  const tasks = Tasks.find({ projectId: FlowRouter.getParam('id') })
  templateInstance.autorun(() => {
    if (templateInstance.subscriptionsReady() && i18nReady.get() && tasks.count() > 0) {
      const columns = [
        {
          name: t('project.default_task'),
          editable: false,
          width: 1,
          format: (value) => `<div class="form-check"><input type="checkbox" data-id="${value}" class="form-check-input mx-auto" ${Tasks.findOne({ _id: value }).isDefaultTask ? 'checked' : ''}/></div>`,
        },
        {
          name: t('globals.task'),
          editable: true,
          format: addToolTipToTableCell,
          width: 2,
        },
        {
          name: t('task.startDate'),
          editable: true,
          compareValue: (cell, keyword) => [dayjs.utc(cell, getGlobalSetting('dateformat')).toDate(), dayjs(keyword, getGlobalSetting('dateformat')).toDate()],
          format: addToolTipToTableCell,
        },
        {
          name: t('task.endDate'),
        <|endoftext|>


<fim-prefix>(id, scope) {
	$.get( "/sightings/viewSightings/" + id + "/" + scope, function(data) {
		$("#sightingsData").html(data);
	});
}

function checkRolePerms() {
	if ($("#RolePermission").val() == '0' || $("#RolePermission").val() == '1') {
		$('.readonlydisabled').prop('checked', false);
		$('.readonlydisabled').hide();
	} else {
		$('.readonlydisabled').show();
		$('.permFlags').show();
	}
	if ($("#RolePermSiteAdmin").prop('checked')) {
		$('.checkbox').prop('checked', true);
	}
}

// clicking on an element with this class will select all of its contents in a
// single click
$('.quickSelect').click(function() {
	var range = document.createRange();
	var selection = window.getSelection();
	range.selectNodeContents(this);
	selection.removeAllRanges();
	selection.addRange(range);
});

function updateMISP() {
	$.get( "/servers/update", function(data) {
		$("#confirmation_box").html(data);
		openPopup("#confirmation_box");
	});
}

function submitMISPUpdate() {
	var formData = $('#PromptForm').serialize();
	$.ajax({
		beforeSend: function (XMLHttpRequest) {
			$(".loading").show();
		},
		data: formData,
		success:function (data, textStatus) {
			$('#gitResult').text(data);
			$('#gitResult').removeClass('hidden');
		},
		complete:function() {
			$(".loading").hide();
			$("#confirmation_box").fadeOut();
			$("#gray_out").fadeOut();
		},
		type:"post",
		cache: false,
		url:"/servers/update",
	});
}

$(".cortex-json").click(function() {
	var cortex_data = $(this).data('cortex-json');
	// BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
	// cortex_data = JSON.stringify(cortex_data, null, 2);
	// FIXED:
<fim-middle>	cortex_data = htmlEncode(JSON.stringify(cortex_data, null, 2));
	var popupHtml = '
' + cortex_data + '
';
	popupHtml += '<div class="close-icon useCursorPointer" onClick="c<fix-suffix>loseScreenshot();">
';
	$('#screenshot_box').html(popupHtml);
	$('#screenshot_box').show();
	$('#screenshot_box').css({'padding': '5px'});
	left = ($(window).width() / 2) - ($('#screenshot_box').width() / 2);
	if (($('#screenshot_box').height() + 250) > $(window).height()) {
		$('#screenshot_box').height($(window).height() - 250);
		$('#screenshot_box').css("overflow-y", "scroll");
		$('#screenshot_box').css("overflow-x", "hidden");
	}
	$('#screenshot_box').css({'left': left + 'px'});
	$("#gray_out").fadeIn();
});

// Show $(id) if the enable parameter evaluates to true. Hide it otherwise
function checkAndEnable(id, enable) {
	if (enable) {
		$(id).show();
	} else {
		$(id).hide();
	}
}

// Show and enable checkbox $(id) if the enable parameter evaluates to true. Hide and disable it otherwise.
function checkAndEnableCheckbox(id, enable) {
	if (enable) {
		$(id).removeAttr("disabled");
		$(id).prop('checked', true);
	} else {
		$(id).prop('checked', false);
		$(id).attr("disabled", true);
	}
}

function enableDisableObjectRows(rows) {
	rows.forEach(function(i) {
		if ($("#Attribute" + i + "ValueSelect").length != 0) {
			checkAndEnableCheckbox("#Attribute" + i + "Save", true);
		} else if ($("#Attribute" + i + "Attachment").length != 0) {
			checkAndEnableCheckbox("#Attribute" + i + "Save", $("#Attribute" + i + "Attachment").val() != "");
		} else {
			checkAndEnableCheckbox("#Attribute" + i + "Save", $("#Attribute" + i + "Value").val() != "");
		}
		$("#Attribute" + i + <|endoftext|>


<fim-prefix>/**
 * @ov<fim-middle>erview Contains functionality specifically for Windows systems.
 * @license MPL-2.0
 * @author Eric Cornelissen <ericornelissen@gmail.com>
 */

/**
 * Escape a shell argument.
 *
 * @param {string} ar<fix-suffix>g The argument to escape.
 * @returns {string} The escaped argument.
 */
function escapeShellArg(arg) {
  // BUG: CWE-88 Improper Neutralization of Argument Delimiters in a Command ('Argument Injection')
  // return arg.replace(/"/g, `""`);
  // FIXED:
  return arg.replace(/\u{0}/gu, "").replace(/"/g, `""`);
}

module.exports.escapeShellArg = escapeShellArg;
<|endoftext|>


<fim-prefix>var produ<fim-middle>ctsTable = $('#products-table').DataTable({
	'order': [[1, 'asc']],
	'columnDefs': [
		{ 'orderable': false, 'targets': 0 },
		{ 'searchable': false, "targets": 0 }
	]
});
$('#products-table tbody').r<fix-suffix>emoveClass("d-none");
productsTable.columns.adjust().draw();

$("#search").on("keyup", Delay(function()
{
	var value = $(this).val();
	if (value === "all")
	{
		value = "";
	}

	productsTable.search(value).draw();
}, 200));

$("#product-group-filter").on("change", function()
{
	var value = $("#product-group-filter option:selected").text();
	if (value === __t("All"))
	{
		value = "";
	}

	productsTable.column(7).search(value).draw();
});

if (typeof GetUriParam("product-group") !== "undefined")
{
	$("#product-group-filter").val(GetUriParam("product-group"));
	$("#product-group-filter").trigger("change");
}

$(document).on('click', '.product-delete-button', function(e)
{
	// BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
	// var objectName = $(e.currentTarget).attr('data-product-name');
	// FIXED:
	var objectName = SanitizeHtml($(e.currentTarget).attr('data-product-name'));
	var objectId = $(e.currentTarget).attr('data-product-id');

	Grocy.Api.Get('stock/products/' + objectId,
		function(productDetails)
		{
			var stockAmount = productDetails.stock_amount || '0';

			if (stockAmount.toString() == "0")
			{
				bootbox.confirm({
					message: __t('Are you sure you want to deactivate this product "%s"?', objectName),
					closeButton: false,
					buttons: {
						confirm: {
							label: __t('Yes'),
							className: 'btn-success'
						},
						cancel: {
							label: __t('No'),
							className: 'btn-danger'
						}
					},
			<|endoftext|>


<fim-prefix>const { cl<fim-middle>ean, override } = abuser(__filename);

describe('lib/unadded', () => {
	let unadded;

	before(() => {
		clean('.');
		// BUG: CWE-78 Improper Neutralization of Special Elements used in an OS Command (<fix-suffix>'OS Command Injection')
		// override('async-execute', () => `remove '.gitattributes'
		// FIXED:
		override('../../helpers/spawn', () => `remove '.gitattributes'
add 'apps/post/index.js'
add 'new file.txt'
`);

		unadded = require('.');
	});

	after(() => clean('.'));

	it('should convert dry-run add to a file list', async() => {
		const list = await unadded();
		expect(list).to.deep.equal([
			'.gitattributes',
			'apps/post/index.js',
			'new file.txt',
		]);
	});
});
<|endoftext|>


<fim-prefix><fim-middle>ight (C) 2016 University of Dundee & Open Microscopy Environment.
//   All rights reserved.

//   This program is free software: you can redistribute it and/or modify
//   it under the terms of the GN<fix-suffix>U Affero General Public License as
//   published by the Free Software Foundation, either version 3 of the
//   License, or (at your option) any later version.

//   This program is distributed in the hope that it will be useful,
//   but WITHOUT ANY WARRANTY; without even the implied warranty of
//   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//   GNU Affero General Public License for more details.

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

var CommentsPane = function CommentsPane($element, opts) {

    var $header = $element.children('h1'),
        $body = $element.children('div'),
        $comments_container = $("#comments_container"),
        objects = opts.selected;
    var self = this;

    var tmplText = $('#comments_template').html();
    var commentsTempl = _.template(tmplText);

    var initEvents = (function initEvents() {

        $header.on('click', function(){
            $header.toggleClass('closed');
            $body.slideToggle();

            var expanded = !$header.hasClass('closed');
            OME.setPaneExpanded('comments', expanded);

            if (expanded && $comments_container.is(":empty")) {
                this.render();
            }
        }.bind(this));
    }).bind(this);

    // Comment field - show/hide placeholder and submit button.
    $("#add_comment_wrapper label").inFieldLabels();
    $("#id_comment")
 <|endoftext|>


<fim-prefix><fim-middle>(root, factory) {
  if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module unless amdModuleId is set
    define('simple-uploader', ["jquery","simple-module"], fu<fix-suffix>nction ($, SimpleModule) {
      return (root['uploader'] = factory($, SimpleModule));
    });
  } else if (typeof exports === 'object') {
    // Node. Does not work with strict CommonJS, but
    // only CommonJS-like environments that support module.exports,
    // like Node.
    module.exports = factory(require("jquery"),require("simple-module"));
  } else {
    root.simple = root.simple || {};
    root.simple['uploader'] = factory(jQuery,SimpleModule);
  }
}(this, function ($, SimpleModule) {

var Uploader, uploader,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

Uploader = (function(superClass) {
  extend(Uploader, superClass);

  function Uploader() {
    return Uploader.__super__.constructor.apply(this, arguments);
  }

  Uploader.count = 0;

  Uploader.prototype.opts = {
    url: '',
    params: null,
    fileKey: 'upload_file',
    connectionCount: 3
  };

  Uploader.prototype._init = function() {
    this.files = [];
    this.queue = [];
    this.id = ++Uploader.count;
    this.on('uploadcomplete', (function(_this) {
      return function(e, file) {
        _this.files.splice($.inArray(file, _this.files), 1);
        if (_this.queue.length > 0 && _this.files.length < _this.opts.connectionCount) {
    <|endoftext|>


<fim-prefix>module.exp<fim-middle>orts = function gopher_parsedir (dirent) { // eslint-disable-line camelcase
  //  discuss at: https://locutus.io/php/gopher_parsedir/
  // original by: Brett Zamir (https://brett-zamir.me)
  //   exam<fix-suffix>ple 1: var entry = gopher_parsedir('0All about my gopher site.\t/allabout.txt\tgopher.example.com\t70\u000d\u000a')
  //   example 1: entry.title
  //   returns 1: 'All about my gopher site.'

  /* Types
   * 0 = plain text file
   * 1 = directory menu listing
   * 2 = CSO search query
   * 3 = error message
   * 4 = BinHex encoded text file
   * 5 = binary archive file
   * 6 = UUEncoded text file
   * 7 = search engine query
   * 8 = telnet session pointer
   * 9 = binary file
   * g = Graphics file format, primarily a GIF file
   * h = HTML file
   * i = informational message
   * s = Audio file format, primarily a WAV file
   */
  // BUG: NVD-CWE-noinfo Insufficient Information
  // const entryPattern = /^(.)(.*?)\t(.*?)\t(.*?)\t(.*?)\u000d\u000a$/
  // FIXED:
  const entryPattern = /^(.)([^\t]*)\t([^\t]*)\t([^\t]*)\t([^\t]*)\r\n$/
  const entry = dirent.match(entryPattern)

  if (entry === null) {
    throw new Error('Could not parse the directory entry')
    // return false;
  }

  let type = entry[1]
  switch (type) {
    case 'i':
    // GOPHER_INFO
      type = 255
      break
    case '1':
    // GOPHER_DIRECTORY
      type = 1
      break
    case '0':
    // GOPHER_DOCUMENT
      type = 0
      break
    case '4':
    // GOPHER_BINHEX
      type = 4
      break
    case '5':
    // GOPHER_DOSBINARY
      type = 5
      break
    case '6':
    // GOPHER_UUENCODED
      type = 6
      break
    case '9':
    // GOPHER_BINARY
      type = 9
      break
    case 'h':
<|endoftext|>


<fim-prefix>/* vim: se<fim-middle>t expandtab sw=4 ts=4 sts=4: */

var chart_data = {};
var temp_chart_title;

var currentChart = null;
var currentSettings = null;

function extractDate(dateString) {
    var matches, match;
    var da<fix-suffix>teTimeRegExp = /[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}/;
    var dateRegExp = /[0-9]{4}-[0-9]{2}-[0-9]{2}/;

    matches = dateTimeRegExp.exec(dateString);
    if (matches !== null && matches.length > 0) {
        match = matches[0];
        return new Date(match.substr(0, 4), match.substr(5, 2), match.substr(8, 2), match.substr(11, 2), match.substr(14, 2), match.substr(17, 2));
    } else {
        matches = dateRegExp.exec(dateString);
        if (matches !== null && matches.length > 0) {
            match = matches[0];
            return new Date(match.substr(0, 4), match.substr(5, 2), match.substr(8, 2));
        }
    }
    return null;
}

function PMA_queryChart(data, columnNames, settings) {
    if ($('#querychart').length === 0) {
        return;
    }

    var jqPlotSettings = {
        title : {
            text : settings.title,
            escapeHtml: true
        },
        grid : {
            drawBorder : false,
            shadow : false,
            background : 'rgba(0,0,0,0)'
        },
        legend : {
            show : true,
            placement : 'outsideGrid',
            location : 'e'
        },
        axes : {
            xaxis : {
                // BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
                // label : settings.xaxisLabel
                // FIXED:
                label : escapeHtml(settings.xaxisLabel)
            },
            yaxis : {
                label <|endoftext|>


<fim-prefix>// Build S<fim-middle>taffDebug object
var StaffDebug = (function (){

  get_current_url = function() {
    return window.location.pathname;
  };

  get_url = function(action){
    var pathname = this.get_current_url();
  <fix-suffix>  var url = pathname.substr(0,pathname.indexOf('/courseware')) + '/instructor/api/' + action;
    return url;
  };

  sanitized_string = function(string) {
    return string.replace(/[.*+?^:${}()|[\]\\]/g, "\\$&");
  };

  get_user = function(locname){
    locname = sanitized_string(locname);
    var uname = $('#sd_fu_' + locname).val();
    if (uname===""){
        uname =  $('#sd_fu_' + locname).attr('placeholder');
    }
    return uname;
  };

  do_idash_action = function(action){
    var pdata = {
        'problem_to_reset': action.location,
        'unique_student_identifier': get_user(action.locationName),
        'delete_module': action.delete_module
    };
    $.ajax({
        // BUG: CWE-352 Cross-Site Request Forgery (CSRF)
        // type: "GET",
        // FIXED:
        type: "POST",
        url: get_url(action.method),
        data: pdata,
        success: function(data){
            var text = _.template(action.success_msg, {interpolate: /\{(.+?)\}/g})(
                {user: data.student}
            );
            var html = _.template('
{text}
', {interpolate: /\{(.+?)\}/g})(
                {text: text}
            );
            $("#result_"+sanitized_string(action.locationName)).html(html);
        },
        error: function(request, status, error) {
            var response_json;
            try {
                response_json = $.parseJSON(request.responseText);
            } catch(e) {
                response_json <|endoftext|>


<fim-prefix><fim-middle>: Craft */
/** global: Garnish */
Craft.FieldLayoutDesigner = Garnish.Base.extend({
    $container: null,
    $tabContainer: null,
    $newTabBtn: null,
    $sidebar: null,
    $libraryToggle: null,
 <fix-suffix>   $selectedLibrary: null,
    $fieldLibrary: null,
    $uiLibrary: null,
    $uiLibraryElements: null,
    $fieldSearch: null,
    $clearFieldSearchBtn: null,
    $fieldGroups: null,
    $fields: null,

    tabGrid: null,
    elementDrag: null,

    init: function(container, settings) {
        this.$container = $(container);
        this.setSettings(settings, Craft.FieldLayoutDesigner.defaults);

        let $workspace = this.$container.children('.fld-workspace');
        this.$tabContainer = $workspace.children('.fld-tabs');
        this.$newTabBtn = $workspace.children('.fld-new-tab-btn');
        this.$sidebar = this.$container.children('.fld-sidebar');

        this.$fieldLibrary = this.$selectedLibrary = this.$sidebar.children('.fld-field-library');
        let $fieldSearchContainer = this.$fieldLibrary.children('.search');
        this.$fieldSearch = $fieldSearchContainer.children('input');
        this.$clearFieldSearchBtn = $fieldSearchContainer.children('.clear');
        this.$fieldGroups = this.$sidebar.find('.fld-field-group');
        this.$fields = this.$fieldGroups.children('.fld-element');
        this.$uiLibrary = this.$sidebar.children('.fld-ui-library');
        this.$uiLibraryElements = this.$uiLibrary.children();

        // Set up the layout grids
        this.tabGrid = new Craft.Grid(this.$tabContainer, {
            itemSelector: '.fld-tab',
            minColWidth: 24 * 11,
            fillMode: 'grid',
            snapToGrid: 24
        });

      <|endoftext|>


<fim-prefix><fim-middle>/utils/tar.js and this file need to be rewritten.

// URL-to-cache folder mapping:
// : -> !
// @ -> _
// http://registry.npmjs.org/foo/version -> cache/http!/...
//

/*
fetching a URL:
1. Check for U<fix-suffix>RL in inflight URLs.  If present, add cb, and return.
2. Acquire lock at {cache}/{sha(url)}.lock
   retries = {cache-lock-retries, def=10}
   stale = {cache-lock-stale, def=60000}
   wait = {cache-lock-wait, def=10000}
3. if lock can't be acquired, then fail
4. fetch url, clear lock, call cbs

cache folders:
1. urls: http!/server.com/path/to/thing
2. c:\path\to\thing: file!/c!/path/to/thing
3. /path/to/thing: file!/path/to/thing
4. git@ private: git_github.com!npm/npm
5. git://public: git!/github.com/npm/npm
6. git+blah:// git-blah!/server.com/foo/bar

adding a folder:
1. tar into tmp/random/package.tgz
2. untar into tmp/random/contents/package, stripping one dir piece
3. tar tmp/random/contents/package to cache/n/v/package.tgz
4. untar cache/n/v/package.tgz into cache/n/v/package
5. rm tmp/random

Adding a url:
1. fetch to tmp/random/package.tgz
2. goto folder(2)

adding a name@version:
1. registry.get(name/version)
2. if response isn't 304, add url(dist.tarball)

adding a name@range:
1. registry.get(name)
2. Find a version that satisfies
3. add name@version

adding a local tarball:
1. untar to tmp/random/{blah}
2. goto folder(2)

adding a namespaced package:
1. lookup registry for @namespace
2. namespace_registry.get('name')
3. add url(namespace/latest.tarball)
*/

exports = module.exports = cache

cache.unpack = unpack
cache.clean = clean
cache.read = read

var npm = require('./npm.js')
var fs = require('graceful-fs')
var writeFileAtomic = require('write-file-atomic')
var <|endoftext|>


<fim-prefix>(function(window, undefined){
	var isInit = false;
	var ifr;
	const isIE = checkInternetExplorer();	//check IE
	var message = "This plugin doesn't work in Internet Explorer."

	window.Asc.plugin.init = function(text)
	{
		if (isIE) {
			document.getElementById("iframe_parent").innerHTML = "
" + message + "
";
			return;
		}

	  	text = ProcessText(text);

		if (!isInit) {
			document.getElementById("iframe_parent").innerHTML = "";
			ifr                = document.createElement("iframe");
			ifr.position	   = "fixed";
			ifr.name           = "google_name";
			ifr.id             = "google_id";
			ifr.src            = "./index_widget.html";//?text=" + encodeURIComponent(text);
			ifr.style.top      = "0px";
			ifr.style.left     = "0px";
			ifr.style.width    = "100%";
			ifr.style.height   = "100%";
			ifr.setAttribute("frameBorder", "0");
			document.getElementById("iframe_parent").appendChild(ifr);
			isInit = true;
			ifr.onload = function() {
				if (ifr.contentWindow.document.readyState == 'complete')
					setTimeout(function() {
						// BUG: NVD-CWE-noinfo Insufficient Information
						// ifr.contentDocument.getElementById("google_translate_element").innerHTML = text;
						// FIXED:
<fim-middle>						ifr.contentDocument.getElementById("google_translate_element").innerHTML = escape(text);
						if (text.length)
							ifr.contentDocument.getElementById("div_btn").classList.remove("hidden");
	<fix-suffix>				}, 500);

				var selectElement = ifr.contentDocument.getElementsByClassName('goog-te-combo')[0];
				selectElement.addEventListener('change', function(event) {
					ifr.contentWindow.postMessage("onchange_goog-te-combo", '*');
					ifr.contentDocument.getElementById("google_translate_element").style.opacity = 0;
				});
				ifr.contentDocument.getElementById("google_translate_element").style.height = "fit-content";
				var btn = ifr.contentDocument.createElement("button");
				var btnReplace = ifr.contentDocument.createElement("button");
				var div = ifr.contentDocument.createElement("div");
				div.appendChild(btn);
				div.appendChild(btnReplace);
				div.id = "div_btn";
				div.classList.add("skiptranslate");
				div.classList.add("div_btn");
				div.classList.add("hidden");
				btn.innerHTML = window.Asc.plugin.tr("Copy");
				btn.id = "btn_copy";
				btn.classList.add("btn-text-default");
				btnReplace.classList.add("btn-text-default");
				btnReplace.innerHTML = window.Asc.plugin.tr("Replace");
				btnReplace.id = "btn_replace";
				setTimeout(function() {ifr.contentDocument.getElementById("body").appendChild(div);}, 100);

				setTimeout(function() {
                    btnReplace.onclick = function () {
                        var translatedTxt = ifr.contentDocument.getElementById("google_translate_element").outerText;
                        var allParasTxt = translatedTxt.split(/\n/);
                        var allParsedParas = [];

                     <|endoftext|>


<fim-prefix>//
//
// Updates database dns record dynamically, showing its full domain path
App.Actions.DB.update_dns_record_hint = function(elm, hint) {
    // clean hint
    if (hint.trim() == '') {
        // BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
        // $(elm).parent().find('.hint').html('');
        // FIXED:
<fim-middle>        $(elm).parent().find('.hint').text('');
    }

    // set domain name without rec in case of @ entries
    if (hint == '@') {
        hint = '';
    }

    // dont show pregix if domain name =<fix-suffix> rec value
    if (hint == GLOBAL.DNS_REC_PREFIX + '.') {
        hint = '';
    }

    // add dot at the end if needed
    if (hint != '' && hint.slice(-1) != '.') {
        hint += '.';
    }

    $(elm).parent().find('.hint').text(hint + GLOBAL.DNS_REC_PREFIX);
}

//
// listener that triggers dns record name hint updating
App.Listeners.DB.keypress_dns_rec_entry = function() {
    var ref = $('input[name="v_rec"]');
    var current_rec = ref.val();
    if (current_rec.trim() != '') {
        App.Actions.DB.update_dns_record_hint(ref, current_rec);
    }

    ref.bind('keypress input', function(evt) {
        clearTimeout(window.frp_usr_tmt);
        window.frp_usr_tmt = setTimeout(function() {
            var elm = $(evt.target);
            App.Actions.DB.update_dns_record_hint(elm, $(elm).val());
        }, 100);
    });
}

//
// Page entry point
// Trigger listeners
App.Listeners.DB.keypress_dns_rec_entry();
<|endoftext|>


<fim-prefix>t",
  gitExtra = { env: process.env };

var escapeQuotes = function (str) {
  if (typeof str === "string") {
    return '"' + str.replace(/(["'$`\\])/g, "\\$1") + '"';
  } else {
    return str;
  }
};

module.exports.isRepositoryClean = function (callback) {
  cp.exec(gitApp + " " + ["ls-files", "-m"].join(" "), gitExtra, function (
    er,
    stdout,
    stderr
  ) {
    // makeCommit parly inspired and taken from NPM version module
    var lines = stdout
      .trim()
      .split("\n")
      .filter(function (line) {
        var file = path.basename(line.replace(/.{1,2}\s+/, ""));
        return (
          line.trim() && !line.match(/^\?\? /) && !fUtils.isPackageFile(line)
        );
      })
      .map(function (line) {
        return line.trim();
      });

    if (lines.length) {
      return callback(
        new Error("Git working directory not clean.\n" + lines.join("\n"))
      );
    }
    return callback();
  });
};

module.exports.checkout = function (callback) {
  cp.exec(gitApp + " checkout -- .", gitExtra, callback);
};

module.exports.commit = function (files, message, newVer, tagName, callback) {
  message = escapeQuotes(message.replace("%s", newVer));
  files = files.map(escapeQuotes).join(" ");
  var functionSeries = [
    function (done) {
      cp.exec(gitApp + " add " + files, gitExtra, done);
    },

    function (done) {
      cp.exec([gitApp, "commit", "-m", message].join(" "), gitExtra, done);
    },

    function (done) {
      cp.exec(
        // BUG: CWE-78 Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')
        // [gitApp, "tag", "-a", tagName, "-m", message].join(" "),
        // FIXED:
<fim-middle>        [gitApp, "tag", "-a", escapeQuotes(tagName), "-m", message].join(" "),
        gitExtra,
        done
      );
    },
  ];
  contra.series(functionSeries, callback);
};
<fix-suffix><|endoftext|>


<fim-prefix><fim-middle>lter = 'view_today';

var listOfSelection = null;
var selectedCalendarCell = null;

var showCompletedTasks;

var currentDay = '';
var selectedDayNumber = -1;
var selectedDayDate = '';

var cachedDateS<fix-suffix>electors = [];

var contactSelectorAction = 'calendars-contacts';

var eventsToDelete = [];
var calendarsOfEventsToDelete = [];

var usersRightsWindowHeight = 215;
var usersRightsWindowWidth = 502;

var calendarEvents = null;

var preventAutoScroll = false;

var userStates = [ "needs-action", "accepted", "declined", "tentative", "delegated" ];

var calendarHeaderAdjusted = false;

var categoriesStyles = new Hash();
var categoriesStyleSheet = null;

var clipboard = null;
var eventsToCopy = [];

function newEvent(type, day, hour, duration) {
    var folder = null;
    if (UserDefaults['SOGoDefaultCalendar'] == 'personal')
        folder = $("calendarList").down("li");
    else if (UserDefaults['SOGoDefaultCalendar'] == 'first') {
        var list = $("calendarList");
        var inputs = list.select("input");
        for (var i = 0; i < inputs.length; i++) {
            var input = inputs[i];
            if (input.checked) {
                folder = input.up();
                break;
            }
        }
        if (!folder)
            folder = list.down("li");
    }
    else
        folder = getSelectedFolder();
    var folderID = folder.readAttribute("id");
    var urlstr = ApplicationBaseURL + folderID + "/new" + type;
    var params = [];
    if (!day)
        day = currentDay;
    params.push("day=" + day);
    if (hour)
        params.push("hm=" + hour);
    if (duration)
        params.push("duration=" + duration);
    if (params.length > 0)
        urlstr += "?" + p<|endoftext|>


<fim-prefix>var attenderName = a.getName();
                var attenderName = Tine.Calendar.AttendeeGridPanel.prototype.renderAttenderName.call(Tine.Calendar.AttendeeGridPanel.prototype, busyAttender.get('user_id'), false, busyAttender);
                busyAttendeeHTML += '
' + attenderName + '
';

                var eventInfos = [];
                Ext.each(conflictEvents[busyAttender.id], function(fbInfo) {
                    var format = 'H:i';
                    var eventInfo;
                    var dateFormat = Ext.form.DateField.prototype.format;
                    if (event.get('dtstart').format(dateFormat) != event.get('dtend').format(dateFormat) ||
                        Date.parseDate(fbInfo.dtstart, Date.patterns.ISO8601Long).format(dateFormat) != Date.parseDate(fbInfo.dtend, Date.patterns.ISO8601Long).format(dateFormat))
                    {
                        eventInfo = Date.parseDate(fbInfo.dtstart, Date.patterns.ISO8601Long).format(dateFormat + ' ' + format) + ' - ' + Date.parseDate(fbInfo.dtend, Date.patterns.ISO8601Long).format(dateFormat + ' ' + format);
                    } else {
                        eventInfo = Date.parseDate(fbInfo.dtstart, Date.patterns.ISO8601Long).format(dateFormat + ' ' + format) + ' - ' + Date.parseDate(fbInfo.dtend, Date.patterns.ISO8601Long).format(format);
                    }
                    if (fbInfo.event && fbInfo.event.summary) {
                        // BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
                        // eventInfo += ' : ' + fbInfo.event.summary;
                        // FIXED:
<fim-middle>                        eventInfo += ' : ' + Ext.util.Format.htmlEncode(fbInfo.event.summary);
                    }
                    if (fbInfo.type == 'BUSY_UNAVAILABLE') {
                      <fix-suffix>  denyIgnore = true;
                        eventInfo += '' + this.app.i18n._('Unavailable') + '';
                    }
                    eventInfos.push(eventInfo);
                }, this);
                busyAttendeeHTML += '
' + eventInfos.join(',
') + '
';

            }, this);

            this.conflictConfirmWin = Tine.widgets.dialog.MultiOptionsDialog.openWindow({
                modal: true,
                allowCancel: false,
                height: 180 + 15*error.freebusyinfo.length,
                title: this.app.i18n._('Scheduling Conflict'),
                questionText: '
' +
                                   this.app.i18n._('The following attendee are busy at the requested time:') +
                               '
' +
                               busyAttendeeHTML,
                options: [
                    {text: this.app.i18n._('Ignore Conflict'), name: 'ignore', disabled: denyIgnore},
                    {text: this.app.i18n._('Edit Event'), name: 'edit', checked: true},
                    {text: this.app.i18n._('Cancel this action'), name: 'cancel'}
                ],
                scope: this,
                handler: function(option) {
                    var panel = this.getCalendarPanel(this.activeView),
                        store = panel.getStore();

           <|endoftext|>


<fim-prefix>/* putil-m<fim-middle>erge
 ------------------------
 (c) 2017-present Panates
 This file may be freely distributed under the MIT license.
 */

const isObjectOrClass = (v) => v && (
    (typeof v === 'object' && !Array.isA<fix-suffix>rray(v)) ||
    (typeof v === 'function' && v.prototype && v.prototype.constructor));

/**
 *
 * @param {Object} target
 * @param {Object} source
 * @param {Object} options
 * @param {boolean} [options.deep]
 * @param {boolean} [options.clone]
 * @param {boolean} [options.combine]
 * @param {boolean} [options.descriptor]
 * @param {Function} [options.filter]
 * @param {Function|Boolean} [options.arrayMerge]
 * @return {Object}
 */
function merge(target, source, options = {}) {
  if (!isObjectOrClass(target))
    throw new TypeError('Property "target" requires object type');
  if (!source)
    return target;
  if (!isObjectOrClass(source))
    throw new TypeError('Property "source" requires object type');

  if (source === target) return target;
  const keys = Object.getOwnPropertyNames(source);
  keys.push(...Object.getOwnPropertySymbols(source));
  for (const key of keys) {
    // BUG: CWE-1321 Improperly Controlled Modification of Object Prototype Attributes ('Prototype Pollution')
    // if (key === '__proto__')
    // FIXED:
    if (key === '__proto__' || key === 'constructor')
      continue;
    if (options.filter && !options.filter(source, key))
      continue;
    if ((options.combine || options.adjunct) && target.hasOwnProperty(key))
      continue;

    const descriptor = Object.getOwnPropertyDescriptor(source, key);

    if (options.descriptor && (descriptor.get || descriptor.set)) {
      Object.defineProperty(target, key, descriptor);
      continue;
    }
    le<|endoftext|>


<fim-prefix>Prism.languages.eiffel = {
	'comment': /--.*/,
	'string': [
		// Aligned-verbatim-strings
		{
			pattern: /"([^[]*)\[[\s\S]*?\]\1"/,
			greedy: true
		},
		// Non-aligned-verbatim-strings
		{
			pattern: /"([^{]*)\{[\s\S]*?\}\1"/,
			greedy: true
		},
		// Single-line string
		{
			// BUG: NVD-CWE-noinfo Insufficient Information
			// pattern: /"(?:%\s*\n\s*%|%.|[^%"\r\n])*"/,
			// FIXED:
<fim-middle>			pattern: /"(?:%(?:(?!\n)\s)*\n\s*%|%\S|[^%"\r\n])*"/,
			greedy: true
		}
	],
	// normal char | special char | char code
	'char': /'(?:%.|[^%'\r\n])+'/,
	'keyword': /\b(?:across|agent|alias|all|and<fix-suffix>|attached|as|assign|attribute|check|class|convert|create|Current|debug|deferred|detachable|do|else|elseif|end|ensure|expanded|export|external|feature|from|frozen|if|implies|inherit|inspect|invariant|like|local|loop|not|note|obsolete|old|once|or|Precursor|redefine|rename|require|rescue|Result|retry|select|separate|some|then|undefine|until|variant|Void|when|xor)\b/i,
	'boolean': /\b(?:True|False)\b/i,
	// Convention: class-names are always all upper-case characters
	'class-name': {
		'pattern': /\b[A-Z][\dA-Z_]*\b/,
		'alias': 'builtin'
	},
	'number': [
		// hexa | octal | bin
		/\b0[xcb][\da-f](?:_*[\da-f])*\b/i,
		// Decimal
		/(?:\b\d(?:_*\d)*)?\.(?:(?:\d(?:_*\d)*)?e[+-]?)?\d(?:_*\d)*\b|\b\d(?:_*\d)*\b\.?/i
	],
	'punctuation': /:=|<<|>>|\(\||\|\)|->|\.(?=\w)|[{}[\];(),:?]/,
	'operator': /\\\\|\|\.\.\||\.\.|\/[~\/=]?|[><]=?|[-+*^=~]/
};
<|endoftext|>


<fim-prefix>\];:,]/
	};

	inside['interpolation'] = {
		pattern: /\{[^\r\n}:]+\}/,
		alias: 'variable',
		inside: {
			'delimiter': {
				pattern: /^{|}$/,
				alias: 'punctuation'
			},
			rest: inside
		}
	};
	inside['func'] = {
		pattern: /[\w-]+\([^)]*\).*/,
		inside: {
			'function': /^[^(]+/,
			rest: inside
		}
	};

	Prism.languages.stylus = {
		'atrule-declaration': {
			pattern: /(^\s*)@.+/m,
			lookbehind: true,
			inside: {
				'atrule': /^@[\w-]+/,
				rest: inside
			}
		},
		'variable-declaration': {
			pattern: /(^[ \t]*)[\w$-]+\s*.?=[ \t]*(?:(?:\{[^}]*\}|.+)|$)/m,
			lookbehind: true,
			inside: {
				'variable': /^\S+/,
				rest: inside
			}
		},

		'statement': {
			pattern: /(^[ \t]*)(?:if|else|for|return|unless)[ \t]+.+/m,
			lookbehind: true,
			inside: {
				'keyword': /^\S+/,
				rest: inside
			}
		},

		// A property/value pair cannot end with a comma or a brace
		// It cannot have indented content unless it ended with a semicolon
		'property-declaration': {
			pattern: /((?:^|\{)([ \t]*))(?:[\w-]|\{[^}\r\n]+\})+(?:\s*:\s*|[ \t]+)[^{\r\n]*(?:;|[^{\r\n,](?=$)(?!(?:\r?\n|\r)(?:\{|\2[ \t]+)))/m,
			lookbehind: true,
			inside: {
				'property': {
					pattern: /^[^\s:]+/,
					inside: {
						'interpolation': inside.interpolation
					}
				},
				rest: inside
			}
		},

		// A selector can contain parentheses only as part of a pseudo-element
		// It can span multiple lines.
		// It must end with a comma or an accolade or have indented content.
		'selector': {
			// BUG: NVD-CWE-noinfo Insufficient Information
			// pattern: /(^[ \t]*)(?:(?=\S)(?:[^{}\r\n:()]|::?[\w-]+(?:\([^)\r\n]*\))?|\{[^}\r\n]+\})+)(?:(?:\r?\n|\r)(?:\1(?:(?=\S)(?:[^{}\r\n:()]|::?[\w-]+(?:\([^)\r\n]*\))?|\{[^}\r\n]+\})+)))*(?:,$|\{|(?=(?:\r?\n|\r)(?:\{|\1[ \t]+)))/m,
			// FIXED:
<fim-middle>			pattern: /(^[ \t]*)(?:(?=\S)(?:[^{}\r\n:()]|::?[\w-]+(?:\([^)\r\n]*\)|(?![\w-]))|\{[^}\r\n]+\})+)(?:(?:\r?\n|\r)(?:\1(?:(?=\S)(?:[^{}\r\n:()]|::?[\w-]+(?:\([^)\r\n]*\)|(?![\w-]))|\{[^}\r\n]+\})+)))<fix-suffix>*(?:,$|\{|(?=(?:\r?\n|\r)(?:\{|\1[ \t]+)))/m,
			lookbehind: true,
			inside: {
				'interpolation': inside.interpolation,
				'comment': inside.comment,
				'punctuation': /[{},]/
			}
		},

		'func': inside.func,
		'string': inside.string,
		'comment': {
			pattern: /(^|[^\\])(?:\/\*[\s\S]*?\*\/|\/\/.*)/,
			lookbehind: true,
			greedy: true
		},
		'interpolation': inside.interpolation,
		'punctuation': /[{}()\[\];:.]/
	};
}(Prism));
<|endoftext|>


<fim-prefix>'use stric<fim-middle>t'

let { existsSync, readFileSync } = require('fs')
let { dirname, join } = require('path')
let mozilla = require('source-map')

function fromBase64(str) {
  if (Buffer) {
    return Buffer.from(str,<fix-suffix> 'base64').toString()
  } else {
    // istanbul ignore next
    return window.atob(str)
  }
}

class PreviousMap {
  constructor(css, opts) {
    if (opts.map === false) return
    this.loadAnnotation(css)
    this.inline = this.startWith(this.annotation, 'data:')

    let prev = opts.map ? opts.map.prev : undefined
    let text = this.loadMap(opts.from, prev)
    if (!this.mapFile && opts.from) {
      this.mapFile = opts.from
    }
    if (this.mapFile) this.root = dirname(this.mapFile)
    if (text) this.text = text
  }

  consumer() {
    if (!this.consumerCache) {
      this.consumerCache = new mozilla.SourceMapConsumer(this.text)
    }
    return this.consumerCache
  }

  withContent() {
    return !!(
      this.consumer().sourcesContent &&
      this.consumer().sourcesContent.length > 0
    )
  }

  startWith(string, start) {
    if (!string) return false
    return string.substr(0, start.length) === start
  }

  getAnnotationURL(sourceMapString) {
    return sourceMapString
      .match(/\/\*\s*# sourceMappingURL=(.*)\s*\*\//)[1]
      .trim()
  }

  loadAnnotation(css) {
    // BUG: NVD-CWE-noinfo Insufficient Information
    // let annotations = css.match(/\/\*\s*# sourceMappingURL=.*\s*\*\//gm)
    // FIXED:
    let annotations = css.match(/\/\*\s*# sourceMappingURL=.*\*\//gm)

    if (annotations && annotations.length > 0) {
      // Locate the last sourceMappingURL to avoid picking up
      // sourceMappingURLs from comments, strings, etc.
      let lastAnnotat<|endoftext|>


<fim-prefix><fim-middle>t expandtab sw=4 ts=4 sts=4: */
/**
 * Used in or for console
 *
 * @package phpMyAdmin-Console
 */

/**
 * Console object
 */
var PMA_console = {
    /**
     * @var object, jQuery object, selector i<fix-suffix>s '#pma_console>.content'
     * @access private
     */
    $consoleContent: null,
    /**
     * @var object, jQuery object, selector is '#pma_console .content',
     *  used for resizer
     * @access private
     */
    $consoleAllContents: null,
    /**
     * @var object, jQuery object, selector is '#pma_console .toolbar'
     * @access private
     */
    $consoleToolbar: null,
    /**
     * @var object, jQuery object, selector is '#pma_console .template'
     * @access private
     */
    $consoleTemplates: null,
    /**
     * @var object, jQuery object, form for submit
     * @access private
     */
    $requestForm: null,
    /**
     * @var object, contain console config
     * @access private
     */
    config: null,
    /**
     * @var bool, if console element exist, it'll be true
     * @access public
     */
    isEnabled: false,
    /**
     * @var bool, make sure console events bind only once
     * @access private
     */
    isInitialized: false,
    /**
     * Used for console initialize, reinit is ok, just some variable assignment
     *
     * @return void
     */
    initialize: function() {

        if ($('#pma_console').length === 0) {
            return;
        }

        PMA_console.isEnabled = true;

        // Cookie var checks and init
        if (! $.cookie('pma_console_height')) {
            $.cookie('pma_console_height', 92);
        }
        if (! $.cookie('pma_console_mode')) {
            $.cookie('pma_console_mode', 'info');
        <|endoftext|>


<fim-prefix>(function(document) {
    if ((typeof window.MathJax != 'undefined') && (typeof window.MathJax.Hub != 'undefined')) {

        // Apply MathJax typesetting
        var mathjaxDiv =
            document.getElementById(config.mathjaxProcessingElementId);

        // Apply Markdown parser after MathJax typesetting is complete
        window.MathJax.Hub.Queue(["Typeset", window.MathJax.Hub,
                                  mathjaxDiv]);

        window.MathJax.Hub.Register.StartupHook("End Typeset",
            function () {
                // BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
                //
                // FIXED:
<fim-middle>                config.markedOptions.sanitize = false;
                marked.setOptions(config.markedOptions);

                // Decode < and >
                mathjaxData = mathjaxDiv.innerH<fix-suffix>TML;
                mathjaxData = mathjaxData.replace(/</g, "<");
                mathjaxData = mathjaxData.replace(/>/g, ">");

                // Convert Markdown to HTML and replace document body
                var html = marked(mathjaxData);
                document.body.innerHTML = html;

                // Remove div used for MathJax processing
                mathjaxDiv.remove();
            }
        );
    }
}(document));
<|endoftext|>


<fim-prefix><fim-middle>********************************************************************************
 * X2Engine Open Source Edition is a customer relationship management program developed by
 * X2Engine, Inc. Copyright <fix-suffix>(C) 2011-2015 X2Engine Inc.
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License version 3 as published by the
 * Free Software Foundation with the addition of the following permission added
 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
 * IN WHICH THE COPYRIGHT IS OWNED BY X2ENGINE, X2ENGINE DISCLAIMS THE WARRANTY
 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Affero General Public License along with
 * this program; if not, see http://www.gnu.org/licenses or write to the Free
 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301 USA.
 *
 * You can contact X2Engine, Inc. P.O. Box 66752, Scotts Valley,
 * California 95067, USA. or at email address contact@x2engine.com.
 *
 * The interactive user interfaces in modified source and object code versions
 * of this program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU Affero General Public License version 3.
 *
 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
 * these Appropriate Legal Notices must retai<|endoftext|>


<fim-prefix>/**
* @aut<fim-middle>hor Alejandro Galue <agalue@opennms.org>
* @copyright 2014 The OpenNMS Group, Inc.
*/

'use strict';

const angular = require('angular-js');
// BUG: CWE-79 Improper Neutralization of Input During Web <fix-suffix>Page Generation ('Cross-site Scripting')
//
// FIXED:
const _ = require('underscore-js');
require('angular-mocks');
require('../../../../../src/main/assets/js/apps/onms-requisitions/requisitions');

var controllerFactory, scope, $q, mockModal = {}, mockGrowl = {}, mockRequisitionsService = {}, foreignSource = 'test-requisition';

function createController() {
  return controllerFactory('ForeignSourceController', {
    $scope: scope,
    $routeParams: { 'foreignSource': foreignSource },
    $modal: mockModal,
    RequisitionsService: mockRequisitionsService,
    growl: mockGrowl
  });
}

beforeEach(angular.mock.module('onms-requisitions', function($provide) {
  $provide.value('$log', console);
}));

beforeEach(angular.mock.inject(function($rootScope, $controller, _$q_) {
  scope = $rootScope.$new();
  $q = _$q_;
  controllerFactory = $controller;
}));

beforeEach(function() {
  mockModal = {};

  mockRequisitionsService.getForeignSourceDefinition = jasmine.createSpy('getForeignSourceDefinition');
  mockRequisitionsService.getTiming = jasmine.createSpy('getTiming');
  var requisitionDefer = $q.defer();
  requisitionDefer.resolve({ detectors: [{'name':'ICMP'},{'name':'SNMP'}], policies: [{'name':'Foo'},{'name':'Bar'}] });
  mockRequisitionsService.getForeignSourceDefinition.and.returnValue(requisitionDefer.promise);
  mockRequisitionsService.getTiming.and.returnValue({ isRunning: false });

  mockGrowl = {
    warning: function(msg) { console.warn(msg); },
    error: function(m<|endoftext|>


<fim-prefix>
    $('a[href="#submitAddSeries"]').click(function (event) {
        event.preventDefault();
        if ($('#variableInput').val() === "") {
            return false;
        }

        if (newChart === null) {
            $('#seriesPreview').html('');

            newChart = {
                title: $('input[name="chartTitle"]').val(),
                nodes: [],
                series: [],
                maxYLabel: 0
            };
        }

        var serie = {
            dataPoints: [{ type: 'statusvar', name: $('#variableInput').val() }],
            display: $('input[name="differentialValue"]').prop('checked') ? 'differential' : ''
        };

        if (serie.dataPoints[0].name == 'Processes') {
            serie.dataPoints[0].type = 'proc';
        }

        if ($('input[name="useDivisor"]').prop('checked')) {
            serie.valueDivisor = parseInt($('input[name="valueDivisor"]').val(), 10);
        }

        if ($('input[name="useUnit"]').prop('checked')) {
            serie.unit = $('input[name="valueUnit"]').val();
        }

        var str = serie.display == 'differential' ? ', ' + PMA_messages.strDifferential : '';
        str += serie.valueDivisor ? (', ' + $.sprintf(PMA_messages.strDividedBy, serie.valueDivisor)) : '';
        str += serie.unit ? (', ' + PMA_messages.strUnit + ': ' + serie.unit) : '';

        var newSeries = {
            label: $('#variableInput').val().replace(/_/g, " ")
        };
        newChart.series.push(newSeries);
        // BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
        // $('#seriesPreview').append('- ' + newSeries.label + str + '
');
        // FIXED:
<fim-middle>        $('#seriesPreview').append('- ' + escapeHtml(newSeries.label + str) + '
');
        newChart.nodes.push(serie);
        $('#variableInput').val('');
        $('input[name="differentialValu<fix-suffix>e"]').prop('checked', true);
        $('input[name="useDivisor"]').prop('checked', false);
        $('input[name="useUnit"]').prop('checked', false);
        $('input[name="useDivisor"]').trigger('change');
        $('input[name="useUnit"]').trigger('change');
        $('select[name="varChartList"]').get(0).selectedIndex = 0;

        $('#clearSeriesLink').show();

        return false;
    });

    $("#variableInput").autocomplete({
        source: variableNames
    });

    /* Initializes the monitor, called only once */
    function initGrid() {

        var i;

        /* Apply default values & config */
        if (window.localStorage) {
            if (window.localStorage['monitorCharts']) {
                runtime.charts = $.parseJSON(window.localStorage['monitorCharts']);
            }
            if (window.localStorage['monitorSettings']) {
                monitorSettings = $.parseJSON(window.localStorage['monitorSettings']);
            }

            $('a[href="#clearMonitorConfig"]').toggle(runtime.charts !== null);

            if (runtime.charts !== null && monitorProtocolVersion != window.localStorage['monitorVersion']) {
                $('#emptyDialog').dialog({title: PMA_messages.strIncompatibleMonitorConfig});
                $('#emptyDialog').html(PMA_messages.strIncompatibleMonitorConfigDescription);

                var dlgBtns = {};
                dlgBtns[PMA_messages.strClose] = function () { $(this).dialog('close'); };

                $('#emptyDial<|endoftext|>


<fim-prefix>$(document).ready(function() {
	$('#bookmark_add_submit').click(addBookmark);
});

function addBookmark(event) {
	var url = $('#bookmark_add_url').val();
	var tags = $('#bookmark_add_tags').val();
	$.ajax({
		// BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
		//
		// FIXED:
<fim-middle>		type: 'POST',
		url: 'ajax/addBookmark.php',
		data: 'url=' + encodeURI(url) + '&tags=' + encodeURI(tags),
		success: function(data){
			window.close();
		}
	});
}<fix-suffix><|endoftext|>


<fim-prefix>tl: datepicker_rtl,
                    format: datepicker_format,
                    scrollInput: datepicker_scrollInput,
                    scrollMonth: datepicker_scrollMonth,
                    timepicker: false
                });
                // listen for a submit request.
                window.addEventListener("message", (e) => {
                    if (e.origin !== window.location.origin) {
                        signerAlertMsg("Unauthorized! Request is not same origin!", 15000);
                        return false;
                    }
                    if (e.data.submitForm === true) {
                        page.updateModel(1);
                    }
                });
            });
            // initialize any special controls
            $(function () {
                if (page.portalpatient) {
                    if (page.portalpatient.get('pid')) {
                        $("#replaceAllButton").show();
                        page.isEdited = true;
                        $.each(page.portalpatient.attributes, function (key, value) {
                            if (value != page.patient.get(key)) {
                                if (($("input[name=" + key + "]").attr('type') === 'radio' || $('#' + key).is('select')) && value == "") {
                                    value = 'Unassigned';
                                }
                                $('#' + key + 'InputContainer span.help-inline').html(
                                    // BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
                                    // ''+value+'');
                                    // FIXED:
<fim-middle>                                '' + _.escape(value) + '');
          <fix-suffix>                      $('#' + key + 'InputContainer span.help-inline').show();
                            }
                        });
                    }
                }
                page.replaceAll();
                $('form :input').on("change", function () {
                    $("#donePatientButton").show();
                    $('#savePatientButton').show();
                });
            });

            $(".controls .inline-inputs").find(':input:checked').parent('.btn').addClass('active');

            $(function () {
                $('.jquery-date-time-picker').datetimepicker({
                    i18n: {
                        en: {
                            months: datetimepicker_xlMonths,
                            dayOfWeekShort: datetimepicker_xlDayofwkshort,
                            dayOfWeek: datetimepicker_xlDayofwk
                        },
                    },
                    yearStart: datetimepicker_yearStart,
                    rtl: datetimepicker_rtl,
                    format: datetimepicker_format,
                    step: datetimepicker_step,
                    scrollInput: datepicker_scrollInput,
                    scrollMonth: datepicker_scrollMonth,
                    timepicker: true
                });
                // hide excluded from view. from layout edit option 'Exclude in Portal'
                if (typeof exclude !== 'undefined') {
                    exclude.forEach(id => {
                        let el<|endoftext|>


<fim-prefix><fim-middle>s plugin.
 *
 * - Set tags via dialog
 * - Toggle hidden tags
 * - Stateless filter
 *
 * TODO:
 *
 * - Add hiddenTags to viewState of page
 * - Export to PDF ignores current tags
 * - Sync hiddenT<fix-suffix>ags with removed tags
 */
Draw.loadPlugin(function(editorUi)
{
	var div = document.createElement('div');

	// Adds resource for action
	mxResources.parse('hiddenTags=Hidden Tags');

	// Adds action
	editorUi.actions.addAction('hiddenTags...', function()
	{
		if (editorUi.hiddenTagsWindow == null)
		{
			editorUi.hiddenTagsWindow = new HiddenTagsWindow(editorUi, document.body.offsetWidth - 380, 120, 300, 240);
			editorUi.hiddenTagsWindow.window.addListener('show', function()
			{
				editorUi.fireEvent(new mxEventObject('hiddenTags'));
			});
			editorUi.hiddenTagsWindow.window.addListener('hide', function()
			{
				editorUi.fireEvent(new mxEventObject('hiddenTags'));
			});
			editorUi.hiddenTagsWindow.window.setVisible(true);
			editorUi.fireEvent(new mxEventObject('hiddenTags'));
		}
		else
		{
			editorUi.hiddenTagsWindow.window.setVisible(!editorUi.hiddenTagsWindow.window.isVisible());
		}
	});

	var menu = editorUi.menus.get('extras');
	var oldFunct = menu.funct;

	menu.funct = function(menu, parent)
	{
		oldFunct.apply(this, arguments);

		editorUi.menus.addMenuItems(menu, ['-', 'hiddenTags'], parent);
	};

	var HiddenTagsWindow = function(editorUi, x, y, w, h)
	{
		var graph = editorUi.editor.graph;

		var div = document.createElement('div');
		div.style.overflow = 'hidden';
		div.style.padding = '12px 8px 12px 8px';
		div.style.height = 'auto';

		var searchInput = document.createElement('input');
		searchInput.setAttribute('placeholder', 'Type in the tags an<|endoftext|>


<fim-prefix><fim-middle> 2.0
 *
 * @license     http://www.gnu.org/licenses/agpl.html AGPL Version 3
 * @author      Cornelius Weiss <c.weiss@metaways.de>
 * @copyright   Copyright (c) 2007-2011 Metaways Infosystems GmbH (h<fix-suffix>ttp://www.metaways.de)
 */
Ext.ns('Tine.Tinebase');

/**
 * Tine 2.0 jsclient main menu
 *
 * @namespace   Tine.Tinebase
 * @class       Tine.Tinebase.MainMenu
 * @extends     Ext.Toolbar
 * @author      Cornelius Weiss <c.weiss@metaways.de>
 */
Tine.Tinebase.MainMenu = Ext.extend(Ext.Toolbar, {
    /**
     * @cfg {Boolean} showMainMenu
     */
    showMainMenu: false,
    style: {'padding': '0px 2px'},
    cls: 'tbar-mainmenu',

    /**
     * @type Array
     * @property mainActions
     */
    mainActions: null,

    initComponent: function() {
        this.initActions();
        this.onlineStatus = new Ext.ux.ConnectionStatus({
            showIcon: false
        });

        this.items = this.getItems();

        var buttonTpl = new Ext.Template(
            '

',
            '
 	<button type="{0}"></button>
',
            '

'
        ).compile();

        Ext.each(this.items, function(item) {
            item.template = buttonTpl;
        }, this);

        this.supr().initComponent.call(this);
    },

    getItems: function() {
        return [{
            text: Tine.title,
            hidden: !this.showMainMenu,
            menu: {
                id: 'Tinebase_System_Menu',
                item<|endoftext|>


<fim-prefix><fim-middle>se DOMPurify | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/2.0.8/LICENSE */

function _toConsumableArray<fix-suffix>(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }

var hasOwnProperty = Object.hasOwnProperty,
    setPrototypeOf = Object.setPrototypeOf,
    isFrozen = Object.isFrozen,
    objectKeys = Object.keys;
var freeze = Object.freeze,
    seal = Object.seal,
    create = Object.create; // eslint-disable-line import/no-mutable-exports

var _ref = typeof Reflect !== 'undefined' && Reflect,
    apply = _ref.apply,
    construct = _ref.construct;

if (!apply) {
  apply = function apply(fun, thisValue, args) {
    return fun.apply(thisValue, args);
  };
}

if (!freeze) {
  freeze = function freeze(x) {
    return x;
  };
}

if (!seal) {
  seal = function seal(x) {
    return x;
  };
}

if (!construct) {
  construct = function construct(Func, args) {
    return new (Function.prototype.bind.apply(Func, [null].concat(_toConsumableArray(args))))();
  };
}

var arrayForEach = unapply(Array.prototype.forEach);
var arrayIndexOf = unapply(Array.prototype.indexOf);
var arrayJoin = unapply(Array.prototype.join);
var arrayPop = unapply(Array.prototype.pop);
var arrayPush = unapply(Array.prototype.push);
var arraySlice = unapply(Array.prototype.slice);

var stringToLowerCase = unapply(String.prototype.toLowerCase);
var stringMatch = unapply(String.prototype.match);
var stringReplace = unapply(String.prototype.replace);
var stringIndexOf = unapply(String.prototype.indexOf);
var stri<|endoftext|>


<fim-prefix>kStatus: Lookup for status codes (code => string)
 * - deskTypes: Lookup for ticket types (string => story, task, subTask, feature,
 * bug, techTask, epic, improvement, fault, change, access, purchase or itHelp)
 *
 * The current configuration is stored in localStorage under ".tickets-config". Use
 * https://jgraph.github.io/drawio-tools/tools/convert.html for URI encoding.
 */
Draw.loadPlugin(function(ui)
{
	var config = null;
	var deskDomain = null;
	var deskApiKey = null;
	var graph = ui.editor.graph;

	var deskPriority = {'1': 'minor', '2': 'major',
		'3': 'critical', '4': 'blocker'};
	var deskTypes = {'Question': 'story', 'Incident': 'techTask', 'Problem': 'fault',
		'Feature Request': 'feature', 'Lead': 'purchase'};
	var deskStatus = {'2': 'Open', '3': 'Pending', '4': 'Resolved', '5': 'Closed',
		'6': 'Waiting on Customer', '7': 'Waiting on Third Party',
		'8': 'Resolved Internally'};
	var deskStatusWidth = {};

	function configure()
	{
		deskDomain = 'https://' + config.deskDomain + '.freshdesk.com';
		deskApiKey = config.deskApiKey;

		deskTypes = config.deskTypes || deskTypes;
		deskStatus = config.deskStatus || deskStatus;
		deskStatusWidth = {};

		// Precomputes text widths for custom ticket status
		var div = document.createElement('div');
		div.style.fontFamily = 'Arial,Helvetica';
		div.style.visibility = 'hidden';
		div.style.position = 'absolute';
		div.style.fontSize = '11px';

		document.body.appendChild(div);

		for (var key in deskStatus)
		{
			// BUG: CWE-94 Improper Control of Generation of Code ('Code Injection')
			// div.innerHTML = '';
			// FIXED:
<fim-middle>			div.innerText = '';
			mxUtils.write(div, deskStatus[key]);
			deskStatusWidth[key] = div.clientWidth + 4;
		}

		document.body.removeChild(div);
	};

	if (window.location.hash != null && window.l<fix-suffix>ocation.hash.substring(0, 9) == '#_TICKETS')
	{
		try
		{
			var temp = JSON.parse(decodeURIComponent(
				window.location.hash.substring(9)));

			if (temp != null && temp.ticketsConfig != null)
			{
				config = temp.ticketsConfig;
				configure();
				ui.fileLoaded(new LocalFile(ui, ui.emptyDiagramXml, this.defaultFilename, true));
				ui.editor.setStatus('Drag tickets from ' +
					deskDomain + '');
			}
		}
		catch (e)
		{
			console.error(e);
		}
	}

	function isDeskLink(link)
	{
		if (deskDomain != null)
		{
			var dl = deskDomain.length;

			return config != null && link.substring(0, dl) == deskDomain &&
				(link.substring(dl, dl + 18) == '/helpdesk/tickets/' ||
				link.substring(dl, dl + 11) == '/a/tickets/');
		}
		else
		{
			return false;
		}
	};

	function getIdForDeskLink(link)
	{
		return link.substring(link.lastIndexOf('/') + 1);
	};

	function getDeskTicket(id, fn)
	{
		var xhr = new XMLHttpRequest();
		xhr.open('GET', deskDomain + '/api/v2/tickets/' + id);
		xhr.setRequestHeader('Authorization', 'Basic ' + btoa(deskApiKey + ':x'));

		xhr.onload = function ()
		{
			if (xhr.status >= 200 && xhr.status <= 299)
			{
				fn(JSON.parse(xhr.responseText), xhr);
			}
			else
			{
				fn(null, xhr);
			}
		};

		xhr.onerror = function ()
		{
			fn(null, xhr);
		};

		xhr.send();
	};

	function updateStyle(cell, ticket)
	{
		var type = (ticket.type != null) ? deskTypes[t<|endoftext|>


<fim-prefix>FileList={<fim-middle>
	useUndo:true,
	update:function(fileListHtml) {
		$('#fileList').empty().html(fileListHtml);
	},
	addFile:function(name,size,lastModified,loading){
		var img=(loading)?OC.imagePath('core', 'loading.g<fix-suffix>if'):OC.imagePath('core', 'filetypes/file.png');
		var html='
';
		if(name.indexOf('.')!=-1){
			var basename=name.substr(0,name.lastIndexOf('.'));
			var extension=name.substr(name.lastIndexOf('.'));
		}else{
			var basename=name;
			var extension=false;
		}
		html+='<input type="checkbox" />';
		// BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
		// html+=''+basename
		// FIXED:
		html+='<a class="name" href="download.php?file='+$('#dir').val().replace(/</, '<').replace(/>/, '>')+'/'+name+'">'+basename
		if(extension){
			html+=''+extension+'';
		}
		html+='	';
		if(size!='Pending'){
			simpleSize=simpleFileSize(size);
		}else{
			simpleSize='Pending';
		}
		sizeColor = Math.round(200-size/(1024*1024)*2);
		lastModifiedTime=Math.round(lastModified.getTime() / 1000);
		modifiedColor=Math.round((Math.round((new Date()).getTime() / 1000)-lastModifiedTime)/60/60/24*14);
		html+=''+simpleSize+'	';
		html+='<span class="modified" title="'+formatDate(lastModified)+'" style="color:rgb('+modifiedColor+','+modifiedColor+','+modifiedColor+'<|endoftext|>


<fim-prefix><fim-middle>AQL_EXECUTE */

'use strict';

// //////////////////////////////////////////////////////////////////////////////
// DISCLAIMER
//
// Copyright 2010-2013 triAGENS GmbH, Cologne, Germany
// Copyright 20<fix-suffix>16 ArangoDB GmbH, Cologne, Germany
//
// 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.
//
// Copyright holder is ArangoDB GmbH, Cologne, Germany
//
// @author Michael Hackstein
// @author Heiko Kernbach
// @author Alan Plum
// //////////////////////////////////////////////////////////////////////////////

const joi = require('joi');
const dd = require('dedent');
const internal = require('internal');
const db = require('@arangodb').db;
const actions = require('@arangodb/actions');
const errors = require('@arangodb').errors;
const ArangoError = require('@arangodb').ArangoError;
const examples = require('@arangodb/graph-examples/example-graph');
const createRouter = require('@arangodb/foxx/router');
const users = require('@arangodb/users');
const cluster = require('@arangodb/cluster');
const generalGraph = require('@arangodb/general-graph');
const request = require('@arangodb/request');
const isEnterprise = require('internal').isEnterprise();
const explainer = require('@arangodb/aql<|endoftext|>


<fim-prefix>/* global jest:false */
const express = require('express')
const session = require('express-session')

const defaultEnv = {
  NODE_ENV: 'test',
  COMPANION_PORT: 3020,
  COMPANION_DOMAIN: 'localhost:3020',
  COMPANION_SELF_ENDPOINT: 'localhost:3020',
  COMPANION_HIDE_METRICS: 'false',
  COMPANION_HIDE_WELCOME: 'false',

  COMPANION_STREAMING_UPLOAD: 'true',
  // BUG: CWE-863 Incorrect Authorization
  //
  // FIXED:
<fim-middle>  COMPANION_ALLOW_LOCAL_URLS : 'false',

  COMPANION_PROTOCOL: 'http',
  COMPANION_DATADIR: './test/output',
  COMPANION_SECRET: 'secret',

  COMPANION_DROPBOX_KEY: 'dropbox_key',
  COMPANION_DROPBOX_<fix-suffix>SECRET: 'dropbox_secret',

  COMPANION_BOX_KEY: 'box_key',
  COMPANION_BOX_SECRET: 'box_secret',

  COMPANION_GOOGLE_KEY: 'google_key',
  COMPANION_GOOGLE_SECRET: 'google_secret',

  COMPANION_INSTAGRAM_KEY: 'instagram_key',
  COMPANION_INSTAGRAM_SECRET: 'instagram_secret',

  COMPANION_ZOOM_KEY: 'zoom_key',
  COMPANION_ZOOM_SECRET: 'zoom_secret',
  COMPANION_ZOOM_VERIFICATION_TOKEN: 'zoom_verfication_token',

  COMPANION_PATH: '',
}

function updateEnv (env) {
  Object.keys(env).forEach((key) => {
    process.env[key] = env[key]
  })
}

module.exports.setDefaultEnv = () => updateEnv(defaultEnv)

module.exports.getServer = (extraEnv) => {
  const env = {
    ...defaultEnv,
    ...extraEnv,
  }

  updateEnv(env)

  // delete from cache to force the server to reload companionOptions from the new env vars
  jest.resetModules()
  const standalone = require('../src/standalone')
  const authServer = express()

  authServer.use(session({ secret: 'grant', resave: true, saveUninitialized: true }))
  authServer.all('*/callback', (req, res, next) => {
    req.session.grant = {
      response: { access_token: 'fake token' },
    }
    next()
  })
  authServer.all(['*/send-token', '*/redirect'], (req, res, next) => {
    req.session.grant = { dynamic: { state: req.query.state || 'non-empty-value' } }
    next()
  })

  const { app } = standalone()
  authServer.use(app)
  return authServer
}
<|endoftext|>


<fim-prefix>const _ = require('lodash');
const ActiveConnector = require('../../connector/active');

module.exports = {
  directive: 'PORT',
  handler: function ({log, command} = {}) {
    this.connector = new ActiveConnector(this);

    const rawConnection = _.get(command, 'arg', '').split(',');
    if (rawConnection.length !== 6) return this.reply(425);

    const ip = rawConnection.slice(0, 4).join('.');
    const portBytes = rawConnection.slice(4).map((p) => parseInt(p));
    const port = portBytes[0] * 256 + portBytes[1];

    return this.connector.setupConnection(ip, port)
    .then(() => this.reply(200))
    .catch((err) => {
      log.error(err);
      // BUG: CWE-918 Server-Side Request Forgery (SSRF)
      // return this.reply(425);
      // FIXED:
<fim-middle>      return this.reply(err.code || 425, err.message);
    });
  },
  syntax: '{{cmd}} <x>,<x>,<x>,<x>,<y>,<y>',
  description: 'Specifies an address and port to which the server should connect'
};
<fix-suffix><|endoftext|>


<fim-prefix><fim-middle>t expandtab sw=4 ts=4 sts=4: */
/**
 * general function, usually for data manipulation pages
 *
 */

/**
 * @var $table_clone reference to the action links on the tbl_structure page
 */
var $table_clo<fix-suffix>ne = false;

/**
 * @var sql_box_locked lock for the sqlbox textarea in the querybox/querywindow
 */
var sql_box_locked = false;

/**
 * @var array holds elements which content should only selected once
 */
var only_once_elements = [];

/**
 * @var   int   ajax_message_count   Number of AJAX messages shown since page load
 */
var ajax_message_count = 0;

/**
 * @var codemirror_editor object containing CodeMirror editor of the query editor in SQL tab
 */
var codemirror_editor = false;

/**
 * @var codemirror_editor object containing CodeMirror editor of the inline query editor
 */
var codemirror_inline_editor = false;

/**
 * @var chart_activeTimeouts object active timeouts that refresh the charts. When disabling a realtime chart, this can be used to stop the continuous ajax requests
 */
var chart_activeTimeouts = {};

/**
 * Make sure that ajax requests will not be cached
 * by appending a random variable to their parameters
 */
$.ajaxPrefilter(function (options, originalOptions, jqXHR) {
    var nocache = new Date().getTime() + "" + Math.floor(Math.random() * 1000000);
    if (typeof options.data == "string") {
        options.data += "&_nocache=" + nocache;
    } else if (typeof options.data == "object") {
        options.data = $.extend(originalOptions.data, {'_nocache' : nocache});
    }
});

/**
 * Add a hidden field to the form to indicate that this will be an
 * Ajax request (only if this hidden field does not exist)
 *
 * @param object   the form
 */
function PMA_prep<|endoftext|>