_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3 values | text stringlengths 52 373k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q29300 | train | function(start, end, line, offset, len) {
// We use typeof because we need to distinguish the number 0 from an undefined or null parameter
if (typeof(start) === "number") { //$NON-NLS-0$
if (typeof(end) !== "number") { //$NON-NLS-0$
end = start;
}
this.moveSelection(start, end);
return true;
} else if (typeof(line) === "number") { //$NON-NLS-0$
var model = this.getModel();
var pos = model.getLineStart(line-1);
if (typeof(offset) === "number") { //$NON-NLS-0$
pos = pos + offset;
}
if (typeof(len) !== "number") { //$NON-NLS-0$
len = 0;
}
this.moveSelection(pos, pos+len);
return true;
}
return false;
} | javascript | {
"resource": ""
} | |
q29301 | train | function(line, column, end, callback) {
if (this._textView) {
var model = this.getModel();
line = Math.max(0, Math.min(line, model.getLineCount() - 1));
var lineStart = model.getLineStart(line);
var start = 0;
if (end === undefined) {
end = 0;
}
if (typeof column === "string") { //$NON-NLS-0$
var index = model.getLine(line).indexOf(column);
if (index !== -1) {
start = index;
end = start + column.length;
}
} else {
start = column;
var lineLength = model.getLineEnd(line) - lineStart;
start = Math.min(start, lineLength);
end = Math.min(end, lineLength);
}
this.moveSelection(lineStart + start, lineStart + end, callback);
}
} | javascript | {
"resource": ""
} | |
q29302 | generateUserInfo | train | function generateUserInfo(serviceRegistry, keyAssistFunction, prefsService) {
prefsService.get("/userMenu").then(function(prefs) {
if (Boolean(prefs) && prefs.disabled === true) {
var menu = lib.node("userMenu");
if (Boolean(menu)) {
menu.parentElement.removeChild(menu);
}
return;
}
var authServices = serviceRegistry.getServiceReferences("orion.core.auth"); //$NON-NLS-0$
authenticationIds = [];
var menuGenerator = customGlobalCommands.createMenuGenerator.call(this, serviceRegistry, keyAssistFunction, prefsService);
if (!menuGenerator) { return; }
for (var i = 0; i < authServices.length; i++) {
var servicePtr = authServices[i];
var authService = serviceRegistry.getService(servicePtr);
getLabel(authService, servicePtr).then(function (label) {
authService.getKey().then(function (key) {
authenticationIds.push(key);
authService.getUser().then(function (jsonData) {
menuGenerator.addUserItem(key, authService, label, jsonData);
}, function (errorData, jsonData) {
menuGenerator.addUserItem(key, authService, label, jsonData);
});
window.addEventListener("storage", function (e) {
if (authRendered[key] === localStorage.getItem(key)) {
return;
}
authRendered[key] = localStorage.getItem(key);
authService.getUser().then(function (jsonData) {
menuGenerator.addUserItem(key, authService, label, jsonData);
}, function (errorData) {
menuGenerator.addUserItem(key, authService, label);
});
}, false);
});
});
}
});
} | javascript | {
"resource": ""
} |
q29303 | setInvocation | train | function setInvocation(commandItem) {
var command = commandItem.command;
if (!command.visibleWhen || command.visibleWhen(item)) {
commandItem.invocation = new mCommands.CommandInvocation(item, item, null, command, commandRegistry);
return new Deferred().resolve(commandItem);
} else if (typeof alternateItem === "function") {
if (!alternateItemDeferred) {
alternateItemDeferred = alternateItem();
}
return Deferred.when(alternateItemDeferred, function (newItem) {
if (newItem && (item === pageItem)) {
// there is an alternate, and it still applies to the current page target
if (!command.visibleWhen || command.visibleWhen(newItem)) {
commandItem.invocation = new mCommands.CommandInvocation(newItem, newItem, null, command, commandRegistry);
return commandItem;
}
}
});
}
return new Deferred().resolve();
} | javascript | {
"resource": ""
} |
q29304 | StatusLineMode | train | function StatusLineMode(viMode) {
var view = viMode.getView();
this.viMode = viMode;
mKeyMode.KeyMode.call(this, view);
this._createActions(view);
} | javascript | {
"resource": ""
} |
q29305 | addPart | train | function addPart(locale, master, needed, toLoad, prefix, suffix) {
if (master[locale]) {
needed.push(locale);
if (master[locale] === true || master[locale] === 1) {
toLoad.push(prefix + locale + '/' + suffix);
}
}
} | javascript | {
"resource": ""
} |
q29306 | getPluralRule | train | function getPluralRule() {
if (!pluralRule) {
var lang = navigator.language || navigator.userLanguage;
// Convert lang to a rule index
pluralRules.some(function(rule) {
if (rule.locales.indexOf(lang) !== -1) {
pluralRule = rule;
return true;
}
return false;
});
// Use rule 0 by default, which is no plural forms at all
if (!pluralRule) {
console.error('Failed to find plural rule for ' + lang);
pluralRule = pluralRules[0];
}
}
return pluralRule;
} | javascript | {
"resource": ""
} |
q29307 | removeNavGrid | train | function removeNavGrid(domNodeWrapperList, domNode) {
if(!domNodeWrapperList){
return;
}
for(var i = 0; i < domNodeWrapperList.length ; i++){
if(domNodeWrapperList[i].domNode === domNode){
domNodeWrapperList.splice(i, 1);
return;
}
}
} | javascript | {
"resource": ""
} |
q29308 | ProjectClient | train | function ProjectClient(serviceRegistry, fileClient) {
this.serviceRegistry = serviceRegistry;
this.fileClient = fileClient;
this.allProjectHandlersReferences = serviceRegistry.getServiceReferences("orion.project.handler"); //$NON-NLS-0$
this.allProjectDeployReferences = serviceRegistry.getServiceReferences("orion.project.deploy"); //$NON-NLS-0$
this._serviceRegistration = serviceRegistry.registerService("orion.project.client", this); //$NON-NLS-0$
this._launchConfigurationsDir = "launchConfigurations"; //$NON-NLS-0$
} | javascript | {
"resource": ""
} |
q29309 | xmlToJson | train | function xmlToJson(xml) {
// Create the return object
var obj = {};
if (xml.nodeType === 1) { // element
// do attributes
if (xml.attributes.length > 0) {
for (var j = 0; j < xml.attributes.length; j++) {
var attribute = xml.attributes.item(j);
obj[attribute.nodeName] = attribute.value;
}
}
} else if (xml.nodeType === 3) { // text
obj = xml.nodeValue.trim(); // add trim here
}
// do children
if (xml.hasChildNodes()) {
for (var i = 0; i < xml.childNodes.length; i++) {
var item = xml.childNodes.item(i);
var nodeName = item.nodeName;
if (typeof(obj[nodeName]) === "undefined") { //$NON-NLS-0$
var tmp = xmlToJson(item);
if (tmp !== "") // if not empty string
obj[nodeName] = tmp;
} else {
if (typeof(obj[nodeName].push) === "undefined") { //$NON-NLS-0$
var old = obj[nodeName];
obj[nodeName] = [];
obj[nodeName].push(old);
}
tmp = xmlToJson(item);
if (tmp !== "") // if not empty string
obj[nodeName].push(tmp);
}
}
}
return obj;
} | javascript | {
"resource": ""
} |
q29310 | RunBar | train | function RunBar(options) {
this._project = null;
this._parentNode = options.parentNode;
this._serviceRegistry = options.serviceRegistry;
this._commandRegistry = options.commandRegistry;
this._fileClient = options.fileClient;
this._progressService = options.progressService;
this._preferencesService = options.preferencesService;
this.statusService = options.statusService;
this.actionScopeId = options.actionScopeId;
this._projectCommands = options.projectCommands;
this._projectClient = options.projectClient;
this._preferences = options.preferences;
this._editorInputManager = options.editorInputManager;
this._generalPreferences = options.generalPreferences;
this._initialize();
this._setLaunchConfigurationsLabel(null);
this._disableAllControls(); // start with controls disabled until a launch configuration is selected
} | javascript | {
"resource": ""
} |
q29311 | train | function(launchConfiguration, checkStatus) {
var errorHandler = function (error) {
// stop the progress spinner in the launch config dropdown trigger
this.setStatus({
error: error || true //if no error was passed in we still want to ensure that the error state is recorded
});
}.bind(this);
if (launchConfiguration) {
this._selectedLaunchConfiguration = launchConfiguration;
this._setLaunchConfigurationsLabel(launchConfiguration);
if (checkStatus) {
this._displayStatusCheck(launchConfiguration);
var startTime = Date.now();
this._checkLaunchConfigurationStatus(launchConfiguration).then(function(_status) {
var interval = Date.now() - startTime;
mMetrics.logTiming("deployment", "check status (launch config)", interval, launchConfiguration.Type); //$NON-NLS-1$ //$NON-NLS-2$
launchConfiguration.status = _status;
this._updateLaunchConfiguration(launchConfiguration);
}.bind(this), errorHandler);
} else {
// do not check the status, only set it in the UI if it is already in the launchConfiguration
if (launchConfiguration.status) {
this.setStatus(launchConfiguration.status);
}
}
} else {
this._stopStatusPolling(); //stop before clearing selected config
this._selectedLaunchConfiguration = null;
this._setLaunchConfigurationsLabel(null);
this.setStatus({});
}
this._menuItemsCache = [];
} | javascript | {
"resource": ""
} | |
q29312 | train | function (project) {
if (project) {
this._projectClient.getProjectLaunchConfigurations(project).then(function(launchConfigurations){
if (project !== this._project) return;
this._setLaunchConfigurations(launchConfigurations);
}.bind(this));
} else {
this._setLaunchConfigurations(null);
}
} | javascript | {
"resource": ""
} | |
q29313 | train | function(launchConfigurations) {
if (launchConfigurations) {
this._enableLaunchConfigurationsDropdown();
launchConfigurations.sort(function(launchConf1, launchConf2) {
return launchConf1.Name.localeCompare(launchConf2.Name);
});
} else {
this._disableLaunchConfigurationsDropdown();
}
this._cacheLaunchConfigurations(launchConfigurations);
if (launchConfigurations && launchConfigurations[0]) {
// select first launch configuration
var hash = this._getHash(launchConfigurations[0]);
var cachedConfig = this._cachedLaunchConfigurations[hash];
this.selectLaunchConfiguration(cachedConfig, true);
} else {
this.selectLaunchConfiguration(null);
}
} | javascript | {
"resource": ""
} | |
q29314 | train | function(command, evnt) {
var buttonNode = evnt.target;
var id = buttonNode.id;
var isEnabled = this._isEnabled(buttonNode);
var disabled = isEnabled ? "" : ".disabled"; //$NON-NLS-1$ //$NON-NLS-0$
mMetrics.logEvent("ui", "invoke", METRICS_LABEL_PREFIX + "." + id +".clicked" + disabled, evnt.which); //$NON-NLS-3$ //$NON-NLS-2$ //$NON-NLS-1$ //$NON-NLS-0$
if (isEnabled) {
if (typeof command === "function") { //$NON-NLS-0$
command.call(this, buttonNode);
} else {
this._commandRegistry.runCommand(command, this._selectedLaunchConfiguration, this, null, null, buttonNode); //$NON-NLS-0$
}
}
} | javascript | {
"resource": ""
} | |
q29315 | _getNodeText | train | function _getNodeText(node) {
return node.sourceFile.text.substr(node.start, node.end - node.start);
} | javascript | {
"resource": ""
} |
q29316 | train | function(item, fieldName) {
if (fieldName === "FriendlyPath") { //$NON-NLS-0$
// Just update the "is valid" column
var rowNode = document.getElementById(this.myTree._treeModel.getId(item));
var oldCell = lib.$(".isValidCell", rowNode); //$NON-NLS-0$
var col_no = lib.$$array("td", rowNode).indexOf(oldCell); //$NON-NLS-0$
var cell = this.renderer.getIsValidCell(col_no, item, rowNode);
// replace oldCell with cell
oldCell.parentNode.replaceChild(cell, oldCell);
}
} | javascript | {
"resource": ""
} | |
q29317 | Inputter | train | function Inputter(options, components) {
this.requisition = components.requisition;
this.focusManager = components.focusManager;
this.element = components.element;
this.element.classList.add('gcli-in-input');
this.element.spellcheck = false;
this.document = this.element.ownerDocument;
this.scratchpad = options.scratchpad;
if (inputterCss != null) {
this.style = util.importCss(inputterCss, this.document, 'gcli-inputter');
}
// Used to distinguish focus from TAB in CLI. See onKeyUp()
this.lastTabDownAt = 0;
// Used to effect caret changes. See _processCaretChange()
this._caretChange = null;
// Ensure that TAB/UP/DOWN isn't handled by the browser
this.onKeyDown = this.onKeyDown.bind(this);
this.onKeyUp = this.onKeyUp.bind(this);
this.element.addEventListener('keydown', this.onKeyDown, false);
this.element.addEventListener('keyup', this.onKeyUp, false);
// Setup History
this.history = new History();
this._scrollingThroughHistory = false;
// Used when we're selecting which prediction to complete with
this._choice = null;
this.onChoiceChange = util.createEvent('Inputter.onChoiceChange');
// Cursor position affects hint severity
this.onMouseUp = this.onMouseUp.bind(this);
this.element.addEventListener('mouseup', this.onMouseUp, false);
if (this.focusManager) {
this.focusManager.addMonitoredElement(this.element, 'input');
}
// Start looking like an asynchronous completion isn't happening
this._completed = RESOLVED;
this.requisition.onTextChange.add(this.textChanged, this);
this.assignment = this.requisition.getAssignmentAt(0);
this.onAssignmentChange = util.createEvent('Inputter.onAssignmentChange');
this.onInputChange = util.createEvent('Inputter.onInputChange');
this.onResize = util.createEvent('Inputter.onResize');
this.onWindowResize = this.onWindowResize.bind(this);
this.document.defaultView.addEventListener('resize', this.onWindowResize, false);
this.requisition.update(this.element.value || '');
} | javascript | {
"resource": ""
} |
q29318 | NavigationOutliner | train | function NavigationOutliner(options) {
var parent = lib.node(options.parent);
if (!parent) { throw "no parent"; } //$NON-NLS-0$
if (!options.serviceRegistry) {throw "no service registry"; } //$NON-NLS-0$
this._parent = parent;
this._registry = options.serviceRegistry;
this.commandService = options.commandService;
this.render();
} | javascript | {
"resource": ""
} |
q29319 | train | function(gitStashLocation, indexMessage, workingDirectoryMessage, includeUntracked){
var service = this;
var payload = {};
if(indexMessage != null) /* note that undefined == null */
payload.IndexMessage = indexMessage;
if(workingDirectoryMessage != null) /* note that undefined == null */
payload.WorkingDirectoryMessage = workingDirectoryMessage;
if(includeUntracked === true)
payload.IncludeUntracked = true;
var clientDeferred = new Deferred();
xhr("POST", gitStashLocation, {
headers : {
"Orion-Version" : "1",
"Content-Type" : contentType
},
timeout : GIT_TIMEOUT,
data: JSON.stringify(payload)
}).then(function(result) {
service._getGitServiceResponse(clientDeferred, result);
}, function(error){
service._handleGitServiceResponseError(clientDeferred, error);
});
return clientDeferred;
} | javascript | {
"resource": ""
} | |
q29320 | FileModel | train | function FileModel(serviceRegistry, root, fileClient, idPrefix, excludeFiles, excludeFolders, filteredResources) {
this.registry = serviceRegistry;
this.root = root;
this.fileClient = fileClient;
this.idPrefix = idPrefix || "";
if (typeof this.idPrefix !== "string") {
this.idPrefix = this.idPrefix.id;
}
this.excludeFiles = Boolean(excludeFiles);
this.excludeFolders = Boolean(excludeFolders);
if(!this.filteredResources) {
//is set from project nav not via arguments
this.filteredResources = filteredResources;
}
this.filter = new FileFilter(this.filteredResources);
this._annotations = [];
// Listen to annotation changed events
this._annotationChangedHandler = this._handleAnnotationChanged.bind(this)
this.fileClient.addEventListener('AnnotationChanged', this._annotationChangedHandler);
} | javascript | {
"resource": ""
} |
q29321 | train | function(item, reroot) {
var deferred = new Deferred();
if (!item || !this.model || !this.myTree) {
return deferred.reject();
}
if (!this.myTree.showRoot && (item.Location === this.treeRoot.Location || item.Location === this.treeRoot.ContentLocation)) {
return deferred.resolve(this.treeRoot);
}
var row = this.getRow(item);
if (row) {
deferred.resolve(row._item || item);
} else if (item.Parents && item.Parents.length > 0) {
item.Parents[0].Parents = item.Parents.slice(1);
return this.expandItem(item.Parents[0], reroot).then(function(parent) {
// Handles model out of sync
var row = this.getRow(item);
if (!row) {
return this.changedItem(parent, true).then(function() {
var row = this.getRow(item);
if (!row) {
parent.children.unshift(item);
this.myTree.refresh(parent, parent.children, false);
row = this.getRow(item);
}
return row ? row._item : new Deferred().reject();
}.bind(this));
}
return row._item || item;
}.bind(this));
} else {
// Handles file not in current tree
if (reroot === undefined || reroot) {
return this.reroot(item);
}
return deferred.reject();
}
return deferred;
} | javascript | {
"resource": ""
} | |
q29322 | train | function(item, reroot) {
return this.showItem(item, reroot).then(function(result) {
this.select(result);
}.bind(this));
} | javascript | {
"resource": ""
} | |
q29323 | train | function(path, force, postLoad) {
if (path && typeof path === "object") {
path = path.ChildrenLocation || path.ContentLocation;
}
path = mFileUtils.makeRelative(path);
var self = this;
if (force || path !== this.treeRoot.Path || path !== this._lastPath) {
this._lastPath = path;
return this.load(this.fileClient.read(path, true), i18nUtil.formatMessage(messages["Loading ${0}"], path), postLoad).then(function() {
self.treeRoot.Path = path;
return self.treeRoot;
}, function(err) {
self.treeRoot.Path = null;
return new Deferred().reject(err);
});
}
return new Deferred().resolve(self.treeRoot);
} | javascript | {
"resource": ""
} | |
q29324 | createSiteServiceCommands | train | function createSiteServiceCommands(serviceRegistry, commandService, options) {
function getFileService(siteServiceRef) {
return mSiteClient.getFileClient(serviceRegistry, siteServiceRef.getProperty('filePattern')); //$NON-NLS-0$
}
options = options || {};
var createCommand = new mCommands.Command({
name : messages["Create"],
tooltip: messages["Create a new site configuration"],
id: "orion.site.create", //$NON-NLS-0$
parameters: new mCommandRegistry.ParametersDescription([new mCommandRegistry.CommandParameter('name', 'text', messages["Name"])]), //$NON-NLS-2$ //$NON-NLS-1$ //$NON-NLS-0$
visibleWhen: function(bah) {
return true;
},
callback : function(data) {
var siteServiceRef = data.items, siteService = serviceRegistry.getService(siteServiceRef);
var fileService = getFileService(siteServiceRef);
var name = data.parameters && data.parameters.valueFor('name'); //$NON-NLS-0$
var progress = serviceRegistry.getService("orion.page.progress");
(progress ? progress.progress(fileService.loadWorkspaces(), "Loading workspaces") : fileService.loadWorkspaces()).then(function(workspaces) {
var workspaceId = workspaces && workspaces[0] && workspaces[0].Id;
if (workspaceId && name) {
siteService.createSiteConfiguration(name, workspaceId).then(function(site) {
options.createCallback(mSiteUtils.generateEditSiteHref(site), site);
}, options.errorCallback);
}
});
}});
commandService.addCommand(createCommand);
} | javascript | {
"resource": ""
} |
q29325 | ParamType | train | function ParamType(typeSpec) {
this.requisition = typeSpec.requisition;
this.isIncompleteName = typeSpec.isIncompleteName;
this.stringifyProperty = 'name';
this.neverForceAsync = true;
} | javascript | {
"resource": ""
} |
q29326 | StatusReportingService | train | function StatusReportingService(serviceRegistry, operationsClient, domId, progressDomId, notificationContainerDomId) {
this._serviceRegistry = serviceRegistry;
this._serviceRegistration = serviceRegistry.registerService("orion.page.message", this); //$NON-NLS-0$
this._operationsClient = operationsClient;
this.notificationContainerDomId = notificationContainerDomId;
this.domId = domId;
this.progressDomId = progressDomId || domId;
this._hookedClose = false;
this._timer = null;
this._clickToDisMiss = true;
this._cancelMsg = null;
this.statusMessage = this.progressMessage = null;
} | javascript | {
"resource": ""
} |
q29327 | train | function(msg, timeout, isAccessible) {
this._init();
this.statusMessage = msg;
var node = lib.node(this.domId);
if(typeof isAccessible === "boolean") {
// this is kind of a hack; when there is good screen reader support for aria-busy,
// this should be done by toggling that instead
var readSetting = node.getAttribute("aria-live"); //$NON-NLS-0$
node.setAttribute("aria-live", isAccessible ? "polite" : "off"); //$NON-NLS-2$ //$NON-NLS-1$ //$NON-NLS-3$
window.setTimeout(function() {
if (msg === this.statusMessage) {
lib.empty(node);
node.appendChild(document.createTextNode(msg));
window.setTimeout(function() { node.setAttribute("aria-live", readSetting); }, 100); //$NON-NLS-0$
}
}.bind(this), 100);
}
else {
lib.empty(node);
node.appendChild(document.createTextNode(msg));
}
if (typeof timeout === "number") {
window.setTimeout(function() {
if (msg === this.statusMessage) {
lib.empty(node);
node.appendChild(document.createTextNode(""));
}
}.bind(this), timeout);
}
} | javascript | {
"resource": ""
} | |
q29328 | train | function(st) {
this._clickToDisMiss = true;
this.statusMessage = st;
this._init();
//could be: responseText from xhrGet, deferred error object, or plain string
var _status = st.responseText || st.message || st;
//accept either a string or a JSON representation of an IStatus
if (typeof _status === "string") {
try {
_status = JSON.parse(_status);
} catch(error) {
//it is not JSON, just continue;
}
}
var message = _status.DetailedMessage || _status.Message || _status;
var color = "#DF0000"; //$NON-NLS-0$
if (_status.Severity) {
switch (_status.Severity) {
case SEV_WARNING:
color = "#FFCC00"; //$NON-NLS-0$
break;
case SEV_ERROR:
color = "#DF0000"; //$NON-NLS-0$
break;
case SEV_INFO:
case SEV_OK:
color = "green"; //$NON-NLS-0$
break;
}
}
var span = document.createElement("span");
span.style.color = color;
span.appendChild(document.createTextNode(message));
var node = lib.node(this.domId);
lib.empty(node);
node.appendChild(span);
this._takeDownSplash();
} | javascript | {
"resource": ""
} | |
q29329 | train | function(message) {
this._clickToDisMiss = false;
this._init();
this.progressMessage = message;
var pageLoader = getPageLoader();
if (pageLoader) {
var step = pageLoader.getStep();
if(step) {
if (typeof message === "object") {
step.message = message.message;
step.detailedMessage = message.detailedMessage;
} else {
step.message = message;
step.detailedMessage = "";
}
pageLoader.update();
return;
}
}
var node = lib.node(this.progressDomId);
lib.empty(node);
node.appendChild(document.createTextNode(message));
var container = lib.node(this.notificationContainerDomId);
container.classList.remove("notificationHide"); //$NON-NLS-0$
if (message && message.length > 0) {
container.classList.add("progressNormal"); //$NON-NLS-0$
container.classList.add("notificationShow"); //$NON-NLS-0$
} else if(this._progressMonitors && this._progressMonitors.length > 0){
return this._renderOngoingMonitors();
}else{
container.classList.remove("notificationShow"); //$NON-NLS-0$
container.classList.add("notificationHide"); //$NON-NLS-0$
}
} | javascript | {
"resource": ""
} | |
q29330 | train | function(deferred, message) {
var that = this;
if(message){
that.setProgressMessage(message);
var finish = function(){
if(message === that.progressMessage){
that.setProgressMessage("");
}
};
deferred.then(finish, finish);
}
return deferred;
} | javascript | {
"resource": ""
} | |
q29331 | damerauLevenshteinDistance | train | function damerauLevenshteinDistance(wordi, wordj) {
var wordiLen = wordi.length;
var wordjLen = wordj.length;
// We only need to store three rows of our dynamic programming matrix.
// (Without swap, it would have been two.)
var row0 = new Array(wordiLen+1);
var row1 = new Array(wordiLen+1);
var row2 = new Array(wordiLen+1);
var tmp;
var i, j;
// The distance between the empty string and a string of size i is the cost
// of i insertions.
for (i = 0; i <= wordiLen; i++) {
row1[i] = i * INSERTION_COST;
}
// Row-by-row, we're computing the edit distance between substrings wordi[0..i]
// and wordj[0..j].
for (j = 1; j <= wordjLen; j++)
{
// Edit distance between wordi[0..0] and wordj[0..j] is the cost of j
// insertions.
row0[0] = j * INSERTION_COST;
for (i = 1; i <= wordiLen; i++) {
// Handle deletion, insertion and substitution: we can reach each cell
// from three other cells corresponding to those three operations. We
// want the minimum cost.
row0[i] = Math.min(
row0[i-1] + DELETION_COST,
row1[i] + INSERTION_COST,
row1[i-1] + (wordi[i-1] === wordj[j-1] ? 0 : SUBSTITUTION_COST));
// We handle swap too, eg. distance between help and hlep should be 1. If
// we find such a swap, there's a chance to update row0[1] to be lower.
if (i > 1 && j > 1 && wordi[i-1] === wordj[j-2] && wordj[j-1] === wordi[i-2]) {
row0[i] = Math.min(row0[i], row2[i-2] + SWAP_COST);
}
}
tmp = row2;
row2 = row1;
row1 = row0;
row0 = tmp;
}
return row1[wordiLen];
} | javascript | {
"resource": ""
} |
q29332 | findUser | train | function findUser(id, user, callback) {
if (typeof user.save === 'function') {
callback(null, user);
} else {
orionAccount.findByUsername(id, callback);
}
} | javascript | {
"resource": ""
} |
q29333 | train | function(oauth, callback) {
orionAccount.find({oauth: new RegExp("^" + oauth + "$", "m")}, function(err, user) {
if (err) {
return callback(err);
}
if (user && user.length) {
return callback(null, user[0]);
}
return callback(null, null);
});
} | javascript | {
"resource": ""
} | |
q29334 | delay | train | function delay(millis, obj) {
return new Promise((resolve, reject) => {
let resolveImpl = d => {
if (d === null || d === undefined) {
resolve(d)
} else if (d instanceof Promise || typeof d.then === 'function' && typeof d.catch === 'function') {
d.then(resolve).catch(reject)
} else if (typeof d === 'function') {
resolveImpl(d())
} else {
resolve(d)
}
}
setTimeout(() => resolveImpl(obj), millis)
})
} | javascript | {
"resource": ""
} |
q29335 | retry | train | async function retry(func, options) {
if (!options.timeoutMs && !options.retry)
throw new Error('Invalid argument: either options.timeoutMs or options.retry must be specified')
if (options.timeoutMs < 0)
throw new Error('Invalid argument: options.timeoutMs < 0')
if (options.retry < 0)
throw new Error('Invalid argument: options.retry < 0')
if (options.intervalMs < 0)
throw new Error('Invalid argument: options.intervalMs < 0')
if (!options.intervalMs && options.timeoutMs) {
options.intervalMs = options.timeoutMs / 60
if (options.intervalMs < 10000)
options.intervalMs = 10000
}
let filter = options.filter || ((err, ret, _hasError) => _hasError)
//start of backward compatibility
if (options.filterReject || options.filterResolve) {
filter = (err, ret, _hasError) => {
if (_hasError)
return options.filterReject && options.filterReject(err)
return options.filterResolve && options.filterResolve(ret)
}
}
//end of backward compatibility
let start = Date.now()
let log = options.log || (()=>0)
let name = options.name || '<no name>'
let n = 0
let checkRetry = async (state) => {
if (options.retry && ++n > options.retry) {
let msg = `RetryTask [${name}] - State=${state}. FAILED: Retry limit reached.`
log(msg)
throw new Error(msg)
}
let now = Date.now()
if (options.timeoutMs && now - start > options.timeoutMs) {
let msg = `RetryTask [${name}] - State=${state}. FAILED: Retry Timeout.`
log(msg)
throw new Error(msg)
}
let msg = ''
if (options.retry) {
msg = `${n}/${options.retry}`
}
if (options.timeoutMs) {
let percent = (now - start) / options.timeoutMs * 100 | 0
if (options.retry)
msg += ', '
msg += `timeout ${percent}%`
}
log(`RetryTask [${name}] - State=${state}. Retry=${msg}...`)
await delay(options.intervalMs)
}
let ret
let err
let _hasError
for (;;) {
ret = undefined
err = undefined
_hasError = undefined
try {
ret = await func()
} catch (e) {
err = e
_hasError = true
}
if (await filter(err, ret, _hasError)) {
await checkRetry(err || ret)
continue
}
if (err)
throw err
return ret
}
} | javascript | {
"resource": ""
} |
q29336 | deepMerge | train | function deepMerge(target, ...sources) {
let src
while (true) {
if (!sources.length)
return target
src = sources.shift()
if (src)
break
}
for (let k in src) {
let v = src[k]
let existing = target[k]
if (typeof v === 'object') {
if (v === null) {
target[k] = null
} else if (Array.isArray(v)) {
target[k] = v.slice()
} else {
if (typeof existing !== 'object')
target[k] = deepMerge({}, v)
else
deepMerge(existing, v)
}
} else {
//v is not object/array
target[k] = v
}
}
return deepMerge(target, ...sources)
} | javascript | {
"resource": ""
} |
q29337 | restoreEventListenerImplementation | train | function restoreEventListenerImplementation() {
global.Element.prototype.addEventListener = nativeAddEventListener;
global.Element.prototype.removeEventListener = nativeRemoveEventListener;
global.document.addEventListener = nativeAddEventListener;
global.document.removeEventListener = nativeRemoveEventListener;
} | javascript | {
"resource": ""
} |
q29338 | BaseClient | train | function BaseClient(opts) {
this.opts = opts || {};
var self = this;
this.sendQConcurrency = opts.sendQueueConcurrency || 5;
this.sendQ = async.queue(function(data, cb) {
self.doSend(data, cb);
}, this.sendQConcurrency);
} | javascript | {
"resource": ""
} |
q29339 | compareString | train | async function compareString (filename, expectedContents) {
try {
const actualContents = await fs.readFile(filename, { encoding: 'utf8' })
return actualContents !== expectedContents
} catch (err) {
return handleError(err)
}
} | javascript | {
"resource": ""
} |
q29340 | compareBuffer | train | async function compareBuffer (filename, expectedContents) {
try {
const actualContents = await fs.readFile(filename)
return !expectedContents.equals(actualContents)
} catch (err) {
return handleError(err)
}
} | javascript | {
"resource": ""
} |
q29341 | compareStream | train | async function compareStream (filename, expectedContents) {
try {
const actualStream = fs.createReadStream(filename)
const result = await streamCompare(expectedContents, actualStream, {
abortOnError: true,
compare: (a, b) => {
return Buffer.compare(a.data, b.data) !== 0
}
})
return result
} catch (err) {
return handleError(err)
}
} | javascript | {
"resource": ""
} |
q29342 | train | function(project) {
if(project.slug.toLowerCase() === 'obs'
|| project.slug.toLowerCase() === 'bible-obs'
|| project.slug.toLowerCase() === 'bible'
|| !project.chunks_url) return Promise.resolve();
return request.read(project.chunks_url)
.then(function(response) {
// consume chunk data
if(response.status !== 200) return Promise.reject(response);
let data;
try {
data = JSON.parse(response.data);
} catch(err) {
console.log(project);
return Promise.reject(err);
}
try {
let language_id = library.addSourceLanguage({
slug: 'en',
name: 'English',
direction: 'ltr'
});
// TODO: retrieve the correct versification name(s) from the source language
let versification_id = library.addVersification({
slug: 'en-US',
name: 'American English'
}, language_id);
if (versification_id > 0) {
for (let chunk of data) {
library.addChunkMarker({
chapter: padSlug(chunk.chp, 2),
verse: padSlug(chunk.firstvs, 2)
}, project.slug, versification_id);
}
}
} catch (err) {
return Promise.reject(err);
}
});
} | javascript | {
"resource": ""
} | |
q29343 | train | function(project) {
return request.read(project.lang_catalog)
.then(function(response) {
// consume language data
if(response.status !== 200) return Promise.reject(response);
let data;
try {
data = JSON.parse(response.data);
} catch(err) {
return Promise.reject(err);
}
let projects = [];
for(let language of data) {
try {
let language_id = library.addSourceLanguage({
slug: language.language.slug,
name: language.language.name,
direction: language.language.direction
});
project.categories = _.map(project.meta, function (names, slug, index) {
return {name: names[index], slug: slug};
}.bind(this, language.project.meta));
if (project.slug.toLowerCase() !== 'obs') {
project.chunks_url = 'https://api.unfoldingword.org/bible/txt/1/' + project.slug + '/chunks.json';
}
let projectId = library.addProject({
slug: project.slug,
name: language.project.name,
desc: language.project.desc,
icon: project.icon,
sort: project.sort,
chunks_url: project.chunks_url,
categories: project.categories,
}, language_id);
projects.push({
id: projectId,
chunks_url: project.chunks_url,
slug: project.slug,
resourceUrl: language.res_catalog,
source_language_slug: language.language.slug,
source_language_id: language_id
});
} catch (err) {
return Promise.reject(err);
}
}
// TRICKY: we just flipped the data hierarchy from project->lang to lang->project for future compatibility
return projects;
});
} | javascript | {
"resource": ""
} | |
q29344 | train | function() {
library.addCatalog({
slug: 'langnames',
url: 'https://td.unfoldingword.org/exports/langnames.json',
modified_at: 0
});
library.addCatalog({
slug: 'new-language-questions',
url: 'https://td.unfoldingword.org/api/questionnaire/',
modified_at: 0
});
library.addCatalog({
slug: 'temp-langnames',
url: 'https://td.unfoldingword.org/api/templanguages/',
modified_at: 0
});
// TRICKY: this catalog should always be indexed after langnames and temp-langnames otherwise the linking will fail!
library.addCatalog({
slug: 'approved-temp-langnames',
url: 'https://td.unfoldingword.org/api/templanguages/assignment/changed/',
modified_at: 0
});
return Promise.resolve();
} | javascript | {
"resource": ""
} | |
q29345 | train | function(url, onProgress) {
onProgress = onProgress || function(){};
return injectGlobalCatalogs()
.then(function() {
library.commit();
return request.read(url);
})
.then(function(response) {
// disable saves for better performance
library.autosave(false);
// index projects and source languages
if (response.status !== 200) return Promise.reject(response);
let projects;
try {
projects = JSON.parse(response.data);
} catch (err) {
return Promise.reject(err);
}
return promiseUtils.chain(downloadSourceLanguages, function(err, data) {
if(err instanceof Error) return Promise.reject(err);
console.log(err);
return false;
}, {compact: true, onProgress: onProgress.bind(null, 'projects')})(projects);
})
.then(function(projects) {
// index resources
library.commit();
if(!projects) return Promise.reject('No projects found');
let list = [];
for(let project of projects) {
for(let localizedProject of project) {
list.push({
id: localizedProject.id,
slug: localizedProject.slug,
source_language_id: localizedProject.source_language_id,
resourceUrl: localizedProject.resourceUrl
});
}
}
return promiseUtils.chain(downloadSourceResources, function(err, data) {
if(err instanceof Error) return Promise.reject(err);
console.log(err);
return false;
}, {compact: true, onProgress: onProgress.bind(null, 'resources')})(list);
}).then(function() {
// keep the promise args clean
library.commit();
library.autosave(true);
return Promise.resolve();
}).catch(function(err) {
library.autosave(true);
return Promise.reject(err);
});
} | javascript | {
"resource": ""
} | |
q29346 | train | function(onProgress) {
onProgress = onProgress || function() {};
let projects = library.public_getters.getProjects();
library.autosave(false);
return promiseUtils.chain(downloadChunks, function(err, data) {
if(err instanceof Error) return Promise.reject(err);
console.log(err);
return false;
}, {compact: true, onProgress: onProgress.bind(null, 'chunks')})(projects)
.then(function() {
library.commit();
library.autosave(true);
return Promise.resolve();
})
.catch(function(err) {
library.autosave(true);
return Promise.reject(err);
});
} | javascript | {
"resource": ""
} | |
q29347 | train | function(onProgress) {
onProgress = onProgress || function() {};
library.autosave(false);
let modules_urls = [
'https://api.unfoldingword.org/ta/txt/1/en/audio_2.json',
'https://api.unfoldingword.org/ta/txt/1/en/checking_1.json',
'https://api.unfoldingword.org/ta/txt/1/en/checking_2.json',
'https://api.unfoldingword.org/ta/txt/1/en/gateway_3.json',
'https://api.unfoldingword.org/ta/txt/1/en/intro_1.json',
'https://api.unfoldingword.org/ta/txt/1/en/process_1.json',
'https://api.unfoldingword.org/ta/txt/1/en/translate_1.json',
'https://api.unfoldingword.org/ta/txt/1/en/translate_2.json'
];
return promiseUtils.chain(downloadTA, function(err, data) {
if(err instanceof Error) return Promise.reject(err);
console.log(err);
return false;
}, {compact: true, onProgress: onProgress.bind(null, 'ta')})(modules_urls)
.then(function() {
library.commit();
library.autosave(true);
return Promise.resolve();
})
.catch(function(err) {
library.autosave(true);
return Promise.reject(err);
});
} | javascript | {
"resource": ""
} | |
q29348 | train | function(onProgress) {
const errorHandler = function(err) {
if(err instanceof Error) {
return Promise.reject(err);
} else {
return Promise.resolve();
}
};
// TRICKY: the language catalogs are dependent so we must run them in order
return updateCatalog('langnames', onProgress)
.catch(errorHandler)
.then(function(response) {
return updateCatalog('temp-langnames', onProgress);
})
.catch(errorHandler)
.then(function(response) {
return updateCatalog('approved-temp-langnames', onProgress);
})
.catch(errorHandler)
.then(function(response) {
return updateCatalog('new-language-questions', onProgress)
})
.catch(errorHandler)
.then(function() {
return Promise.resolve();
});
} | javascript | {
"resource": ""
} | |
q29349 | train | function(data, onProgress) {
onProgress = onProgress || function() {};
return new Promise(function(resolve, reject) {
try {
let languages = JSON.parse(data);
_.forEach(languages, function (language, index) {
language.slug = language.lc;
language.name = language.ln;
language.anglicized_name = language.ang;
language.direction = language.ld;
language.region = language.lr;
language.country_codes = language.cc || [];
language.aliases = language.alt || [];
language.is_gateway_language = language.gl ? language.gl : false;
try {
library.addTargetLanguage(language);
} catch (err) {
console.error('Failed to add target language', language);
reject(err);
return;
}
onProgress(languages.length, index + 1);
});
resolve();
} catch(err) {
reject(err);
}
});
} | javascript | {
"resource": ""
} | |
q29350 | train | function(data, onProgress) {
onProgress = onProgress || function() {};
return new Promise(function(resolve, reject) {
try {
let obj = JSON.parse(data);
_.forEach(obj.languages, function (questionnaire, index) {
// format
questionnaire.language_slug = questionnaire.slug;
questionnaire.language_name = questionnaire.name;
questionnaire.td_id = questionnaire.questionnaire_id;
questionnaire.language_direction = questionnaire.dir.toLowerCase() === 'rtl' ? 'rtl' : 'ltr';
try {
let id = library.addQuestionnaire(questionnaire);
if (id > 0) {
// add questions
_.forEach(questionnaire.questions, function (question, n) {
// format question
question.is_required = question.required ? 1 : 0;
question.depends_on = question.depends_on === null ? -1 : question.depends_on;
question.td_id = question.id;
try {
library.addQuestion(question, id);
} catch (err) {
console.error('Failed to add question', question);
reject(err);
return;
}
// broadcast itemized progress if there is only one questionnaire
if (obj.languages.length == 1) {
onProgress(questionnaire.questions.length, n + 1);
}
});
} else {
console.error('Failed to add questionnaire', questionnaire);
}
} catch (err) {
console.error('Failed to add questionnaire', questionnaire);
reject(err);
return;
}
// broadcast overall progress if there are multiple questionnaires.
if (obj.languages.length > 1) {
onProgress(obj.languages.length, index + 1);
}
});
resolve();
} catch (err) {
reject(err);
}
});
} | javascript | {
"resource": ""
} | |
q29351 | train | function(formats) {
for(let format of formats) {
// TODO: rather than hard coding the mime type use library.spec.base_mime_type
if(format.mime_type.match(/application\/tsrc\+.+/)) {
return format;
}
}
return null;
} | javascript | {
"resource": ""
} | |
q29352 | train | function(languageSlug, projectSlug, resourceSlug, progressCallback) {
// support passing args as an object
if(languageSlug != null && typeof languageSlug == 'object') {
resourceSlug = languageSlug.resourceSlug;
projectSlug = languageSlug.projectSlug;
languageSlug = languageSlug.languageSlug;
}
let destFile;
let tempFile;
let containerDir;
return new Promise(function(resolve, reject) {
try {
resolve(library.public_getters.getResource(languageSlug, projectSlug, resourceSlug));
} catch(err) {
reject(err);
}
})
.then(function(resource) {
if(!resource) return Promise.reject(new Error('Unknown resource'));
let containerFormat = getResourceContainerFormat(resource.formats);
if(!containerFormat) return Promise.reject(new Error('Missing resource container format'));
let containerSlug = rc.tools.makeSlug(languageSlug, projectSlug, resourceSlug);
containerDir = path.join(resourceDir, containerSlug);
destFile = containerDir + '.' + rc.tools.spec.file_ext;
tempFile = containerDir + '.download';
rimraf.sync(tempFile);
mkdirp(path.dirname(containerDir));
if(!containerFormat.url) return Promise.reject('Missing resource format url');
return request.download(containerFormat.url, tempFile, progressCallback);
})
.then(function(response) {
if(response.status !== 200) {
rimraf.sync(tempFile);
return Promise.reject(response);
}
// replace old files
rimraf.sync(containerDir);
return new Promise(function(resolve, reject) {
mv(tempFile, destFile, {clobber: true}, function(err) {
if(err) {
reject(err);
} else {
resolve(destFile);
}
});
});
});
} | javascript | {
"resource": ""
} | |
q29353 | train | function(languageSlug, projectSlug, resourceSlug) {
return new Promise(function(resolve, reject) {
try {
resolve(library.public_getters.getResource(languageSlug, projectSlug, resourceSlug));
} catch(err) {
reject(err);
}
})
.then(function(resource) {
if(!resource) return Promise.reject(new Error('Unknown resource'));
let containerSlug = rc.tools.makeSlug(languageSlug, projectSlug, resourceSlug);
let directory = path.join(resourceDir, containerSlug);
let archive = directory + '.' + rc.tools.spec.file_ext;
return rc.open(archive, directory, opts);
});
} | javascript | {
"resource": ""
} | |
q29354 | train | function(languageSlug, projectSlug, resourceSlug) {
return new Promise(function(resolve, reject) {
try {
resolve(library.public_getters.getResource(languageSlug, projectSlug, resourceSlug));
} catch(err) {
reject(err);
}
})
.then(function(resource) {
if(!resource) return Promise.reject(new Error('Unknown resource'));
let containerSlug = rc.tools.makeSlug(languageSlug, projectSlug, resourceSlug);
let directory = path.join(resourceDir, containerSlug);
opts.clean = true; // remove the directory once closed.
return rc.close(directory, opts);
});
} | javascript | {
"resource": ""
} | |
q29355 | train | function() {
return new Promise(function(resolve, reject) {
try {
let files;
if(fileUtils.fileExists(resourceDir)) {
files = fs.readdirSync(resourceDir);
files = _.uniqBy(files, function (f) {
return path.basename(f, '.' + rc.tools.spec.file_ext);
}).map(function(f) { return path.join(resourceDir, f);});
}
if(!files) files = [];
resolve(files);
} catch (err) {
reject(err);
}
}).then(function(files) {
return promiseUtils.chain(rc.tools.inspect, function(err) {
console.error(err);
return false;
})(files);
});
} | javascript | {
"resource": ""
} | |
q29356 | train | function() {
return new Promise(function(resolve, reject) {
try{
resolve(library.listSourceLanguagesLastModified());
} catch (err) {
reject(err);
}
}).then(function(languages) {
return listResourceContainers()
.then(function(results) {
// flatten modified_at
let local = {};
for(let info of results) {
try {
if(!local[info.language.slug]) local[info.language.slug] = -1;
let old = local[info.language.slug];
local[info.language.slug] = info.modified_at > old ? info.modified_at : old;
} catch (err) {
console.error(err);
}
}
return inferUpdates(local, languages);
});
});
} | javascript | {
"resource": ""
} | |
q29357 | train | function(languageSlug) {
return new Promise(function(resolve, reject) {
try{
resolve(library.listProjectsLastModified(languageSlug));
} catch (err) {
reject(err);
}
}).then(function(projects) {
return listResourceContainers()
.then(function(results) {
// flatten modified_at
let local = {};
for(let info of results) {
try {
if(languageSlug && info.language.slug !== languageSlug) continue;
if(!local[info.project.slug]) local[info.project.slug] = -1;
let old = local[info.project.slug];
local[info.project.slug] = info.modified_at > old ? info.modified_at : old;
} catch (err) {
console.error(err);
}
}
return inferUpdates(local, projects);
});
});
} | javascript | {
"resource": ""
} | |
q29358 | FREEZE | train | function FREEZE(obj, all = false) {
if (UoN(obj)) return obj;
// ----------------------------------------------------------
let iss = ISS(obj), iEN = OoA.has(iss), dfl, res;
// ----------------------------------------------------------
if (!iEN||iss=='function') return obj;
if (!!obj.toJS) obj = obj.toJS();
if (ISCONFIG(obj)||ISPTYPE(obj)) return obj;
// ----------------------------------------------------------
dfl = [{},[]][-(-(iss==OoA[1]))];
res = Assign(dfl, obj);
// ----------------------------------------------------------
if (!!all) res = FromJS(res).map((v)=>(
FREEZE(v, all)
)).toJS();
// ----------------------------------------------------------
return Object.freeze(res);
} | javascript | {
"resource": ""
} |
q29359 | IDPTYPE | train | function IDPTYPE() {
let make = ()=>(Math.random().toString(36).slice(2)), rslt = make();
while (global.__PTYPES__.has(rslt)) { rslt = make(); }
return rslt;
} | javascript | {
"resource": ""
} |
q29360 | GETCONFIG | train | function GETCONFIG(name) {
return {
GNConfig: GNConfig,
RouteGN: RouteGN,
RouteAU: RouteAU,
RouteDB: RouteDB,
GNHeaders: GNHeaders,
GNParam: GNParam,
GNDescr: GNDescr,
}[name];
} | javascript | {
"resource": ""
} |
q29361 | MERGER | train | function MERGER(oldVal, newVal) {
let onme = CNAME(oldVal), ocon = ISCONFIG(oldVal), otyp = ISPTYPE(oldVal),
nnme = CNAME(newVal), ncon = ISCONFIG(newVal), ntyp = ISPTYPE(newVal);
if (otyp || ntyp) { return newVal; };
if (ocon && ncon && onme==nnme) {
return new GETCONFIG(onme)(Assign(oldVal, newVal));
};
if (ocon && onme=='GNParam') {
if (nnme=='array') return oldVal.AddVersion(newVal[0], newVal[1]);
if (nnme=='List' ) return oldVal.AddVersion(newVal.get(0), newVal.get(1).toJS());
};
return newVal;
} | javascript | {
"resource": ""
} |
q29362 | ThrowType | train | function ThrowType(name, type, value, actual) {
console.log('THIS:', this)
let THS = this, pfx = (!!THS ? THS.Name||THS.Scheme : '');
throw new TypeError(
`${pfx} property, [${name}], must be one of the following, <${
type.join('> or <').toTitleCase()
}>. Got <${actual.toTitleCase()}> (${value}) instead.`
);
} | javascript | {
"resource": ""
} |
q29363 | descriptor | train | function descriptor(obj) {
if (!obj || 'object' !== typeof obj || Array.isArray(obj)) return false;
var keys = Object.keys(obj);
//
// A descriptor can only be a data or accessor descriptor, never both.
// An data descriptor can only specify:
//
// - configurable
// - enumerable
// - (optional) value
// - (optional) writable
//
// And an accessor descriptor can only specify;
//
// - configurable
// - enumerable
// - (optional) get
// - (optional) set
//
if (
('value' in obj || 'writable' in obj)
&& ('function' === typeof obj.set || 'function' === typeof obj.get)
) return false;
return !!keys.length && keys.every(function allowed(key) {
var type = description[key]
, valid = type === undefined || is(obj[key], type);
return key in description && valid;
});
} | javascript | {
"resource": ""
} |
q29364 | predefine | train | function predefine(obj, pattern) {
pattern = pattern || predefine.READABLE;
return function predefined(method, description, clean) {
//
// If we are given a description compatible Object, use that instead of
// setting it as value. This allows easy creation of getters and setters.
//
if (
!predefine.descriptor(description)
|| is(description, 'object')
&& !clean
&& !predefine.descriptor(predefine.mixin({}, pattern, description))
) { description = {
value: description
};
}
//
// Prevent thrown errors when we attempt to override a readonly
// property
//
var described = Object.getOwnPropertyDescriptor(obj, method);
if (described && !described.configurable) {
return predefined;
}
Object.defineProperty(obj, method, !clean
? predefine.mixin({}, pattern, description)
: description
);
return predefined;
};
} | javascript | {
"resource": ""
} |
q29365 | lazy | train | function lazy(obj, prop, fn) {
Object.defineProperty(obj, prop, {
configurable: true,
get: function get() {
return Object.defineProperty(this, prop, {
value: fn.call(this)
})[prop];
},
set: function set(value) {
return Object.defineProperty(this, prop, {
value: value
})[prop];
}
});
} | javascript | {
"resource": ""
} |
q29366 | remove | train | function remove(obj, keep) {
if (!obj) return false;
keep = keep || [];
for (var prop in obj) {
if (has.call(obj, prop) && !~keep.indexOf(prop)) {
delete obj[prop];
}
}
return true;
} | javascript | {
"resource": ""
} |
q29367 | mixin | train | function mixin(target) {
Array.prototype.slice.call(arguments, 1).forEach(function forEach(o) {
Object.getOwnPropertyNames(o).forEach(function eachAttr(attr) {
Object.defineProperty(target, attr, Object.getOwnPropertyDescriptor(o, attr));
});
});
return target;
} | javascript | {
"resource": ""
} |
q29368 | each | train | function each(collection, iterator, context) {
if (arguments.length === 1) {
iterator = collection;
collection = this;
}
var isArray = Array.isArray(collection || this)
, length = collection.length
, i = 0
, value;
if (context) {
if (isArray) {
for (; i < length; i++) {
value = iterator.apply(collection[ i ], context);
if (value === false) break;
}
} else {
for (i in collection) {
value = iterator.apply(collection[ i ], context);
if (value === false) break;
}
}
} else {
if (isArray) {
for (; i < length; i++) {
value = iterator.call(collection[i], i, collection[i]);
if (value === false) break;
}
} else {
for (i in collection) {
value = iterator.call(collection[i], i, collection[i]);
if (value === false) break;
}
}
}
return this;
} | javascript | {
"resource": ""
} |
q29369 | init | train | function init (file) {
if (!postcssify.entry) {
if (dest) {
log.info('output: %s', dest)
process.on('beforeExit', () => {
if (!postcssify.complete) {
postcssify.complete = true
bundle()
}
})
postcssify.entry = file
} else {
return
}
}
return true
} | javascript | {
"resource": ""
} |
q29370 | bundle | train | function bundle () {
const ordered = order(deps[postcssify.entry], [], {})
const l = ordered.length
let ast
for (let i = 0; i < l; i++) {
const file = ordered[i]
const style = styles[file]
if (style === void 0) {
return
} else {
if (!ast) {
ast = style.clone()
} else {
ast.append(style)
}
}
}
if (ast) {
postcss(processors).process(ast.toResult(), { to: dest, map: true }).then((result) => {
fs.writeFile(dest, result.css, (err) => {
if (err) {
throw err
} else {
log.info('updated: %s', dest)
}
})
}).catch((err) => log.error(err))
}
} | javascript | {
"resource": ""
} |
q29371 | order | train | function order (d, arr, visited) {
for (let i in d) {
if (!visited[i]) {
let obj = d[i]
visited[i] = true
arr = arr.concat(order(obj, [], visited))
if (css(i)) {
arr.push(i)
}
}
}
return arr
} | javascript | {
"resource": ""
} |
q29372 | pad | train | function pad(str, length, char) {
return new BespokeString(str).pad(length, char).toString()
} | javascript | {
"resource": ""
} |
q29373 | train | function(callback, options) {
return new Promise((resolve, reject) => {
let op = () => {
return this.channel.subscribe(callback, options)
.then(resolve, reject);
};
this.on('failed', function(err) {
reject(err);
}).once();
this.handle('subscribe', op);
});
} | javascript | {
"resource": ""
} | |
q29374 | parseFnKeyConst | train | function parseFnKeyConst( str_ , runtime ) {
var separatorIndex = nextSeparator( str_ , runtime ) ;
var str = str_.slice( runtime.i , separatorIndex ) ;
//console.log( 'str before:' , str_ ) ;
//console.log( 'str after:' , str ) ;
//var indexOf ;
//str = str.slice( runtime.i , runtime.iEndOfLine ) ;
//if ( ( indexOf = str.indexOf( ' ' ) ) !== -1 ) { str = str.slice( 0 , indexOf ) ; }
runtime.i += str.length ;
if (
str_[ separatorIndex ] === ':' ||
( str_[ separatorIndex ] === ' ' && afterSpacesChar( str_ , runtime , separatorIndex ) === ':' )
) {
// This is a key, return the unquoted string
return str ;
}
else if ( str in common.constants ) {
return common.constants[ str ] ;
}
else if ( fnOperators[ str ] ) {
return fnOperators[ str ] ;
}
else if ( str in expressionConstants ) {
return expressionConstants[ str ] ;
}
else if ( runtime.operators[ str ] ) {
return runtime.operators[ str ] ;
}
else if ( str in runtime.constants ) {
return runtime.constants[ str ] ;
}
throw new SyntaxError( "Unexpected '" + str + "' in expression" ) ;
} | javascript | {
"resource": ""
} |
q29375 | train | function(scope) {
if (!_argValidator.checkString(scope)) {
scope = _applicationScope;
}
let config = _configCache[scope];
if (!config) {
const data = _deepDefaults(
_deepDefaults({}, _config[scope]),
_config.default
);
config = new AppConfig(data);
if (_isInitialized) {
_configCache[scope] = config;
}
}
return config;
} | javascript | {
"resource": ""
} | |
q29376 | MultipartParser | train | function MultipartParser(request, fileFields, limits) {
Object.defineProperties(this, {
/**
* The HTTP request containing a multipart body.
*
* @property request
* @type Request
* @final
*/
request: {value: request},
/**
* The list of file field descriptors.
*
* @property fileFields
* @type Array
* @final
*/
fileFields: {value: fileFields || []},
/**
* Multipart limits configuration.
*
* @property limits
* @type Object
* @final
*/
limits: {value: limits},
/**
* Final paths of files detected in multipart body.
*
* @property detectedFilesPaths
* @type Array
* @final
*/
detectedFilesPaths: {value: []}
});
if (!this.request)
throw new TypeError('A MultipartParser needs a request');
} | javascript | {
"resource": ""
} |
q29377 | plain | train | function plain() {
var mw = core.base();
mw.plain = function (str) {
return String(str);
};
mw.error = function (str) {
return mw.plain(str);
};
mw.warning = function (str) {
return mw.plain(str);
};
mw.success = function (str) {
return mw.plain(str);
};
mw.accent = function (str) {
return mw.plain(str);
};
mw.muted = function (str) {
return mw.plain(str);
};
mw.toString = function () {
return '<ministyle-plain>';
};
return mw;
} | javascript | {
"resource": ""
} |
q29378 | empty | train | function empty() {
var mw = plain();
mw.plain = function (str) {
str = String(str);
var ret = '';
for (var i = 0; i < str.length; i++) {
ret += ' ';
}
return ret;
};
mw.toString = function () {
return '<ministyle-empty>';
};
return mw;
} | javascript | {
"resource": ""
} |
q29379 | influxUdp | train | function influxUdp(opts) {
BaseClient.apply(this, arguments);
opts = opts || {};
this.host = opts.host || '127.0.0.1';
this.port = opts.port || 4444;
this.socket = dgram.createSocket('udp4');
} | javascript | {
"resource": ""
} |
q29380 | train | function(_url,_href){
if (!_url) return;
var _info = location.parse(_url);
this._$dispatchEvent('onbeforechange',_info);
var _umi = this.__doRewriteUMI(
_info.path,_href||_info.href
);
return this.__groups[this.__pbseed]._$hasUMI(_umi);
} | javascript | {
"resource": ""
} | |
q29381 | train | function(_target,_message){
var _from = _message.from;
while(!!_target){
if (_target._$getPath()!=_from){
_doSendMessage(_target,_message);
}
_target = _target._$getParent();
}
} | javascript | {
"resource": ""
} | |
q29382 | train | function(_target,_message){
var _from = _message.from;
_t3._$breadthFirstSearch(
_target,function(_node){
if (_node._$getPath()!=_from){
_doSendMessage(_node,_message);
}
}
);
} | javascript | {
"resource": ""
} | |
q29383 | doTokenValidation | train | function doTokenValidation(token,publicKey,appId) {
var parts = token.split('.');
if (parts.length < 3) {
ibmlogger.getLogger().debug("The token decode failure details:", token);
return Q.reject(RejectionMessage("The token is malformed.", token,RejectionMessage.INVALID_TOKEN_ERROR));
}
if (parts[2].trim() === '' && publicKey) {
return Q.reject(RejectionMessage("The token missing the signature.", token,RejectionMessage.INVALID_TOKEN_ERROR));
}
var valid;
if (publicKey) {
try {
valid = jws.verify(token, publicKey);
if (!valid) {
return Q.reject(RejectionMessage("The token was verified failed with the public key.", token,RejectionMessage.INVALID_TOKEN_ERROR));
}
}
catch (e) {
return Q.reject(RejectionMessage("An error occurred when verifying the token"+e.message, token, RejectionMessage.INVALID_TOKEN_ERROR));
}
}
var decodedToken = jws.decode(token,{json:true});
if (!decodedToken) {
return Q.reject(RejectionMessage("The token was decoded failed", token, RejectionMessage.INVALID_TOKEN_ERROR));
}
var payload = decodedToken.payload;
if (payload.exp) {
if (Math.round(Date.now()) / 1000 >= payload.exp) {
return Q.reject(RejectionMessage("The token has been expired.", token, RejectionMessage.INVALID_TOKEN_ERROR));
}
}
if (payload.aud) {
if (payload.aud != appId) {
return Q.reject(RejectionMessage("The aud in token is inconsistent with the given application id."+payload.aud+","+appId, token, RejectionMessage.INVALID_TOKEN_ERROR));
}
}
/*
if (options.audience) {
if (payload.aud !== options.audience) {
return Q.reject(RejectionMessage("The audience is different from the expected aud:"+options.audience, token, RejectionMessage.INVALID_TOKEN_ERROR));
}
}
if (options.issuer) {
if (payload.iss !== options.issuer) {
return Q.reject(RejectionMessage("The issuer is different from the expected iss:"+options.issuer, token, RejectionMessage.INVALID_TOKEN_ERROR));
}
}
*/
return Q.resolve(payload);
} | javascript | {
"resource": ""
} |
q29384 | getErrorMessage | train | function getErrorMessage(errors) {
if (_.isArray(errors)) {
return _.uniq(_.pluck(errors, 'stack')).join().replace(/instance./g, '');
} else if (errors) {
return errors.message;
}
} | javascript | {
"resource": ""
} |
q29385 | message | train | function message( data , color ) {
var k , messageString = '' ;
if ( data.mon ) {
messageString = '\n' ;
if ( color ) {
for ( k in data.mon ) {
messageString += string.ansi.green + k + string.ansi.reset + ': ' +
string.ansi.cyan + data.mon[ k ] + string.ansi.reset + '\n' ;
}
}
else {
for ( k in data.mon ) { messageString += k + ': ' + data.mon[ k ] + '\n' ; }
}
}
else if ( Array.isArray( data.messageData ) && data.isFormat ) {
//if ( color ) { messageString = string.ansi.italic + string.formatMethod.apply( { color: true } , data.messageData ) ; }
//else { messageString = string.formatMethod.apply( { color: false } , data.messageData ) ; }
messageString = string.formatMethod.apply( color ? formatColor : format , data.messageData ) ;
}
else if ( data.messageData instanceof Error ) {
messageString = string.inspectError( { style: color ? 'color' : 'none' } , data.messageData ) ;
}
else if ( typeof data.messageData !== 'string' ) {
messageString = string.inspect( { style: color ? 'color' : 'none' } , data.messageData ) ;
}
else {
// Even if messageData is not an array, it may contains markup, so it should be formated anyway
//messageString = data.messageData ;
messageString = string.formatMethod.call( color ? formatColor : format , data.messageData ) ;
}
return messageString ;
} | javascript | {
"resource": ""
} |
q29386 | hashSymbol | train | function hashSymbol( value ) {
var i , iMax , hash = 0 , output , offset ;
value = '' + value ;
// At least 3 passes
offset = 3 * 16 / value.length ;
for ( i = 0 , iMax = value.length ; i < iMax ; i ++ ) {
hash ^= value.charCodeAt( i ) << ( ( i * offset ) % 16 ) ;
//hash += value.charCodeAt( i ) ;
//hash += value.charCodeAt( i ) * ( i + 1 ) ;
}
output = symbols[ hash % symbols.length ] ;
hash = Math.floor( hash / symbols.length ) ;
output = string.ansi[ fgColors[ hash % fgColors.length ] ] + output ;
hash = Math.floor( hash / fgColors.length ) ;
output = string.ansi[ bgColors[ hash % bgColors.length ] ] + output ;
hash = Math.floor( hash / bgColors.length ) ;
output += string.ansi.reset ;
return output ;
} | javascript | {
"resource": ""
} |
q29387 | globExts | train | function globExts() {
let exts = _.flattenDeep(_.concat.apply(null, arguments));
return (exts.length <= 1) ? (exts[0] && `.${exts[0]}` || ``) : `.{${exts.join(`,`)}}`;
} | javascript | {
"resource": ""
} |
q29388 | train | function() {
this.emit('acquiring');
const onAcquisitionError = (err) => {
logger.debug('Resource acquisition failed with error', err);
this.emit('failed', err);
this.handle('failed');
};
const onAcquired = (o) => {
this.item = o;
this.waitInterval = 0;
if (this.item.on) {
this.disposeHandle = this.item.once(disposalEvent || 'close', (err) => {
logger.info('Resource lost, releasing', err);
this.emit('lost');
this.transition('released');
});
this.item.once('error', (err) => {
logger.info('Resource error', err);
this.transition('failed');
});
this.item.on('drain', () => {
this.emit('drain');
});
}
this.transition('acquired');
};
const onException = (ex) => {
logger.debug('Resource acquisition failed with exception', ex);
this.emit('failed', ex);
this.handle('failed');
};
factory()
.then(onAcquired, onAcquisitionError)
.catch(onException);
} | javascript | {
"resource": ""
} | |
q29389 | train | function (str) {
var arr = str.split('.');
var obj = root[arr.shift()];
while (arr.length && obj) {
obj = obj[arr.shift()];
}
return obj;
} | javascript | {
"resource": ""
} | |
q29390 | train | function (name, instance, singleton) {
var arr = (isArray(name)) ? name : (isArray(instance)) ? instance : undefined; // If its a simple array of subviews or configs
var map = (!arr && isObject(name) && name instanceof View === false) ? name : undefined; // If its a mapping of subviews
var viewOptions = (!arr && instance instanceof View === false) ? instance : undefined;
var key;
var i;
var len;
if (map) {
singleton = (typeof instance === 'boolean') ? instance : undefined;
for (key in map) {
if (map.hasOwnProperty(key)) {
map[key] = (isArray(map[key])) ? map[key] : [map[key]];
len = map[key].length;
if (len && map[key][0] instanceof View) {
this._addInstance(key, map[key], singleton);
} else {
i = -1;
while (++i < len) {
this._init(key, map[key][i], singleton);
}
}
}
}
return this;
}
instance = (name instanceof View) ? name : instance;
name = (typeof name === 'string' || typeof name === "number") ? name : undefined;
singleton = (typeof singleton === 'boolean') ? singleton :
(!name && typeof instance === 'boolean') ? instance : undefined;
if (viewOptions) {
this._init(name, viewOptions, singleton);
return this;
}
if (arr && (len = arr.length)) { //eslint-disable-line no-cond-assign
if (arr[0] instanceof View) {
this._addInstance(name, arr, singleton);
} else {
i = -1;
while (++i < len) {
this._init(name, arr[i], singleton);
}
}
return this;
}
if (instance) {
this._addInstance(name, instance, singleton);
} else if (name) {
this._init(name, singleton);
}
return this;
} | javascript | {
"resource": ""
} | |
q29391 | train | function (key, instance) {
if (key instanceof View) {
instance = key;
key = undefined;
}
this._addInstance(key, instance);
return this;
} | javascript | {
"resource": ""
} | |
q29392 | train | function (key, instances) {
if (isArray(key)) {
instances = key;
key = undefined;
}
var i = -1;
var len = instances.length;
while (++i < len) {
this._addInstance(key, instances[i]);
}
return this;
} | javascript | {
"resource": ""
} | |
q29393 | train | function (map) {
var key;
for (key in map) {
if (map.hasOwnProperty(key)) {
this.addInstance(key, map[key]);
}
}
return this;
} | javascript | {
"resource": ""
} | |
q29394 | train | function (keys, options) {
var views = [];
var len = keys.length;
var i = -1;
while (++i < len) {
views.push(this._init(keys[i], options));
}
return views;
} | javascript | {
"resource": ""
} | |
q29395 | train | function (options) {
var key;
for (key in this.config) {
if (this.config.hasOwnProperty(key) && this.config[key].singleton) {
this._init(key, options);
}
}
return this;
} | javascript | {
"resource": ""
} | |
q29396 | train | function (map) {
var key;
for (key in map) {
if (map.hasOwnProperty(key)) {
this._init(key, map[key]);
}
}
return this;
} | javascript | {
"resource": ""
} | |
q29397 | train | function (name, config) {
var map = (isObject(name) && !isArray(name)) ? name : false;
if (map) {
each(map, this._addConfig, this);
return this;
}
return this._addConfig(config, name);
} | javascript | {
"resource": ""
} | |
q29398 | train | function (key) {
var i = -1;
var len;
var subViews;
var subMgr = new SubViewManager(null, this.parent, this.options);
subMgr.config = this.config;
subViews = (isArray(key)) ? key : (isFunction(key)) ? this.filter(key) : this.getByType(key);
len = subViews.length;
while (++i < len) {
subMgr.add(subViews[i]._subviewtype, subViews[i]);
}
return subMgr;
} | javascript | {
"resource": ""
} | |
q29399 | train | function (preserveElems, clearConfigs) {
if (!preserveElems) {
this.removeElems();
}
this.subViews = [];
if (this.parent && this.parent.subViews) {
this.parent.subViews = this.subViews;
}
this._subViewsByType = {};
this._subViewSingletons = {};
this._subViewsByCid = {};
this._subViewsByModelCid = {};
if (clearConfigs) {
this.config = {};
}
return this;
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.