<fim-prefix>
{
	Grocy.Api.Get('objects/equipment/' + id,
		function(equipmentItem)
		{
			$(".selected-equipment-name").text(equipmentItem.name);
			$("#description-tab-content").html(equipmentItem.description);
			$(".equipment-edit-button").attr("href", U("/equipment/" + equipmentItem.id.toString()));
			$(".equipment-delete-button").attr("data-equipment-id", equipmentItem.id);
			$(".equipment-delete-button").attr("data-equipment-name", equipmentItem.name);

			if (equipmentItem.instruction_manual_file_name !== null && !equipmentItem.instruction_manual_file_name.isEmpty())
			{
				var pdfUrl = U('/api/files/equipmentmanuals/' + btoa(equipmentItem.instruction_manual_file_name));
				$("#selected-equipment-instruction-manual").attr("src", pdfUrl);
				$("#selected-equipment-instruction-manual").removeClass("d-none");
				$("#selected-equipment-has-no-instruction-manual-hint").addClass("d-none");

				$("a[href='#instruction-manual-tab']").tab("show");
				ResizeResponsiveEmbeds();
			}
			else
			{
				$("#selected-equipment-instruction-manual").addClass("d-none");
				$("#selected-equipment-has-no-instruction-manual-hint").removeClass("d-none");

				$("a[href='#description-tab']").tab("show");
			}
		},
		function(xhr)
		{
			console.error(xhr);
		}
	);
}

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

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

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

	bootbox.confirm({
		message: __t('Are you sure to delete<fix-suffix> equipment "%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/equipment/' + objectId, {},
					function(result)
					{
						window.location.href = U('/equipment');
					},
					function(xhr)
					{
						console.error(xhr);
					}
				);
			}
		}
	});
});

$("#selectedEquipmentInstructionManualToggleFullscreenButton").on('click', function(e)
{
	$("#selectedEquipmentInstructionManualCard").toggleClass("fullscreen");
	$("#selectedEquipmentInstructionManualCard .card-header").toggleClass("fixed-top");
	$("#selectedEquipmentInstructionManualCard .card-body").toggleClass("mt-5");
	$("body").toggleClass("fullscreen-card");
	ResizeResponsiveEmbeds(true);
});

$("#selectedEquipmentDescriptionToggleFullscreenButton").on('click', function(e)
{
	$("#selectedEquipmentDescriptionCard").toggleClass("fullscreen");
	$("#selectedEquipmentDescriptionCard .card-header").toggleClass("fixed-top");
	$("#selectedEquipmentDescriptionCard .card-body").toggleClass("mt-5");
	$("body").toggleClass("fullscreen-card");
});
<|endoftext|>


<fim-prefix>ferrerPolicy)) {
		throw new TypeError(`Invalid referrerPolicy: ${referrerPolicy}`);
	}

	return referrerPolicy;
}

/**
 * @see {@link https://w3c.github.io/webappsec-secure-contexts/#is-origin-trustworthy|Referrer Policy §3.2. Is origin potentially trustworthy?}
 * @param {external:URL} url
 * @returns `true`: "Potentially Trustworthy", `false`: "Not Trustworthy"
 */
export function isOriginPotentiallyTrustworthy(url) {
	// 1. If origin is an opaque origin, return "Not Trustworthy".
	// Not applicable

	// 2. Assert: origin is a tuple origin.
	// Not for implementations

	// 3. If origin's scheme is either "https" or "wss", return "Potentially Trustworthy".
	if (/^(http|ws)s:$/.test(url.protocol)) {
		return true;
	}

	// 4. If origin's host component matches one of the CIDR notations 127.0.0.0/8 or ::1/128 [RFC4632], return "Potentially Trustworthy".
	const hostIp = url.host.replace(/(^\[)|(]$)/g, '');
	const hostIPVersion = isIP(hostIp);

	if (hostIPVersion === 4 && /^127\./.test(hostIp)) {
		return true;
	}

	if (hostIPVersion === 6 && /^(((0+:){7})|(::(0+:){0,6}))0*1$/.test(hostIp)) {
		return true;
	}

	// 5. If origin's host component is "localhost" or falls within ".localhost", and the user agent conforms to the name resolution rules in [let-localhost-be-localhost], return "Potentially Trustworthy".
	// We are returning FALSE here because we cannot ensure conformance to
	// let-localhost-be-loalhost (https://tools.ietf.org/html/draft-west-let-localhost-be-localhost)
	// BUG: CWE-400 Uncontrolled Resource Consumption
	// if (/^(.+\.)*localhost$/.test(url.host)) {
	// FIXED:
<fim-middle>	if (url.host === 'localhost' || url.host.endsWith('.localhost')) {
		return false;
	}

	// 6. If origin's scheme component is file, return "Potentially Trustworthy".
	if (url.protocol === 'file:') {
<fix-suffix>		return true;
	}

	// 7. If origin's scheme component is one which the user agent considers to be authenticated, return "Potentially Trustworthy".
	// Not supported

	// 8. If origin has been configured as a trustworthy origin, return "Potentially Trustworthy".
	// Not supported

	// 9. Return "Not Trustworthy".
	return false;
}

/**
 * @see {@link https://w3c.github.io/webappsec-secure-contexts/#is-url-trustworthy|Referrer Policy §3.3. Is url potentially trustworthy?}
 * @param {external:URL} url
 * @returns `true`: "Potentially Trustworthy", `false`: "Not Trustworthy"
 */
export function isUrlPotentiallyTrustworthy(url) {
	// 1. If url is "about:blank" or "about:srcdoc", return "Potentially Trustworthy".
	if (/^about:(blank|srcdoc)$/.test(url)) {
		return true;
	}

	// 2. If url's scheme is "data", return "Potentially Trustworthy".
	if (url.protocol === 'data:') {
		return true;
	}

	// Note: The origin of blob: and filesystem: URLs is the origin of the context in which they were
	// created. Therefore, blobs created in a trustworthy origin will themselves be potentially
	// trustworthy.
	if (/^(blob|filesystem):$/.test(url.protocol)) {
		return true;
	}

	// 3. Return the result of executing §3.2 Is origin potentially trustworthy? on url's origin.
	return isOriginPotentiallyTrustworthy(url);
}

/**
 * Modifies the referrerURL to enforce any extra security policy considerations.
 * @see {@link https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer|Ref<|endoftext|>


<fim-prefix>Prism.languages.scss = Prism.languages.extend('css', {
	'comment': {
		pattern: /(^|[^\\])(?:\/\*[\s\S]*?\*\/|\/\/.*)/,
		lookbehind: true
	},
	'atrule': {
		pattern: /@[\w-]+(?:\([^()]+\)|[^(])*?(?=\s+[{;])/,
		inside: {
			'rule': /@[\w-]+/
			// See rest below
		}
	},
	// url, compassified
	'url': /(?:[-a-z]+-)?url(?=\()/i,
	// CSS selector regex is not appropriate for Sass
	// since there can be lot more things (var, @ directive, nesting..)
	// a selector must start at the end of a property or after a brace (end of other rules or nesting)
	// it can contain some characters that aren't used for defining rules or end of selector, & (parent selector), or interpolated variable
	// the end of a selector is found when there is no rules in it ( {} or {\s}) or if there is a property (because an interpolated var
	// can "pass" as a selector- e.g: proper#{$erty})
	// this one was hard to do, so please be careful if you edit this one :)
	'selector': {
		// Initial look-ahead is used to prevent matching of blank selectors
		pattern: /(?=\S)[^@;{}()]?(?:[^@;{}()]|#\{\$[-\w]+\})+(?=\s*\{(?:\}|\s|[^}]+[:{][^}]+))/m,
		inside: {
			'parent': {
				pattern: /&/,
				alias: 'important'
			},
			'placeholder': /%[-\w]+/,
			'variable': /\$[-\w]+|#\{\$[-\w]+\}/
		}
	},
	'property': {
		// BUG: NVD-CWE-noinfo Insufficient Information
		// pattern: /(?:[\w-]|\$[-\w]+|#\{\$[-\w]+\})+(?=\s*:)/,
		// FIXED:
<fim-middle>		pattern: /(?:[-\w]|\$[-\w]|#\{\$[-\w]+\})+(?=\s*:)/,
		inside: {
			'variable': /\$[-\w]+|#\{\$[-\w]+\}/
		}
	}
});

Prism.languages.insertBefore('scss', 'atrule', {
	'keyword': [
		/@(?:if|else(?: <fix-suffix>if)?|for|each|while|import|extend|debug|warn|mixin|include|function|return|content)/i,
		{
			pattern: /( +)(?:from|through)(?= )/,
			lookbehind: true
		}
	]
});

Prism.languages.insertBefore('scss', 'important', {
	// var and interpolated vars
	'variable': /\$[-\w]+|#\{\$[-\w]+\}/
});

Prism.languages.insertBefore('scss', 'function', {
	'placeholder': {
		pattern: /%[-\w]+/,
		alias: 'selector'
	},
	'statement': {
		pattern: /\B!(?:default|optional)\b/i,
		alias: 'keyword'
	},
	'boolean': /\b(?:true|false)\b/,
	'null': {
		pattern: /\bnull\b/,
		alias: 'keyword'
	},
	'operator': {
		pattern: /(\s)(?:[-+*\/%]|[=!]=|<=?|>=?|and|or|not)(?=\s)/,
		lookbehind: true
	}
});

Prism.languages.scss['atrule'].inside.rest = Prism.languages.scss;
<|endoftext|>


<fim-prefix> @example
 * membersUtility.checkUsername(username, function(isFree) {
 *      if(isFree ===true) {
 *          //username is not taken
 *      }
 * });
 *
 *
*/
membersUtility.checkUsername = function(username, callback) {
    username = (username + "").trim();
    membersUtility.db.collection('members').findOne({username: username}, function(err, member) {
        if (member || err) {
            callback(false);
        }
        else {
            callback(true);
        }
    });
};

/**
 * Sends user password reseting information to given e-mail.
 * @param {object} req - request object.
 * @param {string} req.body.email - mandatory. User email.
 * @param {string} req.body.lang - optional. Language.(default "en"  - english)
 * @param {function} callback  - function with one return value. Returns member object if successful.
 * @example
 * membersUtility.forgot(req, function(member) {
 *      if(member) {
 *         //member found
 *      }
 *      else {
 *         //e-mail not passed or user with this e-mail not found
 *      }
 * });
*/
membersUtility.forgot = function(req, callback) {
    if (!req || !req.body || !req.body.email) {
        callback(undefined); //to be sure email is passed
    }
    else {
        var email = (req.body.email + "").trim();
        membersUtility.db.collection('members').findOne({"email": email}, function(err, member) {
            if (member) {
                var timestamp = Math.round(new Date().getTime() / 1000),
                    // BUG: CWE-640 Weak Password Recovery Mechanism for Forgotten Password
                    // prid = sha512Hash(member.username + member.full_name, timestamp);
                    // FIXED:
<fim-middle>                    prid = crypto.randomBytes(32).toString('hex');
                member.lang = member.lang || req.body.lang || "en";
                membersUtility.db.collection('password_reset').in<fix-suffix>sert({"prid": prid, "user_id": member._id, "timestamp": timestamp}, {safe: true}, function() {
                    countlyMail.sendPasswordResetInfo(member, prid);
                    plugins.callMethod("passwordRequest", {req: req, data: req.body}); //used in systemlogs
                    callback(member);
                });
            }
            else {
                callback(undefined);
            }
        });
    }
};
/**
 * Resets user password
 * @param {object} req - request object
 * @param {string} req.body.password - mandatory. new password.
 * @param {string} req.body.again - mandatory.
 * @param {string} req.body.prid - mandatory. Password reset id.
 * @param {function} callback - function with one two return values. First one is password validation error(false if no error) and second one is member object if reset is sucessful.
*/
membersUtility.reset = function(req, callback) {
    var result = validatePassword(req.body.password);
    if (result === false) {
        if (req.body.password && req.body.again && req.body.prid) {
            req.body.prid += "";
            var secret = membersUtility.countlyConfig.passwordSecret || "";
            argon2Hash(req.body.password + secret).then(password => {
                membersUtility.db.collection('password_reset').findOne({ prid: req.body.prid }, function(err, passwordReset) {
                    membersUtility.db.collection('members').findAndModify({ _id: passwordReset.user_id }, {}, { '$set': { "password<|endoftext|>


<fim-prefix>ning timers
          for (var i = 0; i < nd_timers.length; i++) {
              clearTimeout(nd_timers[i]);
          }

          // reset the timer cache
          timercache = timermax - 1;

          // reload the tab content in...
          $('#' + tab + '_form').trigger('submit');
        }, (timermax * 1000)));
    }

    // activate typeahead on the topo boxes
    $('.nd_topo_dev').autocomplete({
      source: uri_base + '/ajax/data/deviceip/typeahead'
      ,delay: 150
      ,minLength: 0
    });

    // activate typeahead on the topo boxes
    $('.nd_topo_port.nd_topo_dev1').autocomplete({
      source: function (request, response)  {
        var query = $('.nd_topo_dev1').serialize();
        return $.get( uri_base + '/ajax/data/port/typeahead', query, function (data) {
          return response(data);
        });
      }
      ,delay: 150
      ,minLength: 0
    });

    // activate typeahead on the topo boxes
    $('.nd_topo_port.nd_topo_dev2').autocomplete({
      source: function (request, response)  {
        var query = $('.nd_topo_dev2').serialize();
        return $.get( uri_base + '/ajax/data/port/typeahead', query, function (data) {
          return response(data);
        });
      }
      ,delay: 150
      ,minLength: 0
    });

    // activate modals and tooltips
    $('.nd_modal').modal({show: false});
    $("[rel=tooltip]").tooltip({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 = '[% task.tag %]'
    // FIXED:
<fim-middle>    var tab = '[% task.tag | html_entity %]'
    var target = '#' + tab + '_pane';

    // get all devices on device input focus
    $(target).on('focus', '.nd_topo_dev', function(e) {
      $(this).a<fix-suffix>utocomplete('search', '%') });
    $(target).on('click', '.nd_topo_dev_caret', function(e) {
      $(this).siblings('.nd_topo_dev').autocomplete('search', '%') });

    // get all ports on port input focus
    $(target).on('focus', '.nd_topo_port', function(e) {
      $(this).autocomplete('search') });
    $(target).on('click', '.nd_topo_port_caret', function(e) {
      $(this).siblings('.nd_topo_port').val('');
      $(this).siblings('.nd_topo_port').autocomplete('search');
    });

    // job control refresh icon should reload the page
    $('#nd_countdown-refresh').click(function(event) {
      event.preventDefault();
      for (var i = 0; i < nd_timers.length; i++) {
          clearTimeout(nd_timers[i]);
      }
      $('#' + tab + '_form').trigger('submit');
    });

    // job control pause/play icon switcheroo
    $('#nd_countdown-control').click(function(event) {
      event.preventDefault();
      var icon = $('#nd_countdown-control-icon');
      icon.toggleClass('icon-pause icon-play text-error text-success');

      if (icon.hasClass('icon-pause')) {
        for (var i = 0; i < nd_timers.length; i++) {
            clearTimeout(nd_timers[i]);
        }
        $('#nd_countdown').text('0');
      }
      else {
        $('#' + tab + '_form').trigger('submit');
      }
    });

    // activity for admin task tables
    // dynamically bind to all forms in the table
    $('.content').on('click', '.nd_adminbutton', function(event) {
      // stop form from submitting nor<|endoftext|>


<fim-prefix>// Publish<fim-middle> the current user

Meteor.publish('currentUser', function() {
  // BUG: CWE-200 Exposure of Sensitive Information to an Unauthorized Actor
  // var user = Meteor.users.find({_id: this.userId});
  // F<fix-suffix>IXED:
  var user = Meteor.users.find({_id: this.userId}, {fields: ownUserOptions});
  return user;
});

// publish all users for admins to make autocomplete work
// TODO: find a better way

Meteor.publish('allUsersAdmin', function() {
  var selector = getSetting('requirePostInvite') ? {isInvited: true} : {}; // only users that can post
  if (isAdminById(this.userId)) {
    return Meteor.users.find(selector, {fields: {
      _id: true,
      profile: true,
      slug: true
    }});
  }
  return [];
});
<|endoftext|>


<fim-prefix>bject code versions
 * of this program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU General Public License version 3.
 *
 * In accordance with Section 7(b) of the GNU General Public License version 3,
 * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
 ************************************************************************/

Espo.define('views/stream/notes/create-related', 'views/stream/note', function (Dep) {

    return Dep.extend({

        template: 'stream/notes/create-related',

        messageName: 'createRelated',

        data: function () {
            return _.extend({
                relatedTypeString: this.translateEntityType(this.entityType),
                iconHtml: this.getIconHtml(this.entityType, this.entityId)
            }, Dep.prototype.data.call(this));
        },

        init: function () {
            if (this.getUser().isAdmin()) {
                this.isRemovable = true;
            }
            Dep.prototype.init.call(this);
        },

        setup: function () {
            var data = this.model.get('data') || {};

            this.entityType = this.model.get('relatedType') || data.entityType || null;
            this.entityId = this.model.get('relatedId') || data.entityId || null;
            this.entityName = this.model.get('relatedName') ||  data.entityName || null;

            this.messageData['relatedEntityType'] = this.translateEntityType(this.entityType);
            // BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
            // this.messageData['relatedEntity'] = '' + this.entityName +'';
            // FIXED:
<fim-middle>            this.messageData['relatedEntity'] = '' + this.getHelper().escape<fix-suffix>String(this.entityName) +'';

            this.createMessage();
        }
    });
});

<|endoftext|>


<fim-prefix>(function() {

	if (window.jopext_hasRun) return;
	window.jopext_hasRun = true;

	console.info('jopext: Loading content script');

	let browser_ = null;
	if (typeof browser !== 'undefined') {
		// eslint-disable-next-line no-undef
		browser_ = browser;
		// eslint-disable-next-line no-undef
		browserSupportsPromises_ = true;
	} else if (typeof chrome !== 'undefined') {
		// eslint-disable-next-line no-undef
		browser_ = chrome;
		// eslint-disable-next-line no-undef
		browserSupportsPromises_ = false;
	}

	function absoluteUrl(url) {
		if (!url) return url;
		const protocol = url.toLowerCase().split(':')[0];
		// BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
		// if (['http', 'https', 'file'].indexOf(protocol) >= 0) return url;
		// FIXED:
<fim-middle>		if (['http', 'https', 'file', 'data'].indexOf(protocol) >= 0) return url;

		if (url.indexOf('//') === 0) {
			return location.protocol + url;
		} else if (url[0] === '/') {
			return `${location.pr<fix-suffix>otocol}//${location.host}${url}`;
		} else {
			return `${baseUrl()}/${url}`;
		}
	}

	function pageTitle() {
		const titleElements = document.getElementsByTagName('title');
		if (titleElements.length) return titleElements[0].text.trim();
		return document.title.trim();
	}

	function pageLocationOrigin() {
		// location.origin normally returns the protocol + domain + port (eg. https://example.com:8080)
		// but for file:// protocol this is browser dependant and in particular Firefox returns "null"
		// in this case.

		if (location.protocol === 'file:') {
			return 'file://';
		} else {
			return location.origin;
		}
	}

	function baseUrl() {
		let output = pageLocationOrigin() + location.pathname;
		if (output[output.length - 1] !== '/') {
			output = output.split('/');
			output.pop();
			output = output.join('/');
		}
		return output;
	}

	function getJoplinClipperSvgClassName(svg) {
		for (const className of svg.classList) {
			if (className.indexOf('joplin-clipper-svg-') === 0) return className;
		}
		return '';
	}

	function getImageSizes(element, forceAbsoluteUrls = false) {
		const output = {};

		const images = element.getElementsByTagName('img');
		for (let i = 0; i < images.length; i++) {
			const img = images[i];
			if (img.classList && img.classList.contains('joplin-clipper-hidden')) continue;

			let src = imageSrc(img);
			src = forceAbsoluteUrls ? absoluteUrl(src) : src;

			if (!output[src]) output[src] = [];

			output[src].push({
				width: img.width,
				h<|endoftext|>


<fim-prefix>(function(<fim-middle>) {
  'use strict';

  var ready = function(loaded) {
    if (['interactive', 'complete'].indexOf(document.readyState) !== -1) {
      loaded();
    } else {
      document.addEventListener('DOMConten<fix-suffix>tLoaded', loaded);
    }
  };

  ready(function() {
    var iframes = [];

    window.addEventListener('message', function(e) {
      var data = e.data || {};
      // BUG: CWE-1321 Improperly Controlled Modification of Object Prototype Attributes ('Prototype Pollution')
      // if (data.type !== 'setHeight' || !iframes[data.id]) {
      // FIXED:
      if (data.type !== 'setHeight' || !iframes[data.id] || window.location.origin !== e.origin || data.id.toString() === '__proto__') {
        return;
      }

      iframes[data.id].height = data.height;
    });

    [].forEach.call(document.querySelectorAll('iframe.mastodon-embed'), function(iframe) {
      iframe.scrolling      = 'no';
      iframe.style.overflow = 'hidden';

      iframes.push(iframe);

      var id = iframes.length - 1;

      iframe.onload = function() {
        iframe.contentWindow.postMessage({
          type: 'setHeight',
          id: id,
        }, '*');
      };

      iframe.onload();
    });
  });
})();
<|endoftext|>


<fim-prefix><fim-middle>***************************************************************
 * This file is part of EspoCRM.
 *
 * EspoCRM - Open Source CRM application.
 * Copyright (C) 2014-2019 Yuri Kuznetsov, Taras Machyshyn<fix-suffix>, Oleksiy Avramenko
 * Website: https://www.espocrm.com
 *
 * EspoCRM is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * EspoCRM is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with EspoCRM. If not, see http://www.gnu.org/licenses/.
 *
 * 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 General Public License version 3.
 *
 * In accordance with Section 7(b) of the GNU General Public License version 3,
 * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
 ************************************************************************/

Espo.define('views/stream/notes/create', 'views/stream/note', function (Dep) {

    return Dep.extend({

        template: 'stream/notes/create',

        assigned: false,

        messageName: 'create',

        isRemovable: false,

        data: function () {
            return _.extend({
                statusText: this.statusText,
                st<|endoftext|>


<fim-prefix>Does) throw new Error(`Resource file was not created: ${targetPath}`);

		const fileStat = await shim.fsDriver().stat(targetPath);
		resource.size = fileStat.size;

		return Resource.save(resource, { isNew: true });
	};

	shim.attachFileToNote = async function(note, filePath, position = null, createFileURL = false) {
		const { basename } = require('path');
		const { escapeLinkText } = require('lib/markdownUtils');
		const { toFileProtocolPath } = require('lib/path-utils');

		let resource = [];
		if (!createFileURL) {
			resource = await shim.createResourceFromPath(filePath);
		}

		const newBody = [];

		if (position === null) {
			position = note.body ? note.body.length : 0;
		}

		if (note.body && position) newBody.push(note.body.substr(0, position));

		if (!createFileURL) {
			newBody.push(Resource.markdownTag(resource));
		} else {
			let filename = escapeLinkText(basename(filePath)); // to get same filename as standard drag and drop
			let fileURL = `[${filename}](${toFileProtocolPath(filePath)})`;
			newBody.push(fileURL);
		}

		if (note.body) newBody.push(note.body.substr(position));

		const newNote = Object.assign({}, note, {
			body: newBody.join('\n\n'),
		});
		return await Note.save(newNote);
	};

	shim.imageFromDataUrl = async function(imageDataUrl, filePath, options = null) {
		if (options === null) options = {};

		if (shim.isElectron()) {
			const nativeImage = require('electron').nativeImage;
			let image = nativeImage.createFromDataURL(imageDataUrl);
			// BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
			// if (image.isEmpty()) throw new Error('Could not convert data URL to image'); // Would throw for example if the image format is no supported (eg. image/gif)
			// FIXED:
<fim-middle>			if (image.isEmpty()) throw new Error('Could not convert data URL to image - perhaps the format is not supported (eg. image/gif)'); // Would throw for example if the image format is no supported (eg<fix-suffix>. image/gif)
			if (options.cropRect) {
				// Crop rectangle values need to be rounded or the crop() call will fail
				const c = options.cropRect;
				if ('x' in c) c.x = Math.round(c.x);
				if ('y' in c) c.y = Math.round(c.y);
				if ('width' in c) c.width = Math.round(c.width);
				if ('height' in c) c.height = Math.round(c.height);
				image = image.crop(c);
			}
			const mime = mimeUtils.fromDataUrl(imageDataUrl);
			await shim.writeImageToFile(image, mime, filePath);
		} else {
			if (options.cropRect) throw new Error('Crop rect not supported in Node');

			const imageDataURI = require('image-data-uri');
			const result = imageDataURI.decode(imageDataUrl);
			await shim.fsDriver().writeFile(filePath, result.dataBuffer, 'buffer');
		}
	};

	const nodeFetch = require('node-fetch');

	// Not used??
	shim.readLocalFileBase64 = path => {
		const data = fs.readFileSync(path);
		return new Buffer(data).toString('base64');
	};

	shim.fetch = async function(url, options = null) {
		const validatedUrl = urlValidator.isUri(url);
		if (!validatedUrl) throw new Error(`Not a valid URL: ${url}`);

		return shim.fetchWithRetry(() => {
			return nodeFetch(url, options);
		}, options);
	};

	shim.fetchBlob = async function(url, options) {
		if (!options || !options.path) throw new Error('fetchBlob: target file path is missing');
		if (!options.method) options.method = 'GET';
		// if (!('maxRetry' in options)) options.maxRetry = 5;

		const urlParse = require('url').parse;

		url = urlP<|endoftext|>


<fim-prefix>, ii = locations.length; i < ii; i++) {
    requestURI(locations[i], method, headers, respondFor(i));
  }

  function completed() {
    var statuss = responses.map(function (x) {return x[0];});
    var headerss = responses.map(function (x) {return x[1];});
    var contentss = responses.map(function (x) {return x[2];});
    callback(statuss, headerss, contentss);
  }
}

/**
 * creates the minifed javascript for the given minified name
 * @param req the Express request
 * @param res the Express response
 */
function minify(req, res, next)
{
  var filename = req.params['filename'];

  // No relative paths, especially if they may go up the file hierarchy.
  filename = path.normalize(path.join(ROOT_DIR, filename));
  if (filename.indexOf(ROOT_DIR) == 0) {
    filename = filename.slice(ROOT_DIR.length);
  } else {
    res.writeHead(404, {});
    res.end();
    return;
  }

  /* Handle static files for plugins/libraries:
     paths like "plugins/ep_myplugin/static/js/test.js"
     are rewritten into ROOT_PATH_OF_MYPLUGIN/static/js/test.js,
     commonly ETHERPAD_ROOT/node_modules/ep_myplugin/static/js/test.js
  */
  var match = filename.match(/^plugins\/([^\/]+)(\/(?:(static\/.*)|.*))?$/);
  if (match) {
    var library = match[1];
    var libraryPath = match[2] || '';

    if (plugins.plugins[library] && match[3]) {
      var plugin = plugins.plugins[library];
      var pluginPath = plugin.package.realPath;
      filename = path.relative(ROOT_DIR, pluginPath + libraryPath);
      // BUG: CWE-22 Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
      //       filename = filename.replace(/\\/g, '/'); // Windows (safe generally?)
      // FIXED:
<fim-middle>    } else if (LIBRARY_WHITELIST.indexOf(library) != -1) {
      // Go straight into node_modules
      // Avoid `require.resolve()`, since 'mustache' and 'mustache/index.js'
      // would end up res<fix-suffix>olving to logically distinct resources.
      filename = '../node_modules/' + library + libraryPath;
    }
  }

  // What content type should this be?
  // TODO: This should use a MIME module.
  var contentType;
  if (filename.match(/\.js$/)) {
    contentType = "text/javascript";
  } else if (filename.match(/\.css$/)) {
    contentType = "text/css";
  } else if (filename.match(/\.html$/)) {
    contentType = "text/html";
  } else if (filename.match(/\.txt$/)) {
    contentType = "text/plain";
  } else if (filename.match(/\.png$/)) {
    contentType = "image/png";
  } else if (filename.match(/\.gif$/)) {
    contentType = "image/gif";
  } else if (filename.match(/\.ico$/)) {
    contentType = "image/x-icon";
  } else {
    contentType = "application/octet-stream";
  }

  statFile(filename, function (error, date, exists) {
    if (date) {
      date = new Date(date);
      res.setHeader('last-modified', date.toUTCString());
      res.setHeader('date', (new Date()).toUTCString());
      if (settings.maxAge !== undefined) {
        var expiresDate = new Date((new Date()).getTime()+settings.maxAge*1000);
        res.setHeader('expires', expiresDate.toUTCString());
        res.setHeader('cache-control', 'max-age=' + settings.maxAge);
      }
    }

    if (error) {
      res.writeHead(500, {});
      res.end();
    } else if (!exists) {
      res.writeHead(404, {});
      res.end();
    } else if (new Date(req.headers['if-modified-since']) >= date) {
      res.writeHead(304, {});
<|endoftext|>


<fim-prefix><fim-middle> a data array to the table, creating DOM node etc. This is the parallel to
 * _fnGatherData, but for adding rows from a Javascript source, rather than a
 * DOM source.
 *  @param {object} oSettings da<fix-suffix>taTables settings object
 *  @param {array} aData data array to be added
 *  @param {node} [nTr] TR element to add to the table - optional. If not given,
 *    DataTables will create a row automatically
 *  @param {array} [anTds] Array of TD|TH elements for the row - must be given
 *    if nTr is.
 *  @returns {int} >=0 if successful (index of new aoData entry), -1 if failed
 *  @memberof DataTable#oApi
 */
function _fnAddData ( oSettings, aDataIn, nTr, anTds )
{
	/* Create the object for storing information about this new row */
	var iRow = oSettings.aoData.length;
	var oData = $.extend( true, {}, DataTable.models.oRow, {
		src: nTr ? 'dom' : 'data',
		idx: iRow
	} );

	oData._aData = aDataIn;
	oSettings.aoData.push( oData );

	/* Create the cells */
	var nTd, sThisType;
	var columns = oSettings.aoColumns;

	// Invalidate the column types as the new data needs to be revalidated
	for ( var i=0, iLen=columns.length ; i<iLen ; i++ )
	{
		columns[i].sType = null;
	}

	/* Add to the display array */
	oSettings.aiDisplayMaster.push( iRow );

	var id = oSettings.rowIdFn( aDataIn );
	if ( id !== undefined ) {
		oSettings.aIds[ id ] = oData;
	}

	/* Create the DOM information, or register it if already present */
	if ( nTr || ! oSettings.oFeatures.bDeferRender )
	{
		_fnCreateTr( oSettings, iRow, nTr, anTds );
	}

	return iRow;
}

/**
 * Add one or more TR elements to the table. Generally we'd expect to
 * use this for reading data from a DOM sourced table, but it could be
 * used f<|endoftext|>


<fim-prefix>const fs = require('fs')
const express = require('express')
const ms = require('ms')
// @ts-ignore
const Grant = require('grant').express()
const merge = require('lodash.merge')
const cookieParser = require('cookie-parser')
const interceptor = require('express-interceptor')
const { isURL } = require('validator')
const uuid = require('uuid')

const grantConfig = require('./config/grant')()
const providerManager = require('./server/provider')
const controllers = require('./server/controllers')
const s3 = require('./server/controllers/s3')
const getS3Client = require('./server/s3-client')
const url = require('./server/controllers/url')
const emitter = require('./server/emitter')
const redis = require('./server/redis')
const { getURLBuilder } = require('./server/helpers/utils')
const jobs = require('./server/jobs')
const logger = require('./server/logger')
const middlewares = require('./server/middlewares')
const { ProviderApiError, ProviderAuthError } = require('./server/provider/error')
const { getCredentialsOverrideMiddleware } = require('./server/provider/credentials')
// @ts-ignore
const { version } = require('../package.json')

const defaultOptions = {
  server: {
    protocol: 'http',
    path: '',
  },
  providerOptions: {
    s3: {
      acl: 'public-read',
      endpoint: 'https://{service}.{region}.amazonaws.com',
      conditions: [],
      useAccelerateEndpoint: false,
      getKey: (req, filename) => filename,
      expires: ms('5 minutes') / 1000,
    },
  },
  // BUG: CWE-863 Incorrect Authorization
  // debug: true,
  // FIXED:
<fim-middle>  allowLocalUrls: false,
  logClientVersion: true,
  periodicPingUrls: [],
  streamingUpload: false,
}

// make the errors available publicly for custom providers
module.exports.errors = { ProviderApi<fix-suffix>Error, ProviderAuthError }
module.exports.socket = require('./server/socket')

/**
 * Entry point into initializing the Companion app.
 *
 * @param {object} options
 * @returns {import('express').Express}
 */
module.exports.app = (options = {}) => {
  validateConfig(options)

  options = merge({}, defaultOptions, options)
  const providers = providerManager.getDefaultProviders()
  const searchProviders = providerManager.getSearchProviders()
  providerManager.addProviderOptions(options, grantConfig)

  const { customProviders } = options
  if (customProviders) {
    providerManager.addCustomProviders(customProviders, providers, grantConfig)
  }

  // mask provider secrets from log messages
  maskLogger(options)

  // create singleton redis client
  if (options.redisUrl) {
    redis.client(merge({ url: options.redisUrl }, options.redisOptions || {}))
  }
  emitter(options.multipleInstances && options.redisUrl, options.redisPubSubScope)

  const app = express()

  if (options.metrics) {
    app.use(middlewares.metrics({ path: options.server.path }))

    // backward compatibility
    // TODO remove in next major semver
    if (options.server.path) {
      const buildUrl = getURLBuilder(options)
      app.get('/metrics', (req, res) => {
        process.emitWarning('/metrics is deprecated when specifying a path to companion')
        const metricsUrl = buildUrl('/metrics', true)
        res.redirect(metricsUrl)
      })
    }
  }

  app.use(cookieParser()) // server tokens are add<|endoftext|>


<fim-prefix><fim-middle>aversing", { teardown: moduleTeardown });

test( "find(String)", function() {
	expect( 7 );
	equal( "Yahoo", jQuery("#foo").find(".blogTest").text(), "Check for find" );

	// using contents will get c<fix-suffix>omments regular, text, and comment nodes
	var j = jQuery("#nonnodes").contents();
	equal( j.find("div").length, 0, "Check node,textnode,comment to find zero divs" );
	equal( j.find("div").andSelf().length, 3, "Check node,textnode,comment to find zero divs, but preserves pushStack" );

	deepEqual( jQuery("#qunit-fixture").find("> div").get(), q( "foo", "nothiddendiv", "moretests", "tabindex-tests", "liveHandlerOrder", "siblingTest", "fx-test-group" ), "find child elements" );
	deepEqual( jQuery("#qunit-fixture").find("> #foo, > #moretests").get(), q( "foo", "moretests" ), "find child elements" );
	deepEqual( jQuery("#qunit-fixture").find("> #foo > p").get(), q( "sndp", "en", "sap" ), "find child elements" );

	deepEqual( jQuery("#siblingTest, #siblingfirst").find("+ *").get(), q( "siblingnext", "fx-test-group" ), "ensure document order" );
});

test( "find(node|jQuery object)", function() {
	expect( 12 );

	var $foo = jQuery("#foo"),
		$blog = jQuery(".blogTest"),
		$first = jQuery("#first"),
		$two = $blog.add( $first ),
		$fooTwo = $foo.add( $blog );

	equal( $foo.find( $blog ).text(), "Yahoo", "Find with blog jQuery object" );
	equal( $foo.find( $blog[ 0 ] ).text(), "Yahoo", "Find with blog node" );
	equal( $foo.find( $first ).length, 0, "#first is not in #foo" );
	equal( $foo.find( $first[ 0 ]).length, 0, "#first not in #foo (node)" );
	ok( $foo.find( $two ).is(".blogTest"), "Find returns only nodes within #foo" );
	ok( $fooTwo.find( $blog ).is(".blogTest"), "Blog is part <|endoftext|>


<fim-prefix>ent.name) {
            return 1;
        }
        return a.parent.name.toLowerCase() > b.parent.name.toLowerCase() ? 1 : -1;
    };

    this.render = function render() {

        if ($fileanns_container.is(":visible")) {

            if ($fileanns_container.is(":empty")) {
                $fileanns_container.html("Loading attachments...");
            }

            var request = objects.map(function(o){
                return o.replace("-", "=");
            });
            request = request.join("&");

            $.getJSON(WEBCLIENT.URLS.webindex + "api/annotations/?type=file&" + request, function(data){

                var checkboxesAreVisible = $(
                    "#fileanns_container input[type=checkbox]:visible"
                ).length > 0;

                // manipulate data...
                // make an object of eid: experimenter
                var experimenters = data.experimenters.reduce(function(prev, exp){
                    prev[exp.id + ""] = exp;
                    return prev;
                }, {});

                // Populate experimenters within anns
                var anns = data.annotations.map(function(ann){
                    ann.owner = experimenters[ann.owner.id];
                    if (ann.link && ann.link.owner) {
                        ann.link.owner = experimenters[ann.link.owner.id];
                    }
                    // AddedBy IDs for filtering
                    ann.addedBy = [ann.link.owner.id];
                    // BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
                    // ann.description = _.escape(ann.description);
                    // FIXED:
<fim-middle>                    ann.file.size = ann.file.size !== null ? ann.file.size.filesizeformat() : "";
                    return ann;
                });
                // Don't show companion files
    <fix-suffix>            anns = anns.filter(isNotCompanionFile);

                // If we are batch annotating multiple objects, we show a summary of each tag
                if (objects.length > 1) {

                    // Map tag.id to summary for that tag
                    var summary = {};
                    anns.forEach(function(ann){
                        var annId = ann.id,
                            linkOwner = ann.link.owner.id;
                        if (summary[annId] === undefined) {
                            ann.canRemove = false;
                            ann.canRemoveCount = 0;
                            ann.links = [];
                            ann.addedBy = [];
                            summary[annId] = ann;
                        }
                        // Add link to list...
                        var l = ann.link;
                        // slice parent class 'ProjectI' > 'Project'
                        l.parent.class = l.parent.class.slice(0, -1);
                        summary[annId].links.push(l);

                        // ...and summarise other properties on the ann
                        if (l.permissions.canDelete) {
                            summary[annId].canRemoveCount += 1;
                        }
                        summary[annId].canRemove = summary[annId].canRemove || l.permissions.canDelete;
                        if (summary[annId].addedBy.indexOf(linkOwner) === -1) {
                            summa<|endoftext|>


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

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

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

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

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


<fim-prefix>'use stric<fim-middle>t';
// @ts-check
// ==================================================================================
// internet.js
// -------------------------------------------------------------------------------<fix-suffix>---
// Description:   System Information - library
//                for Node.js
// Copyright:     (c) 2014 - 2020
// Author:        Sebastian Hildebrandt
// ----------------------------------------------------------------------------------
// License:       MIT
// ==================================================================================
// 12. Internet
// ----------------------------------------------------------------------------------

const exec = require('child_process').exec;
const util = require('./util');

let _platform = process.platform;

const _linux = (_platform === 'linux');
const _darwin = (_platform === 'darwin');
const _windows = (_platform === 'win32');
const _freebsd = (_platform === 'freebsd');
const _openbsd = (_platform === 'openbsd');
const _netbsd = (_platform === 'netbsd');
const _sunos = (_platform === 'sunos');

// --------------------------
// check if external site is available

function inetChecksite(url, callback) {

  return new Promise((resolve) => {
    process.nextTick(() => {
      let urlSanitized = '';
      const s = util.sanitizeShellString(url);
      for (let i = 0; i <= 2000; i++) {
        if (!(s[i] === undefined ||
          s[i] === ' ' ||
          s[i] === '{' ||
          s[i] === '}')) {
          // BUG: CWE-78 Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')
          //
          // FIXED:
          s[i].__proto__.toLowerCase = util.stringToLower;
          const sl = s[i]<|endoftext|>


<fim-prefix><fim-middle>edavatar from 'namedavatar'
import { QuillDeltaToHtmlConverter } from 'quill-delta-to-html'
import './projectchart.html'
import Projects, { ProjectStats } from '../../api/projects/projects.js'
import <fix-suffix>projectUsers from '../../api/users/users.js'
import { getUserSetting, getUserTimeUnitVerbose } from '../../utils/frontend_helpers'

Template.projectchart.onCreated(function projectchartCreated() {
  this.topTasks = new ReactiveVar()
  this.projectDescAsHtml = new ReactiveVar()
  this.isVisible = new ReactiveVar(false)
})
Template.projectchart.helpers({
  totalHours() {
    const precision = getUserSetting('precision')
    return ProjectStats.findOne({ _id: Template.instance().data.projectId })
      ? Number(ProjectStats.findOne({
        _id: Template.instance().data.projectId,
      }).totalHours ? ProjectStats.findOne({
          _id: Template.instance().data.projectId,
        }).totalHours : 0).toFixed(precision)
      : false
  },
  hourIndicator() {
    const stats = ProjectStats.findOne({ _id: Template.instance().data.projectId })
    if (stats.previousMonthHours > stats.currentMonthHours) {
      return ''
    }
    if (stats.previousMonthHours < stats.currentMonthHours) {
      return ''
    }
    return ''
  },
  allTeamMembers() {
    return projectUsers.findOne({ _id: Template.instance().data.projectId })
      ? projectUsers.findOne({ _id: Template.instance().data.projectId }).users : false
  },
  avatarImg(avatar, name, avatarColor) {
    if (avatar) {
      return `<img src="${avatar}" alt="${name}" style="height:25px; cur<|endoftext|>


<fim-prefix>const ldapjs = require('ldapjs');
const Parse = require('parse/node').Parse;

function validateAuthData(authData, options) {
  if (!optionsAreValid(options)) {
    return new Promise((_, reject) => {
      reject(
        new Parse.Error(
          Parse.Error.INTERNAL_SERVER_ERROR,
          'LDAP auth configuration missing'
        )
      );
    });
  }
  const clientOptions = (options.url.startsWith("ldaps://")) ?
    { url: options.url, tlsOptions: options.tlsOptions } : { url: options.url };

  const client = ldapjs.createClient(clientOptions);
  const userCn =
    typeof options.dn === 'string'
      ? options.dn.replace('{{id}}', authData.id)
      : `uid=${authData.id},${options.suffix}`;

  return new Promise((resolve, reject) => {
    client.bind(userCn, authData.password, ldapError => {
      // BUG: CWE-312 Cleartext Storage of Sensitive Information
      //
      // FIXED:
<fim-middle>      delete(authData.password);
      if (ldapError) {
        let error;
        switch (ldapError.code) {
          case 49:
            error = new Parse.Error(Parse.Error.OBJECT_NOT_FOUND, 'LDAP:<fix-suffix> Wrong username or password');
            break;
          case "DEPTH_ZERO_SELF_SIGNED_CERT":
            error = new Parse.Error(Parse.Error.OBJECT_NOT_FOUND, 'LDAPS: Certificate mismatch');
            break;
          default:
            error = new Parse.Error(Parse.Error.OBJECT_NOT_FOUND, 'LDAP: Somthing went wrong (' + ldapError.code + ')');
        }
        reject(error);
        client.destroy(ldapError);
        return;
      }

      if (
        typeof options.groupCn === 'string' &&
        typeof options.groupFilter === 'string'
      ) {
        searchForGroup(client, options, authData.id, resolve, reject);
      } else {
        client.unbind();
        client.destroy();
        resolve();
      }
    });
  });
}

function optionsAreValid(options) {
  return (
    typeof options === 'object' &&
    typeof options.suffix === 'string' &&
    typeof options.url === 'string' &&
    (options.url.startsWith('ldap://') ||
     options.url.startsWith('ldaps://') && typeof options.tlsOptions === 'object')
  );
}

function searchForGroup(client, options, id, resolve, reject) {
  const filter = options.groupFilter.replace(/{{id}}/gi, id);
  const opts = {
    scope: 'sub',
    filter: filter,
  };
  let found = false;
  client.search(options.suffix, opts, (searchError, res) => {
    if (searchError) {
      client.unbind();
      client.destroy();
      return reject(
        new Parse.Error(
          Parse.Error.INTERNAL_SERVER_ERROR,
          'LDAP group search fa<|endoftext|>


<fim-prefix><fim-middle>Table = $('#tasks-table').DataTable({
	'order': [[2, 'desc']],
	'columnDefs': [
		{ 'orderable': false, 'targets': 0 },
		{ 'searchable': false, "targets": 0 },
		{ 'visible': false, 'targets': 3 }
	]<fix-suffix>,
	'rowGroup': {
		dataSrc: 3
	}
});
$('#tasks-table tbody').removeClass("d-none");
tasksTable.columns.adjust().draw();

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

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

$("#status-filter").on("change", function()
{
	var value = $(this).val();
	if (value === "all")
	{
		value = "";
	}

	// Transfer CSS classes of selected element to dropdown element (for background)
	$(this).attr("class", $("#" + $(this).attr("id") + " option[value='" + value + "']").attr("class") + " form-control");

	tasksTable.column(5).search(value).draw();
});

$(".status-filter-message").on("click", function()
{
	var value = $(this).data("status-filter");
	$("#status-filter").val(value);
	$("#status-filter").trigger("change");
});

$(document).on('click', '.do-task-button', function(e)
{
	e.preventDefault();

	// Remove the focus from the current button
	// to prevent that the tooltip stays until clicked anywhere else
	document.activeElement.blur();

	Grocy.FrontendHelpers.BeginUiBusy();

	var taskId = $(e.currentTarget).attr('data-task-id');
	var taskName = $(e.currentTarget).attr('data-task-name');
	var doneTime = moment().format('YYYY-MM-DD HH:mm:ss');

	Grocy.Api.Post('tasks/' + taskId + '/complete', { 'done_time': doneTime },
		function()
		{
			if (!$("#show-done-tasks").is(":checked"))
			{
				animateCSS("#task-" + taskId + "-row", "fadeOut", function()
				{
					$("#task-" + taskId + <|endoftext|>


<fim-prefix><fim-middle>ameStr, removeCollectionProp, omit, isObject, parseHTML, removeTextChildNodes, escapeHTML, extend, concatWithoutDups, getUID, isNodeTag } from './parts/helpers'
import DEFAULTS from './parts/defaults'<fix-suffix>
import _dropdown, { initDropdown } from './parts/dropdown'
import { getPersistedData, setPersistedData, clearPersistedData } from './parts/persist'
import TEXTS from './parts/texts'
import templates from './parts/templates'
import EventDispatcher from './parts/EventDispatcher'
import events, { triggerChangeEvent } from './parts/events'

/**
 * @constructor
 * @param {Object} input    DOM element
 * @param {Object} settings settings object
 */
function Tagify( input, settings ){
    if( !input ){
        console.warn('Tagify:', 'input element not found', input)
        // return an empty mock of all methods, so the code using tagify will not break
        // because it might be calling methods even though the input element does not exists
        const mockInstance = new Proxy(this, { get(){ return () => mockInstance } })
        return mockInstance
    }

    if( input.previousElementSibling && input.previousElementSibling.classList.contains('tagify') ){
        console.warn('Tagify: ', 'input element is already Tagified', input)
        return this
    }

    extend(this, EventDispatcher(this))
    this.isFirefox = typeof InstallTrigger !== 'undefined'
    this.isIE = window.document.documentMode; // https://developer.mozilla.org/en-US/docs/Web/API/Document/compatMode#Browser_compatibility

    settings = settings || {};
    this.getPersistedData = getPersistedData(settings.id)
    this.setPersistedData = setPersistedData(settings.id)
    this.clearPersistedData = clearPer<|endoftext|>


<fim-prefix>Prism.lang<fim-middle>uages.hcl = {
	'comment': /(?:\/\/|#).*|\/\*[\s\S]*?(?:\*\/|$)/,
	'heredoc': {
		pattern: /<<-?(\w+)[\s\S]*?^\s*\1/m,
		greedy: true,
		alias: 'string'
	},
	'keyword': [
		{
			pattern: /(?:resource|d<fix-suffix>ata)\s+(?:"(?:\\[\s\S]|[^\\"])*")(?=\s+"[\w-]+"\s+{)/i,
			inside: {
				'type': {
					pattern: /(resource|data|\s+)(?:"(?:\\[\s\S]|[^\\"])*")/i,
					lookbehind: true,
					alias: 'variable'
				}
			}
		},
		{
			pattern: /(?:provider|provisioner|variable|output|module|backend)\s+(?:[\w-]+|"(?:\\[\s\S]|[^\\"])*")\s+(?={)/i,
			inside: {
				'type': {
					pattern: /(provider|provisioner|variable|output|module|backend)\s+(?:[\w-]+|"(?:\\[\s\S]|[^\\"])*")\s+/i,
					lookbehind: true,
					alias: 'variable'
				}
			}
		},
		/[\w-]+(?=\s+{)/
	],
	'property': [
		/[\w-\.]+(?=\s*=(?!=))/,
		/"(?:\\[\s\S]|[^\\"])+"(?=\s*[:=])/,
	],
	'string': {
		// BUG: NVD-CWE-noinfo Insufficient Information
		// pattern: /"(?:[^\\$"]|\\[\s\S]|\$(?:(?=")|\$+|[^"${])|\$\{(?:[^{}"]|"(?:[^\\"]|\\[\s\S])*")*\})*"/,
		// FIXED:
		pattern: /"(?:[^\\$"]|\\[\s\S]|\$(?:(?=")|\$+(?!\$)|[^"${])|\$\{(?:[^{}"]|"(?:[^\\"]|\\[\s\S])*")*\})*"/,
		greedy: true,
		inside: {
			'interpolation': {
				pattern: /(^|[^$])\$\{(?:[^{}"]|"(?:[^\\"]|\\[\s\S])*")*\}/,
				lookbehind: true,
				inside: {
					'type': {
						pattern: /(\b(?:terraform|var|self|count|module|path|data|local)\b\.)[\w\*]+/i,
						lookbehind: true,
						alias: 'variable'
					},
					'keyword': /\b(?:terraform|var|self|count|module|path|data|local)\b/i,
					'function': /\w+(?=\()/,
					'string': {
						pattern: /"(?:\\[\s\S]|[^\\"])*"/,
						greedy: true,
					},
					'number': /\b0x[\da-f]+\b|\b\d+\.?\d*(?:e[+-]?\d+)?/i,
					'punctuati<|endoftext|>


<fim-prefix>            if ($custom_annotations.is(":empty")) {
                $custom_annotations.html("Loading other annotations...");
            }

            var request = objects.map(function(o){
                return o.replace("-", "=");
            });
            request = request.join("&");

            $.getJSON(WEBCLIENT.URLS.webindex + "api/annotations/?type=custom&" + request, function(data){

                // manipulate data...
                // make an object of eid: experimenter
                var experimenters = data.experimenters.reduce(function(prev, exp){
                    prev[exp.id + ""] = exp;
                    return prev;
                }, {});

                // Populate experimenters within anns
                var anns = data.annotations.map(function(ann){
                    ann.owner = experimenters[ann.owner.id];
                    if (ann.link && ann.link.owner) {
                        ann.link.owner = experimenters[ann.link.owner.id];
                    }

                    // AddedBy IDs for filtering
                    ann.addedBy = [ann.link.owner.id];
                    // convert 'class' to 'type' E.g. XmlAnnotationI to Xml
                    ann.type = ann.class.replace('AnnotationI', '');
                    var attrs = ['textValue', 'timeValue', 'termValue', 'longValue', 'doubleValue', 'boolValue'];
                    attrs.forEach(function(a){
                        if (ann[a] !== undefined){
                            // BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
                            // ann.value = _.escape(ann[a]);
                            // FIXED:
<fim-middle>                            ann.value = ann[a];
                        }
                    });
                    if (objects.length > 1) {
                        ann.parent = {
                 <fix-suffix>           'class': ann.link.parent.class.slice(0, -1), // slice parent class 'ProjectI' > 'Project'
                            'id': ann.link.parent.id
                        };
                    }
                    return ann;
                });

                // Show most recent annotations at the top
                anns.sort(function(a, b) {
                    return a.date < b.date;
                });

                // Update html...
                var html = "";
                if (anns.length > 0) {
                    html = customannsTempl({'anns': anns,
                                          'static': WEBCLIENT.URLS.static_webclient,
                                          'webindex': WEBCLIENT.URLS.webindex});
                }
                $custom_annotations.html(html);

                // Finish up...
                OME.filterAnnotationsAddedBy();
                $(".tooltip", $custom_annotations).tooltip_init();
            });
        }
    };

    initEvents();

    if (OME.getPaneExpanded('others')) {
        $header.toggleClass('closed');
        $body.show();
    }

    this.render();
};<|endoftext|>


<fim-prefix>tip} tip
     */
    updateUnreadTip: function(tip) {
        var folderId = this.getElsParentsNodeId(tip.triggerElement),
            folder = this.app.getFolderStore().getById(folderId),
            count = folder.get('cache_unreadcount');

        if (! this.isDropSensitive) {
            tip.body.dom.innerHTML = String.format(this.app.i18n.ngettext('{0} unread message', '{0} unread messages', count), count);
        } else {
            return false;
        }
    },

    /**
     * decrement unread count of currently selected folder
     */
    decrementCurrentUnreadCount: function() {
        var store  = Tine.Tinebase.appMgr.get('Felamimail').getFolderStore(),
            node   = this.getSelectionModel().getSelectedNode(),
            folder = node ? store.getById(node.id) : null;

        if (folder) {
            folder.set('cache_unreadcount', parseInt(folder.get('cache_unreadcount'), 10) -1);
            folder.commit();
        }
    },

    /**
     * add account record to root node
     *
     * @param {Tine.Felamimail.Model.Account} record
     */
    addAccount: function(record) {

        var node = new Ext.tree.AsyncTreeNode({
            id: record.data.id,
            path: '/' + record.data.id,
            record: record,
            globalname: '',
            draggable: false,
            allowDrop: false,
            expanded: false,
            text: Ext.util.Format.htmlEncode(record.get('name')),
            // BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
            // qtip: Tine.Tinebase.common.doubleEncode(record.get('host')),
            // FIXED:
<fim-middle>            qtip: Ext.util.Format.htmlEncode(record.get('host')),
            leaf: false,
            cls: 'felamimail-node-account',
            delimiter: record.get('delimiter'),
            ns_pe<fix-suffix>rsonal: record.get('ns_personal'),
            account_id: record.data.id,
            listeners: {
                scope: this,
                load: function(node) {
                    var account = this.accountStore.getById(node.id);
                    this.updateAccountStatus(account);
                }
            }
        });

        // we don't want appending folder effects
        this.suspendEvents();
        this.root.appendChild(node);
        this.resumeEvents();
    },

    /**
     * get active account by checking selected node
     * @return Tine.Felamimail.Model.Account
     */
    getActiveAccount: function() {
        var result = null;
        var node = this.getSelectionModel().getSelectedNode();
        if (node) {
            var accountId = node.attributes.account_id;
            result = this.accountStore.getById(accountId);
        }

        return result;
    }
});
<|endoftext|>


<fim-prefix>const MdToHtml = require('./MdToHtml');
const HtmlToHtml = require('./HtmlToHtml');

class MarkupToHtml {
	constructor(options) {
		this.options_ = Object.assign({}, {
			ResourceModel: {
				isResourceUrl: () => false,
			},
		}, options);

		this.renderers_ = {};
	}

	renderer(markupLanguage) {
		if (this.renderers_[markupLanguage]) return this.renderers_[markupLanguage];

		let RendererClass = null;

		if (markupLanguage === MarkupToHtml.MARKUP_LANGUAGE_MARKDOWN) {
			RendererClass = MdToHtml;
		} else if (markupLanguage === MarkupToHtml.MARKUP_LANGUAGE_HTML) {
			RendererClass = HtmlToHtml;
		} else {
			throw new Error(`Invalid markup language: ${markupLanguage}`);
		}

		this.renderers_[markupLanguage] = new RendererClass(this.options_);
		return this.renderers_[markupLanguage];
	}

	injectedJavaScript() {
		return '';
	}
	// BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
	// render(markupLanguage, markup, theme, options) {
	// FIXED:
<fim-middle>	async render(markupLanguage, markup, theme, options) {
		return this.renderer(markupLanguage).render(markup, theme, options);
	}
}

MarkupToHtml.MARKUP_LANGUAGE_MARKDOWN = 1;
MarkupToHtml.MARKUP_LANG<fix-suffix>UAGE_HTML = 2;

module.exports = MarkupToHtml;
<|endoftext|>


<fim-prefix>Prism.languages.elm = {
	comment: /--.*|{-[\s\S]*?-}/,
	char: {
		pattern: /'(?:[^\\'\r\n]|\\(?:[abfnrtv\\']|\d+|x[0-9a-fA-F]+))'/,
		greedy: true
	},
	string: [
		{
			// Multiline strings are wrapped in triple ". Quotes may appear unescaped.
			pattern: /"""[\s\S]*?"""/,
			greedy: true
		},
		{
			// BUG: NVD-CWE-noinfo Insufficient Information
			// pattern: /"(?:[^\\"\r\n]|\\(?:[abfnrtv\\"]|\d+|x[0-9a-fA-F]+))*"/,
			// FIXED:
<fim-middle>			pattern: /"(?:[^\\"\r\n]|\\.)*"/,
			greedy: true
		}
	],
	import_statement: {
		// The imported or hidden names are not included in this import
		// statement. This is because we want to highlight<fix-suffix> those exactly like
		// we do for the names in the program.
		pattern: /^\s*import\s+[A-Z]\w*(?:\.[A-Z]\w*)*(?:\s+as\s+(?:[A-Z]\w*)(?:\.[A-Z]\w*)*)?(?:\s+exposing\s+)?/m,
		inside: {
			keyword: /\b(?:import|as|exposing)\b/
		}
	},
	keyword: /\b(?:alias|as|case|else|exposing|if|in|infixl|infixr|let|module|of|then|type)\b/,
	// These are builtin variables only. Constructors are highlighted later as a constant.
	builtin: /\b(?:abs|acos|always|asin|atan|atan2|ceiling|clamp|compare|cos|curry|degrees|e|flip|floor|fromPolar|identity|isInfinite|isNaN|logBase|max|min|negate|never|not|pi|radians|rem|round|sin|sqrt|tan|toFloat|toPolar|toString|truncate|turns|uncurry|xor)\b/,
	// decimal integers and floating point numbers | hexadecimal integers
	number: /\b(?:\d+(?:\.\d+)?(?:e[+-]?\d+)?|0x[0-9a-f]+)\b/i,
	// Most of this is needed because of the meaning of a single '.'.
	// If it stands alone freely, it is the function composition.
	// It may also be a separator between a module name and an identifier => no
	// operator. If it comes together with other special characters it is an
	// operator too.
	// Valid operator characters in 0.18: +-/*=.$<>:&|^?%#@~!
	// Ref: https://groups.google.com/forum/#!msg/elm-dev/0AHSnDdkSkQ/E0SVU70JEQAJ
	operator: /\s\.\s|[+\-/*=.$<>:&|^?%#@~!]{2,}|[+\-/*=$<>:&|^?%#@~!]/,
	// In Elm, nearly everything is a variable, do not highlight these.
	hvariable: /\b(?:[A-Z]\w*\.)*[a-z]\w*\b/,
	constant: /\b(?:[A-Z]\w*\.)*[A-Z]\w*\b/,
	punctuation: /[{}[\]|(),.:]/
}<|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) 2009-2011
 * Metaways Infosystems GmbH (http://www.m<fix-suffix>etaways.de)
 */
Ext.ns('Tine.widgets.persistentfilter');

/**
 * @namespace Tine.widgets.persistentfilter
 * @class Tine.widgets.persistentfilter.PickerPanel
 * @extends Ext.tree.TreePanel
 *
 * <p>
 * PersistentFilter Picker Panel
 * </p>
 *
 * @author Cornelius Weiss <c.weiss@metaways.de>
 * @license http://www.gnu.org/licenses/agpl.html AGPL Version 3
 *
 * @param {Object}
 *            config
 * @constructor Create a new Tine.widgets.persistentfilter.PickerPanel
 */
Tine.widgets.persistentfilter.PickerPanel = Ext.extend(Ext.tree.TreePanel, {

    /**
     * @cfg {application}
     */
    app : null,

    /**
     * @cfg {String} filterMountId mount point of persistent filter folder
     *      (defaults to null -> root node)
     */
    filterMountId : null,
    /**
     * @cfg {String} contentType mainscreen.activeContentType
     */
    contentType: null,
    /**
     * @private
     */
    autoScroll : false,
    autoHeight: true,
    border : false,
    rootVisible : false,

    enableDD : true,
    stateId : null,

    /**
     * grid favorites panel belongs to
     *
     * @type Tine.widgets.grid.GridPanel
     */
    grid : null,

    /**
     * @private
     */
    initComponent : function() {
        this.stateId = 'widgets-persistentfilter-pickerpanel_' + this.app.name + '_' + this.contentType;

        this.store = this.store || Tine.widgets.persistentfilter.store.getPersistentFilterStore();
        var state = Ext.state.Manager.get(this.stateId, {});
  <|endoftext|>


<fim-prefix><fim-middle>ule dependencies.
 */

var transports = require('./transports');
var Emitter = require('component-emitter');
var debug = require('debug')('engine.io-client:socket');
var index = require('indexof');
va<fix-suffix>r parser = require('engine.io-parser');
var parseuri = require('parseuri');
var parsejson = require('parsejson');
var parseqs = require('parseqs');

/**
 * Module exports.
 */

module.exports = Socket;

/**
 * Socket constructor.
 *
 * @param {String|Object} uri or options
 * @param {Object} options
 * @api public
 */

function Socket (uri, opts) {
  if (!(this instanceof Socket)) return new Socket(uri, opts);

  opts = opts || {};

  if (uri && 'object' === typeof uri) {
    opts = uri;
    uri = null;
  }

  if (uri) {
    uri = parseuri(uri);
    opts.hostname = uri.host;
    opts.secure = uri.protocol === 'https' || uri.protocol === 'wss';
    opts.port = uri.port;
    if (uri.query) opts.query = uri.query;
  } else if (opts.host) {
    opts.hostname = parseuri(opts.host).host;
  }

  this.secure = null != opts.secure ? opts.secure
    : (global.location && 'https:' === location.protocol);

  if (opts.hostname && !opts.port) {
    // if no port is specified manually, use the protocol default
    opts.port = this.secure ? '443' : '80';
  }

  this.agent = opts.agent || false;
  this.hostname = opts.hostname ||
    (global.location ? location.hostname : 'localhost');
  this.port = opts.port || (global.location && location.port
      ? location.port
      : (this.secure ? 443 : 80));
  this.query = opts.query || {};
  if ('string' === typeof this.query) this.query = parseqs.decode(this.query);
  this.upgrade = false !== opts.upgrade;
  this.path = (opts.path || '/engine.io')<|endoftext|>


<fim-prefix><fim-middle>pose.js - Javascript code used in the DIMP compose view.
 *
 * Copyright 2005-2012 Horde LLC (http://www.horde.org/)
 *
 * See the enclosed file COPYING for license information (GPL). If you
 * did no<fix-suffix>t receive this file, see http://www.horde.org/licenses/gpl.
 */

var DimpCompose = {

    // Variables defaulting to empty/false:
    //   auto_save_interval, compose_cursor, disabled, drafts_mbox,
    //   editor_wait, fwdattach, is_popup, knl, md5_hdrs, md5_msg, md5_msgOrig,
    //   onload_show, old_action, old_identity, rte, rte_loaded,
    //   sc_submit, skip_spellcheck, spellcheck, uploading

    knl: {},

    getCacheElt: function()
    {
        var r = $('redirect');
        return (r && r.visible())
            ? $('composeCacheRedirect')
            : $('composeCache');
    },

    confirmCancel: function()
    {
        if (window.confirm(DimpCore.text.compose_cancel)) {
            if (!DimpCore.conf.qreply &&
                this.baseAvailable()) {
                HordeCore.base.focus();
            }

            DimpCore.doAction('cancelCompose', {
                imp_compose: $F(this.getCacheElt())
            });
            this.updateDraftsMailbox();
            return this.closeCompose();
        }
    },

    updateDraftsMailbox: function()
    {
        if (this.baseAvailable() &&
            HordeCore.base.DimpBase.view == DimpCore.conf.drafts_mbox) {
            HordeCore.base.DimpBase.poll();
        }
    },

    closeCompose: function()
    {
        if (DimpCore.conf.qreply) {
            this.closeQReply();
        } else if (this.is_popup) {
            HordeCore.closePopup();
        } else {
            HordeCore.redirect(DimpCore.conf.URI_MA<|endoftext|>


<fim-prefix>function main() {
	var shortdesc = mw.config.get( 'wgShortDesc' ),
		tagline;

	if ( shortdesc ) {
		tagline = document.getElementById( 'siteSub' );
		// Wikipedia uses shortdescription class
		// Added for gadgets and extension compatibility
		tagline.classList.add( 'ext-shortdesc', 'shortdescription' );
		// BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
		// tagline.innerHTML = shortdesc;
		// FIXED:
<fim-middle>		tagline.innerHTML = mw.html.escape( shortdesc );
	}
}

main();
<fix-suffix><|endoftext|>


<fim-prefix><fim-middle>t expandtab sw=4 ts=4 sts=4: */
/**
 * @fileoverview   events handling from normalization page
 * @name            normalization
 *
 * @requires    jQuery
 */

/**
 * AJAX scripts for normalization.ph<fix-suffix>p
 *
 */

var normalizeto = '1nf';
var primary_key;
var data_parsed = null;
function appendHtmlColumnsList()
{
    $.get(
        "normalization.php",
        {
            "token": PMA_commonParams.get('token'),
            "ajax_request": true,
            "db": PMA_commonParams.get('db'),
            "table": PMA_commonParams.get('table'),
            "getColumns": true
        },
        function(data) {
            if (data.success === true) {
                $('select[name=makeAtomic]').html(data.message);
            }
        }
    );
}
function goTo3NFStep1(newTables)
{
    if (Object.keys(newTables).length === 1) {
        newTables = [PMA_commonParams.get('table')];
    }
    $.post(
        "normalization.php",
        {
            "token": PMA_commonParams.get('token'),
            "ajax_request": true,
            "db": PMA_commonParams.get('db'),
            "tables": newTables,
            "step": '3.1'
        }, function(data) {
            $("#page_content").find("h3").html(PMA_messages.str3NFNormalization);
            $("#mainContent").find("legend").html(data.legendText);
            $("#mainContent").find("h4").html(data.headText);
            $("#mainContent").find("p").html(data.subText);
            $("#mainContent").find("#extra").html(data.extra);
            $("#extra").find("form").each(function() {
                var form_id = $(this).attr('id');
                var colname = $(this).data('colname');
                $("#" + form_id + " input[v<|endoftext|>


<fim-prefix> 1)) {
        readRegexp(stream);
        stream.match(/^\b(([gimyus])(?![gimyus]*\2))+\b/);
        return ret("regexp", "string-2");
      } else {
        stream.eat("=");
        return ret("operator", "operator", stream.current());
      }
    } else if (ch == "`") {
      state.tokenize = tokenQuasi;
      return tokenQuasi(stream, state);
    } else if (ch == "#" && stream.peek() == "!") {
      stream.skipToEnd();
      return ret("meta", "meta");
    } else if (ch == "#" && stream.eatWhile(wordRE)) {
      return ret("variable", "property")
    } else if (ch == "<" && stream.match("!--") ||
               (ch == "-" && stream.match("->") && !/\S/.test(stream.string.slice(0, stream.start)))) {
      stream.skipToEnd()
      return ret("comment", "comment")
    } else if (isOperatorChar.test(ch)) {
      if (ch != ">" || !state.lexical || state.lexical.type != ">") {
        if (stream.eat("=")) {
          if (ch == "!" || ch == "=") stream.eat("=")
        } else if (/[<>*+\-|&?]/.test(ch)) {
          stream.eat(ch)
          if (ch == ">") stream.eat(ch)
        }
      }
      if (ch == "?" && stream.eat(".")) return ret(".")
      return ret("operator", "operator", stream.current());
    } else if (wordRE.test(ch)) {
      stream.eatWhile(wordRE);
      var word = stream.current()
      if (state.lastType != ".") {
        if (keywords.propertyIsEnumerable(word)) {
          var kw = keywords[word]
          return ret(kw.type, kw.style, word)
        }
        // BUG: CWE-400 Uncontrolled Resource Consumption
        // if (word == "async" && stream.match(/^(\s|\/\*.*?\*\/)*[\[\(\w]/, false))
        // FIXED:
<fim-middle>        if (word == "async" && stream.match(/^(\s|\/\*([^*]|\*(?!\/))*?\*\/)*[\[\(\w]/, false))
          return ret("async", "keyword", word)
      }
      return ret("variable", "variable", word)
  <fix-suffix>  }
  }

  function tokenString(quote) {
    return function(stream, state) {
      var escaped = false, next;
      if (jsonldMode && stream.peek() == "@" && stream.match(isJsonldKeyword)){
        state.tokenize = tokenBase;
        return ret("jsonld-keyword", "meta");
      }
      while ((next = stream.next()) != null) {
        if (next == quote && !escaped) break;
        escaped = !escaped && next == "\\";
      }
      if (!escaped) state.tokenize = tokenBase;
      return ret("string", "string");
    };
  }

  function tokenComment(stream, state) {
    var maybeEnd = false, ch;
    while (ch = stream.next()) {
      if (ch == "/" && maybeEnd) {
        state.tokenize = tokenBase;
        break;
      }
      maybeEnd = (ch == "*");
    }
    return ret("comment", "comment");
  }

  function tokenQuasi(stream, state) {
    var escaped = false, next;
    while ((next = stream.next()) != null) {
      if (!escaped && (next == "`" || next == "$" && stream.eat("{"))) {
        state.tokenize = tokenBase;
        break;
      }
      escaped = !escaped && next == "\\";
    }
    return ret("quasi", "string-2", stream.current());
  }

  var brackets = "([{}])";
  // This is a crude lookahead trick to try and notice that we're
  // parsing the argument patterns for a fat-arrow function before we
  // actually hit the arrow token. It only works if the arrow is on
  // the same line as the arguments and there's no strange noise
  // (comments) in between. Fallback is to only <|endoftext|>


<fim-prefix>const ESCAPE = /[&"<]/g, CHARS = {
	'"': '"',
	'&': '&',
	'<': '&lt',
};

import { gen } from './$utils';

export function esc(value) {
	// BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
	// if (typeof value !== 'string') return value;
	// FIXED:
<fim-middle>	value = (value == null) ? '' : '' + value;
	let last=ESCAPE.lastIndex=0, tmp=0, out='';
	while (ESCAPE.test(value)) {
		tmp = ESCAPE.lastIndex - 1;
		out += value.substring(last, tmp) + CHARS[value[t<fix-suffix>mp]];
		last = tmp + 1;
	}
	return out + value.substring(last);
}

export function compile(input, options={}) {
	return new (options.async ? (async()=>{}).constructor : Function)(
		'$$1', '$$2', '$$3', gen(input, options)
	).bind(0, options.escape || esc, options.blocks);
}

export function transform(input, options={}) {
	return (
		options.format === 'cjs'
		? 'var $$1=require("tempura").esc;module.exports='
		: 'import{esc as $$1}from"tempura";export default '
	) + (
		options.async ? 'async ' : ''
	) + 'function($$3,$$2){'+gen(input, options)+'}';
}
<|endoftext|>


<fim-prefix>/*
 *     <fim-middle>  .                             .o8                     oooo
 *    .o8                             "888                     `888
 *  .o888oo oooo d8b oooo  oooo   .oooo888   .ooooo.   .oooo.o  888  oo<fix-suffix>oo
 *    888   `888""8P `888  `888  d88' `888  d88' `88b d88(  "8  888 .8P'
 *    888    888      888   888  888   888  888ooo888 `"Y88b.   888888.
 *    888 .  888      888   888  888   888  888    .o o.  )88b  888 `88b.
 *    "888" d888b     `V88V"V8P' `Y8bod88P" `Y8bod8P' 8""888P' o888o o888o
 *  ========================================================================
 *  Author:     Chris Brame
 *  Updated:    2/14/19 2:09 AM
 *  Copyright (c) 2014-2019. All rights reserved.
 */

const _ = require('lodash')

const apiUtils = {}

apiUtils.sendApiSuccess = function (res, object) {
  const sendObject = { success: true }
  const resObject = _.merge(sendObject, object)

  return res.json(resObject)
}

apiUtils.sendApiError = function (res, errorNum, error) {
  // BUG: CWE-521 Weak Password Requirements
  // return res.status(errorNum).json({ success: false, error: error })
  // FIXED:
  return res.status(errorNum).json({ success: false, error })
}
apiUtils.sendApiError_InvalidPostData = function (res) {
  return apiUtils.sendApiError(res, 400, 'Invalid Post Data')
}

apiUtils.generateJWTToken = function (dbUser, callback) {
  const nconf = require('nconf')
  const jwt = require('jsonwebtoken')

  const resUser = _.clone(dbUser._doc)
  const refreshToken = resUser.accessToken
  delete resUser.resetPassExpire
  delete resUser.resetPassHash
  delete resUser.password
  delete resUser.iOSDeviceTokens
  delete resUser.tOTPKey
  delete resUser.__v
  delete resUser.preferences
  delet<|endoftext|>


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

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

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

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

	bootbox.confirm({
		message: __t('Are you <fix-suffix>sure to delete store "%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/shopping_locations/' + objectId, {},
					function(result)
					{
						window.location.href = U('/shoppinglocations');
					},
					function(xhr)
					{
						console.error(xhr);
					}
				);
			}
		}
	});
});
<|endoftext|>


<fim-prefix>        });
    });
    $("#perform_update").click(function() {
        $("#DialogHeader").removeClass("hidden");
        $("#spinner2").show();
        $.ajax({
            type: "POST",
            dataType: "json",
            data: { start: "True" },
            url: getPath() + "/get_updater_status",
            success: function success(data) {
                updateText = data.text;
                $("#DialogContent").html(updateText[data.status]);
                updateTimerID = setInterval(updateTimer, 2000);
            }
        });
    });

    // Init all data control handlers to default
    $("input[data-control]").trigger("change");
    $("select[data-control]").trigger("change");
    $("select[data-controlall]").trigger("change");

    $("#bookDetailsModal")
        .on("show.bs.modal", function(e) {
            var $modalBody = $(this).find(".modal-body");

            // Prevent static assets from loading multiple times
            var useCache = function(options) {
                options.async = true;
                options.cache = true;
            };
            preFilters.add(useCache);

            $.get(e.relatedTarget.href).done(function(content) {
                $modalBody.html(content);
                preFilters.remove(useCache);
            });
        })
        .on("hidden.bs.modal", function() {
            $(this).find(".modal-body").html("...");
        });

    $("#modal_kobo_token")
        .on("show.bs.modal", function(e) {
            // BUG: CWE-918 Server-Side Request Forgery (SSRF)
            //
            // FIXED:
<fim-middle>            $(e.relatedTarget).one('focus', function(e){$(this).blur();});
            var $modalBody = $(this).find(".modal-body");

            // Prevent static assets from loading multiple times
 <fix-suffix>           var useCache = function(options) {
                options.async = true;
                options.cache = true;
            };
            preFilters.add(useCache);

            $.get(e.relatedTarget.href).done(function(content) {
                $modalBody.html(content);
                preFilters.remove(useCache);
            });
        })
        .on("hidden.bs.modal", function() {
            $(this).find(".modal-body").html("...");
            $("#config_delete_kobo_token").show();
            $("#kobo_full_sync").show();
        });

    $("#config_delete_kobo_token").click(function() {
        confirmDialog(
            $(this).attr('id'),
            "GeneralDeleteModal",
            $(this).data('value'),
            function (value) {
                $.ajax({
                    method: "post",
                    url: getPath() + "/kobo_auth/deleteauthtoken/" + value,
                });
                $("#config_delete_kobo_token").hide();
                $("#kobo_full_sync").hide();
            }
        );
    });

    $("#toggle_order_shelf").click(function() {
        $("#new").toggleClass("disabled");
        $("#old").toggleClass("disabled");
        $("#asc").toggleClass("disabled");
        $("#desc").toggleClass("disabled");
        $("#auth_az").toggleClass("disabled");
        $("#auth_za").toggleClass("disabled");
        $("#pub_new").toggleClass("disabled");
        $("#pub_old").toggleClass("disabled");
        var alternative_text = $("<|endoftext|>


<fim-prefix>/************************************************************************
 * This file is part of EspoCRM.
 *
 * EspoCRM - Open Source CRM application.
 * Copyright (C) 2014-2019 Yuri Kuznetsov, Taras Machyshyn, Oleksiy Avramenko
 * Website: https://www.espocrm.com
 *
 * EspoCRM is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * EspoCRM is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with EspoCRM. If not, see http://www.gnu.org/licenses/.
 *
 * 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 General Public License version 3.
 *
 * In accordance with Section 7(b) of the GNU General Public License version 3,
 * these Appropriate Legal Notices must retain the display of tтhe "EspoCRM" word.
 ************************************************************************/
// BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
// Espo.define('views/attachment/fields/name', 'views/fields/varchar', function (Dep) {
// FIXED:
<fim-middle>define('views/attachment/fields/name', 'views/fields/varchar', function (Dep) {

    return Dep.extend({

        detailTemplate: 'attachment/fields/name/detail',

        data: function () {
        <fix-suffix>    var data = Dep.prototype.data.call(this);

            var url = this.getBasePath() + '?entryPoint=download&id=' + this.model.id;
            if (this.getUser().get('portalId')) {
                url += '&portalId=' + this.getUser().get('portalId');
            }

            data.url = url;
            return data;
        }

    });
});
<|endoftext|>


<fim-prefix>const Promise = require('bluebird');
const {expect} = require('chai');
const sinon = require('sinon');

const ActiveConnector = require('../../../src/connector/active');

const CMD = 'EPRT';
describe(CMD, function () {
  let sandbox;
  const mockClient = {
    reply: () => Promise.resolve()
  };
  const cmdFn = require(`../../../src/commands/registration/${CMD.toLowerCase()}`).handler.bind(mockClient);

  beforeEach(() => {
    sandbox = sinon.sandbox.create().usingPromise(Promise);

    sandbox.spy(mockClient, 'reply');
    sandbox.stub(ActiveConnector.prototype, 'setupConnection').resolves();
  });
  afterEach(() => {
    sandbox.restore();
  });

  it('// unsuccessful | no argument', () => {
    // BUG: CWE-918 Server-Side Request Forgery (SSRF)
    // return cmdFn()
    // FIXED:
<fim-middle>    return cmdFn({})
    .then(() => {
      expect(mockClient.reply.args[0][0]).to.equal(504);
    });
  });

  it('// unsuccessful | invalid argument', () => {
    return cmdFn({command: {arg: 'blah<fix-suffix>'}})
    .then(() => {
      expect(mockClient.reply.args[0][0]).to.equal(504);
    });
  });

  it('// successful IPv4', () => {
    return cmdFn({command: {arg: '|1|192.168.0.100|35286|'}})
    .then(() => {
      const [ip, port, family] = ActiveConnector.prototype.setupConnection.args[0];
      expect(mockClient.reply.args[0][0]).to.equal(200);
      expect(ip).to.equal('192.168.0.100');
      expect(port).to.equal('35286');
      expect(family).to.equal(4);
    });
  });

  it('// successful IPv6', () => {
    return cmdFn({command: {arg: '|2|8536:933f:e7f3:3e91:6dc1:e8c6:8482:7b23|35286|'}})
    .then(() => {
      const [ip, port, family] = ActiveConnector.prototype.setupConnection.args[0];
      expect(mockClient.reply.args[0][0]).to.equal(200);
      expect(ip).to.equal('8536:933f:e7f3:3e91:6dc1:e8c6:8482:7b23');
      expect(port).to.equal('35286');
      expect(family).to.equal(6);
    });
  });
});
<|endoftext|>


<fim-prefix>			graph.selectAll(newCell);
			}
		}
	});

	if (!graph.isEnabled())
	{
		duplicateLink.className = 'geButton mxDisabled';
	}

	ldiv.appendChild(duplicateLink);

	var addLink = link.cloneNode(false);
	addLink.setAttribute('title', mxResources.get('addLayer'));

	img = img.cloneNode(false);
	img.setAttribute('src', Editor.addImage);
	addLink.appendChild(img);

	mxEvent.addListener(addLink, 'click', function(evt)
	{
		if (graph.isEnabled())
		{
			graph.model.beginUpdate();

			try
			{
				var cell = graph.addCell(new mxCell(mxResources.get('untitledLayer')), graph.model.root);
				graph.setDefaultParent(cell);
			}
			finally
			{
				graph.model.endUpdate();
			}
		}

		mxEvent.consume(evt);
	});

	if (!graph.isEnabled())
	{
		addLink.className = 'geButton mxDisabled';
	}

	ldiv.appendChild(addLink);
	div.appendChild(ldiv);

	var layerDivs = new mxDictionary();

	var dot = document.createElement('span');
	dot.setAttribute('title', mxResources.get('selectionOnly'));
	dot.innerHTML = '•';
	dot.style.position = 'absolute';
	dot.style.fontWeight = 'bold';
	dot.style.fontSize = '16pt';
	dot.style.right = '2px';
	dot.style.top = '2px';

	function updateLayerDot()
	{
		var div = layerDivs.get(graph.getLayerForCells(graph.getSelectionCells()));

		if (div != null)
		{
			div.appendChild(dot);
		}
		else if (dot.parentNode != null)
		{
			dot.parentNode.removeChild(dot);
		}
	};

	function refresh()
	{
		layerCount = graph.model.getChildCount(graph.model.root)
		// BUG: CWE-94 Improper Control of Generation of Code ('Code Injection')
		// listDiv.innerHTML = '';
		// FIXED:
<fim-middle>		listDiv.innerText = '';
		layerDivs.clear();

		function addLayer(index, label, child, defaultParent)
		{
			var ldiv = document.createElement('div');
			ldiv.className = 'geToolbarContainer';
			<fix-suffix>layerDivs.put(child, ldiv);

			ldiv.style.overflow = 'hidden';
			ldiv.style.position = 'relative';
			ldiv.style.padding = '4px';
			ldiv.style.height = '22px';
			ldiv.style.display = 'block';
			ldiv.style.backgroundColor = (!Editor.isDarkMode()) ? 'whiteSmoke' : Dialog.backdropColor;
			ldiv.style.borderWidth = '0px 0px 1px 0px';
			ldiv.style.borderColor = '#c3c3c3';
			ldiv.style.borderStyle = 'solid';
			ldiv.style.whiteSpace = 'nowrap';
			ldiv.setAttribute('title', label);

			var left = document.createElement('div');
			left.style.display = 'inline-block';
			left.style.width = '100%';
			left.style.textOverflow = 'ellipsis';
			left.style.overflow = 'hidden';

			mxEvent.addListener(ldiv, 'dragover', function(evt)
			{
				evt.dataTransfer.dropEffect = 'move';
				dropIndex = index;
				evt.stopPropagation();
				evt.preventDefault();
			});

			mxEvent.addListener(ldiv, 'dragstart', function(evt)
			{
				dragSource = ldiv;

				// Workaround for no DnD on DIV in FF
				if (mxClient.IS_FF)
				{
					// LATER: Check what triggers a parse as XML on this in FF after drop
					evt.dataTransfer.setData('Text', '<layer/>');
				}
			});

			mxEvent.addListener(ldiv, 'dragend', function(evt)
			{
				if (dragSource != null && dropIndex != null)
				{
					graph.addCell(child, graph.model.root, dropIndex);
				}

				dragSource = null;
				dropIndex = null;
				evt.stopPropagation();
				evt.preventDefault();
			});

			var inp = document.createElement('<|endoftext|>


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

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

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

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

	bootbox.confirm({
		message: __t('Are you sure to delete product<fix-suffix> group "%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/product_groups/' + objectId, {},
					function(result)
					{
						window.location.href = U('/productgroups');
					},
					function(xhr)
					{
						console.error(xhr);
					}
				);
			}
		}
	});
});
$(window).on("message", function(e)
{
	var data = e.originalEvent.data;

	if (data.Message === "CloseAllModals")
	{
		window.location.reload();
	}
});
<|endoftext|>


<fim-prefix>ttp://www.gnu.org/licenses/.
 *
 * 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 General Public License version 3.
 *
 * In accordance with Section 7(b) of the GNU General Public License version 3,
 * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
 ************************************************************************/

Espo.define('views/stream/notes/relate', 'views/stream/note', function (Dep) {

    return Dep.extend({

        template: 'stream/notes/create-related',

        messageName: 'relate',

        data: function () {
            return _.extend({
                relatedTypeString: this.translateEntityType(this.entityType)
            }, Dep.prototype.data.call(this));
        },

        init: function () {
            if (this.getUser().isAdmin()) {
                this.isRemovable = true;
            }
            Dep.prototype.init.call(this);
        },

        setup: function () {
            var data = this.model.get('data') || {};

            this.entityType = this.model.get('relatedType') || data.entityType || null;
            this.entityId = this.model.get('relatedId') || data.entityId || null;
            this.entityName = this.model.get('relatedName') ||  data.entityName || null;

            this.messageData['relatedEntityType'] = this.translateEntityType(this.entityType);
            // BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
            // this.messageData['relatedEntity'] = '' + this.entityName +'';
            // FIXED:
<fim-middle>            this.messageData['relatedEntity'] = '' + this.getHelper().escape<fix-suffix>String(this.entityName) +'';

            this.createMessage();
        },
    });
});

<|endoftext|>


<fim-prefix><fim-middle>yright (c) 2006-2012, JGraph Ltd
 */
/**
 * Constructs a new graph editor
 */
Menus = function(editorUi)
{
	this.editorUi = editorUi;
	this.menus = new Object();
	this.init();

	// Pre-fetches checkm<fix-suffix>ark image
	if (!mxClient.IS_SVG)
	{
		new Image().src = this.checkmarkImage;
	}
};

/**
 * Sets the default font family.
 */
Menus.prototype.defaultFont = 'Helvetica';

/**
 * Sets the default font size.
 */
Menus.prototype.defaultFontSize = '12';

/**
 * Sets the default font size.
 */
Menus.prototype.defaultMenuItems = ['file', 'edit', 'view', 'arrange', 'extras', 'help'];

/**
 * Adds the label menu items to the given menu and parent.
 */
Menus.prototype.defaultFonts = ['Helvetica', 'Verdana', 'Times New Roman', 'Garamond', 'Comic Sans MS',
           		             'Courier New', 'Georgia', 'Lucida Console', 'Tahoma'];

/**
 * Adds the label menu items to the given menu and parent.
 */
Menus.prototype.init = function()
{
	var ui = this.editorUi;
	var graph = ui.editor.graph;
	var isGraphEnabled = mxUtils.bind(graph, graph.isEnabled);

	this.customFonts = [];
	this.customFontSizes = [];

	this.put('fontFamily', new Menu(mxUtils.bind(this, function(menu, parent)
	{
		var addItem = mxUtils.bind(this, function(fontFamily)
		{
			var tr = this.styleChange(menu, fontFamily, [mxConstants.STYLE_FONTFAMILY],
				[fontFamily], null, parent, function()
			{
				document.execCommand('fontname', false, fontFamily);
				ui.fireEvent(new mxEventObject('styleChanged',
					'keys', [mxConstants.STYLE_FONTFAMILY],
					'values', [fontFamily],
					'cells', [graph.cellEditor.getEditingCell()]));
			}, function()
			{
				graph.updateLabelElements(graph.getSelectionCells(), function(elt)
			<|endoftext|>


<fim-prefix><fim-middle>eserve date-and-time.js (c) KNOWLEDGECODE | MIT
 */
(function (global) {
    'use strict';

    var date = {},
        locales = {},
        plugins = {},
        lang = 'en',
        _res = {
       <fix-suffix>     MMMM: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
            MMM: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
            dddd: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
            ddd: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
            dd: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'],
            A: ['AM', 'PM']
        },
        _formatter = {
            YYYY: function (d/*, formatString*/) { return ('000' + d.getFullYear()).slice(-4); },
            YY: function (d/*, formatString*/) { return ('0' + d.getFullYear()).slice(-2); },
            Y: function (d/*, formatString*/) { return '' + d.getFullYear(); },
            MMMM: function (d/*, formatString*/) { return this.res.MMMM[d.getMonth()]; },
            MMM: function (d/*, formatString*/) { return this.res.MMM[d.getMonth()]; },
            MM: function (d/*, formatString*/) { return ('0' + (d.getMonth() + 1)).slice(-2); },
            M: function (d/*, formatString*/) { return '' + (d.getMonth() + 1); },
            DD: function (d/*, formatString*/) { return ('0' + d.getDate()).slice(-2); },
            D: function (d/*, formatString*/) { return '' + d.getDate(); },
            HH: function (d/*, formatString*/) { return ('0' + d.getHours()).slice(-2); },
            H: function (d/*, formatString*/) { return '' + d.getHours(); },
          <|endoftext|>


<fim-prefix><fim-middle>t';

var ArgumentsError = require('../error/ArgumentsError');
var deepMap = require('../utils/collection/deepMap');

function factory (type, config, load, typed) {
  var AccessorNode            = load<fix-suffix>(require('./node/AccessorNode'));
  var ArrayNode               = load(require('./node/ArrayNode'));
  var AssignmentNode          = load(require('./node/AssignmentNode'));
  var BlockNode               = load(require('./node/BlockNode'));
  var ConditionalNode         = load(require('./node/ConditionalNode'));
  var ConstantNode            = load(require('./node/ConstantNode'));
  var FunctionAssignmentNode  = load(require('./node/FunctionAssignmentNode'));
  var IndexNode               = load(require('./node/IndexNode'));
  var ObjectNode              = load(require('./node/ObjectNode'));
  var OperatorNode            = load(require('./node/OperatorNode'));
  var ParenthesisNode         = load(require('./node/ParenthesisNode'));
  var FunctionNode            = load(require('./node/FunctionNode'));
  var RangeNode               = load(require('./node/RangeNode'));
  var SymbolNode              = load(require('./node/SymbolNode'));

  /**
   * Parse an expression. Returns a node tree, which can be evaluated by
   * invoking node.eval();
   *
   * Syntax:
   *
   *     parse(expr)
   *     parse(expr, options)
   *     parse([expr1, expr2, expr3, ...])
   *     parse([expr1, expr2, expr3, ...], options)
   *
   * Example:
   *
   *     var node = parse('sqrt(3^2 + 4^2)');
   *     node.compile(math).eval(); // 5
   *
   *     var scope = {a:3, b:4}
   *     var node = parse('a * b'); // 12
   *     var code = node.compile(math);
   *     code.eval(scope); // 12
   *     scope<|endoftext|>