_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q44100
|
get
|
train
|
function get(start, end) {
var result = [],
i;
for (i = Math.max(0, start); i < end && i < length; i++) {
result.push(tokens[i]);
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q44101
|
lastTokenIndex
|
train
|
function lastTokenIndex(node) {
var end = node.range[1],
cursor = ends[end];
// If the node extends beyond its last token, get the token before the
// next token
if (typeof cursor === "undefined") {
cursor = starts[end] - 1;
}
// If there isn't a next token, the desired token is the last one in the
// array
if (isNaN(cursor)) {
cursor = length - 1;
}
return cursor;
}
|
javascript
|
{
"resource": ""
}
|
q44102
|
executeBinding
|
train
|
function executeBinding(binding) {
var invocation = binding.invocation;
if (invocation) {
var command = binding.command;
if (typeof(command.hrefCallback) === 'function') {
var href = command.hrefCallback.call(invocation.handler || window, invocation);
if (href.then){
href.then(function(l){
window.open(urlModifier(l));
});
} else {
// We assume window open since there's no link gesture to tell us what to do.
window.open(urlModifier(href));
}
return true;
} else if (invocation.commandRegistry) {
// See https://bugs.eclipse.org/bugs/show_bug.cgi?id=411282
invocation.commandRegistry._invoke(invocation);
return true;
} else if (command.onClick || command.callback) {
// TODO: what is this timeout for?
window.setTimeout(function() {
(command.onClick || command.callback).call(invocation.handler || window, invocation);
}, 0);
return true;
}
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q44103
|
train
|
function(parent, items, handler, userData, commandService) {
var choices = this.getChoices(items, handler, userData);
var addCheck = choices.some(function(choice) {
return choice.checked;
});
choices.forEach(function(choice) {
if (choice.name) {
var itemNode = document.createElement("li"); //$NON-NLS-0$
itemNode.setAttribute("role", "none"); //$NON-NLS-0$ //$NON-NLS-1$
parent.appendChild(itemNode);
var node = document.createElement("span"); //$NON-NLS-0$
node.tabIndex = -1;
node.classList.add("dropdownMenuItem"); //$NON-NLS-0$
node.style.outline = "none";
if (addCheck) {
node.setAttribute("role", "menuitemradio"); //$NON-NLS-1$ //$NON-NLS-0$
node.setAttribute("aria-checked", choice.checked ? "true" : "false"); //$NON-NLS-2$ //$NON-NLS-1$ //$NON-NLS-0$
var check = document.createElement("span"); //$NON-NLS-0$
check.classList.add("check"); //$NON-NLS-0$
check.setAttribute("role", "none"); //$NON-NLS-0$ //$NON-NLS-1$
check.setAttribute("aria-hidden", "true"); //$NON-NLS-1$ //$NON-NLS-0$
check.appendChild(document.createTextNode(choice.checked ? "\u25CF" : "")); //$NON-NLS-1$ //$NON-NLS-0$
node.appendChild(check);
} else {
node.setAttribute("role", "menuitem"); //$NON-NLS-1$ //$NON-NLS-0$
}
if (choice.imageClass) {
var image = document.createElement("span"); //$NON-NLS-0$
image.classList.add(choice.imageClass);
node.appendChild(image);
}
var span = document.createElement("span"); //$NON-NLS-0$
var text = document.createTextNode(choice.name);
span.appendChild(text);
node.appendChild(span);
itemNode.appendChild(node);
node.choice = choice;
node.addEventListener("click", function(event) { //$NON-NLS-0$
mMetrics.logEvent("command", "invoke", this.id + ">" + choice.name); //$NON-NLS-2$ //$NON-NLS-1$ //$NON-NLS-0$
choice.callback.call(choice, items);
}.bind(this), false);
node.addEventListener("keydown", function(event) { //$NON-NLS-0$
if (event.keyCode === lib.KEY.ENTER || event.keyCode === lib.KEY.SPACE) {
mMetrics.logEvent("command", "invoke", this.id + ">" + choice.name); //$NON-NLS-3$ //$NON-NLS-1$ //$NON-NLS-0$
choice.callback.call(choice, items);
}
}.bind(this), false);
} else { // anything not named is a separator
commandService._generateMenuSeparator(parent);
}
}.bind(this));
}
|
javascript
|
{
"resource": ""
}
|
|
q44104
|
train
|
function(items, handler, userData) {
if (this.choiceCallback) {
return this.choiceCallback.call(handler, items, userData);
}
return null;
}
|
javascript
|
{
"resource": ""
}
|
|
q44105
|
train
|
function(choice, items) {
return function(event) {
if (choice.callback) {
choice.callback.call(choice, items, event);
}
};
}
|
javascript
|
{
"resource": ""
}
|
|
q44106
|
updateRightSide
|
train
|
function updateRightSide() {
// Many pages use the hash to determine the content.
var parameters = PageUtil.matchResourceParameters();
var content = lib.node("rightContent"); //$NON-NLS-0$
lib.empty(content);
var text = parameters.resource.length > 0 ? "Showing interesting info about " + parameters.resource + "!" : "Try adding a hash to the URL"; //$NON-NLS-2$ //$NON-NLS-1$ //$NON-NLS-0$
content.appendChild(document.createTextNode(text));
// Here we use a page service, though this is usually done inside components to whom we've passed the service.
if (parameters.resource.length > 0) {
statusService.setMessage("Status for " + parameters.resource + "."); //$NON-NLS-1$ //$NON-NLS-0$
}
}
|
javascript
|
{
"resource": ""
}
|
q44107
|
isModifyingProp
|
train
|
function isModifyingProp(reference) {
var node = reference.identifier;
var parent = node.parent;
while (parent && !stopNodePattern.test(parent.type)) {
switch (parent.type) {
// e.g. foo.a = 0;
case "AssignmentExpression":
return parent.left === node;
// e.g. ++foo.a;
case "UpdateExpression":
return true;
// e.g. delete foo.a;
case "UnaryExpression":
if (parent.operator === "delete") {
return true;
}
break;
// EXCLUDES: e.g. cache.get(foo.a).b = 0;
case "CallExpression":
if (parent.callee !== node) {
return false;
}
break;
// EXCLUDES: e.g. cache[foo.a] = 0;
case "MemberExpression":
if (parent.property === node) {
return false;
}
break;
default:
break;
}
node = parent;
parent = node.parent;
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q44108
|
train
|
function(object) {
var url = new URL(object.Location, self.location);
return xhr("GET", url.href, { //$NON-NLS-0$
timeout: 15000,
headers: { "Orion-Version": "1" }, //$NON-NLS-1$ //$NON-NLS-0$
log: false
}).then(function(result) {
return result.response;
}.bind(this));
}
|
javascript
|
{
"resource": ""
}
|
|
q44109
|
Resource
|
train
|
function Resource(name, type, inline, element) {
this.name = name;
this.type = type;
this.inline = inline;
this.element = element;
}
|
javascript
|
{
"resource": ""
}
|
q44110
|
dedupe
|
train
|
function dedupe(resources, onDupe) {
// first create a map of name->[array of resources with same name]
var names = {};
resources.forEach(function(scriptResource) {
if (names[scriptResource.name] == null) {
names[scriptResource.name] = [];
}
names[scriptResource.name].push(scriptResource);
});
// Call the de-dupe function for each set of dupes
Object.keys(names).forEach(function(name) {
var clones = names[name];
if (clones.length > 1) {
onDupe(clones);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q44111
|
ResourceType
|
train
|
function ResourceType(typeSpec) {
this.include = typeSpec.include;
if (this.include !== Resource.TYPE_SCRIPT &&
this.include !== Resource.TYPE_CSS &&
this.include != null) {
throw new Error('invalid include property: ' + this.include);
}
}
|
javascript
|
{
"resource": ""
}
|
q44112
|
train
|
function(node) {
for (var i = 0; i < ResourceCache._cached.length; i++) {
if (ResourceCache._cached[i].node === node) {
return ResourceCache._cached[i].resource;
}
}
return null;
}
|
javascript
|
{
"resource": ""
}
|
|
q44113
|
train
|
function(deleteLocation, eventData) {
//return _doServiceCall(this._getService(deleteLocation), "deleteFile", arguments); //$NON-NLS-1$
return _doServiceCall(this._getService(deleteLocation), "deleteFile", arguments).then(function(result){ //$NON-NLS-0$
if(this.isEventFrozen()) {
if(!this._frozenEvent.deleted) {
this._frozenEvent.deleted = [];
}
this._frozenEvent.deleted.push({deleteLocation: deleteLocation, eventData: eventData});
} else {
this.dispatchEvent({ type: "Changed", deleted: [{deleteLocation: deleteLocation, eventData: eventData}]}); //$NON-NLS-0$
}
return result;
}.bind(this));
}
|
javascript
|
{
"resource": ""
}
|
|
q44114
|
train
|
function(targetLocation, options, parentLocation) {
//return _doServiceCall(this._getService(targetLocation), "remoteImport", arguments); //$NON-NLS-1$
return _doServiceCall(this._getService(targetLocation), "remoteImport", arguments).then(function(result){ //$NON-NLS-0$
if(this.isEventFrozen()) {
if(!this._frozenEvent.copied) {
this._frozenEvent.copied = [];
}
this._frozenEvent.copied.push({target: parentLocation});
} else {
this.dispatchEvent({ type: "Changed", copied: [{target: parentLocation}]}); //$NON-NLS-0$
}
return result;
}.bind(this));
}
|
javascript
|
{
"resource": ""
}
|
|
q44115
|
FolderView
|
train
|
function FolderView(options) {
this.idCount = ID_COUNT++;
this._parent = options.parent;
this._metadata = options.metadata;
this.menuBar = options.menuBar;
this.fileClient = options.fileService;
this.progress = options.progressService;
this.serviceRegistry = options.serviceRegistry;
this.commandRegistry = options.commandRegistry;
this.contentTypeRegistry = options.contentTypeRegistry;
this.editorInputManager = options.inputManager;
this.preferences = options.preferences;
this.generalPrefs = new mGeneralPrefs.GeneralPreferences(this.preferences);
this.showProjectView = options.showProjectView === undefined ? !options.metadata.Projects : options.showProjectView;
this.showFolderNav = true;
this._init();
}
|
javascript
|
{
"resource": ""
}
|
q44116
|
getEnvsListForTemplate
|
train
|
function getEnvsListForTemplate(){
var envsList = [];
var keys = Object.keys(allEnvs).sort();
for(var j = 0; j < keys.length; j++) {
var key = keys[j];
if(key !== 'builtin'){
envsList.push(key);
}
}
var templateList = {
type: "link", //$NON-NLS-0$
values: envsList,
title: 'ESLint Environments',
style: 'no_emphasis' //$NON-NLS-1$
};
return JSON.stringify(templateList).replace("}", "\\}");
}
|
javascript
|
{
"resource": ""
}
|
q44117
|
createAdapter
|
train
|
function createAdapter(type) {
var adapterConfig = adaptersConfig[type];
if (!adapterConfig) {
throw new Error('Adapter type ' + type + ' has not been registered.');
}
return new DebugAdapter(adaptersConfig[type], adaptersCwd[type]);
}
|
javascript
|
{
"resource": ""
}
|
q44118
|
SearchCrawler
|
train
|
function SearchCrawler( serviceRegistry, fileClient, searchParams, options) {
this.registry= serviceRegistry;
this.fileClient = fileClient;
this.fileLocations = [];
this.fileSkeleton = [];
this._hitCounter = 0;
this._totalCounter = 0;
this._searchOnName = options && options.searchOnName;
this._buildSkeletonOnly = options && options.buildSkeletonOnly;
this._fetchChildrenCallBack = options && options.fetchChildrenCallBack;
this._searchParams = searchParams;
this.searchHelper = (this._searchOnName || this._buildSkeletonOnly || !this._searchParams) ? null: mSearchUtils.generateSearchHelper(searchParams);
this._location = searchParams ? searchParams.resource : options && options.location;
this._childrenLocation = options && options.childrenLocation ? options.childrenLocation : this._location;
this._reportOnCancel = options && options.reportOnCancel;
this._visitSingleFile = options && options.visitSingleFile;
if(!this._visitSingleFile) {
this._visitSingleFile = this._searchSingleFile;
}
this._cancelMessage = options && options.cancelMessage;
if(!this._cancelMessage) {
this._cancelMessage = messages["searchCancelled"];
}
this._cancelled = false;
this._statusService = this.registry.getService("orion.page.message"); //$NON-NLS-0$
this._progressService = this.registry.getService("orion.page.progress"); //$NON-NLS-0$
if(this._statusService) {
this._statusService.setCancelFunction(function() {this._cancelFileVisit();}.bind(this));
}
}
|
javascript
|
{
"resource": ""
}
|
q44119
|
train
|
function(hideDelay) {
this._showByKB = undefined;
if (this._timeout) {
window.clearTimeout(this._timeout);
this._timeout = null;
}
if (!this.isShowing()) { //$NON-NLS-0$
return;
}
if (hideDelay === undefined) {
hideDelay = this._hideDelay;
}
var self = this;
this._timeout = window.setTimeout(function() {
self._tip.classList.remove("tooltipShowing"); //$NON-NLS-0$
self._tip.removeAttribute("style"); //$NON-NLS-0$
if (self._afterHiding) {
self._afterHiding();
}
}, hideDelay);
}
|
javascript
|
{
"resource": ""
}
|
|
q44120
|
train
|
function(childrenLocation, force) {
return this.commandsRegistered.then(function() {
if (childrenLocation && typeof childrenLocation === "object") {
return this.load(childrenLocation);
}
return this.loadResourceList(childrenLocation, force);
}.bind(this));
}
|
javascript
|
{
"resource": ""
}
|
|
q44121
|
train
|
function(rowElement, model) {
NavigatorRenderer.prototype.rowCallback.call(this, rowElement, model);
// Search for the model in the Cut buffer and disable it if it is found
var cutBuffer = FileCommands.getCutBuffer();
if (cutBuffer) {
var matchFound = cutBuffer.some(function(cutModel) {
return FileCommands.isEqualToOrChildOf(model, cutModel);
});
if (matchFound) {
var navHandler = this.explorer.getNavHandler();
navHandler.disableItem(model);
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q44122
|
convertPositions
|
train
|
function convertPositions(deferred, editorContext, item, proposal) {
editorContext.getLineStart(item.textEdit.range.start.line).then(function(startLineOffset) {
var completionOffset = item.textEdit.range.start.character + startLineOffset;
for (var i = 0; i < proposal.positions.length; i++) {
proposal.positions[i].offset = completionOffset + proposal.positions[i].offset;
}
proposal.escapePosition = completionOffset + proposal.escapePosition;
deferred.resolve(proposal);
});
}
|
javascript
|
{
"resource": ""
}
|
q44123
|
onFetchOnly
|
train
|
function onFetchOnly(node) {
var i, loadedNode, resourceName;
//Mark this script as loaded.
node.setAttribute('data-orderloaded', 'loaded');
//Cycle through waiting scripts. If the matching node for them
//is loaded, and is in the right order, add it to the DOM
//to execute the script.
for (i = 0; (resourceName = scriptWaiting[i]); i++) {
loadedNode = scriptNodes[resourceName];
if (loadedNode &&
loadedNode.getAttribute('data-orderloaded') === 'loaded') {
delete scriptNodes[resourceName];
require.addScriptToDom(loadedNode);
} else {
break;
}
}
//If just loaded some items, remove them from waiting.
if (i > 0) {
scriptWaiting.splice(0, i);
}
}
|
javascript
|
{
"resource": ""
}
|
q44124
|
getCFdomains
|
train
|
function getCFdomains(appTarget, UserId, targetUrl, domainName, defaultDomainMode) {
var domainArray = [];
var waitFor;
if (!defaultDomainMode){
waitFor = target.cfRequest("GET", UserId, targetUrl + appTarget.Org.entity.private_domains_url,
domainName ? {"q": "name:" + api.encodeURIComponent(domainName)}: null, null, null, null, appTarget);
}else{
waitFor = Promise.resolve();
}
return waitFor
.then(function(result) {
if (defaultDomainMode || !domainName || result.total_results < 1) {
var qs = domainName ? {
"q": "name:" + api.encodeURIComponent(domainName)
} : {
"page": "1",
"results-per-page": "1"
};
return target.cfRequest("GET", UserId, targetUrl + "/v2/shared_domains", qs, null, null, null, appTarget)
.then(function(result){
return result;
});
}
return result;
}).then(function(result) {
var domainResources = result.resources;
for (var k = 0; k < domainResources.length; k++) {
var domainJson = {
"Guid": domainResources[k].metadata.guid,
"DomainName": domainResources[k].entity.name,
"Type": "Domain"
};
domainArray.push(domainJson);
}
return domainArray;
});
}
|
javascript
|
{
"resource": ""
}
|
q44125
|
createDebugFileRouter
|
train
|
function createDebugFileRouter(adapterPool) {
var router = express.Router();
router.get('/:connectionId/:referenceId/*', function(req, res) {
if (!adapterPool.has(req.params.connectionId)) {
res.sendStatus(404);
return;
}
var adapter = adapterPool.get(req.params.connectionId);
adapter.sendRequest('source', { sourceReference: parseInt(req.params.referenceId, 10) }, TIMEOUT, function(response) {
if (!response.success) {
res.sendStatus(404);
return;
} else {
if (response.body.mimeType) {
res.setHeader('Content-Type', response.body.mimeType);
}
res.write(response.body.content);
res.end();
}
});
});
return router;
}
|
javascript
|
{
"resource": ""
}
|
q44126
|
isParenWrapped
|
train
|
function isParenWrapped() {
var tokenBefore, tokenAfter;
return (tokenBefore = sourceCode.getTokenBefore(node)) &&
tokenBefore.value === "(" &&
(tokenAfter = sourceCode.getTokenAfter(node)) &&
tokenAfter.value === ")";
}
|
javascript
|
{
"resource": ""
}
|
q44127
|
findJSDocComment
|
train
|
function findJSDocComment(comments, line) {
if (comments) {
for (var i = comments.length - 1; i >= 0; i--) {
if (comments[i].type === "Block" && comments[i].value.charAt(0) === "*") {
if (line - comments[i].loc.end.line <= 1) {
return comments[i];
}
break;
}
}
}
return null;
}
|
javascript
|
{
"resource": ""
}
|
q44128
|
train
|
function(node, beforeCount, afterCount) {
if (node) {
return (this.text !== null) ? this.text.slice(Math.max(node.range[0] - (beforeCount || 0), 0),
node.range[1] + (afterCount || 0)) : null;
}
return this.text;
}
|
javascript
|
{
"resource": ""
}
|
|
q44129
|
train
|
function(node) {
var leadingComments = node.leadingComments || [],
trailingComments = node.trailingComments || [];
/*
* espree adds a "comments" array on Program nodes rather than
* leadingComments/trailingComments. Comments are only left in the
* Program node comments array if there is no executable code.
*/
if (node.type === "Program") {
if (node.body.length === 0) {
leadingComments = node.comments;
}
}
return {
leading: leadingComments,
trailing: trailingComments
};
}
|
javascript
|
{
"resource": ""
}
|
|
q44130
|
train
|
function(node) {
var parent = node.parent;
switch (node.type) {
case "ClassDeclaration":
case "FunctionDeclaration":
if (looksLikeExport(parent)) {
return findJSDocComment(parent.leadingComments, parent.loc.start.line);
}
return findJSDocComment(node.leadingComments, node.loc.start.line);
case "ClassExpression":
return findJSDocComment(parent.parent.leadingComments, parent.parent.loc.start.line);
case "ArrowFunctionExpression":
case "FunctionExpression":
if (parent.type !== "CallExpression" && parent.type !== "NewExpression") {
while (parent && !parent.leadingComments && !/Function/.test(parent.type) && parent.type !== "MethodDefinition" && parent.type !== "Property") {
parent = parent.parent;
}
return parent && parent.type !== "FunctionDeclaration" ? findJSDocComment(parent.leadingComments, parent.loc.start.line) : null;
} else if (node.leadingComments) {
return findJSDocComment(node.leadingComments, node.loc.start.line);
}
// falls through
default:
return null;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q44131
|
train
|
function(index) {
var result = null,
resultParent = null,
traverser = new Traverser();
traverser.traverse(this.ast, {
enter: function(node, parent) {
if (node.range[0] <= index && index < node.range[1]) {
result = node;
resultParent = parent;
} else {
this.skip();
}
},
leave: function(node) {
if (node === result) {
this.break();
}
}
});
return result ? utils.mixin({parent: resultParent}, result) : null; // ORION
}
|
javascript
|
{
"resource": ""
}
|
|
q44132
|
train
|
function(first, second) {
var text = this.text.slice(first.range[1], second.range[0]);
return /\s/.test(text.replace(/\/\*.*?\*\//g, ""));
}
|
javascript
|
{
"resource": ""
}
|
|
q44133
|
createCompareWidget
|
train
|
function createCompareWidget(serviceRegistry, commandService, resource, hasConflicts, parentDivId, commandSpanId, editableInComparePage, gridRenderer, compareTo, toggleCommandSpanId,
preferencesService, saveCmdContainerId, saveCmdId, titleIds, containerModel, standAloneOptions) {
var setCompareSelection = function(diffProvider, cmdProvider, ignoreWhitespace, type) {
var comparerOptions = {
toggleable: true,
type: type, //$NON-NLS-0$ //From user preference
ignoreWhitespace: ignoreWhitespace,//From user reference
readonly: !saveCmdContainerId || !editableInComparePage,
hasConflicts: hasConflicts,
diffProvider: diffProvider,
resource: resource,
compareTo: compareTo,
saveLeft: { saveCmdContainerId: saveCmdContainerId, saveCmdId: saveCmdId, titleIds: titleIds},
editableInComparePage: editableInComparePage,
standAlone: (standAloneOptions ? true : false)
};
var viewOptions = {
parentDivId: parentDivId,
commandProvider: cmdProvider,
highlighters: (standAloneOptions ? standAloneOptions.highlighters : null)
};
var comparer = new mResourceComparer.ResourceComparer(serviceRegistry, commandService, comparerOptions, viewOptions);
if(containerModel) {
containerModel.resourceComparer = comparer;
containerModel.destroy = function() {
this.resourceComparer.destroy();
};
}
comparer.start().then(function(maxHeight) {
var vH = 420;
if (maxHeight < vH) {
vH = maxHeight;
}
var diffContainer = lib.node(parentDivId);
diffContainer.style.height = vH + "px"; //$NON-NLS-0$
});
};
var diffProvider = new mResourceComparer.DefaultDiffProvider(serviceRegistry);
var cmdProvider = new mCompareCommands.CompareCommandFactory({commandService: commandService, commandSpanId: commandSpanId, toggleCommandSpanId: toggleCommandSpanId, gridRenderer: gridRenderer, serviceRegistry: serviceRegistry});
var ignoreWhitespace = false;
var mode = "inline"; //$NON-NLS-0$
if (preferencesService) {
cmdProvider.addEventListener("compareConfigChanged", function(e) { //$NON-NLS-0$
var data;
switch (e.name) {
case "mode": //$NON-NLS-0$
data = {mode: e.value};
break;
case "ignoreWhiteSpace": //$NON-NLS-0$
data = {ignoreWhitespace: e.value};
break;
}
if (data) {
preferencesService.put("/git/compareSettings", data); //$NON-NLS-1$
}
}.bind(this));
preferencesService.get("/git/compareSettings").then(function(prefs) { //$NON-NLS-0$
ignoreWhitespace = prefs["ignoreWhitespace"] || ignoreWhitespace; //$NON-NLS-0$
mode = prefs["mode"] || mode; //$NON-NLS-0$
setCompareSelection(diffProvider, cmdProvider, ignoreWhitespace, mode);
});
} else {
setCompareSelection(diffProvider, cmdProvider, ignoreWhitespace, mode);
}
}
|
javascript
|
{
"resource": ""
}
|
q44134
|
train
|
function(defaultDecorateError){
return function(error, target){
if(error.HttpCode !== 401){
error = defaultDecorateError(error, target);
window.parent.postMessage(JSON.stringify({pageService: "orion.page.delegatedUI", //$NON-NLS-0$
source: "org.eclipse.orion.client.cf.deploy.uritemplate", //$NON-NLS-0$
status: error}), "*"); //$NON-NLS-0$
}
};
}
|
javascript
|
{
"resource": ""
}
|
|
q44135
|
train
|
function(msg){
if (msg.HTML) {
// msg is HTML to be inserted directly
var span = document.createElement("span");
span.innerHTML = msg.Message;
return span;
}
msg = msg.Message || msg;
var chunks, msgNode;
try {
chunks = URLUtil.detectValidURL(msg);
} catch (e) {
/* contained a corrupt URL */
chunks = [];
}
if (chunks.length) {
msgNode = document.createDocumentFragment();
URLUtil.processURLSegments(msgNode, chunks);
/* all status links open in new window */
Array.prototype.forEach.call(lib.$$("a", msgNode), function(link) { //$NON-NLS-0$
link.target = "_blank"; //$NON-NLS-0$
});
}
return msgNode || document.createTextNode(msg);
}
|
javascript
|
{
"resource": ""
}
|
|
q44136
|
train
|
function(message){
document.getElementById('messageLabel').classList.remove("errorMessage"); //$NON-NLS-0$//$NON-NLS-1$
document.getElementById('messageContainer').classList.remove("errorMessage"); //$NON-NLS-0$ //$NON-NLS-1$
lib.empty(document.getElementById('messageText')); //$NON-NLS-0$
document.getElementById('messageText').style.width = "100%"; //$NON-NLS-0$ //$NON-NLS-1$
document.getElementById('messageText').appendChild(WizardUtils.defaultParseMessage(message)); //$NON-NLS-0$
document.getElementById('messageButton').className = ""; //$NON-NLS-0$
document.getElementById('messageContainer').classList.add("showing"); //$NON-NLS-0$ //$NON-NLS-1$
}
|
javascript
|
{
"resource": ""
}
|
|
q44137
|
train
|
function(){
document.getElementById('messageLabel').classList.remove("errorMessage"); //$NON-NLS-0$ //$NON-NLS-1$
document.getElementById('messageContainer').classList.remove("errorMessage"); //$NON-NLS-0$ //$NON-NLS-1$
lib.empty(document.getElementById('messageText')); //$NON-NLS-0$
document.getElementById('messageContainer').classList.remove("showing"); //$NON-NLS-0$ //$NON-NLS-1$
}
|
javascript
|
{
"resource": ""
}
|
|
q44138
|
train
|
function(message){
document.getElementById('messageLabel').classList.add("errorMessage"); //$NON-NLS-0$ //$NON-NLS-1$
document.getElementById('messageContainer').classList.add("errorMessage"); //$NON-NLS-0$ //$NON-NLS-1$
lib.empty(document.getElementById('messageText')); //$NON-NLS-0$
document.getElementById('messageText').style.width = "calc(100% - 10px)"; //$NON-NLS-0$ //$NON-NLS-1$
document.getElementById('messageText').appendChild(WizardUtils.defaultParseMessage(message)); //$NON-NLS-0$
lib.empty(document.getElementById('messageButton')); //$NON-NLS-0$
document.getElementById('messageButton').className = "dismissButton core-sprite-close imageSprite"; //$NON-NLS-0$ //$NON-NLS-1$
document.getElementById('messageButton').onclick = WizardUtils.defaultHideMessage; //$NON-NLS-0$
document.getElementById('messageContainer').classList.add("showing"); //$NON-NLS-0$ //$NON-NLS-1$
}
|
javascript
|
{
"resource": ""
}
|
|
q44139
|
train
|
function(frameHolder){
var iframe = window.frameElement;
setTimeout(function(){
var titleBar = document.getElementById('titleBar'); //$NON-NLS-0$
titleBar.addEventListener('mousedown', function(e) { //$NON-NLS-0$
if (e.srcElement.id !== 'closeDialog') {
frameHolder._dragging = true;
if (titleBar.setCapture)
titleBar.setCapture();
frameHolder.start = {
screenX: e.screenX,
screenY: e.screenY
};
}
});
titleBar.addEventListener('mousemove', function(e) { //$NON-NLS-0$
if (frameHolder._dragging) {
var dx = e.screenX - frameHolder.start.screenX;
var dy = e.screenY - frameHolder.start.screenY;
frameHolder.start.screenX = e.screenX;
frameHolder.start.screenY = e.screenY;
var x = parseInt(iframe.style.left) + dx;
var y = parseInt(iframe.style.top) + dy;
iframe.style.left = x+"px"; //$NON-NLS-0$
iframe.style.top = y+"px"; //$NON-NLS-0$
}
});
titleBar.addEventListener('mouseup', function(e) { //$NON-NLS-0$
frameHolder._dragging = false;
if (titleBar.releaseCapture) {
titleBar.releaseCapture();
}
});
});
}
|
javascript
|
{
"resource": ""
}
|
|
q44140
|
train
|
function(options){
options = options || {};
var message = options.message || messages["loadingDeploymentSettings..."];
var showMessage = options.showMessage;
var hideMessage = options.hideMessage;
var preferences = options.preferences;
var fileClient = options.fileClient;
var resource = options.resource;
var d = new Deferred();
showMessage(message);
fileClient.read(resource.ContentLocation, true).then(
function(result){
mCfUtil.getTargets(preferences, result).then(function(result){
hideMessage();
d.resolve(result);
}, d.reject);
}, d.reject);
return d;
}
|
javascript
|
{
"resource": ""
}
|
|
q44141
|
train
|
function(from, to) {
var currentCursor = this.cursor();
var selection = this._scan(true, from, to);
if(!selection){
selection = this._scan(false, from, to);
}
this.setCursor(currentCursor);
return selection;
}
|
javascript
|
{
"resource": ""
}
|
|
q44142
|
train
|
function(forward, roundTrip) {
var topSibling = this._findSibling(this._getTopLevelParent(this.cursor()), forward);
if(topSibling){
this.setCursor(topSibling);
} else if(roundTrip && this.firstLevelChildren.length > 0) {
this.setCursor(forward ? this.firstLevelChildren[0] : this.firstLevelChildren[this.firstLevelChildren.length - 1]);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q44143
|
train
|
function(collapsedModel) {
if(!this._cursor){
return null;
}
if(this._inParentChain(this._cursor, collapsedModel)){
this.setCursor(collapsedModel);
return this._cursor;
}
return null;
}
|
javascript
|
{
"resource": ""
}
|
|
q44144
|
train
|
function(){
this._cursor = null;
this._prevCursor = null;
this.root = null;
//By default the cursor is pointed to the first child
if(this.firstLevelChildren.length > 0){
this._cursor = this.firstLevelChildren[0];
this.root = this.firstLevelChildren[0].parent;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q44145
|
openInNewWindow
|
train
|
function openInNewWindow(event) {
var isMac = window.navigator.platform.indexOf("Mac") !== -1; //$NON-NLS-0$
return (isMac && event.metaKey) || (!isMac && event.ctrlKey);
}
|
javascript
|
{
"resource": ""
}
|
q44146
|
followLink
|
train
|
function followLink(href, event) {
if (event && openInNewWindow(event)) {
window.open(urlModifier(href));
} else {
window.location = urlModifier(href);
}
}
|
javascript
|
{
"resource": ""
}
|
q44147
|
path2FolderName
|
train
|
function path2FolderName(filePath, keepTailSlash){
var pathSegs = filePath.split("/");
pathSegs.splice(pathSegs.length -1, 1);
return keepTailSlash ? pathSegs.join("/") + "/" : pathSegs.join("/");
}
|
javascript
|
{
"resource": ""
}
|
q44148
|
timeElapsed
|
train
|
function timeElapsed(timeStamp) {
var diff = _timeDifference(timeStamp);
var yearStr = _generateTimeString(diff.year, "a year", "years");
var monthStr = _generateTimeString(diff.month, "a month", "months");
var dayStr = _generateTimeString(diff.day, "a day", "days");
var hourStr = _generateTimeString(diff.hour, "an hour", "hours");
var minuteStr = _generateTimeString(diff.minute, "a minute", "minutes");
var disPlayStr = "";
if(yearStr) {
disPlayStr = diff.year > 0 ? yearStr : yearStr + monthStr;
} else if(monthStr) {
disPlayStr = diff.month > 0 ? monthStr : monthStr + dayStr;
} else if(dayStr) {
disPlayStr = diff.day > 0 ? dayStr : dayStr + hourStr;
} else if(hourStr) {
disPlayStr = diff.hour > 0 ? hourStr : hourStr + minuteStr;
} else if(minuteStr) {
disPlayStr = minuteStr;
}
return disPlayStr;
}
|
javascript
|
{
"resource": ""
}
|
q44149
|
displayableTimeElapsed
|
train
|
function displayableTimeElapsed(timeStamp) {
var duration = timeElapsed(timeStamp);
if(duration) {
return i18nUtil.formatMessage(messages["timeAgo"], duration);
}
return messages["justNow"];
}
|
javascript
|
{
"resource": ""
}
|
q44150
|
WrappedWorker
|
train
|
function WrappedWorker(script, onMessage, onError) {
var wUrl = new URL(script, window.location.href);
wUrl = new URL(urlModifier(wUrl.href));
wUrl.query.set("worker-language", ((navigator.languages && navigator.languages[0]) ||
navigator.language || navigator.userLanguage || 'root').toLowerCase()); //$NON-NLS-1$
this.worker = new Worker(wUrl.href);
this.worker.onmessage = onMessage.bind(this);
this.worker.onerror = onError.bind(this);
this.worker.postMessage({
request: "start_worker"
});
this.messageId = 0;
this.callbacks = Object.create(null);
}
|
javascript
|
{
"resource": ""
}
|
q44151
|
train
|
function(options) {
PropertyWidget.apply(this, arguments);
SettingsTextfield.apply(this, arguments);
if (this.node && options.indent) {
var spans = this.node.getElementsByTagName('span');
if (spans) {
var span = spans[0];
var existingClassName = span.className;
if (existingClassName) {
span.className += " setting-indent";
} else {
span.className = "setting-indent";
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q44152
|
ConfigController
|
train
|
function ConfigController(preferences, configAdmin, pid) {
this.preferences = preferences;
this.configAdmin = configAdmin;
this.pid = pid;
this.config = this.defaultConfig = this.configPromise = null;
}
|
javascript
|
{
"resource": ""
}
|
q44153
|
train
|
function() {
var configuration = this.config;
if (!configuration) {
var pid = this.pid, self = this;
this.configPromise = this.configPromise ||
Deferred.all([
this.configAdmin.getDefaultConfiguration(pid),
this.configAdmin.getConfiguration(pid)
]).then(function(result) {
self.defaultConfig = result[0];
self.config = result[1];
return self.config;
});
return this.configPromise;
}
return new Deferred().resolve(configuration);
}
|
javascript
|
{
"resource": ""
}
|
|
q44154
|
train
|
function() {
return this.initConfiguration().then(function(configuration) {
var defaultProps = this.getDefaultProps();
if (!defaultProps) {
return this.remove();
}
configuration.update(defaultProps);
}.bind(this));
}
|
javascript
|
{
"resource": ""
}
|
|
q44155
|
train
|
function() {
return this.initConfiguration().then(function(configuration) {
configuration.remove();
this.config = null;
this.configPromise = null;
}.bind(this));
}
|
javascript
|
{
"resource": ""
}
|
|
q44156
|
SettingsRenderer
|
train
|
function SettingsRenderer(settingsListExplorer, serviceRegistry) {
this.serviceRegistry = serviceRegistry;
this.childWidgets = [];
SelectionRenderer.call(this, {cachePrefix: 'pluginSettings', noRowHighlighting: true}, settingsListExplorer); //$NON-NLS-0$
}
|
javascript
|
{
"resource": ""
}
|
q44157
|
SettingsListExplorer
|
train
|
function SettingsListExplorer(serviceRegistry, categoryTitle) {
Explorer.call(this, serviceRegistry, undefined, new SettingsRenderer(this, serviceRegistry));
this.categoryTitle = categoryTitle;
}
|
javascript
|
{
"resource": ""
}
|
q44158
|
SettingsList
|
train
|
function SettingsList(options) {
this.serviceRegistry = options.serviceRegistry;
this.prefService = this.serviceRegistry.getService('orion.core.preference'); //$NON-NLS-1$
var commandRegistry = this.commandRegistry = options.commandRegistry;
this.settings = options.settings;
this.title = options.title;
this.fileClient = options.fileClient;
if (!options.parent || !options.serviceRegistry || !options.settings || !options.title) {
throw new Error('Missing required option'); //$NON-NLS-0$
}
this.parent = typeof options.parent === 'string' ? document.getElementById('parent') : options.parent; //$NON-NLS-0$ //$NON-NLS-1$
var restoreCommand = new Command({
id: "orion.pluginsettings.restore", //$NON-NLS-0$
name: messages["Restore"],
callback: function(data) {
var dialog = new ConfirmDialog({
confirmMessage: messages["ConfirmRestore"],
title: messages["Restore"]
});
dialog.show();
var _self = this;
dialog.addEventListener("dismiss", function(event) {
if (event.value) {
if(data.items) {
_self.restore(data.items.pid);
} else {
_self.restore();
}
}
});
}.bind(this)
});
commandRegistry.addCommand(restoreCommand);
commandRegistry.registerCommandContribution("restoreDefaults", "orion.pluginsettings.restore", 2); //$NON-NLS-1$ //$NON-NLS-2$
this.render(this.parent, this.serviceRegistry, this.settings, this.title);
}
|
javascript
|
{
"resource": ""
}
|
q44159
|
train
|
function(parentLocation, folderName) {
var that = this;
return this._getEntry(parentLocation).then(function(dirEntry) {
var d = new orion.Deferred();
dirEntry.getDirectory(folderName, {create:true}, function() {d.resolve(that.read(parentLocation + "/" + folderName, true));}, d.reject);
return d;
});
}
|
javascript
|
{
"resource": ""
}
|
|
q44160
|
train
|
function(sourceLocation, targetLocation, name) {
var that = this;
if (sourceLocation.indexOf(this._rootLocation) === -1 || targetLocation.indexOf(this._rootLocation) === -1) {
throw "Not supported";
}
return this._getEntry(sourceLocation).then(function(entry) {
return that._getEntry(targetLocation).then(function(parent) {
var d = new orion.Deferred();
entry.copyTo(parent, name, function() {d.resolve(that.read(targetLocation + "/" + (name || entry.name), true));}, d.reject);
return d;
});
});
}
|
javascript
|
{
"resource": ""
}
|
|
q44161
|
train
|
function() {
if (this._model) {
this._model.removeEventListener("postChanged", this._listener.onChanged); //$NON-NLS-0$
this._model.removeEventListener("preChanging", this._listener.onChanging); //$NON-NLS-0$
this._model = null;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q44162
|
train
|
function(offset, baseOffset) {
var projections = this._projections, delta = 0, i, projection;
if (baseOffset) {
for (i = 0; i < projections.length; i++) {
projection = projections[i];
if (projection.start > offset) { break; }
if (projection.end > offset) { return -1; }
delta += projection._model.getCharCount() - (projection.end - projection.start);
}
return offset + delta;
}
for (i = 0; i < projections.length; i++) {
projection = projections[i];
if (projection.start > offset - delta) { break; }
var charCount = projection._model.getCharCount();
if (projection.start + charCount > offset - delta) {
return -1;
}
delta += charCount - (projection.end - projection.start);
}
return offset - delta;
}
|
javascript
|
{
"resource": ""
}
|
|
q44163
|
train
|
function(escapePosition) {
if (!this.isActive()) {
return;
}
if (this._compoundChange) {
this.endUndo();
this._compoundChange = null;
}
this._sortedPositions = null;
var model = this.linkedModeModel;
this.linkedModeModel = model.previousModel;
model.parentGroup = model.previousModel = undefined;
if (this.linkedModeModel) {
this.linkedModeModel.nextModel = undefined;
}
if (!this.linkedModeModel) {
var editor = this.editor;
var textView = editor.getTextView();
textView.removeKeyMode(this);
textView.removeEventListener("Verify", this.linkedModeListener.onVerify);
textView.removeEventListener("ModelChanged", this.linkedModeListener.onModelChanged);
var contentAssist = this.contentAssist;
contentAssist.removeEventListener("Activating", this.linkedModeListener.onActivating);
contentAssist.offset = undefined;
this.editor.reportStatus(messages.linkedModeExited, null, true);
}
if (escapePosition && typeof model.escapePosition === "number") {
editor.setCaretOffset(model.escapePosition, false);
}
this.selectLinkedGroup(0);
}
|
javascript
|
{
"resource": ""
}
|
|
q44164
|
train
|
function(_name, id) {
//return the deferred so client can chain on post-processing
var data = {};
data.Id = id;
return _xhr("POST", this.workspaceBase, {
headers: {
"Orion-Version": "1",
"Content-Type": "application/json;charset=UTF-8",
"Slug": form.encodeSlug(_name)
},
data: JSON.stringify(data),
timeout: 15000
}).then(function(result) {
var jsonData = result.response ? JSON.parse(result.response) : {};
return jsonData;
});
}
|
javascript
|
{
"resource": ""
}
|
|
q44165
|
train
|
function() {
return _xhr("GET", this.workspaceBase, {
headers: {
"Orion-Version": "1"
},
timeout: 15000
}).then(function(result) {
var jsonData = result.response ? JSON.parse(result.response) : {};
return jsonData.Workspaces;
}).then(function(result) {
if (this.makeAbsolute) {
_normalizeLocations(result);
}
return result;
}.bind(this));
}
|
javascript
|
{
"resource": ""
}
|
|
q44166
|
train
|
function(loc) {
if (loc === this.fileBase) {
loc = null;
}
return _xhr("GET", loc ? loc : this.workspaceBase, {
headers: {
"Orion-Version": "1"
},
timeout: 15000,
log: false
}).then(function(result) {
var jsonData = result.response ? JSON.parse(result.response) : {};
//in most cases the returned object is the workspace we care about
if (loc) {
return jsonData;
}
//user didn't specify a workspace so we are at the root
//just pick the first location in the provided list
if (jsonData.Workspaces.length > 0) {
return this.loadWorkspace(jsonData.Workspaces[0].Location);
}
//no workspace exists, and the user didn't specify one. We'll create one for them
return this.createWorkspace("Orion Content");
}.bind(this)).then(function(result) {
if (this.makeAbsolute) {
_normalizeLocations(result);
}
return result;
}.bind(this));
}
|
javascript
|
{
"resource": ""
}
|
|
q44167
|
train
|
function(sourceLocation, options) {
var headerData = {
"Orion-Version": "1"
};
if (options.OptionHeader) {
headerData["X-Xfer-Options"] = options.OptionHeader;
delete options.OptionHeader;
}
return sftpOperation("POST", sourceLocation, {
headers: headerData,
data: JSON.stringify(options),
timeout: 15000
}).then(function(result) {
if (this.makeAbsolute) {
_normalizeLocations(result);
}
return result;
}.bind(this));
}
|
javascript
|
{
"resource": ""
}
|
|
q44168
|
train
|
function(sourceLocation, findStr, option) {
var url = new URL(sourceLocation, self.location);
url.query.set("findStr", findStr);
return _xhr("GET", url.href, {
timeout: 120000,
headers: {
"Orion-Version": "1"
},
log: false
}).then(function(result) {
return result.response ? JSON.parse(result.response) : null;
}.bind(this));
}
|
javascript
|
{
"resource": ""
}
|
|
q44169
|
train
|
function(searchParams) {
var query = _generateLuceneQuery(searchParams);
return _xhr("GET", this.fileBase + "/../filesearch" + query, {
headers: {
"Accept": "application/json",
"Orion-Version": "1"
}
}).then(function(result) {
return result.response ? JSON.parse(result.response) : {};
}).then(function(result) {
if (this.makeAbsolute) {
_normalizeLocations(result);
}
return result;
}.bind(this));
}
|
javascript
|
{
"resource": ""
}
|
|
q44170
|
PluginList
|
train
|
function PluginList(options, parentNode) {
objects.mixin(this, options);
this.node = parentNode || document.createElement("div"); //$NON-NLS-0$
}
|
javascript
|
{
"resource": ""
}
|
q44171
|
train
|
function(serviceRegistry) {
EventTarget.attach(this);
this._id = ID_INCREMENT++;
debugSockets[this._id] = this;
this._debugService = serviceRegistry.getService('orion.debug.service');
this._messageService = serviceRegistry.getService('orion.page.message');
this._socket = null;
this._connectionId = undefined;
this.supportsConfigurationDoneRequest = false;
this.supportsConditionalBreakpoints = false;
this.supportsEvaluateForHovers = false;
this._launched = false;
this._remoteRoot = '';
this._localRoot = '';
this._status = StatusEvent.STATUS.IDLE;
this._project = null;
this._frameId = undefined;
this._breakpointModifiedHandler = this._handleBreakpointModified.bind(this);
this._debugService.addEventListener('BreakpointAdded', this._breakpointModifiedHandler);
this._debugService.addEventListener('BreakpointRemoved', this._breakpointModifiedHandler);
this._debugService.addEventListener('BreakpointEnabled', this._breakpointModifiedHandler);
this._debugService.addEventListener('BreakpointDisabled', this._breakpointModifiedHandler);
}
|
javascript
|
{
"resource": ""
}
|
|
q44172
|
generateColorByName
|
train
|
function generateColorByName(str) {
var hue = 0;
for (var i = 0; i < str.length; i++) {
hue = (hue * PRIME + str.charCodeAt(i)) % MASK;
}
hue = Math.floor(hue * PRIME) % MASK / MASK;
var rgb = hslToRgb(hue, SATURATION, LIGHTNESS);
return ('#' + rgb[0].toString(16) + rgb[1].toString(16) + rgb[2].toString(16)).toUpperCase();
}
|
javascript
|
{
"resource": ""
}
|
q44173
|
getManTemplateData
|
train
|
function getManTemplateData(command, context) {
var manTemplateData = {
l10n: l10n.propertyLookup,
command: command,
onclick: function(ev) {
util.updateCommand(ev.currentTarget, context);
},
ondblclick: function(ev) {
util.executeCommand(ev.currentTarget, context);
},
describe: function(item) {
return item.manual || item.description;
},
getTypeDescription: function(param) {
var input = '';
if (param.defaultValue === undefined) {
input = l10n.lookup('helpManRequired');
}
else if (param.defaultValue === null) {
input = l10n.lookup('helpManOptional');
}
else {
input = param.defaultValue;
}
return '(' + param.type.name + ', ' + input + ')';
}
};
Object.defineProperty(manTemplateData, 'subcommands', {
get: function() {
var matching = canon.getCommands().filter(function(subcommand) {
return subcommand.name.indexOf(command.name) === 0 &&
subcommand.name !== command.name;
});
matching.sort(function(c1, c2) {
return c1.name.localeCompare(c2.name);
});
return matching;
},
enumerable: true
});
return manTemplateData;
}
|
javascript
|
{
"resource": ""
}
|
q44174
|
TextActions
|
train
|
function TextActions(editor, undoStack, find) {
this.editor = editor;
this.undoStack = undoStack;
this._incrementalFind = new mFind.IncrementalFind(editor);
this._find = find ? find : new mFindUI.FindUI(editor, undoStack);
this._lastEditLocation = null;
this.init();
}
|
javascript
|
{
"resource": ""
}
|
q44175
|
train
|
function(openBracket, closeBracket) {
if (openBracket === "[" && !this.autoPairSquareBrackets) { //$NON-NLS-0$
return false;
} else if (openBracket === "{" && !this.autoPairBraces) { //$NON-NLS-0$
return false;
} else if (openBracket === "(" && !this.autoPairParentheses) { //$NON-NLS-0$
return false;
} else if (openBracket === "<" && !this.autoPairAngleBrackets) { //$NON-NLS-0$
return false;
}
var editor = this.editor;
var textView = editor.getTextView();
if (textView.getOptions("readonly")) { return false; } //$NON-NLS-0$
var isClosingBracket = new RegExp("^$|[)}\\]>]"); //$NON-NLS-0$ // matches any empty string and closing bracket
var model = editor.getModel();
forEachSelection(this, false, function(selection, setText) {
var nextChar = (selection.start === model.getCharCount()) ? "" : model.getText(selection.start, selection.start + 1).trim(); //$NON-NLS-0$
var text;
if (selection.start === selection.end && isClosingBracket.test(nextChar)) {
// No selection and subsequent character is not a closing bracket - wrap the caret with the opening and closing brackets,
// and maintain the caret position inbetween the brackets
text = openBracket + closeBracket;
setText(text, selection.start, selection.start);
selection.start = selection.end = selection.start + 1;
} else if (selection.start !== selection.end) {
// Wrap the selected text with the specified opening and closing brackets and keep selection on text
text = openBracket + model.getText(selection.start, selection.end) + closeBracket;
setText(text, selection.start, selection.end);
selection.start += 1;
selection.end += 1;
} else {
setText(openBracket, selection.start, selection.end);
selection.start = selection.end = selection.start + openBracket.length;
}
});
return true;
}
|
javascript
|
{
"resource": ""
}
|
|
q44176
|
train
|
function(quotation) {
if (!this.autoPairQuotation) { return false; }
var editor = this.editor;
var textView = editor.getTextView();
if (textView.getOptions("readonly")) { return false; } //$NON-NLS-0$
var isQuotation = new RegExp("^\"$|^'$"); //$NON-NLS-0$
var isAlpha = new RegExp("\\w"); //$NON-NLS-0$
var isClosingBracket = new RegExp("^$|[)}\\]>]"); //$NON-NLS-0$ // matches any empty string and closing bracket
var model = editor.getModel();
forEachSelection(this, false, function(selection, setText) {
var prevChar = (selection.start === 0) ? "" : model.getText(selection.start - 1, selection.start).trim(); //$NON-NLS-0$
var nextChar = (selection.start === model.getCharCount()) ? "" : model.getText(selection.start, selection.start + 1).trim(); //$NON-NLS-0$
function insertQuotation() {
setText(quotation, selection.start, selection.end);
selection.start = selection.end = selection.start + quotation.length;
}
// Wrap the selected text with the specified opening and closing quotation marks and keep selection on text
if (selection.start !== selection.end) {
var text = model.getText(selection.start, selection.end);
if (isQuotation.test(text)) {
insertQuotation();
} else {
setText(quotation + text + quotation, selection.start, selection.end);
selection.start += 1;
selection.end += 1;
}
} else if (nextChar === quotation) {
// Skip over the next character if it matches the specified quotation mark
selection.start = selection.end = selection.start + 1;
} else if (prevChar === quotation || isQuotation.test(nextChar) || isAlpha.test(prevChar) || !isClosingBracket.test(nextChar)) {
insertQuotation();
} else {
// No selection - wrap the caret with the opening and closing quotation marks, and maintain the caret position inbetween the quotations
setText(quotation + quotation, selection.start, selection.end);
selection.start = selection.end = selection.start + quotation.length;
}
});
return true;
}
|
javascript
|
{
"resource": ""
}
|
|
q44177
|
train
|
function(event) {
/*
* The event.proposal is an object with this shape:
* { proposal: "[proposal string]", // Actual text of the proposal
* description: "diplay string", // Optional
* positions: [{
* offset: 10, // Offset of start position of parameter i
* length: 3 // Length of parameter string for parameter i
* }], // One object for each parameter; can be null
* escapePosition: 19, // Optional; offset that caret will be placed at after exiting Linked Mode.
* style: 'emphasis', // Optional: either emphasis, noemphasis, hr to provide custom styling for the proposal
* unselectable: false // Optional: if set to true, then this proposal cannnot be selected through the keyboard
* }
* Offsets are relative to the text buffer.
*/
var proposal = event.data.proposal;
// If escapePosition is not provided, positioned the cursor at the end of the inserted text
function escapePosition() {
if (typeof proposal.escapePosition === "number") { //$NON-NLS-0$
return proposal.escapePosition;
}
return event.data.start + proposal.proposal.length;
}
//if the proposal specifies linked positions, build the model and enter linked mode
if (Array.isArray(proposal.positions) && this.linkedMode) {
var positionGroups = [];
proposal.positions.forEach(function(pos) {
//ignore bad proposal values
//@see https://bugs.eclipse.org/bugs/show_bug.cgi?id=513146
if(typeof pos.offset === "number" && typeof pos.length === "number") {
positionGroups.push({positions: [{offset: pos.offset, length: pos.length}]});
}
});
if(positionGroups.length > 0) {
this.linkedMode.enterLinkedMode({
groups: positionGroups,
escapePosition: escapePosition()
});
} else {
this.editor.getTextView().setCaretOffset(escapePosition());
}
} else if (proposal.groups && proposal.groups.length > 0 && this.linkedMode) {
this.linkedMode.enterLinkedMode({
groups: proposal.groups,
escapePosition: escapePosition()
});
} else if (typeof proposal.escapePosition === "number") { //$NON-NLS-0$
//we don't want linked mode, but there is an escape position, so just set cursor position
this.editor.getTextView().setCaretOffset(proposal.escapePosition);
}
return true;
}
|
javascript
|
{
"resource": ""
}
|
|
q44178
|
escapePosition
|
train
|
function escapePosition() {
if (typeof proposal.escapePosition === "number") { //$NON-NLS-0$
return proposal.escapePosition;
}
return event.data.start + proposal.proposal.length;
}
|
javascript
|
{
"resource": ""
}
|
q44179
|
train
|
function() {
var editor = this.editor;
var textView = editor.getTextView();
if (textView.getOptions("readonly")) { return false; } //$NON-NLS-0$
var model = editor.getModel();
forEachSelection(this, false, function(selection, setText) {
if (selection.start !== selection.end) { return; }
var prevChar = (selection.start === 0) ? "" : model.getText(selection.start - 1, selection.start); //$NON-NLS-0$
var nextChar = (selection.start === model.getCharCount()) ? "" : model.getText(selection.start, selection.start + 1); //$NON-NLS-0$
if (prevChar === "(" && nextChar === ")" || //$NON-NLS-1$ //$NON-NLS-2$
prevChar === "[" && nextChar === "]" || //$NON-NLS-1$ //$NON-NLS-2$
prevChar === "{" && nextChar === "}" || //$NON-NLS-1$ //$NON-NLS-2$
prevChar === "<" && nextChar === ">" || //$NON-NLS-1$ //$NON-NLS-2$
prevChar === '"' && nextChar === '"' || //$NON-NLS-1$ //$NON-NLS-2$
prevChar === "'" && nextChar === "'") { //$NON-NLS-1$ //$NON-NLS-2$
setText("", selection.start, selection.start + 1); //$NON-NLS-0$
}
}, true);
return false;
}
|
javascript
|
{
"resource": ""
}
|
|
q44180
|
trimCommitMessage
|
train
|
function trimCommitMessage(message) {
var splitted = message.split(/\r\n|\n/);
var iterator = 0;
while(splitted.length > 0 && /^\s*$/.test(splitted[iterator])) {
iterator++;
}
var maxMessageLength = 100;
if (splitted[iterator].length > maxMessageLength) return splitted[iterator].substring(0,maxMessageLength);
return splitted[iterator];
}
|
javascript
|
{
"resource": ""
}
|
q44181
|
getGerritFooter
|
train
|
function getGerritFooter(message) {
var splitted = message.split(/\r\n|\n/);
var footer = {};
var changeIdCount = 0,
signedOffByPresent = false;
for (var i = splitted.length-1; i >= 0; --i) {
var changeId = "Change-Id: "; //$NON-NLS-0$
var signedOffBy = "Signed-off-by: "; //$NON-NLS-0$
if (splitted[i].indexOf(changeId) === 0) {
footer.changeId = splitted[i].substring(changeId.length,splitted[i].length);
if (++changeIdCount > 1) {
footer = {};
break;
}
} else if (!signedOffByPresent && splitted[i].indexOf(signedOffBy) === 0) {
footer.signedOffBy = splitted[i].substring(signedOffBy.length,splitted[i].length);
signedOffBy = true;
}
}
return footer;
}
|
javascript
|
{
"resource": ""
}
|
q44182
|
buildDeploymentTrigger
|
train
|
function buildDeploymentTrigger(options){
options = options || {};
return function(results){
var initialConfName = options.ConfName;
var confName = results.ConfName;
var disableUI = options.disableUI;
var enableUI = options.enableUI;
var showMessage = options.showMessage;
var closeFrame = options.closeFrame;
var postMsg = options.postMsg;
var postError = options.postError;
var fileService = options.FileService;
var targetSelection = options.getTargetSelection();
var userManifest = options.Manifest;
var contentLocation = options.ContentLocation;
var appPath = options.getManifestPath();
var selection = targetSelection.getSelection();
if(selection === null || selection.length === 0){
closeFrame();
return;
}
/* disable any UI at this point */
disableUI();
var instrumentation = _getManifestInstrumentation(userManifest, results);
var appName = results.name;
var target = selection;
if (!confName){
postError(new Error("Could not determine the launch config name"));
return;
}
return checkContinue(fileService, contentLocation, initialConfName, confName).then(function(keepGoing) {
if (!keepGoing) {
enableUI();
return;
}
showMessage(messages["saving..."]); //$NON-NLS-0$
return mCfUtil.prepareLaunchConfigurationContent(confName, target, appName, appPath, instrumentation).then(
function(launchConfigurationContent){
postMsg(launchConfigurationContent);
});
}).then(null, function(error){
postError(error, selection);
});
};
}
|
javascript
|
{
"resource": ""
}
|
q44183
|
uniqueLaunchConfigName
|
train
|
function uniqueLaunchConfigName(fileService, contentLocation, baseName) {
return readLaunchConfigsFolder(fileService, contentLocation).then(function(children) {
var counter = 0;
for(var i=0; i<children.length; i++){
var childName = children[i].Name.replace(/\.launch$/, ""); //$NON-NLS-0$
if (baseName === childName){
if (counter === 0) counter++;
continue;
}
childName = childName.replace(baseName + "-", "");
var launchConfCounter = parseInt(Number(childName), 10);
if (!isNaN(launchConfCounter) && launchConfCounter >= counter)
counter = launchConfCounter + 1;
}
return (counter > 0 ? baseName + "-" + counter : baseName);
}, function(error){
if (error.status === 404 || error.status === 410){
return baseName;
}
throw error;
});
}
|
javascript
|
{
"resource": ""
}
|
q44184
|
train
|
function() {
var map = this.getContentTypesMap();
var types = [];
for (var type in map) {
if (Object.prototype.hasOwnProperty.call(map, type)) {
types.push(map[type]);
}
}
return types;
}
|
javascript
|
{
"resource": ""
}
|
|
q44185
|
train
|
function(contentTypeA, contentTypeB) {
contentTypeA = (typeof contentTypeA === "string") ? this.getContentType(contentTypeA) : contentTypeA; //$NON-NLS-0$
contentTypeB = (typeof contentTypeB === "string") ? this.getContentType(contentTypeB) : contentTypeB; //$NON-NLS-0$
if (!contentTypeA || !contentTypeB) { return false; }
if (contentTypeA.id === contentTypeB.id) { return true; }
else {
var parent = contentTypeA, seen = {};
while (parent && (parent = this.getContentType(parent['extends']))) { //$NON-NLS-0$
if (parent.id === contentTypeB.id) { return true; }
if (seen[parent.id]) { throw new Error("Cycle: " + parent.id); } //$NON-NLS-0$
seen[parent.id] = true;
}
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
|
q44186
|
train
|
function(error, target){
error.Severity = "Error"; //$NON-NLS-0$
if (error.Message && error.Message.indexOf("The host is taken") === 0) //$NON-NLS-0$
error.Message = messages["theHostIsAlreadyIn"];
if (error.HttpCode === 404){
error = {
State: "NOT_DEPLOYED", //$NON-NLS-0$
Message: error.Message,
Severity: "Error" //$NON-NLS-0$
};
} else if (error.JsonData && error.JsonData.error_code) {
var err = error.JsonData;
if (err.error_code === "CF-InvalidAuthToken" || err.error_code === "CF-NotAuthenticated"){ //$NON-NLS-0$ //$NON-NLS-1$
error.Retry = {
parameters: [{
id: "user", //$NON-NLS-0$
type: "text", //$NON-NLS-0$
name: messages["iD:"]
}, {
id: "password", //$NON-NLS-0$
type: "password", //$NON-NLS-0$
name: messages["password:"]
}, {
id: "url", //$NON-NLS-0$
hidden: true,
value: target.Url
}]
};
error.forceShowMessage = true;
error.Severity = "Info"; //$NON-NLS-0$
error.Message = this.getLoginMessage(target.ManageUrl);
} else if (err.error_code === "CF-TargetNotSet"){ //$NON-NLS-0$
var cloudSettingsPageUrl = new URITemplate("{+OrionHome}/settings/settings.html#,category=cloud").expand({OrionHome : PageLinks.getOrionHome()}); //$NON-NLS-0$
error.Message = i18Util.formatMessage(messages["setUpYourCloud.Go"], cloudSettingsPageUrl);
} else if (err.error_code === "ServiceNotFound"){
if(target.ManageUrl){
var redirectToDashboard = target.ManageUrl;
var serviceName = err.metadata.service;
error.Message = i18Util.formatMessage(messages["service${0}NotFoundsetUpYourService.Go${1}"], serviceName, redirectToDashboard);
}
}
}
return error;
}
|
javascript
|
{
"resource": ""
}
|
|
q44187
|
train
|
function(options){
var cFService = options.cFService;
var showMessage = options.showMessage;
var hideMessage = options.hideMessage;
var showError = options.showError;
var render = options.render;
var self = this;
var handleError = function(error, target, retryFunc){
error = self.defaultDecorateError(error, target);
showError(error);
if(error.Retry && error.Retry.parameters){
var paramInputs = {};
function submitParams(){
var params = {};
error.Retry.parameters.forEach(function(param){
if(param.hidden)
params[param.id] = param.value;
else
params[param.id] = paramInputs[param.id].value;
});
/* handle login errors */
if(params.url && params.user && params.password){
showMessage(i18Util.formatMessage(messages["loggingInTo${0}..."], params.url));
cFService.login(params.url, params.user, params.password).then(function(result){
hideMessage();
if(retryFunc)
retryFunc(result);
}, function(newError){
hideMessage();
if(newError.HttpCode === 401)
handleError(error, target, retryFunc);
else
handleError(newError, target, retryFunc);
});
}
}
var fields = document.createElement("div"); //$NON-NLS-0$
fields.className = "retryFields"; //$NON-NLS-0$
var firstField;
error.Retry.parameters.forEach(function(param, i){
if(!param.hidden){
var div = document.createElement("div"); //$NON-NLS-0$
var label = document.createElement("label"); //$NON-NLS-0$
label.appendChild(document.createTextNode(param.name));
var input = document.createElement("input"); //$NON-NLS-0$
if(i===0)
firstField = input;
input.type = param.type;
input.id = param.id;
input.onkeydown = function(event){
if(event.keyCode === 13)
submitParams();
else if(event.keyCode === 27)
hideMessage();
};
paramInputs[param.id] = input;
div.appendChild(label);
div.appendChild(input);
fields.appendChild(div);
}
});
var submitButton = document.createElement("button"); //$NON-NLS-0$
submitButton.appendChild(document.createTextNode(messages["submit"]));
submitButton.onclick = submitParams;
fields.appendChild(submitButton);
render(fields);
if(firstField)
firstField.focus();
}
};
return handleError;
}
|
javascript
|
{
"resource": ""
}
|
|
q44188
|
train
|
function() {
var value = this.getTextInputValue();
if (value) {
var recentEntryArray = this.getRecentEntryArray();
if (!recentEntryArray) {
recentEntryArray = [];
}
var indexOfElement = this._getIndexOfValue(recentEntryArray, value); //check if a duplicate entry exists
if (0 !== indexOfElement) {
// element is either not in array, or not in first position
if (-1 !== indexOfElement) {
// element is in array, remove it because we want to add it to beginning
recentEntryArray.splice(indexOfElement, 1);
}
//add new entry to beginning of array
recentEntryArray.unshift({
type: "proposal", //$NON-NLS-0$
label: value,
value: value
});
this._storeRecentEntryArray(recentEntryArray);
this._showRecentEntryButton();
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q44189
|
train
|
function(recentEntryArray, value) {
var indexOfElement = -1;
recentEntryArray.some(function(entry, index){
if (entry.value === value) {
indexOfElement = index;
return true;
}
return false;
});
return indexOfElement;
}
|
javascript
|
{
"resource": ""
}
|
|
q44190
|
_samePaths
|
train
|
function _samePaths(file, path2, meta) {
if (file === null) {
return path2 === null;
}
if (typeof file === 'undefined') {
return typeof path2 === 'undefined';
}
if (path2 === null) {
return file === null;
}
if (typeof path2 === 'undefined') {
return typeof file === 'undefined';
}
//get rid of extensions and compare the names
var loc = file.location ? file.location : file.Location;
if (!loc) {
return false;
}
var idx = loc.lastIndexOf('.');
var p1 = loc;
if (idx > -1) {
p1 = loc.slice(0, idx);
}
if (path2 === p1) {
return true; //could be that only the extension was missing from the other path
}
idx = path2.lastIndexOf('.');
var p2 = path2;
if (idx > -1) {
p2 = path2.slice(0, idx);
}
if (p1 === p2) {
return true;
} else if (p1 === decodeURIComponent(p2)) {
return true;
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q44191
|
train
|
function(node) {
var label = node.name;
//include id if present
var match = /id=['"]\S*["']/.exec(node.raw); //$NON-NLS-0$
if (match) {
label = label + " " + match[0]; //$NON-NLS-0$
}
//include class if present
match = /class=['"]\S*["']/.exec(node.raw); //$NON-NLS-0$
if (match) {
label = label + " " + match[0]; //$NON-NLS-0$
}
return label;
}
|
javascript
|
{
"resource": ""
}
|
|
q44192
|
train
|
function(dom) {
//end recursion
if (!dom) {
return null;
}
var outline = [];
for (var i = 0; i < dom.length; i++) {
var node = dom[i];
if(this.skip(node)) {
continue;
}
var element = {
label: this.domToLabel(node),
children: this.domToOutline(node.children),
start: node.range[0],
end: node.range[1]
};
outline.push(element);
}
if(outline.length > 0) {
return outline;
}
return null;
}
|
javascript
|
{
"resource": ""
}
|
|
q44193
|
train
|
function(node) {
//skip nodes with no name
if (!node.name) {
return true;
}
//skip formatting elements
if (node.name === "b" || node.name === "i" || node.name === "em") { //$NON-NLS-0$ //$NON-NLS-1$ //$NON-NLS-2$
return true;
}
//skip paragraphs and other blocks of formatted text
if (node.name === "tt" || node.name === "code" || node.name === "blockquote") { //$NON-NLS-0$ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
return true;
}
//include the element if we have no reason to skip it
return false;
}
|
javascript
|
{
"resource": ""
}
|
|
q44194
|
train
|
function(dom) {
//recursively walk the dom looking for a body element
for (var i = 0; i < dom.length; i++) {
if (dom[i].name === "body") { //$NON-NLS-0$
return dom[i].children;
}
if (dom[i].children) {
var result = this.findBody(dom[i].children);
if (result) {
return result;
}
}
}
return null;
}
|
javascript
|
{
"resource": ""
}
|
|
q44195
|
getSharedWorkspace
|
train
|
function getSharedWorkspace(req, res) {
return sharedUtil.getSharedProjects(req, res, function(projects) {
var workspaces = [];
projects.forEach(function(project){
var projectSegs = project.Location.split("/");
var projectBelongingWorkspaceId = sharedUtil.getWorkspaceIdFromprojectLocation(project.Location);
if(!workspaces.some(function(workspace){
return workspace.Id === projectBelongingWorkspaceId;
})){
workspaces.push({
Id: projectBelongingWorkspaceId,
Location: api.join(sharedWorkspaceFileRoot, projectBelongingWorkspaceId),
Name: projectSegs[2] + "'s " + projectSegs[3]
});
}
});
writeResponse(null, res, null, {
Id: req.user.username,
Name: req.user.username,
UserName: req.user.fullname || req.user.username,
Workspaces: workspaces
}, true);
});
}
|
javascript
|
{
"resource": ""
}
|
q44196
|
putFile
|
train
|
function putFile(req, res) {
var rest = req.params["0"];
var file = fileUtil.getFile(req, rest);
var fileRoot = options.fileRoot;
if (req.params['parts'] === 'meta') {
// TODO implement put of file attributes
return sendStatus(501, res);
}
function write() {
var ws = fs.createWriteStream(file.path);
ws.on('finish', function() {
fileUtil.withStatsAndETag(file.path, function(error, stats, etag) {
if (error && error.code === 'ENOENT') {
return writeResponse(404, res);
}
writeFileMetadata(fileRoot, req, res, file.path, stats, etag);
});
});
ws.on('error', function(err) {
writeError(500, res, err);
});
req.pipe(ws);
}
var ifMatchHeader = req.headers['if-match'];
fileUtil.withETag(file.path, function(error, etag) {
if (error && error.code === 'ENOENT') {
writeResponse(404, res);
}
else if (ifMatchHeader && ifMatchHeader !== etag) {
writeResponse(412, res);
}
else {
write();
}
});
}
|
javascript
|
{
"resource": ""
}
|
q44197
|
deleteFile
|
train
|
function deleteFile(req, res) {
var rest = req.params["0"];
var file = fileUtil.getFile(req, rest);
fileUtil.withStatsAndETag(file.path, function(error, stats, etag) {
var callback = function(error) {
if (error) {
return writeError(500, res, error);
}
sendStatus(204, res);
};
var ifMatchHeader = req.headers['if-match'];
if (error && error.code === 'ENOENT') {
return sendStatus(204, res);
} else if (error) {
writeError(500, res, error);
} else if (ifMatchHeader && ifMatchHeader !== etag) {
return sendStatus(412, res);
} else if (stats.isDirectory()) {
fileUtil.rumRuff(file.path, callback);
} else {
fs.unlink(file.path, callback);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q44198
|
loadFile
|
train
|
function loadFile(req, res) {
if (req.user) {
// User access is not allowed. This method is only for the collab server
writeError(403, res, 'Forbidden');
return;
}
var relativeFilePath = req.params['0'];
var hubid = req.params['hubId'];
return sharedProjects.getProjectPathFromHubID(hubid)
.then(function(filepath) {
if (!filepath) {
writeError(404, res, 'Session not found: ' + hubid);
return;
}
getTree(req, res);
});
}
|
javascript
|
{
"resource": ""
}
|
q44199
|
train
|
function (a, b) {
var dx = (b[0] - a[0]) * this.kx;
var dy = (b[1] - a[1]) * this.ky;
if (!dx && !dy) return 0;
var bearing = Math.atan2(dx, dy) * 180 / Math.PI;
if (bearing > 180) bearing -= 360;
return bearing;
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.