language
stringclasses 3
values | text
stringlengths 543
3.57k
|
---|---|
javascript | <fim-prefix>var attenderName = a.getName();
var attenderName = Tine.Calendar.AttendeeGridPanel.prototype.renderAttenderName.call(Tine.Calendar.AttendeeGridPanel.prototype, busyAttender.get('user_id'), false, busyAttender);
busyAttendeeHTML += '<div class="cal-conflict-attendername">' + attenderName + '</div>';
var eventInfos = [];
Ext.each(conflictEvents[busyAttender.id], function(fbInfo) {
var format = 'H:i';
var eventInfo;
var dateFormat = Ext.form.DateField.prototype.format;
if (event.get('dtstart').format(dateFormat) != event.get('dtend').format(dateFormat) ||
Date.parseDate(fbInfo.dtstart, Date.patterns.ISO8601Long).format(dateFormat) != Date.parseDate(fbInfo.dtend, Date.patterns.ISO8601Long).format(dateFormat))
{
eventInfo = Date.parseDate(fbInfo.dtstart, Date.patterns.ISO8601Long).format(dateFormat + ' ' + format) + ' - ' + Date.parseDate(fbInfo.dtend, Date.patterns.ISO8601Long).format(dateFormat + ' ' + format);
} else {
eventInfo = Date.parseDate(fbInfo.dtstart, Date.patterns.ISO8601Long).format(dateFormat + ' ' + format) + ' - ' + Date.parseDate(fbInfo.dtend, Date.patterns.ISO8601Long).format(format);
}
if (fbInfo.event && fbInfo.event.summary) {
// BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
// eventInfo += ' : ' + fbInfo.event.summary;
// FIXED:
<fim-middle> eventInfo += ' : ' + Ext.util.Format.htmlEncode(fbInfo.event.summary);
}
if (fbInfo.type == 'BUSY_UNAVAILABLE') {
<fix-suffix> denyIgnore = true;
eventInfo += '<span class="cal-conflict-eventinfos-unavailable">' + this.app.i18n._('Unavailable') + '</span>';
}
eventInfos.push(eventInfo);
}, this);
busyAttendeeHTML += '<div class="cal-conflict-eventinfos">' + eventInfos.join(', <br />') + '</div>';
}, this);
this.conflictConfirmWin = Tine.widgets.dialog.MultiOptionsDialog.openWindow({
modal: true,
allowCancel: false,
height: 180 + 15*error.freebusyinfo.length,
title: this.app.i18n._('Scheduling Conflict'),
questionText: '<div class = "cal-conflict-heading">' +
this.app.i18n._('The following attendee are busy at the requested time:') +
'</div>' +
busyAttendeeHTML,
options: [
{text: this.app.i18n._('Ignore Conflict'), name: 'ignore', disabled: denyIgnore},
{text: this.app.i18n._('Edit Event'), name: 'edit', checked: true},
{text: this.app.i18n._('Cancel this action'), name: 'cancel'}
],
scope: this,
handler: function(option) {
var panel = this.getCalendarPanel(this.activeView),
store = panel.getStore();
<|endoftext|> |
javascript | <fim-prefix>/* putil-m<fim-middle>erge
------------------------
(c) 2017-present Panates
This file may be freely distributed under the MIT license.
*/
const isObjectOrClass = (v) => v && (
(typeof v === 'object' && !Array.isA<fix-suffix>rray(v)) ||
(typeof v === 'function' && v.prototype && v.prototype.constructor));
/**
*
* @param {Object} target
* @param {Object} source
* @param {Object} options
* @param {boolean} [options.deep]
* @param {boolean} [options.clone]
* @param {boolean} [options.combine]
* @param {boolean} [options.descriptor]
* @param {Function} [options.filter]
* @param {Function|Boolean} [options.arrayMerge]
* @return {Object}
*/
function merge(target, source, options = {}) {
if (!isObjectOrClass(target))
throw new TypeError('Property "target" requires object type');
if (!source)
return target;
if (!isObjectOrClass(source))
throw new TypeError('Property "source" requires object type');
if (source === target) return target;
const keys = Object.getOwnPropertyNames(source);
keys.push(...Object.getOwnPropertySymbols(source));
for (const key of keys) {
// BUG: CWE-1321 Improperly Controlled Modification of Object Prototype Attributes ('Prototype Pollution')
// if (key === '__proto__')
// FIXED:
if (key === '__proto__' || key === 'constructor')
continue;
if (options.filter && !options.filter(source, key))
continue;
if ((options.combine || options.adjunct) && target.hasOwnProperty(key))
continue;
const descriptor = Object.getOwnPropertyDescriptor(source, key);
if (options.descriptor && (descriptor.get || descriptor.set)) {
Object.defineProperty(target, key, descriptor);
continue;
}
le<|endoftext|> |
javascript | <fim-prefix>Prism.languages.eiffel = {
'comment': /--.*/,
'string': [
// Aligned-verbatim-strings
{
pattern: /"([^[]*)\[[\s\S]*?\]\1"/,
greedy: true
},
// Non-aligned-verbatim-strings
{
pattern: /"([^{]*)\{[\s\S]*?\}\1"/,
greedy: true
},
// Single-line string
{
// BUG: NVD-CWE-noinfo Insufficient Information
// pattern: /"(?:%\s*\n\s*%|%.|[^%"\r\n])*"/,
// FIXED:
<fim-middle> pattern: /"(?:%(?:(?!\n)\s)*\n\s*%|%\S|[^%"\r\n])*"/,
greedy: true
}
],
// normal char | special char | char code
'char': /'(?:%.|[^%'\r\n])+'/,
'keyword': /\b(?:across|agent|alias|all|and<fix-suffix>|attached|as|assign|attribute|check|class|convert|create|Current|debug|deferred|detachable|do|else|elseif|end|ensure|expanded|export|external|feature|from|frozen|if|implies|inherit|inspect|invariant|like|local|loop|not|note|obsolete|old|once|or|Precursor|redefine|rename|require|rescue|Result|retry|select|separate|some|then|undefine|until|variant|Void|when|xor)\b/i,
'boolean': /\b(?:True|False)\b/i,
// Convention: class-names are always all upper-case characters
'class-name': {
'pattern': /\b[A-Z][\dA-Z_]*\b/,
'alias': 'builtin'
},
'number': [
// hexa | octal | bin
/\b0[xcb][\da-f](?:_*[\da-f])*\b/i,
// Decimal
/(?:\b\d(?:_*\d)*)?\.(?:(?:\d(?:_*\d)*)?e[+-]?)?\d(?:_*\d)*\b|\b\d(?:_*\d)*\b\.?/i
],
'punctuation': /:=|<<|>>|\(\||\|\)|->|\.(?=\w)|[{}[\];(),:?]/,
'operator': /\\\\|\|\.\.\||\.\.|\/[~\/=]?|[><]=?|[-+*^=~]/
};
<|endoftext|> |
javascript | <fim-prefix>\];:,]/
};
inside['interpolation'] = {
pattern: /\{[^\r\n}:]+\}/,
alias: 'variable',
inside: {
'delimiter': {
pattern: /^{|}$/,
alias: 'punctuation'
},
rest: inside
}
};
inside['func'] = {
pattern: /[\w-]+\([^)]*\).*/,
inside: {
'function': /^[^(]+/,
rest: inside
}
};
Prism.languages.stylus = {
'atrule-declaration': {
pattern: /(^\s*)@.+/m,
lookbehind: true,
inside: {
'atrule': /^@[\w-]+/,
rest: inside
}
},
'variable-declaration': {
pattern: /(^[ \t]*)[\w$-]+\s*.?=[ \t]*(?:(?:\{[^}]*\}|.+)|$)/m,
lookbehind: true,
inside: {
'variable': /^\S+/,
rest: inside
}
},
'statement': {
pattern: /(^[ \t]*)(?:if|else|for|return|unless)[ \t]+.+/m,
lookbehind: true,
inside: {
'keyword': /^\S+/,
rest: inside
}
},
// A property/value pair cannot end with a comma or a brace
// It cannot have indented content unless it ended with a semicolon
'property-declaration': {
pattern: /((?:^|\{)([ \t]*))(?:[\w-]|\{[^}\r\n]+\})+(?:\s*:\s*|[ \t]+)[^{\r\n]*(?:;|[^{\r\n,](?=$)(?!(?:\r?\n|\r)(?:\{|\2[ \t]+)))/m,
lookbehind: true,
inside: {
'property': {
pattern: /^[^\s:]+/,
inside: {
'interpolation': inside.interpolation
}
},
rest: inside
}
},
// A selector can contain parentheses only as part of a pseudo-element
// It can span multiple lines.
// It must end with a comma or an accolade or have indented content.
'selector': {
// BUG: NVD-CWE-noinfo Insufficient Information
// pattern: /(^[ \t]*)(?:(?=\S)(?:[^{}\r\n:()]|::?[\w-]+(?:\([^)\r\n]*\))?|\{[^}\r\n]+\})+)(?:(?:\r?\n|\r)(?:\1(?:(?=\S)(?:[^{}\r\n:()]|::?[\w-]+(?:\([^)\r\n]*\))?|\{[^}\r\n]+\})+)))*(?:,$|\{|(?=(?:\r?\n|\r)(?:\{|\1[ \t]+)))/m,
// FIXED:
<fim-middle> pattern: /(^[ \t]*)(?:(?=\S)(?:[^{}\r\n:()]|::?[\w-]+(?:\([^)\r\n]*\)|(?![\w-]))|\{[^}\r\n]+\})+)(?:(?:\r?\n|\r)(?:\1(?:(?=\S)(?:[^{}\r\n:()]|::?[\w-]+(?:\([^)\r\n]*\)|(?![\w-]))|\{[^}\r\n]+\})+)))<fix-suffix>*(?:,$|\{|(?=(?:\r?\n|\r)(?:\{|\1[ \t]+)))/m,
lookbehind: true,
inside: {
'interpolation': inside.interpolation,
'comment': inside.comment,
'punctuation': /[{},]/
}
},
'func': inside.func,
'string': inside.string,
'comment': {
pattern: /(^|[^\\])(?:\/\*[\s\S]*?\*\/|\/\/.*)/,
lookbehind: true,
greedy: true
},
'interpolation': inside.interpolation,
'punctuation': /[{}()\[\];:.]/
};
}(Prism));
<|endoftext|> |
javascript | <fim-prefix>'use stric<fim-middle>t'
let { existsSync, readFileSync } = require('fs')
let { dirname, join } = require('path')
let mozilla = require('source-map')
function fromBase64(str) {
if (Buffer) {
return Buffer.from(str,<fix-suffix> 'base64').toString()
} else {
// istanbul ignore next
return window.atob(str)
}
}
class PreviousMap {
constructor(css, opts) {
if (opts.map === false) return
this.loadAnnotation(css)
this.inline = this.startWith(this.annotation, 'data:')
let prev = opts.map ? opts.map.prev : undefined
let text = this.loadMap(opts.from, prev)
if (!this.mapFile && opts.from) {
this.mapFile = opts.from
}
if (this.mapFile) this.root = dirname(this.mapFile)
if (text) this.text = text
}
consumer() {
if (!this.consumerCache) {
this.consumerCache = new mozilla.SourceMapConsumer(this.text)
}
return this.consumerCache
}
withContent() {
return !!(
this.consumer().sourcesContent &&
this.consumer().sourcesContent.length > 0
)
}
startWith(string, start) {
if (!string) return false
return string.substr(0, start.length) === start
}
getAnnotationURL(sourceMapString) {
return sourceMapString
.match(/\/\*\s*# sourceMappingURL=(.*)\s*\*\//)[1]
.trim()
}
loadAnnotation(css) {
// BUG: NVD-CWE-noinfo Insufficient Information
// let annotations = css.match(/\/\*\s*# sourceMappingURL=.*\s*\*\//gm)
// FIXED:
let annotations = css.match(/\/\*\s*# sourceMappingURL=.*\*\//gm)
if (annotations && annotations.length > 0) {
// Locate the last sourceMappingURL to avoid picking up
// sourceMappingURLs from comments, strings, etc.
let lastAnnotat<|endoftext|> |
javascript | <fim-prefix><fim-middle>t expandtab sw=4 ts=4 sts=4: */
/**
* Used in or for console
*
* @package phpMyAdmin-Console
*/
/**
* Console object
*/
var PMA_console = {
/**
* @var object, jQuery object, selector i<fix-suffix>s '#pma_console>.content'
* @access private
*/
$consoleContent: null,
/**
* @var object, jQuery object, selector is '#pma_console .content',
* used for resizer
* @access private
*/
$consoleAllContents: null,
/**
* @var object, jQuery object, selector is '#pma_console .toolbar'
* @access private
*/
$consoleToolbar: null,
/**
* @var object, jQuery object, selector is '#pma_console .template'
* @access private
*/
$consoleTemplates: null,
/**
* @var object, jQuery object, form for submit
* @access private
*/
$requestForm: null,
/**
* @var object, contain console config
* @access private
*/
config: null,
/**
* @var bool, if console element exist, it'll be true
* @access public
*/
isEnabled: false,
/**
* @var bool, make sure console events bind only once
* @access private
*/
isInitialized: false,
/**
* Used for console initialize, reinit is ok, just some variable assignment
*
* @return void
*/
initialize: function() {
if ($('#pma_console').length === 0) {
return;
}
PMA_console.isEnabled = true;
// Cookie var checks and init
if (! $.cookie('pma_console_height')) {
$.cookie('pma_console_height', 92);
}
if (! $.cookie('pma_console_mode')) {
$.cookie('pma_console_mode', 'info');
<|endoftext|> |
javascript | <fim-prefix>(function(document) {
if ((typeof window.MathJax != 'undefined') && (typeof window.MathJax.Hub != 'undefined')) {
// Apply MathJax typesetting
var mathjaxDiv =
document.getElementById(config.mathjaxProcessingElementId);
// Apply Markdown parser after MathJax typesetting is complete
window.MathJax.Hub.Queue(["Typeset", window.MathJax.Hub,
mathjaxDiv]);
window.MathJax.Hub.Register.StartupHook("End Typeset",
function () {
// BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
//
// FIXED:
<fim-middle> config.markedOptions.sanitize = false;
marked.setOptions(config.markedOptions);
// Decode < and >
mathjaxData = mathjaxDiv.innerH<fix-suffix>TML;
mathjaxData = mathjaxData.replace(/</g, "<");
mathjaxData = mathjaxData.replace(/>/g, ">");
// Convert Markdown to HTML and replace document body
var html = marked(mathjaxData);
document.body.innerHTML = html;
// Remove div used for MathJax processing
mathjaxDiv.remove();
}
);
}
}(document));
<|endoftext|> |
javascript | <fim-prefix><fim-middle>********************************************************************************
* X2Engine Open Source Edition is a customer relationship management program developed by
* X2Engine, Inc. Copyright <fix-suffix>(C) 2011-2015 X2Engine Inc.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by the
* Free Software Foundation with the addition of the following permission added
* to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
* IN WHICH THE COPYRIGHT IS OWNED BY X2ENGINE, X2ENGINE DISCLAIMS THE WARRANTY
* OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along with
* this program; if not, see http://www.gnu.org/licenses or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* You can contact X2Engine, Inc. P.O. Box 66752, Scotts Valley,
* California 95067, USA. or at email address contact@x2engine.com.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retai<|endoftext|> |
javascript | <fim-prefix>/**
* @aut<fim-middle>hor Alejandro Galue <agalue@opennms.org>
* @copyright 2014 The OpenNMS Group, Inc.
*/
'use strict';
const angular = require('angular-js');
// BUG: CWE-79 Improper Neutralization of Input During Web <fix-suffix>Page Generation ('Cross-site Scripting')
//
// FIXED:
const _ = require('underscore-js');
require('angular-mocks');
require('../../../../../src/main/assets/js/apps/onms-requisitions/requisitions');
var controllerFactory, scope, $q, mockModal = {}, mockGrowl = {}, mockRequisitionsService = {}, foreignSource = 'test-requisition';
function createController() {
return controllerFactory('ForeignSourceController', {
$scope: scope,
$routeParams: { 'foreignSource': foreignSource },
$modal: mockModal,
RequisitionsService: mockRequisitionsService,
growl: mockGrowl
});
}
beforeEach(angular.mock.module('onms-requisitions', function($provide) {
$provide.value('$log', console);
}));
beforeEach(angular.mock.inject(function($rootScope, $controller, _$q_) {
scope = $rootScope.$new();
$q = _$q_;
controllerFactory = $controller;
}));
beforeEach(function() {
mockModal = {};
mockRequisitionsService.getForeignSourceDefinition = jasmine.createSpy('getForeignSourceDefinition');
mockRequisitionsService.getTiming = jasmine.createSpy('getTiming');
var requisitionDefer = $q.defer();
requisitionDefer.resolve({ detectors: [{'name':'ICMP'},{'name':'SNMP'}], policies: [{'name':'Foo'},{'name':'Bar'}] });
mockRequisitionsService.getForeignSourceDefinition.and.returnValue(requisitionDefer.promise);
mockRequisitionsService.getTiming.and.returnValue({ isRunning: false });
mockGrowl = {
warning: function(msg) { console.warn(msg); },
error: function(m<|endoftext|> |
javascript | <fim-prefix>
$('a[href="#submitAddSeries"]').click(function (event) {
event.preventDefault();
if ($('#variableInput').val() === "") {
return false;
}
if (newChart === null) {
$('#seriesPreview').html('');
newChart = {
title: $('input[name="chartTitle"]').val(),
nodes: [],
series: [],
maxYLabel: 0
};
}
var serie = {
dataPoints: [{ type: 'statusvar', name: $('#variableInput').val() }],
display: $('input[name="differentialValue"]').prop('checked') ? 'differential' : ''
};
if (serie.dataPoints[0].name == 'Processes') {
serie.dataPoints[0].type = 'proc';
}
if ($('input[name="useDivisor"]').prop('checked')) {
serie.valueDivisor = parseInt($('input[name="valueDivisor"]').val(), 10);
}
if ($('input[name="useUnit"]').prop('checked')) {
serie.unit = $('input[name="valueUnit"]').val();
}
var str = serie.display == 'differential' ? ', ' + PMA_messages.strDifferential : '';
str += serie.valueDivisor ? (', ' + $.sprintf(PMA_messages.strDividedBy, serie.valueDivisor)) : '';
str += serie.unit ? (', ' + PMA_messages.strUnit + ': ' + serie.unit) : '';
var newSeries = {
label: $('#variableInput').val().replace(/_/g, " ")
};
newChart.series.push(newSeries);
// BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
// $('#seriesPreview').append('- ' + newSeries.label + str + '<br/>');
// FIXED:
<fim-middle> $('#seriesPreview').append('- ' + escapeHtml(newSeries.label + str) + '<br/>');
newChart.nodes.push(serie);
$('#variableInput').val('');
$('input[name="differentialValu<fix-suffix>e"]').prop('checked', true);
$('input[name="useDivisor"]').prop('checked', false);
$('input[name="useUnit"]').prop('checked', false);
$('input[name="useDivisor"]').trigger('change');
$('input[name="useUnit"]').trigger('change');
$('select[name="varChartList"]').get(0).selectedIndex = 0;
$('#clearSeriesLink').show();
return false;
});
$("#variableInput").autocomplete({
source: variableNames
});
/* Initializes the monitor, called only once */
function initGrid() {
var i;
/* Apply default values & config */
if (window.localStorage) {
if (window.localStorage['monitorCharts']) {
runtime.charts = $.parseJSON(window.localStorage['monitorCharts']);
}
if (window.localStorage['monitorSettings']) {
monitorSettings = $.parseJSON(window.localStorage['monitorSettings']);
}
$('a[href="#clearMonitorConfig"]').toggle(runtime.charts !== null);
if (runtime.charts !== null && monitorProtocolVersion != window.localStorage['monitorVersion']) {
$('#emptyDialog').dialog({title: PMA_messages.strIncompatibleMonitorConfig});
$('#emptyDialog').html(PMA_messages.strIncompatibleMonitorConfigDescription);
var dlgBtns = {};
dlgBtns[PMA_messages.strClose] = function () { $(this).dialog('close'); };
$('#emptyDial<|endoftext|> |
javascript | <fim-prefix>$(document).ready(function() {
$('#bookmark_add_submit').click(addBookmark);
});
function addBookmark(event) {
var url = $('#bookmark_add_url').val();
var tags = $('#bookmark_add_tags').val();
$.ajax({
// BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
//
// FIXED:
<fim-middle> type: 'POST',
url: 'ajax/addBookmark.php',
data: 'url=' + encodeURI(url) + '&tags=' + encodeURI(tags),
success: function(data){
window.close();
}
});
}<fix-suffix><|endoftext|> |
javascript | <fim-prefix>tl: datepicker_rtl,
format: datepicker_format,
scrollInput: datepicker_scrollInput,
scrollMonth: datepicker_scrollMonth,
timepicker: false
});
// listen for a submit request.
window.addEventListener("message", (e) => {
if (e.origin !== window.location.origin) {
signerAlertMsg("Unauthorized! Request is not same origin!", 15000);
return false;
}
if (e.data.submitForm === true) {
page.updateModel(1);
}
});
});
// initialize any special controls
$(function () {
if (page.portalpatient) {
if (page.portalpatient.get('pid')) {
$("#replaceAllButton").show();
page.isEdited = true;
$.each(page.portalpatient.attributes, function (key, value) {
if (value != page.patient.get(key)) {
if (($("input[name=" + key + "]").attr('type') === 'radio' || $('#' + key).is('select')) && value == "") {
value = 'Unassigned';
}
$('#' + key + 'InputContainer span.help-inline').html(
// BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
// '<a class="editval text-primary" onclick="page.toggleVal(this); return false;" data-tstate=new data-id="'+key+'">'+value+'</a>');
// FIXED:
<fim-middle> '<a class="editval text-primary" onclick="page.toggleVal(this); return false;" data-tstate=new data-id="' + _.escape(key) + '">' + _.escape(value) + '</a>');
<fix-suffix> $('#' + key + 'InputContainer span.help-inline').show();
}
});
}
}
page.replaceAll();
$('form :input').on("change", function () {
$("#donePatientButton").show();
$('#savePatientButton').show();
});
});
$(".controls .inline-inputs").find(':input:checked').parent('.btn').addClass('active');
$(function () {
$('.jquery-date-time-picker').datetimepicker({
i18n: {
en: {
months: datetimepicker_xlMonths,
dayOfWeekShort: datetimepicker_xlDayofwkshort,
dayOfWeek: datetimepicker_xlDayofwk
},
},
yearStart: datetimepicker_yearStart,
rtl: datetimepicker_rtl,
format: datetimepicker_format,
step: datetimepicker_step,
scrollInput: datepicker_scrollInput,
scrollMonth: datepicker_scrollMonth,
timepicker: true
});
// hide excluded from view. from layout edit option 'Exclude in Portal'
if (typeof exclude !== 'undefined') {
exclude.forEach(id => {
let el<|endoftext|> |
javascript | <fim-prefix><fim-middle>s plugin.
*
* - Set tags via dialog
* - Toggle hidden tags
* - Stateless filter
*
* TODO:
*
* - Add hiddenTags to viewState of page
* - Export to PDF ignores current tags
* - Sync hiddenT<fix-suffix>ags with removed tags
*/
Draw.loadPlugin(function(editorUi)
{
var div = document.createElement('div');
// Adds resource for action
mxResources.parse('hiddenTags=Hidden Tags');
// Adds action
editorUi.actions.addAction('hiddenTags...', function()
{
if (editorUi.hiddenTagsWindow == null)
{
editorUi.hiddenTagsWindow = new HiddenTagsWindow(editorUi, document.body.offsetWidth - 380, 120, 300, 240);
editorUi.hiddenTagsWindow.window.addListener('show', function()
{
editorUi.fireEvent(new mxEventObject('hiddenTags'));
});
editorUi.hiddenTagsWindow.window.addListener('hide', function()
{
editorUi.fireEvent(new mxEventObject('hiddenTags'));
});
editorUi.hiddenTagsWindow.window.setVisible(true);
editorUi.fireEvent(new mxEventObject('hiddenTags'));
}
else
{
editorUi.hiddenTagsWindow.window.setVisible(!editorUi.hiddenTagsWindow.window.isVisible());
}
});
var menu = editorUi.menus.get('extras');
var oldFunct = menu.funct;
menu.funct = function(menu, parent)
{
oldFunct.apply(this, arguments);
editorUi.menus.addMenuItems(menu, ['-', 'hiddenTags'], parent);
};
var HiddenTagsWindow = function(editorUi, x, y, w, h)
{
var graph = editorUi.editor.graph;
var div = document.createElement('div');
div.style.overflow = 'hidden';
div.style.padding = '12px 8px 12px 8px';
div.style.height = 'auto';
var searchInput = document.createElement('input');
searchInput.setAttribute('placeholder', 'Type in the tags an<|endoftext|> |
javascript | <fim-prefix><fim-middle> 2.0
*
* @license http://www.gnu.org/licenses/agpl.html AGPL Version 3
* @author Cornelius Weiss <c.weiss@metaways.de>
* @copyright Copyright (c) 2007-2011 Metaways Infosystems GmbH (h<fix-suffix>ttp://www.metaways.de)
*/
Ext.ns('Tine.Tinebase');
/**
* Tine 2.0 jsclient main menu
*
* @namespace Tine.Tinebase
* @class Tine.Tinebase.MainMenu
* @extends Ext.Toolbar
* @author Cornelius Weiss <c.weiss@metaways.de>
*/
Tine.Tinebase.MainMenu = Ext.extend(Ext.Toolbar, {
/**
* @cfg {Boolean} showMainMenu
*/
showMainMenu: false,
style: {'padding': '0px 2px'},
cls: 'tbar-mainmenu',
/**
* @type Array
* @property mainActions
*/
mainActions: null,
initComponent: function() {
this.initActions();
this.onlineStatus = new Ext.ux.ConnectionStatus({
showIcon: false
});
this.items = this.getItems();
var buttonTpl = new Ext.Template(
'<table id="{4}" cellspacing="0" class="x-btn {3}"><tbody class="{1}">',
'<tr><td class="x-btn-ml"><i> </i></td><td class="x-btn-mc"><em class="{2}" unselectable="on"><button type="{0}"></button></em></td><td class="x-btn-mr"><i> </i></td></tr>',
'</tbody></table>'
).compile();
Ext.each(this.items, function(item) {
item.template = buttonTpl;
}, this);
this.supr().initComponent.call(this);
},
getItems: function() {
return [{
text: Tine.title,
hidden: !this.showMainMenu,
menu: {
id: 'Tinebase_System_Menu',
item<|endoftext|> |
javascript | <fim-prefix><fim-middle>se DOMPurify | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/2.0.8/LICENSE */
function _toConsumableArray<fix-suffix>(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
var hasOwnProperty = Object.hasOwnProperty,
setPrototypeOf = Object.setPrototypeOf,
isFrozen = Object.isFrozen,
objectKeys = Object.keys;
var freeze = Object.freeze,
seal = Object.seal,
create = Object.create; // eslint-disable-line import/no-mutable-exports
var _ref = typeof Reflect !== 'undefined' && Reflect,
apply = _ref.apply,
construct = _ref.construct;
if (!apply) {
apply = function apply(fun, thisValue, args) {
return fun.apply(thisValue, args);
};
}
if (!freeze) {
freeze = function freeze(x) {
return x;
};
}
if (!seal) {
seal = function seal(x) {
return x;
};
}
if (!construct) {
construct = function construct(Func, args) {
return new (Function.prototype.bind.apply(Func, [null].concat(_toConsumableArray(args))))();
};
}
var arrayForEach = unapply(Array.prototype.forEach);
var arrayIndexOf = unapply(Array.prototype.indexOf);
var arrayJoin = unapply(Array.prototype.join);
var arrayPop = unapply(Array.prototype.pop);
var arrayPush = unapply(Array.prototype.push);
var arraySlice = unapply(Array.prototype.slice);
var stringToLowerCase = unapply(String.prototype.toLowerCase);
var stringMatch = unapply(String.prototype.match);
var stringReplace = unapply(String.prototype.replace);
var stringIndexOf = unapply(String.prototype.indexOf);
var stri<|endoftext|> |
javascript | <fim-prefix>kStatus: Lookup for status codes (code => string)
* - deskTypes: Lookup for ticket types (string => story, task, subTask, feature,
* bug, techTask, epic, improvement, fault, change, access, purchase or itHelp)
*
* The current configuration is stored in localStorage under ".tickets-config". Use
* https://jgraph.github.io/drawio-tools/tools/convert.html for URI encoding.
*/
Draw.loadPlugin(function(ui)
{
var config = null;
var deskDomain = null;
var deskApiKey = null;
var graph = ui.editor.graph;
var deskPriority = {'1': 'minor', '2': 'major',
'3': 'critical', '4': 'blocker'};
var deskTypes = {'Question': 'story', 'Incident': 'techTask', 'Problem': 'fault',
'Feature Request': 'feature', 'Lead': 'purchase'};
var deskStatus = {'2': 'Open', '3': 'Pending', '4': 'Resolved', '5': 'Closed',
'6': 'Waiting on Customer', '7': 'Waiting on Third Party',
'8': 'Resolved Internally'};
var deskStatusWidth = {};
function configure()
{
deskDomain = 'https://' + config.deskDomain + '.freshdesk.com';
deskApiKey = config.deskApiKey;
deskTypes = config.deskTypes || deskTypes;
deskStatus = config.deskStatus || deskStatus;
deskStatusWidth = {};
// Precomputes text widths for custom ticket status
var div = document.createElement('div');
div.style.fontFamily = 'Arial,Helvetica';
div.style.visibility = 'hidden';
div.style.position = 'absolute';
div.style.fontSize = '11px';
document.body.appendChild(div);
for (var key in deskStatus)
{
// BUG: CWE-94 Improper Control of Generation of Code ('Code Injection')
// div.innerHTML = '';
// FIXED:
<fim-middle> div.innerText = '';
mxUtils.write(div, deskStatus[key]);
deskStatusWidth[key] = div.clientWidth + 4;
}
document.body.removeChild(div);
};
if (window.location.hash != null && window.l<fix-suffix>ocation.hash.substring(0, 9) == '#_TICKETS')
{
try
{
var temp = JSON.parse(decodeURIComponent(
window.location.hash.substring(9)));
if (temp != null && temp.ticketsConfig != null)
{
config = temp.ticketsConfig;
configure();
ui.fileLoaded(new LocalFile(ui, ui.emptyDiagramXml, this.defaultFilename, true));
ui.editor.setStatus('Drag tickets from <a href="' + deskDomain +
'/a/tickets/filters/all_tickets" target="_blank">' +
deskDomain + '</a>');
}
}
catch (e)
{
console.error(e);
}
}
function isDeskLink(link)
{
if (deskDomain != null)
{
var dl = deskDomain.length;
return config != null && link.substring(0, dl) == deskDomain &&
(link.substring(dl, dl + 18) == '/helpdesk/tickets/' ||
link.substring(dl, dl + 11) == '/a/tickets/');
}
else
{
return false;
}
};
function getIdForDeskLink(link)
{
return link.substring(link.lastIndexOf('/') + 1);
};
function getDeskTicket(id, fn)
{
var xhr = new XMLHttpRequest();
xhr.open('GET', deskDomain + '/api/v2/tickets/' + id);
xhr.setRequestHeader('Authorization', 'Basic ' + btoa(deskApiKey + ':x'));
xhr.onload = function ()
{
if (xhr.status >= 200 && xhr.status <= 299)
{
fn(JSON.parse(xhr.responseText), xhr);
}
else
{
fn(null, xhr);
}
};
xhr.onerror = function ()
{
fn(null, xhr);
};
xhr.send();
};
function updateStyle(cell, ticket)
{
var type = (ticket.type != null) ? deskTypes[t<|endoftext|> |
javascript | <fim-prefix>FileList={<fim-middle>
useUndo:true,
update:function(fileListHtml) {
$('#fileList').empty().html(fileListHtml);
},
addFile:function(name,size,lastModified,loading){
var img=(loading)?OC.imagePath('core', 'loading.g<fix-suffix>if'):OC.imagePath('core', 'filetypes/file.png');
var html='<tr data-type="file" data-size="'+size+'">';
if(name.indexOf('.')!=-1){
var basename=name.substr(0,name.lastIndexOf('.'));
var extension=name.substr(name.lastIndexOf('.'));
}else{
var basename=name;
var extension=false;
}
html+='<td class="filename" style="background-image:url('+img+')"><input type="checkbox" />';
// BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
// html+='<a class="name" href="download.php?file='+$('#dir').val()+'/'+name+'"><span class="nametext">'+basename
// FIXED:
html+='<a class="name" href="download.php?file='+$('#dir').val().replace(/</, '<').replace(/>/, '>')+'/'+name+'"><span class="nametext">'+basename
if(extension){
html+='<span class="extension">'+extension+'</span>';
}
html+='</span></a></td>';
if(size!='Pending'){
simpleSize=simpleFileSize(size);
}else{
simpleSize='Pending';
}
sizeColor = Math.round(200-size/(1024*1024)*2);
lastModifiedTime=Math.round(lastModified.getTime() / 1000);
modifiedColor=Math.round((Math.round((new Date()).getTime() / 1000)-lastModifiedTime)/60/60/24*14);
html+='<td class="filesize" title="'+humanFileSize(size)+'" style="color:rgb('+sizeColor+','+sizeColor+','+sizeColor+')">'+simpleSize+'</td>';
html+='<td class="date"><span class="modified" title="'+formatDate(lastModified)+'" style="color:rgb('+modifiedColor+','+modifiedColor+','+modifiedColor+'<|endoftext|> |
javascript | <fim-prefix><fim-middle>AQL_EXECUTE */
'use strict';
// //////////////////////////////////////////////////////////////////////////////
// DISCLAIMER
//
// Copyright 2010-2013 triAGENS GmbH, Cologne, Germany
// Copyright 20<fix-suffix>16 ArangoDB GmbH, Cologne, Germany
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Copyright holder is ArangoDB GmbH, Cologne, Germany
//
// @author Michael Hackstein
// @author Heiko Kernbach
// @author Alan Plum
// //////////////////////////////////////////////////////////////////////////////
const joi = require('joi');
const dd = require('dedent');
const internal = require('internal');
const db = require('@arangodb').db;
const actions = require('@arangodb/actions');
const errors = require('@arangodb').errors;
const ArangoError = require('@arangodb').ArangoError;
const examples = require('@arangodb/graph-examples/example-graph');
const createRouter = require('@arangodb/foxx/router');
const users = require('@arangodb/users');
const cluster = require('@arangodb/cluster');
const generalGraph = require('@arangodb/general-graph');
const request = require('@arangodb/request');
const isEnterprise = require('internal').isEnterprise();
const explainer = require('@arangodb/aql<|endoftext|> |
javascript | <fim-prefix>/* global jest:false */
const express = require('express')
const session = require('express-session')
const defaultEnv = {
NODE_ENV: 'test',
COMPANION_PORT: 3020,
COMPANION_DOMAIN: 'localhost:3020',
COMPANION_SELF_ENDPOINT: 'localhost:3020',
COMPANION_HIDE_METRICS: 'false',
COMPANION_HIDE_WELCOME: 'false',
COMPANION_STREAMING_UPLOAD: 'true',
// BUG: CWE-863 Incorrect Authorization
//
// FIXED:
<fim-middle> COMPANION_ALLOW_LOCAL_URLS : 'false',
COMPANION_PROTOCOL: 'http',
COMPANION_DATADIR: './test/output',
COMPANION_SECRET: 'secret',
COMPANION_DROPBOX_KEY: 'dropbox_key',
COMPANION_DROPBOX_<fix-suffix>SECRET: 'dropbox_secret',
COMPANION_BOX_KEY: 'box_key',
COMPANION_BOX_SECRET: 'box_secret',
COMPANION_GOOGLE_KEY: 'google_key',
COMPANION_GOOGLE_SECRET: 'google_secret',
COMPANION_INSTAGRAM_KEY: 'instagram_key',
COMPANION_INSTAGRAM_SECRET: 'instagram_secret',
COMPANION_ZOOM_KEY: 'zoom_key',
COMPANION_ZOOM_SECRET: 'zoom_secret',
COMPANION_ZOOM_VERIFICATION_TOKEN: 'zoom_verfication_token',
COMPANION_PATH: '',
}
function updateEnv (env) {
Object.keys(env).forEach((key) => {
process.env[key] = env[key]
})
}
module.exports.setDefaultEnv = () => updateEnv(defaultEnv)
module.exports.getServer = (extraEnv) => {
const env = {
...defaultEnv,
...extraEnv,
}
updateEnv(env)
// delete from cache to force the server to reload companionOptions from the new env vars
jest.resetModules()
const standalone = require('../src/standalone')
const authServer = express()
authServer.use(session({ secret: 'grant', resave: true, saveUninitialized: true }))
authServer.all('*/callback', (req, res, next) => {
req.session.grant = {
response: { access_token: 'fake token' },
}
next()
})
authServer.all(['*/send-token', '*/redirect'], (req, res, next) => {
req.session.grant = { dynamic: { state: req.query.state || 'non-empty-value' } }
next()
})
const { app } = standalone()
authServer.use(app)
return authServer
}
<|endoftext|> |
javascript | <fim-prefix>const _ = require('lodash');
const ActiveConnector = require('../../connector/active');
module.exports = {
directive: 'PORT',
handler: function ({log, command} = {}) {
this.connector = new ActiveConnector(this);
const rawConnection = _.get(command, 'arg', '').split(',');
if (rawConnection.length !== 6) return this.reply(425);
const ip = rawConnection.slice(0, 4).join('.');
const portBytes = rawConnection.slice(4).map((p) => parseInt(p));
const port = portBytes[0] * 256 + portBytes[1];
return this.connector.setupConnection(ip, port)
.then(() => this.reply(200))
.catch((err) => {
log.error(err);
// BUG: CWE-918 Server-Side Request Forgery (SSRF)
// return this.reply(425);
// FIXED:
<fim-middle> return this.reply(err.code || 425, err.message);
});
},
syntax: '{{cmd}} <x>,<x>,<x>,<x>,<y>,<y>',
description: 'Specifies an address and port to which the server should connect'
};
<fix-suffix><|endoftext|> |
javascript | <fim-prefix><fim-middle>t expandtab sw=4 ts=4 sts=4: */
/**
* general function, usually for data manipulation pages
*
*/
/**
* @var $table_clone reference to the action links on the tbl_structure page
*/
var $table_clo<fix-suffix>ne = false;
/**
* @var sql_box_locked lock for the sqlbox textarea in the querybox/querywindow
*/
var sql_box_locked = false;
/**
* @var array holds elements which content should only selected once
*/
var only_once_elements = [];
/**
* @var int ajax_message_count Number of AJAX messages shown since page load
*/
var ajax_message_count = 0;
/**
* @var codemirror_editor object containing CodeMirror editor of the query editor in SQL tab
*/
var codemirror_editor = false;
/**
* @var codemirror_editor object containing CodeMirror editor of the inline query editor
*/
var codemirror_inline_editor = false;
/**
* @var chart_activeTimeouts object active timeouts that refresh the charts. When disabling a realtime chart, this can be used to stop the continuous ajax requests
*/
var chart_activeTimeouts = {};
/**
* Make sure that ajax requests will not be cached
* by appending a random variable to their parameters
*/
$.ajaxPrefilter(function (options, originalOptions, jqXHR) {
var nocache = new Date().getTime() + "" + Math.floor(Math.random() * 1000000);
if (typeof options.data == "string") {
options.data += "&_nocache=" + nocache;
} else if (typeof options.data == "object") {
options.data = $.extend(originalOptions.data, {'_nocache' : nocache});
}
});
/**
* Add a hidden field to the form to indicate that this will be an
* Ajax request (only if this hidden field does not exist)
*
* @param object the form
*/
function PMA_prep<|endoftext|> |
javascript | <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|> |
javascript | <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|> |
javascript | <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|> |
javascript | <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|> |
javascript | <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|> |
javascript | <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|> |
javascript | <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'] = '<a href="#' + this.entityType + '/view/' + this.entityId + '">' + this.entityName +'</a>';
// FIXED:
<fim-middle> this.messageData['relatedEntity'] = '<a href="#' + this.getHelper().escapeString(this.entityType) + '/view/' + this.getHelper().escapeString(this.entityId) + '">' + this.getHelper().escape<fix-suffix>String(this.entityName) +'</a>';
this.createMessage();
}
});
});
<|endoftext|> |
javascript | <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|> |
javascript | <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|> |
javascript | <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|> |
javascript | <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|> |
javascript | <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|> |
javascript | <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|> |
javascript | <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|> |
javascript | <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|> |
javascript | <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|> |
javascript | <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|> |
javascript | <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|> |
javascript | <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 '<i class="d-md-none fa fa-arrow-circle-up"></i>'
}
if (stats.previousMonthHours < stats.currentMonthHours) {
return '<i class="d-md-none fa fa-arrow-circle-down"></i>'
}
return '<i class="d-md-none fa fa-minus-square"></i>'
},
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|> |
javascript | <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|> |
javascript | <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|> |
javascript | <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|> |
javascript | <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|> |
javascript | <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|> |
javascript | <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|> |
javascript | <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|> |
javascript | <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|> |
javascript | <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|> |
javascript | <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|> |
javascript | <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|> |
javascript | <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|> |
javascript | <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|> |
javascript | <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|> |
javascript | <fim-prefix>const ESCAPE = /[&"<]/g, CHARS = {
'"': '"',
'&': '&',
'<': '<',
};
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|> |
javascript | <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|> |
javascript | <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|> |
javascript | <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|> |
javascript | <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|> |
javascript | <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|> |
javascript | <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|> |
javascript | <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|> |
javascript | <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'] = '<a href="#' + this.entityType + '/view/' + this.entityId + '">' + this.entityName +'</a>';
// FIXED:
<fim-middle> this.messageData['relatedEntity'] = '<a href="#' + this.getHelper().escapeString(this.entityType) + '/view/' + this.getHelper().escapeString(this.entityId) + '">' + this.getHelper().escape<fix-suffix>String(this.entityName) +'</a>';
this.createMessage();
},
});
});
<|endoftext|> |
javascript | <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|> |
javascript | <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|> |
javascript | <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|> |
javascript | <fim-prefix>turn tags;
},
parseTags : function(el) {
var id = el.id,
num = id.split('-check-num-')[1],
taxbox = $(el).closest('.tagsdiv'),
thetags = taxbox.find('.the-tags'),
current_tags = thetags.val().split( tagDelimiter ),
new_tags = [];
delete current_tags[num];
$.each( current_tags, function( key, val ) {
val = $.trim( val );
if ( val ) {
new_tags.push( val );
}
});
thetags.val( this.clean( new_tags.join( tagDelimiter ) ) );
this.quickClicks( taxbox );
return false;
},
quickClicks : function( el ) {
var thetags = $('.the-tags', el),
tagchecklist = $('.tagchecklist', el),
id = $(el).attr('id'),
current_tags, disabled;
if ( ! thetags.length )
return;
disabled = thetags.prop('disabled');
current_tags = thetags.val().split( tagDelimiter );
tagchecklist.empty();
$.each( current_tags, function( key, val ) {
var span, xbutton;
val = $.trim( val );
if ( ! val )
return;
// Create a new span, and ensure the text is properly escaped.
span = $('<span />').text( val );
// If tags editing isn't disabled, create the X button.
if ( ! disabled ) {
/*
* Build the X buttons, hide the X icon with aria-hidden and
* use visually hidden text for screen readers.
*/
xbutton = $( '<button type="button" id="' + id + '-check-num-' + key + '" class="ntdelbutton">' +
'<span class="remove-tag-icon" aria-hidden="true"></span>' +
// BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
// '<span class="screen-reader-text">' + window.tagsSuggestL10n.removeTerm + ' ' + val + '</span>' +
// FIXED:
<fim-middle> '<span class="screen-reader-text">' + window.tagsSuggestL10n.removeTerm + ' ' + span.html() + '</span>' +
'</button>' );
xbutton.on( 'click keypress', function( e ) {
// On cli<fix-suffix>ck or when using the Enter/Spacebar keys.
if ( 'click' === e.type || 13 === e.keyCode || 32 === e.keyCode ) {
/*
* When using the keyboard, move focus back to the
* add new tag field. Note: when releasing the pressed
* key this will fire the `keyup` event on the input.
*/
if ( 13 === e.keyCode || 32 === e.keyCode ) {
$( this ).closest( '.tagsdiv' ).find( 'input.newtag' ).focus();
}
tagBox.userAction = 'remove';
tagBox.parseTags( this );
}
});
span.prepend( ' ' ).prepend( xbutton );
}
// Append the span to the tag list.
tagchecklist.append( span );
});
// The buttons list is built now, give feedback to screen reader users.
tagBox.screenReadersMessage();
},
flushTags : function( el, a, f ) {
var tagsval, newtags, text,
tags = $( '.the-tags', el ),
newtag = $( 'input.newtag', el );
a = a || false;
text = a ? $(a).text() : newtag.val();
/*
* Return if there's no new tag or if the input field is empty.
* Note: when using the keyboard to add tags, focus is moved back to
* the input field and the `keyup` event attached on this field will
* fire when releasing the pressed key. Checking also for the field
* emptiness avoids to set the tags and call quickClicks() again.
*/
if ( 'undefined' == typeof( text ) || '' === text ) {
return false;
}
tagsval = tags.val();
newtags = tagsval ? tagsval +<|endoftext|> |
javascript | <fim-prefix><fim-middle>ple plugin.
*/
Draw.loadPlugin(function(ui) {
var div = document.createElement('div');
div.style.background = Editor.isDarkMode() ? Editor.darkColor : '#ffffff';
div.style.border = '1px solid gr<fix-suffix>ay';
div.style.opacity = '0.8';
div.style.padding = '10px';
div.style.paddingTop = '0px';
div.style.width = '20%';
div.innerHTML = '<p><i>' + mxResources.get('nothingIsSelected') + '</i></p>';
var graph = ui.editor.graph;
if (!ui.editor.isChromelessView())
{
div.style.boxSizing = 'border-box';
div.style.minHeight = '100%';
div.style.width = '100%';
var iiw = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
var dataWindow = new mxWindow('Data', div, iiw - 320, 60, 200, 130, true, true);
dataWindow.destroyOnClose = false;
dataWindow.setMaximizable(false);
dataWindow.setResizable(true);
dataWindow.setScrollable(true);
dataWindow.setClosable(true);
dataWindow.contentWrapper.style.overflowY = 'scroll';
// Adds resource for action
mxResources.parse('extractData=Extract Data');
// Adds action
ui.actions.addAction('extractData...', function()
{
dataWindow.setVisible(!dataWindow.isVisible());
});
var menu = ui.menus.get('extras');
var oldFunct = menu.funct;
menu.funct = function(menu, parent)
{
oldFunct.apply(this, arguments);
ui.menus.addMenuItems(menu, ['-', 'extractData'], parent);
};
}
else
{
div.style.position = 'absolute';
div.style.minWidth = '200px';
div.style.top = '40px';
div.style.right = '20px';
document.body.appendChild(div);
}
// Highlights current cell
var highlight = new mxCellHighlight(graph, '#00ff00', 8);
var ignored = ['label',<|endoftext|> |
javascript | <fim-prefix><fim-middle>Prism) {
// $ set | grep '^[A-Z][^[:space:]]*=' | cut -d= -f1 | tr '\n' '|'
// + LC_ALL, RANDOM, REPLY, SECONDS.
// + make sure PS1..4 are here as they are not always set,
// - some useless things<fix-suffix>.
var envVars = '\\b(?:BASH|BASHOPTS|BASH_ALIASES|BASH_ARGC|BASH_ARGV|BASH_CMDS|BASH_COMPLETION_COMPAT_DIR|BASH_LINENO|BASH_REMATCH|BASH_SOURCE|BASH_VERSINFO|BASH_VERSION|COLORTERM|COLUMNS|COMP_WORDBREAKS|DBUS_SESSION_BUS_ADDRESS|DEFAULTS_PATH|DESKTOP_SESSION|DIRSTACK|DISPLAY|EUID|GDMSESSION|GDM_LANG|GNOME_KEYRING_CONTROL|GNOME_KEYRING_PID|GPG_AGENT_INFO|GROUPS|HISTCONTROL|HISTFILE|HISTFILESIZE|HISTSIZE|HOME|HOSTNAME|HOSTTYPE|IFS|INSTANCE|JOB|LANG|LANGUAGE|LC_ADDRESS|LC_ALL|LC_IDENTIFICATION|LC_MEASUREMENT|LC_MONETARY|LC_NAME|LC_NUMERIC|LC_PAPER|LC_TELEPHONE|LC_TIME|LESSCLOSE|LESSOPEN|LINES|LOGNAME|LS_COLORS|MACHTYPE|MAILCHECK|MANDATORY_PATH|NO_AT_BRIDGE|OLDPWD|OPTERR|OPTIND|ORBIT_SOCKETDIR|OSTYPE|PAPERSIZE|PATH|PIPESTATUS|PPID|PS1|PS2|PS3|PS4|PWD|RANDOM|REPLY|SECONDS|SELINUX_INIT|SESSION|SESSIONTYPE|SESSION_MANAGER|SHELL|SHELLOPTS|SHLVL|SSH_AUTH_SOCK|TERM|UID|UPSTART_EVENTS|UPSTART_INSTANCE|UPSTART_JOB|UPSTART_SESSION|USER|WINDOWID|XAUTHORITY|XDG_CONFIG_DIRS|XDG_CURRENT_DESKTOP|XDG_DATA_DIRS|XDG_GREETER_DATA_DIR|XDG_MENU_PREFIX|XDG_RUNTIME_DIR|XDG_SEAT|XDG_SEAT_PATH|XDG_SESSION_DESKTOP|XDG_SESSION_ID|XDG_SESSION_PATH|XDG_SESSION_TYPE|XDG_VTNR|XMODIFIERS)\\b';
var commandAfterHeredoc = {
pattern: /(^(["']?)\w+\2)[ \t]+\S.*/,
lookbehind: true,
alias: 'punctuation', // this looks reasonably well in all themes
inside: null // see below
};
var insideString = {
'bash': commandAfterHeredoc,
'environment': {
pattern: RegExp("\\$" + envVars),
alias: 'constant'<|endoftext|> |
javascript | <fim-prefix>/**
* Original by Aaron Harun: http://aahacreative.com/2012/07/31/php-syntax-highlighting-prism/
* Modified by Miles Johnson: http://milesj.me
* Rewritten by Tom Pavelec
*
* Supports PHP 5.3 - 8.0
*/
(function (Prism) {
var comment = /\/\*[\s\S]*?\*\/|\/\/.*|#(?!\[).*/;
var constant = [
{
pattern: /\b(?:false|true)\b/i,
alias: 'boolean'
},
/\b[A-Z_][A-Z0-9_]*\b(?!\s*\()/,
/\b(?:null)\b/i,
];
// BUG: NVD-CWE-noinfo Insufficient Information
// var number = /\b0b[01]+\b|\b0x[\da-f]+\b|(?:\b\d+(?:_\d+)*\.?(?:\d+(?:_\d+)*)*|\B\.\d+)(?:e[+-]?\d+)?/i;
// FIXED:
<fim-middle> var number = /\b0b[01]+\b|\b0x[\da-f]+\b|(?:\b\d+(?:_\d+)*\.?(?:\d+(?:_\d+)*)?|\B\.\d+)(?:e[+-]?\d+)?/i;
var operator = /<?=>|\?\?=?|\.{3}|\??->|[!=]=?=?|::|\*\*=?|--|\+\+|&&|\|\||<<|>>|[?~]|[/^|%*&<fix-suffix><>.+-]=?/;
var punctuation = /[{}\[\](),:;]/;
Prism.languages.php = {
'delimiter': {
pattern: /\?>$|^<\?(?:php(?=\s)|=)?/i,
alias: 'important'
},
'comment': comment,
'variable': /\$+(?:\w+\b|(?={))/i,
'package': {
pattern: /(namespace\s+|use\s+(?:function\s+)?)(?:\\?\b[a-z_]\w*)+\b(?!\\)/i,
lookbehind: true,
inside: {
'punctuation': /\\/
}
},
'keyword': [
{
pattern: /(\(\s*)\b(?:bool|boolean|int|integer|float|string|object|array)\b(?=\s*\))/i,
alias: 'type-casting',
greedy: true,
lookbehind: true
},
{
pattern: /([(,?]\s*)\b(?:bool|int|float|string|object|array(?!\s*\()|mixed|self|static|callable|iterable|(?:null|false)(?=\s*\|))\b(?=\s*\$)/i,
alias: 'type-hint',
greedy: true,
lookbehind: true
},
{
pattern: /([(,?]\s*[a-z0-9_|]\|\s*)(?:null|false)\b(?=\s*\$)/i,
alias: 'type-hint',
greedy: true,
lookbehind: true
},
{
pattern: /(\)\s*:\s*\??\s*)\b(?:bool|int|float|string|object|void|array(?!\s*\()|mixed|self|static|callable|iterable|(?:null|false)(?=\s*\|))\b/i,
alias: 'return-type',
greedy: true,
lookbehind: true
},
{
pattern: /(\)\s*:\s*\??\s*[a-z0-9_|]\|\s*)(?:null|false)\b/i,
alias: 'return-type',
greedy: true,
lookbehind: true
},
{
pattern: /\b(?:bool|int|float|string|object|void|array(?!\s*\()|mixed|iterable|(?:null|false)(?=\s*\|))\b/i,
alias: 'type-declaration',
greedy: true
},
{
pattern: /(\|\s*)(?:<|endoftext|> |
javascript | <fim-prefix><fim-middle>t expandtab sw=4 ts=4 sts=4: */
/**
* @fileoverview functions used wherever an sql query form is used
*
* @requires jQuery
* @requires js/functions.js
*
*/
var $data_a;
var prevScrollX<fix-suffix> = 0, fixedTop;
/**
* decode a string URL_encoded
*
* @param string str
* @return string the URL-decoded string
*/
function PMA_urldecode(str)
{
return decodeURIComponent(str.replace(/\+/g, '%20'));
}
/**
* endecode a string URL_decoded
*
* @param string str
* @return string the URL-encoded string
*/
function PMA_urlencode(str)
{
return encodeURIComponent(str).replace(/\%20/g, '+');
}
/**
* Get the field name for the current field. Required to construct the query
* for grid editing
*
* @param $this_field jQuery object that points to the current field's tr
*/
function getFieldName($this_field)
{
var this_field_index = $this_field.index();
// ltr or rtl direction does not impact how the DOM was generated
// check if the action column in the left exist
var left_action_exist = !$('#table_results').find('th:first').hasClass('draggable');
// number of column span for checkbox and Actions
var left_action_skip = left_action_exist ? $('#table_results').find('th:first').attr('colspan') - 1 : 0;
// If this column was sorted, the text of the a element contains something
// like <small>1</small> that is useful to indicate the order in case
// of a sort on multiple columns; however, we dont want this as part
// of the column name so we strip it ( .clone() to .end() )
var field_name = $('#table_results')
.find('thead')
.find('th:eq(' + (this_field_index - left_action_skip) + ') a')
.clone() <|endoftext|> |
javascript | <fim-prefix>omSelection.prototype.validateMassActionDialogForm = function () {
var that = this;
var newListName = this.dialogElem$.find ('.new-list-name');
auxlib.destroyErrorFeedbackBox ($(newListName));
var listName = $(newListName).val ();
if(listName === '' || listName === null) {
auxlib.createErrorFeedbackBox ({
prevElem: $(newListName),
message: that.translations['blankListNameError']
});
$('#mass-action-dialog-loading-anim').remove ();
this.dialogElem$.dialog ('widget').find ('.x2-dialog-go-button').show ();
return false;
}
return true;
};
NewListFromSelection.prototype.afterExecute = function () {
var that = this;
var newListName = this.dialogElem$.find ('.new-list-name');
$(newListName).val ('');
this.dialogElem$.dialog ('close');
this.massActionsManager.massActionInProgress = false;
};
NewListFromSelection.prototype.getExecuteParams = function () {
var that = this;
var params = x2.MassAction.prototype.getExecuteParams.call (this);
var newListName = this.dialogElem$.find ('.new-list-name');
var listName = $(newListName).val ();
params['listName'] = listName;
return params;
};
/**
* This complicated method is used to switch mass actions (from new list to add to list) after
* the first batch is completed.
* @return MassAddToList
*/
NewListFromSelection.prototype.convertToAddToList = function (listId, dialogState) {
var that = this;
// BUG: CWE-20 Improper Input Validation
// var addToList = this.massActionsManager.massActionObjects['addToList'];
// FIXED:
<fim-middle> var addToList = this.massActionsManager.massActionObjects['MassAddToList'];
var newListName = this.dialogElem$.find ('.new-list-name');
var listName = $(newListName).val ();
addToList.<fix-suffix>addListOption (listId, listName);
addToList.setListId (listId);
addToList.progressBar = this.progressBar;
addToList.recordCount = this.recordCount;
dialogState.superExecuteParams.listId = listId;
dialogState.superExecuteParams.massAction = addToList.massActionName;
return addToList;
};
/**
* Overrides parent method so that after the first batch is completed, requests are made to add to
* that list. This is accomplished by swapping out the mass action objects after the first
* response. This method also handles the case where the list could not be created successfully.
*/
NewListFromSelection.prototype._nextBatch = function (dialog, dialogState) {
var that = this;
this._beforeNextBatch ();
dialogState.batchOperInProgress = true;
$.ajax({
url: that.massActionsManager.massActionUrl,
type:'POST',
data: $.extend (dialogState.superExecuteParams, {
uid: dialogState.uid
}),
dataType: 'json',
success: function (data) {
dialogState.batchOperInProgress = false;
var response = data;
that.massActionsManager._displayFlashesList (
response, $(dialog).find ('.super-mass-action-feedback-box'));
if (response['successes'] === -1) { // list could not be created
dialog.dialog ('close');
return;
}
if (response['failure']) {
dialogState.loadingAnim$.hide ()<|endoftext|> |
javascript | <fim-prefix>Prism.languages.markup = {
// BUG: NVD-CWE-Other Other
// 'comment': /<!--[\s\S]*?-->/,
// FIXED:
<fim-middle> 'comment': /<!--(?:(?!<!--)[\s\S])*?-->/,
'prolog': /<\?[\s\S]+?\?>/,
'doctype': {
// https://www.w3.org/TR/xml/#NT-doctypedecl
pattern: /<!DOCTYPE(?:[^>"'[\]]|"[^"]*"|'[^']*')+(?:\[(?:[^<"'\]]<fix-suffix>|"[^"]*"|'[^']*'|<(?!!--)|<!--(?:[^-]|-(?!->))*-->)*\]\s*)?>/i,
greedy: true,
inside: {
'internal-subset': {
pattern: /(^[^\[]*\[)[\s\S]+(?=\]>$)/,
lookbehind: true,
greedy: true,
inside: null // see below
},
'string': {
pattern: /"[^"]*"|'[^']*'/,
greedy: true
},
'punctuation': /^<!|>$|[[\]]/,
'doctype-tag': /^DOCTYPE/,
'name': /[^\s<>'"]+/
}
},
'cdata': /<!\[CDATA\[[\s\S]*?\]\]>/i,
'tag': {
pattern: /<\/?(?!\d)[^\s>\/=$<%]+(?:\s(?:\s*[^\s>\/=]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+(?=[\s>]))|(?=[\s/>])))+)?\s*\/?>/,
greedy: true,
inside: {
'tag': {
pattern: /^<\/?[^\s>\/]+/,
inside: {
'punctuation': /^<\/?/,
'namespace': /^[^\s>\/:]+:/
}
},
'special-attr': [],
'attr-value': {
pattern: /=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+)/,
inside: {
'punctuation': [
{
pattern: /^=/,
alias: 'attr-equals'
},
/"|'/
]
}
},
'punctuation': /\/?>/,
'attr-name': {
pattern: /[^\s>\/]+/,
inside: {
'namespace': /^[^\s>\/:]+:/
}
}
}
},
'entity': [
{
pattern: /&[\da-z]{1,8};/i,
alias: 'named-entity'
},
/&#x?[\da-f]{1,8};/i
]
};
Prism.languages.markup['tag'].inside['attr-value'].inside['entity'] =
Prism.languages.markup['entity'];
Prism.languages.markup['doctype'].inside['internal-subset'].inside = Prism.languages.markup;
// Plugin to make entity title show the real entity, idea by Roman Komarov
Prism.hooks.ad<|endoftext|> |
javascript | <fim-prefix>Prism.lang<fim-middle>uages.q = {
'string': /"(?:\\.|[^"\\\r\n])*"/,
'comment': [
// From http://code.kx.com/wiki/Reference/Slash:
// When / is following a space (or a right parenthesis, bracket, or brace), it is ign<fix-suffix>ored with the rest of the line.
{
pattern: /([\t )\]}])\/.*/,
lookbehind: true,
greedy: true
},
// From http://code.kx.com/wiki/Reference/Slash:
// A line which has / as its first character and contains at least one other non-whitespace character is a whole-line comment and is ignored entirely.
// A / on a line by itself begins a multiline comment which is terminated by the next \ on a line by itself.
// If a / is not matched by a \, the multiline comment is unterminated and continues to end of file.
// The / and \ must be the first char on the line, but may be followed by any amount of whitespace.
{
// BUG: NVD-CWE-noinfo Insufficient Information
// pattern: /(^|\r?\n|\r)\/[\t ]*(?:(?:\r?\n|\r)(?:.*(?:\r?\n|\r))*?(?:\\(?=[\t ]*(?:\r?\n|\r))|$)|\S.*)/,
// FIXED:
pattern: /(^|\r?\n|\r)\/[\t ]*(?:(?:\r?\n|\r)(?:.*(?:\r?\n|\r(?!\n)))*?(?:\\(?=[\t ]*(?:\r?\n|\r))|$)|\S.*)/,
lookbehind: true,
greedy: true
},
// From http://code.kx.com/wiki/Reference/Slash:
// A \ on a line by itself with no preceding matching / will comment to end of file.
{
pattern: /^\\[\t ]*(?:\r?\n|\r)[\s\S]+/m,
greedy: true
},
{
pattern: /^#!.+/m,
greedy: true
}
],
'symbol': /`(?::\S+|[\w.]*)/,
'datetime': {
pattern: /0N[mdzuvt]|0W[dtz]|\d{4}\.\d\d(?:m|\.\d\d(?:T(?:\d\d(?::\d\d(?::\d\d(?:[.:]\d\d\d)?)?)?)?)?[dz]?)|\d\d:\d\d(?::\d\d(?:[.:]\d\d\d)?)?[uvt]?/,
alias: 'number'
},
// The negative look-ahead prevents bad highlighting
// <|endoftext|> |
javascript | <fim-prefix>//
//
// Updates database dns record dynamically, showing its full domain path
App.Actions.DB.update_dns_record_hint = function(elm, hint) {
// clean hint
if (hint.trim() == '') {
// BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
// $(elm).parent().find('.hint').html('');
// FIXED:
<fim-middle> $(elm).parent().find('.hint').text('');
}
// set domain name without rec in case of @ entries
if (hint == '@') {
hint = '';
}
// dont show pregix if domain name =<fix-suffix> rec value
if (hint == GLOBAL.DNS_REC_PREFIX + '.') {
hint = '';
}
// add dot at the end if needed
if (hint != '' && hint.slice(-1) != '.') {
hint += '.';
}
$(elm).parent().find('.hint').text(hint + GLOBAL.DNS_REC_PREFIX);
}
//
// listener that triggers dns record name hint updating
App.Listeners.DB.keypress_dns_rec_entry = function() {
var ref = $('input[name="v_rec"]');
var current_rec = ref.val();
if (current_rec.trim() != '') {
App.Actions.DB.update_dns_record_hint(ref, current_rec);
}
ref.bind('keypress input', function(evt) {
clearTimeout(window.frp_usr_tmt);
window.frp_usr_tmt = setTimeout(function() {
var elm = $(evt.target);
App.Actions.DB.update_dns_record_hint(elm, $(elm).val());
}, 100);
});
}
//
// Page entry point
// Trigger listeners
App.Listeners.DB.keypress_dns_rec_entry();
<|endoftext|> |
javascript | <fim-prefix>var profil<fim-middle>es = []
// Attempts to send a test email by POSTing to /campaigns/
function sendTestEmail() {
var headers = [];
$.each($("#headersTable").DataTable().rows().data(), function (i, header) {
<fix-suffix> headers.push({
key: unescapeHtml(header[0]),
value: unescapeHtml(header[1]),
})
})
var test_email_request = {
template: {},
first_name: $("input[name=to_first_name]").val(),
last_name: $("input[name=to_last_name]").val(),
email: $("input[name=to_email]").val(),
position: $("input[name=to_position]").val(),
url: '',
smtp: {
from_address: $("#from").val(),
host: $("#host").val(),
username: $("#username").val(),
password: $("#password").val(),
ignore_cert_errors: $("#ignore_cert_errors").prop("checked"),
headers: headers,
}
}
btnHtml = $("#sendTestModalSubmit").html()
$("#sendTestModalSubmit").html('<i class="fa fa-spinner fa-spin"></i> Sending')
// Send the test email
api.send_test_email(test_email_request)
.success(function (data) {
$("#sendTestEmailModal\\.flashes").empty().append("<div style=\"text-align:center\" class=\"alert alert-success\">\
<i class=\"fa fa-check-circle\"></i> Email Sent!</div>")
$("#sendTestModalSubmit").html(btnHtml)
})
.error(function (data) {
// BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
// <i class=\"fa fa-exclamation-circle\"></i> " + data.responseJSON.message + "</div>")
// FIXED:
$("#sendTestEmail<|endoftext|> |
javascript | <fim-prefix>return '(?:' + parenthesesRegex + ')'; }),
flags || '');
}
var modifierTokens = {
'css': {
pattern: /\{[^}]+\}/,
inside: {
rest: Prism.languages.css
}
},
'class-id': {
pattern: /(\()[^)]+(?=\))/,
lookbehind: true,
alias: 'attr-value'
},
'lang': {
pattern: /(\[)[^\]]+(?=\])/,
lookbehind: true,
alias: 'attr-value'
},
// Anything else is punctuation (the first pattern is for row/col spans inside tables)
'punctuation': /[\\\/]\d+|\S/
};
var textile = Prism.languages.textile = Prism.languages.extend('markup', {
'phrase': {
pattern: /(^|\r|\n)\S[\s\S]*?(?=$|\r?\n\r?\n|\r\r)/,
lookbehind: true,
inside: {
// h1. Header 1
'block-tag': {
pattern: withModifier(/^[a-z]\w*(?:<MOD>|<PAR>|[<>=])*\./.source),
inside: {
'modifier': {
pattern: withModifier(/(^[a-z]\w*)(?:<MOD>|<PAR>|[<>=])+(?=\.)/.source),
lookbehind: true,
inside: modifierTokens
},
'tag': /^[a-z]\w*/,
'punctuation': /\.$/
}
},
// # List item
// * List item
'list': {
pattern: withModifier(/^[*#]+<MOD>*\s+.+/.source, 'm'),
inside: {
'modifier': {
pattern: withModifier(/(^[*#]+)<MOD>+/.source),
lookbehind: true,
inside: modifierTokens
},
'punctuation': /^[*#]+/
}
},
// | cell | cell | cell |
'table': {
// Modifiers can be applied to the row: {color:red}.|1|2|3|
// or the cell: |{color:red}.1|2|3|
// BUG: NVD-CWE-noinfo Insufficient Information
// pattern: withModifier(/^(?:(?:<MOD>|<PAR>|[<>=^~])+\.\s*)?(?:\|(?:(?:<MOD>|<PAR>|[<>=^~_]|[\\/]\d+)+\.)?[^|]*)+\|/.source, 'm'),
// FIXED:
<fim-middle> pattern: withModifier(/^(?:(?:<MOD>|<PAR>|[<>=^~])+\.\s*)?(?:\|(?:(?:<MOD>|<PAR>|[<>=^~_]|[\\/]\d+)+\.|(?!(?:<MOD>|<PAR>|[<>=^~_]|[\\/]\d+)+\.))[^|]*)+\|/.source, 'm'),
inside: {
'modi<fix-suffix>fier': {
// Modifiers for rows after the first one are
// preceded by a pipe and a line feed
pattern: withModifier(/(^|\|(?:\r?\n|\r)?)(?:<MOD>|<PAR>|[<>=^~_]|[\\/]\d+)+(?=\.)/.source),
lookbehind: true,
inside: modifierTokens
},
'punctuation': /\||^\./
}
},
'inline': {
pattern: withModifier(/(^|[^a-zA-Z\d])(\*\*|__|\?\?|[*_%@+\-^~])<MOD>*.+?\2(?![a-zA-Z\d])/.source),
lookbehind: true,
inside: {
// Note: superscripts and subscripts are not handled specifically
// *bold*, **bold**
'bold': {
pattern: withModifier(/(^(\*\*?)<MOD>*).+?(?=\2)/.source),
lookbehind: true
},
// _italic_, __italic__
'italic': {
pattern: withModifier(/(^(__?)<MOD>*).+?(?=\2)/.source),
lookbehind: true
},
// ??cite??
'cite': {
pattern: withModifier(/(^\?\?<MOD>*).+?(?=\?\?)/.source),
lookbehind: true,
alias: 'string'
},
// @code@
'code': {
pattern: withModifier(/(^@<MOD>*).+?(?=@)/.source),
lookbehind: true,
alias: 'keyword'
},
// +inserted+
'inserted': {
pattern: withModifier(/(^\+<MOD>*).+?(?=\+)/.source),
lookbehind: true
},
// -deleted-
'deleted': {
pattern: withModifier(/(^-<MOD>*).+?(?=-)/.source),
lookbehind: true
},
// %span%
'span': {
pattern: withModifier(/(^%<MOD>*).+?(?=%)/.source),
<|endoftext|> |
javascript | <fim-prefix><fim-middle> 2.0
*
* @package Tinebase
* @license http://www.gnu.org/licenses/agpl.html AGPL Version 3
* @author Alexander Stintzing <a.stintzing@metaways.de>
* @copyright Copyright (c) 2013 M<fix-suffix>etaways Infosystems GmbH (http://www.metaways.de)
*
*/
Ext.ns('Tine.widgets.relation');
/**
* @namespace Tine.widgets.relation
* @class Tine.widgets.relation.GridRenderer
* @author Alexander Stintzing <a.stintzing@metaways.de>
* @extends Ext.Component
*/
Tine.widgets.relation.GridRenderer = function(config) {
Ext.apply(this, config);
Tine.widgets.relation.GridRenderer.superclass.constructor.call(this);
};
Ext.extend(Tine.widgets.relation.GridRenderer, Ext.Component, {
appName: null,
type: null,
foreignApp: null,
foreignModel: null,
relModel: null,
recordClass: null,
/**
* initializes the component
*/
initComponent: function() {
Tine.log.debug('Initializing relation renderer with config:');
Tine.log.debug('appName: ' + this.appName + ', type: ' + this.type + ', foreignApp: ' + this.foreignApp + ', foreignModel: ' + this.foreignModel);
this.relModel = this.foreignApp + '_Model_' + this.foreignModel;
},
/**
*
* @param {Array} relations
*/
render: function(relations) {
if ((! relations) || (relations.length == 0)) {
return '';
}
if (! this.recordClass) {
if (! Tine[this.foreignApp]) {
Tine.log.warn('Tine.widgets.relation.GridRenderer::render - ForeignApp not found: ' + this.foreignApp);
return '';
}
<|endoftext|> |
javascript | <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/fields/link-multiple-with-primary', 'views/fields/link-multiple', function (Dep) {
return Dep.extend({
primaryLink: null,
events: {
'click [data-action="switchPrimary"]': function (e) {
$target = $(e.currentTarget);
var id = $target.data('id');
if (!$t<|endoftext|> |
javascript | <fim-prefix>bels/:id': 'labels/delete',
'POST /api/boards/:boardId/lists': 'lists/create',
'PATCH /api/lists/:id': 'lists/update',
'DELETE /api/lists/:id': 'lists/delete',
'GET /api/boards/:boardId/cards': 'cards/index',
'POST /api/boards/:boardId/cards': 'cards/create',
'GET /api/cards/:id': 'cards/show',
'PATCH /api/cards/:id': 'cards/update',
'DELETE /api/cards/:id': 'cards/delete',
'POST /api/cards/:cardId/memberships': 'card-memberships/create',
'DELETE /api/cards/:cardId/memberships': 'card-memberships/delete',
'POST /api/cards/:cardId/labels': 'card-labels/create',
'DELETE /api/cards/:cardId/labels/:labelId': 'card-labels/delete',
'POST /api/cards/:cardId/tasks': 'tasks/create',
'PATCH /api/tasks/:id': 'tasks/update',
'DELETE /api/tasks/:id': 'tasks/delete',
'POST /api/cards/:cardId/attachments': 'attachments/create',
'PATCH /api/attachments/:id': 'attachments/update',
'DELETE /api/attachments/:id': 'attachments/delete',
'GET /api/cards/:cardId/actions': 'actions/index',
'POST /api/cards/:cardId/comment-actions': 'comment-actions/create',
'PATCH /api/comment-actions/:id': 'comment-actions/update',
'DELETE /api/comment-actions/:id': 'comment-actions/delete',
'GET /api/notifications': 'notifications/index',
'GET /api/notifications/:id': 'notifications/show',
'PATCH /api/notifications/:ids': 'notifications/update',
'GET /attachments/:id/download/:filename': {
action: 'attachments/download',
skipAssets: false,
},
// BUG: CWE-22 Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
// 'GET /attachments/:id/download/thumbnails/:filename': {
// FIXED:
<fim-middle> 'GET /attachments/:id/download/thumbnails/cover-256.jpg': {
action: 'attachments/download-thumbnail',
skipAssets: false,
},
'GET /*': {
view: 'index',
skipAssets: true,
},
};
<fix-suffix><|endoftext|> |
javascript | <fim-prefix><fim-middle>opyright (C) 2001-2018 OTRS AG, https://otrs.com/
// --
// This software comes with ABSOLUTELY NO WARRANTY. For details, see
// the enclosed file COPYING for license information (GPL). If you
// did n<fix-suffix>ot receive this file, see https://www.gnu.org/licenses/gpl-3.0.txt.
// --
"use strict";
var Core = Core || {};
Core.Agent = Core.Agent || {};
Core.Agent.Admin = Core.Agent.Admin || {};
/**
* @namespace Core.Agent.Admin.SupportDataCollector
* @memberof Core.Agent.Admin
* @author OTRS AG
* @description
* This namespace contains the special module function for SupportDataCollector module.
*/
Core.Agent.Admin.SupportDataCollector = (function (TargetNS) {
/*
* @name Init
* @memberof Core.Agent.Admin.SupportDataCollector
* @function
* @description
* This function initializes module functionality
*/
TargetNS.Init = function () {
// Bind event on SendUpdate button
$('#SendUpdate').on('click', function (Event) {
var TextClass = '';
Core.UI.Dialog.ShowContentDialog('<div class="Spacing Center"><span class="AJAXLoader W33pc" title='+ Core.Language.Translate("Sending Update...") + '></span></div>',Core.Language.Translate("Sending Update..."), '10px', 'Center', true, undefined, true);
Core.AJAX.FunctionCall(Core.Config.Get('CGIHandle'), 'Action=' + Core.Config.Get('Action') + ';Subaction=SendUpdate;', function (Response) {
var ResponseMessage = Core.Language.Translate('Support Data information was successfully sent.');
// if the waiting dialog was canceled,
// do not show the search dialog as well
if (!$('.<|endoftext|> |
javascript | <fim-prefix><fim-middle>core
*
* This source file is available under two different licenses:
* - GNU General Public License version 3 (GPLv3)
* - Pimcore Commercial License (PCL)
* Full copyright and license information<fix-suffix> is available in
* LICENSE.md which is distributed with this source code.
*
* @copyright Copyright (c) Pimcore GmbH (http://www.pimcore.org)
* @license http://www.pimcore.org/license GPLv3 and PCL
*/
pimcore.registerNS("pimcore.settings.thumbnail.item");
pimcore.settings.thumbnail.item = Class.create({
initialize: function (data, parentPanel) {
this.parentPanel = parentPanel;
this.data = data;
this.currentIndex = 0;
this.medias = {};
this.addLayout();
// add default panel
this.addMediaPanel("default", this.data.items, false, true);
// add medias
if (this.data["medias"]) {
Ext.iterate(this.data.medias, function (key, items) {
this.addMediaPanel(key, items, true, false);
}.bind(this));
}
},
addLayout: function () {
var panelButtons = [];
let buttonConfig = {
text: t("save"),
iconCls: "pimcore_icon_apply",
handler: this.save.bind(this),
disabled: !this.data.writeable
};
if (!this.data.writeable) {
buttonConfig.tooltip = t("config_not_writeable");
}
panelButtons.push(buttonConfig);
this.mediaPanel = new Ext.TabPanel({
autoHeight: true,
plugins: [Ext.create('Ext.ux.TabReorderer', {})]
});
var addViewPortButton = {
xtype: 'panel',
style: 'margin-bott<|endoftext|> |
javascript | <fim-prefix>Prism.lang<fim-middle>uages.fortran = {
'quoted-number': {
pattern: /[BOZ](['"])[A-F0-9]+\1/i,
alias: 'number'
},
'string': {
// BUG: NVD-CWE-noinfo Insufficient Information
// pattern: /(?:\w+_)?(['"])(?:\1\1|&<fix-suffix>(?:\r\n?|\n)(?:\s*!.+(?:\r\n?|\n))?|(?!\1).)*(?:\1|&)/,
// FIXED:
pattern: /(?:\w+_)?(['"])(?:\1\1|&(?:\r\n?|\n)(?:[ \t]*!.*(?:\r\n?|\n)|(?![ \t]*!))|(?!\1).)*(?:\1|&)/,
inside: {
'comment': {
pattern: /(&(?:\r\n?|\n)\s*)!.*/,
lookbehind: true
}
}
},
'comment': {
pattern: /!.*/,
greedy: true
},
'boolean': /\.(?:TRUE|FALSE)\.(?:_\w+)?/i,
'number': /(?:\b\d+(?:\.\d*)?|\B\.\d+)(?:[ED][+-]?\d+)?(?:_\w+)?/i,
'keyword': [
// Types
/\b(?:INTEGER|REAL|DOUBLE ?PRECISION|COMPLEX|CHARACTER|LOGICAL)\b/i,
// END statements
/\b(?:END ?)?(?:BLOCK ?DATA|DO|FILE|FORALL|FUNCTION|IF|INTERFACE|MODULE(?! PROCEDURE)|PROGRAM|SELECT|SUBROUTINE|TYPE|WHERE)\b/i,
// Statements
/\b(?:ALLOCATABLE|ALLOCATE|BACKSPACE|CALL|CASE|CLOSE|COMMON|CONTAINS|CONTINUE|CYCLE|DATA|DEALLOCATE|DIMENSION|DO|END|EQUIVALENCE|EXIT|EXTERNAL|FORMAT|GO ?TO|IMPLICIT(?: NONE)?|INQUIRE|INTENT|INTRINSIC|MODULE PROCEDURE|NAMELIST|NULLIFY|OPEN|OPTIONAL|PARAMETER|POINTER|PRINT|PRIVATE|PUBLIC|READ|RETURN|REWIND|SAVE|SELECT|STOP|TARGET|WHILE|WRITE)\b/i,
// Others
/\b(?:ASSIGNMENT|DEFAULT|ELEMENTAL|ELSE|ELSEWHERE|ELSEIF|ENTRY|IN|INCLUDE|INOUT|KIND|NULL|ONLY|OPERATOR|OUT|PURE|RECURSIVE|RESULT|SEQUENCE|STAT|THEN|USE)\b/i
],
'operator': [
/\*\*|\/\/|=>|[=\/]=|[<>]=?|::|[+\-*=%]|\.[A-Z]+\./i,
{
// Use lookbehind to prevent confusion with (/ /)
pattern: /(^|(?!\().)\/(?!\))/,
lookbehind: true
}
],
'punctuation': /\(\/|\/\)|[(),;:&]/
};
<|endoftext|> |
javascript | <fim-prefix>var choresTable = $('#chores-table').DataTable({
'order': [[1, 'asc']],
'columnDefs': [
{ 'orderable': false, 'targets': 0 },
{ 'searchable': false, "targets": 0 }
]
});
$('#chores-table tbody').removeClass("d-none");
choresTable.columns.adjust().draw();
$("#search").on("keyup", Delay(function()
{
var value = $(this).val();
if (value === "all")
{
value = "";
}
choresTable.search(value).draw();
}, 200));
$(document).on('click', '.chore-delete-button', function(e)
{
// BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
// var objectName = $(e.currentTarget).attr('data-chore-name');
// FIXED:
<fim-middle> var objectName = SanitizeHtml($(e.currentTarget).attr('data-chore-name'));
var objectId = $(e.currentTarget).attr('data-chore-id');
bootbox.confirm({
message: __t('Are you sure to delete chore "<fix-suffix>%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/chores/' + objectId, {},
function(result)
{
window.location.href = U('/chores');
},
function(xhr)
{
console.error(xhr);
}
);
}
}
});
});
<|endoftext|> |
javascript | <fim-prefix> showPanel();
}
var xVals = data.map(getPos('x')).filter(notUndef);
var yVals = data.map(getPos('y')).filter(notUndef);
minX = Math.min.apply(null, xVals);
maxX = Math.max.apply(null, xVals);
var midX = ((maxX - minX)/2) + minX;
minY = Math.min.apply(null, yVals);
maxY = Math.max.apply(null, yVals);
// Resize the well_birds_eye according to extent of field positions...
var whRatio = 1;
if (maxX !== minX || maxY !== minY) {
whRatio = (maxX - minX) / (maxY - minY);
}
var width = 200;
var height = 200;
var top = 4;
if (whRatio > 1) {
height = 200/whRatio;
top = ((200 - height) / 2) + 4;
} else {
width = whRatio * 200;
}
$well_birds_eye.css({'width': width + 'px', 'height': height + 'px', 'top': top + 'px'});
// Add images, positioned by percent...
var html = data.map(function(ws){
// check if min===max to avoid zero-division error
var x = (maxX === minX) ? 0.5 : (ws.position.x.value - minX)/(maxX - minX);
var y = (maxY === minY) ? 0.5 : (ws.position.y.value - minY)/(maxY - minY);
// BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
// return '<img style="left: ' + (x * 100) + '%; top: ' + (y * 100) + '%" title="' + ws.name + '" data-imageId="' + ws.id + '" />';
// FIXED:
<fim-middle> return '<img style="left: ' + (x * 100) + '%; top: ' + (y * 100) + '%" title="' + ws.name.escapeHTML() + '" data-imageId="' + ws.id + '" />';
}, "");
<fix-suffix> $well_birds_eye.append(html.join(""));
}
}
};
// Used by WellIndexForm in forms.py
window.changeField = function changeField(field) {
var datatree = $.jstree.reference('#dataTree');
var $container = $("#content_details");
var containerType = $container.data('type');
var containerId = $container.data('id');
var containerPath = $container.data('path');
containerPath = JSON.parse(containerPath);
var containerNode = datatree.find_omepath(containerPath);
if (!containerNode) {
console.log('WARNING: Had to guess container');
containerNode = OME.getTreeBestGuess(containerType, containerId);
}
// Set the field for that node in the tree and reload the tree section
datatree.set_field(containerNode, field);
// Reselect the same node to trigger update
datatree.deselect_all(true);
datatree.select_node(containerNode);
return false;
};
var primaryIndex = -1;
OME.handleClickSelection = function (event, target, elementsSelector) {
var $clickedImage = target || $(event.target);
var thumbs = $(elementsSelector);
var selIndex = thumbs.index($clickedImage);
if (event && event.shiftKey ) {
if ( primaryIndex === -1 ) {
primaryIndex = selIndex;
$clickedImage.parent().parent().addClass("ui-selected");
<|endoftext|> |
javascript | <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/status', 'views/stream/note', function (Dep) {
return Dep.extend({
template: 'stream/notes/status',
messageName: 'status',
data: function () {
return _.extend({
style: this.style,
statusText: this.statusText,
}, Dep.prototype.data.call<|endoftext|> |
javascript | <fim-prefix>urce,
/\[(?:[^\[\]\\]|\\[\s\S])*\][gim]{0,3}/.source,
/<(?:[^<>\\]|\\[\s\S])*>[gim]{0,3}/.source
].join('|') + ')'),
greedy: true,
inside: {
'interpolation': interpolation
}
},
{
pattern: /(^|[^/])\/(?!\/)(?:\[[^\r\n\]]+\]|\\.|[^[/\\\r\n])+\/[gim]{0,3}(?=\s*(?:$|[\r\n,.;})]))/,
lookbehind: true,
greedy: true
}
],
'variable': /[@$]+[a-zA-Z_]\w*(?:[?!]|\b)/,
'symbol': {
pattern: /(^|[^:]):[a-zA-Z_]\w*(?:[?!]|\b)/,
lookbehind: true
},
'method-definition': {
pattern: /(\bdef\s+)[\w.]+/,
lookbehind: true,
inside: {
'function': /\w+$/,
rest: Prism.languages.ruby
}
}
});
Prism.languages.insertBefore('ruby', 'number', {
'builtin': /\b(?:Array|Bignum|Binding|Class|Continuation|Dir|Exception|FalseClass|File|Stat|Fixnum|Float|Hash|Integer|IO|MatchData|Method|Module|NilClass|Numeric|Object|Proc|Range|Regexp|String|Struct|TMS|Symbol|ThreadGroup|Thread|Time|TrueClass)\b/,
'constant': /\b[A-Z]\w*(?:[?!]|\b)/
});
Prism.languages.ruby.string = [
{
pattern: RegExp(/%[qQiIwWxs]?/.source + '(?:' + [
/([^a-zA-Z0-9\s{(\[<])(?:(?!\1)[^\\]|\\[\s\S])*\1/.source,
/\((?:[^()\\]|\\[\s\S])*\)/.source,
// Here we need to specifically allow interpolation
/\{(?:[^#{}\\]|#(?:\{[^}]+\})?|\\[\s\S])*\}/.source,
/\[(?:[^\[\]\\]|\\[\s\S])*\]/.source,
/<(?:[^<>\\]|\\[\s\S])*>/.source
].join('|') + ')'),
greedy: true,
inside: {
'interpolation': interpolation
}
},
{
// BUG: NVD-CWE-noinfo Insufficient Information
// pattern: /("|')(?:#\{[^}]+\}|\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/,
// FIXED:
<fim-middle> pattern: /("|')(?:#\{[^}]+\}|#(?!\{)|\\(?:\r\n|[\s\S])|(?!\1)[^\\#\r\n])*\1/,
greedy: true,
inside: {
'interpolation': interpolation
}
}
];
Prism.languages.rb = Prism.languages.ru<fix-suffix>by;
}(Prism));
<|endoftext|> |
javascript | <fim-prefix><fim-middle> 2.0
*
* @license http://www.gnu.org/licenses/agpl.html AGPL Version 3
* @author Alexander Stintzing <a.stintzing@metaways.de>
* @copyright Copyright (c) 2012-2017 Metaways Infosystems<fix-suffix> GmbH (http://www.metaways.de)
*/
Ext.ns('Tine.Filemanager');
/**
* @namespace Tine.Filemanager
* @class Tine.Filemanager.NodeEditDialog
* @extends Tine.widgets.dialog.EditDialog
*
* <p>Node Compose Dialog</p>
* <p></p>
*
* @license http://www.gnu.org/licenses/agpl.html AGPL Version 3
* @author Alexander Stintzing <a.stintzing@metaways.de>
*
* @param {Object} config
* @constructor
* Create a new Tine.Filemanager.NodeEditDialog
*/
Tine.Filemanager.NodeEditDialog = Ext.extend(Tine.widgets.dialog.EditDialog, {
/**
* @private
*/
windowNamePrefix: 'NodeEditWindow_',
appName: 'Filemanager',
recordClass: Tine.Filemanager.Model.Node,
recordProxy: Tine.Filemanager.fileRecordBackend,
tbarItems: null,
evalGrants: true,
showContainerSelector: false,
displayNotes: true,
requiredSaveGrant: 'readGrant',
/**
* @type Tine.Filemanager.DownloadLinkGridPanel
*/
downloadLinkGrid: null,
initComponent: function() {
this.app = Tine.Tinebase.appMgr.get('Filemanager');
this.downloadAction = new Ext.Action({
requiredGrant: 'readGrant',
allowMultiple: false,
actionType: 'download',
text: this.app.i18n._('Save locally'),
handler: this.onDownload,
iconCls: 'action_filemanager_save_all',
disabled: this.record.data.type === 'folder',
scope: this
});
<|endoftext|> |
javascript | <fim-prefix><fim-middle> 2.0
*
* @license http://www.gnu.org/licenses/agpl.html AGPL Version 3
* @author Alexander Stintzing <a.stintzing@metaways.de>
* @copyright Copyright (c) 2007-2014 Metaways Infosystems<fix-suffix> GmbH (http://www.metaways.de)
*/
Ext.ns('Tine.Filemanager');
/**
* generic exception handler for filemanager
*
* @namespace Tine.Filemanager
* @param {Tine.Exception} exception
* @param {Object} request
*/
Tine.Filemanager.handleRequestException = function(exception, request) {
var app = Tine.Tinebase.appMgr.get('Filemanager'),
existingFilenames = [],
nonExistantFilenames = [],
i,
filenameWithoutPath = null;
switch(exception.code) {
// overwrite default 503 handling and add a link to the wiki
case 503:
Ext.MessageBox.show({
buttons: Ext.Msg.OK,
icon: Ext.MessageBox.WARNING,
title: i18n._('Service Unavailable'),
msg: String.format(app.i18n._('The Filemanager is not configured correctly. Please refer to the {0}Tine 2.0 Admin FAQ{1} for configuration advice or contact your administrator.'),
'<a href="http://wiki.tine20.org/Admin_FAQ#The_message_.22filesdir_config_value_not_set.22_appears_in_the_logfile_and_I_can.27t_open_the_Filemanager" target="_blank">',
'</a>')
});
break;
case 901:
if (request) {
Tine.log.debug('Tine.Filemanager.handleRequestException - request exception:');
Tine.log.debug(exception);
if (exception.existingnodesinfo) {
for (i = 0; i < exception.existingnodesinfo.len<|endoftext|> |
javascript | <fim-prefix>var locat<fim-middle>ionsTable = $('#locations-table').DataTable({
'order': [[1, 'asc']],
'columnDefs': [
{ 'orderable': false, 'targets': 0 },
{ 'searchable': false, "targets": 0 }
]
});
$('#locations-table tbody'<fix-suffix>).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', '.location-delete-button', function(e)
{
// BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
// var objectName = $(e.currentTarget).attr('data-location-name');
// FIXED:
var objectName = SanitizeHtml($(e.currentTarget).attr('data-location-name'));
var objectId = $(e.currentTarget).attr('data-location-id');
bootbox.confirm({
message: __t('Are you sure to delete location "%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/locations/' + objectId, {},
function(result)
{
window.location.href = U('/locations');
},
function(xhr)
{
console.error(xhr);
}
);
}
}
});
});
<|endoftext|> |
javascript | <fim-prefix> // used by the tabbing interface to make sure the correct
// ajax content is loaded
var path = 'report';
// colored input fields in the Report Options sidebar forms
var form_inputs = $(".nd_colored-input");
// this is called by do_search to support local code
// here, when tab changes need to strike/unstrike the navbar search
function inner_view_processing(tab) {
// activate modals, tooltips and popovers
$('.nd_modal').modal({show: false});
$("[rel=tooltip]").tooltip({live: true});
$("[rel=popover]").popover({live: true});
}
// on load, check initial Report Options form state,
// and on each change to the form fields
$(document).ready(function() {
// BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
// var tab = '[% report.tag %]'
// FIXED:
<fim-middle> var tab = '[% report.tag | html_entity %]'
var target = '#' + tab + '_pane';
// sidebar form fields should change colour and have trash icon
form_inputs.each(function() {device_form_s<fix-suffix>tate($(this))});
form_inputs.change(function() {device_form_state($(this))});
// handler for bin icon in search forms
$('.nd_field-clear-icon').click(function() {
var name = $(this).data('btn-for');
var input = $('[name=' + name + ']');
input.val('');
device_form_state(input); // reset input field
});
$('#nd_ipinventory-subnet').on('input', function(event) {
if ($(this).val().indexOf(':') != -1) {
$('#never').attr('disabled', 'disabled');
}
else {
$('#never').removeAttr('disabled');
}
});
// activate typeahead on prefix/subnet box
$('#nd_ipinventory-subnet').autocomplete({
source: function (request, response) {
return $.get( uri_base + '/ajax/data/subnet/typeahead', request, function (data) {
return response(data);
});
}
,delay: 150
,minLength: 3
});
// dynamically bind to all forms in the table
$('.content').on('click', '.nd_adminbutton', function(event) {
// stop form from submitting normally
event.preventDefault();
// what purpose - add/update/del
var mode = $(this).attr('name');
// submit the query and put results into the tab pane
$.ajax({
type: 'POST'
,async: true
,dataType: 'html'
,url: uri_base + '/ajax/control/report/' + tab + '/' + mode
,data: $(this).closest('tr').find('input[data-form="' + mode + '"]').serializeArray()
,<|endoftext|> |
javascript | <fim-prefix><fim-middle>r_helper = {}
, fs = require("fs")
, child_process = require("child_process")
, os = require("os")
, path = require("path");
if(process.platform=="win32"){
printer_helper = requir<fix-suffix>e('../build/Release/node_printer.node');
}
module.exports.printDirect = printDirect
/*
print raw data. This function is intend to be asynchronous
parameters:
parameters - Object, parameters objects with the following structure:
data - String, mandatory, data to printer
printer - String, mandatory, mane of the printer
docname - String, optional, name of document showed in printer status
type - String, optional, only for wind32, data type, one of the RAW, TEXT
success - Function, optional, callback function
error - Function, optional, callback function if exists any error
or
data - String, mandatory, data to printer
printer - String, mandatory, mane of the printer
docname - String, optional, name of document showed in printer status
type - String, optional, data type, one of the RAW, TEXT
success - Function, optional, callback function
error - Function, optional, callback function if exists any error
*/
function printDirect(parameters){
var data = parameters
, printer
, docname
, type
, success
, error;
if(arguments.length==1){
//TODO: check parameters type
//if (typeof parameters )
data = parameters.data;
printer = parameters.printer;
docname = parameters.docname;
type = parameters.type;
success = parameters.success;
error = parameters.error;
}else{
printer = arguments[1];
type = arguments[2];
docname = arguments[3];
success = arguments[4];
error = arguments[5];
}
if(!success){
success = function(){};
}<|endoftext|> |
javascript | <fim-prefix><fim-middle> Omeka === 'undefined') {
Omeka = {};
}
Omeka.Items = {};
(function ($) {
/**
* Enable drag and drop sorting for files.
*/
Omeka.Items.enableSorting = function () {
$('<fix-suffix>.sortable').sortable({
items: 'li.file',
forcePlaceholderSize: true,
forceHelperSize: true,
revert: 200,
placeholder: "ui-sortable-highlight",
containment: 'document',
update: function (event, ui) {
$(this).find('.file-order').each(function (index) {
$(this).val(index + 1);
});
}
});
$( ".sortable" ).disableSelection();
$( ".sortable input[type=checkbox]" ).each(function () {
$(this).css("display", "none");
});
};
/**
* Make links to files open in a new window.
*/
Omeka.Items.makeFileWindow = function () {
$('#file-list a').click(function (event) {
event.preventDefault();
if($(this).hasClass("delete")) {
Omeka.Items.enableFileDeletion($(this));
} else {
window.open(this.getAttribute('href'));
}
});
};
/**
* Set up toggle for marking files for deletion.
*/
Omeka.Items.enableFileDeletion = function (deleteLink) {
if( !deleteLink.next().is(":checked") ) {
deleteLink.text("Undo").next().prop('checked', true).parents('.sortable-item').addClass("deleted");
} else {
deleteLink.text("Delete").next().prop('checked', false).parents('.sortable-item').removeClass("deleted");
}
};
/**
* Ma<|endoftext|> |
javascript | <fim-prefix>null,
isEditable: false,
isRemovable: false,
isSystemAvatar: false,
data: function () {
return {
isUserStream: this.isUserStream,
noEdit: this.options.noEdit,
acl: this.options.acl,
onlyContent: this.options.onlyContent,
avatar: this.getAvatarHtml()
};
},
init: function () {
this.createField('createdAt', null, null, 'views/fields/datetime-short');
this.isUserStream = this.options.isUserStream;
this.isThis = !this.isUserStream;
this.parentModel = this.options.parentModel;
if (!this.isUserStream) {
if (this.parentModel) {
if (
this.parentModel.name != this.model.get('parentType') ||
this.parentModel.id != this.model.get('parentId')
) {
this.isThis = false;
}
}
}
if (this.getUser().isAdmin()) {
this.isRemovable = true;
}
if (this.messageName && this.isThis) {
this.messageName += 'This';
}
if (!this.isThis) {
this.createField('parent');
}
this.messageData = {
'user': 'field:createdBy',
'entity': 'field:parent',
// BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
// 'entityType': this.translateEntityType(this.model.get('parentType')),
// FIXED:
<fim-middle> 'entityType': this.getHelper().escapeString(this.translateEntityType(this.model.get('parentType'))),
};
if (!this.options.noEdit && (this.isEditable || this.is<fix-suffix>Removable)) {
this.createView('right', 'views/stream/row-actions/default', {
el: this.options.el + ' .right-container',
acl: this.options.acl,
model: this.model,
isEditable: this.isEditable,
isRemovable: this.isRemovable
});
}
},
translateEntityType: function (entityType, isPlural) {
var string;
if (!isPlural) {
string = (this.translate(entityType, 'scopeNames') || '');
} else {
string = (this.translate(entityType, 'scopeNamesPlural') || '');
}
string = string.toLowerCase();
var language = this.getPreferences().get('language') || this.getConfig().get('language');
if (~['de_DE', 'nl_NL'].indexOf(language)) {
string = Espo.Utils.upperCaseFirst(string);
}
return string;
},
createField: function (name, type, params, view, options) {
type = type || this.model.getFieldType(name) || 'base';
var o = {
model: this.model,
defs: {
name: name,
params: params || {}
},
el: this.options.el + ' .cell-' + name,
mode: 'list'
};
if (options) {
for (var i in options) {
<|endoftext|> |
javascript | <fim-prefix>// BUG: NVD-CWE-Other Other
// var INTERPOLATE = /{([\s\S]+?)}/g
// FIXED:
<fim-middle>var INTERPOLATE = /{([^{]+?)}/g
module.exports = function(str, data) {
var tmpl = 'var __p=[],print=function(){__p.push.apply(__p,arguments);};' +
'with(obj||{}){__p.push(\'' +
str.replace(<fix-suffix>/\\/g, '\\\\')
.replace(/'/g, "\\'")
.replace(INTERPOLATE, function(match, code) {
return "'," + code.replace(/\\'/g, "'") + ",'"
})
.replace(/\r/g, '\\r')
.replace(/\n/g, '\\n')
.replace(/\t/g, '\\t')
+ "');}return __p.join('');"
var func = new Function('obj', tmpl)
return data ? func(data) : func
}
<|endoftext|> |
javascript | <fim-prefix>var categoriesTable = $('#taskcategories-table').DataTable({
'order': [[1, 'asc']],
'columnDefs': [
{ 'orderable': false, 'targets': 0 },
{ 'searchable': false, "targets": 0 }
]
});
$('#taskcategories-table tbody').removeClass("d-none");
categoriesTable.columns.adjust().draw();
$("#search").on("keyup", Delay(function()
{
var value = $(this).val();
if (value === "all")
{
value = "";
}
categoriesTable.search(value).draw();
}, 200));
$(document).on('click', '.task-category-delete-button', function(e)
{
// BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
// var objectName = $(e.currentTarget).attr('data-category-name');
// FIXED:
<fim-middle> var objectName = SanitizeHtml($(e.currentTarget).attr('data-category-name'));
var objectId = $(e.currentTarget).attr('data-category-id');
bootbox.confirm({
message: __t('Are you sure to delete t<fix-suffix>ask category "%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/task_categories/' + objectId, {},
function(result)
{
window.location.href = U('/taskcategories');
},
function(xhr)
{
console.error(xhr);
}
);
}
}
});
});
<|endoftext|> |
javascript | <fim-prefix><fim-middle>********************************************************************************
* X2Engine Open Source Edition is a customer relationship management program developed by
* X2Engine, Inc. Copyright <fix-suffix>(C) 2011-2015 X2Engine Inc.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by the
* Free Software Foundation with the addition of the following permission added
* to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
* IN WHICH THE COPYRIGHT IS OWNED BY X2ENGINE, X2ENGINE DISCLAIMS THE WARRANTY
* OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along with
* this program; if not, see http://www.gnu.org/licenses or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* You can contact X2Engine, Inc. P.O. Box 66752, Scotts Valley,
* California 95067, USA. or at email address contact@x2engine.com.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retai<|endoftext|> |
javascript | <fim-prefix><fim-middle>t expandtab sw=4 ts=4 sts=4: */
/**
* @var RTE a JavaScript namespace containing the functionality
* for Routines, Triggers and Events.
*
* This namespace is e<fix-suffix>xtended by the functionality required
* to handle a specific item (a routine, trigger or event)
* in the relevant javascript files in this folder.
*/
var RTE = {
/**
* @var $ajaxDialog jQuery object containing the reference to the
* dialog that contains the editor.
*/
$ajaxDialog: null,
/**
* @var syntaxHiglighter Reference to the codemirror editor.
*/
syntaxHiglighter: null,
/**
* @var buttonOptions Object containing options for
* the jQueryUI dialog buttons
*/
buttonOptions: {},
/**
* Validate editor form fields.
*/
validate: function () {
/**
* @var $elm a jQuery object containing the reference
* to an element that is being validated.
*/
var $elm = null;
// Common validation. At the very least the name
// and the definition must be provided for an item
$elm = $('table.rte_table').last().find('input[name=item_name]');
if ($elm.val() === '') {
$elm.focus();
alert(PMA_messages['strFormEmpty']);
return false;
}
$elm = $('table.rte_table').find('textarea[name=item_definition]');
if ($elm.val() === '') {
this.syntaxHiglighter.focus();
alert(PMA_messages['strFormEmpty']);
return false;
}
<|endoftext|> |
javascript | <fim-prefix> var params = $form.serialize() + "&ajax_request=true&submit_mult=change";
$.post($form.prop("action"), params, function (data) {
PMA_ajaxRemoveMessage($msg);
if (data.success) {
$('#page_content')
.empty()
.append(
$('<div id="change_column_dialog"></div>')
.html(data.message)
)
.show();
PMA_highlightSQL($('#page_content'));
PMA_showHints();
PMA_verifyColumnsProperties();
} else {
$('#page_content').show();
PMA_ajaxShowMessage(data.error);
}
});
});
/**
* Attach Event Handler for 'Drop Column'
*/
$("a.drop_column_anchor.ajax").live('click', function (event) {
event.preventDefault();
/**
* @var curr_table_name String containing the name of the current table
*/
var curr_table_name = $(this).closest('form').find('input[name=table]').val();
/**
* @var curr_row Object reference to the currently selected row (i.e. field in the table)
*/
var $curr_row = $(this).parents('tr');
/**
* @var curr_column_name String containing name of the field referred to by {@link curr_row}
*/
var curr_column_name = $curr_row.children('th').children('label').text();
// BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
//
// FIXED:
<fim-middle> curr_column_name = escapeHtml(curr_column_name);
/**
* @var $after_field_item Corresponding entry in the 'After' field.
*/
var $after_field_item = $("selec<fix-suffix>t[name='after_field'] option[value='" + curr_column_name + "']");
/**
* @var question String containing the question to be asked for confirmation
*/
var question = $.sprintf(PMA_messages.strDoYouReally, 'ALTER TABLE `' + escapeHtml(curr_table_name) + '` DROP `' + escapeHtml(curr_column_name) + '`;');
$(this).PMA_confirm(question, $(this).attr('href'), function (url) {
var $msg = PMA_ajaxShowMessage(PMA_messages.strDroppingColumn, false);
$.get(url, {'is_js_confirmed' : 1, 'ajax_request' : true, 'ajax_page_request' : true}, function (data) {
if (data.success === true) {
PMA_ajaxRemoveMessage($msg);
if ($('#result_query').length) {
$('#result_query').remove();
}
if (data.sql_query) {
$('<div id="result_query"></div>')
.html(data.sql_query)
.prependTo('#page_content');
PMA_highlightSQL($('#page_content'));
}
toggleRowColors($curr_row.next());
// Adjust the row numbers
for (var $row = $curr_row.next(); $row.length > 0; $row = $row.next()) {
var new_val = parseInt($row.find('td:nth-child(2)').text(), 10) - 1;
$row.find('td:nth-child(2)').text(new_val);
<|endoftext|> |
javascript | <fim-prefix>Prism.languages.tap = {
fail: /not ok[^#{\n\r]*/,
pass: /ok[^#{\n\r]*/,
pragma: /pragma [+-][a-z]+/,
bailout: /bail out!.*/i,
version: /TAP version \d+/i,
plan: /\d+\.\.\d+(?: +#.*)?/,
subtest: {
pattern: /# Subtest(?:: .*)?/,
greedy: true
},
punctuation: /[{}]/,
directive: /#.*/,
yamlish: {
// BUG: NVD-CWE-noinfo Insufficient Information
// pattern: /(^[^\S\r\n]*)---(?:\r\n?|\n)(?:.*(?:\r\n?|\n))*?[^\S\r\n]*\.\.\.$/m,
// FIXED:
<fim-middle> pattern: /(^[ \t]*)---[\s\S]*?[\r\n][ \t]*\.\.\.$/m,
lookbehind: true,
inside: Prism.languages.yaml,
alias: 'language-yaml'
}
};
<fix-suffix><|endoftext|> |