repo
stringlengths 5
67
| path
stringlengths 4
116
| func_name
stringlengths 0
58
| original_string
stringlengths 52
373k
| language
stringclasses 1
value | code
stringlengths 52
373k
| code_tokens
list | docstring
stringlengths 4
11.8k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 86
226
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
webgme/webgme-engine
|
src/client/gmeNodeSetter.js
|
setSetAttribute
|
function setSetAttribute(path, setName, attrName, attrValue, msg) {
var node = _getNode(path);
if (node) {
state.core.setSetAttribute(node, setName, attrName, attrValue);
saveRoot(typeof msg === 'string' ?
msg : 'setSetAttribute(' + path + ',' + setName + ',' + attrName + ',' +
JSON.stringify(attrValue) + ')');
}
}
|
javascript
|
function setSetAttribute(path, setName, attrName, attrValue, msg) {
var node = _getNode(path);
if (node) {
state.core.setSetAttribute(node, setName, attrName, attrValue);
saveRoot(typeof msg === 'string' ?
msg : 'setSetAttribute(' + path + ',' + setName + ',' + attrName + ',' +
JSON.stringify(attrValue) + ')');
}
}
|
[
"function",
"setSetAttribute",
"(",
"path",
",",
"setName",
",",
"attrName",
",",
"attrValue",
",",
"msg",
")",
"{",
"var",
"node",
"=",
"_getNode",
"(",
"path",
")",
";",
"if",
"(",
"node",
")",
"{",
"state",
".",
"core",
".",
"setSetAttribute",
"(",
"node",
",",
"setName",
",",
"attrName",
",",
"attrValue",
")",
";",
"saveRoot",
"(",
"typeof",
"msg",
"===",
"'string'",
"?",
"msg",
":",
"'setSetAttribute('",
"+",
"path",
"+",
"','",
"+",
"setName",
"+",
"','",
"+",
"attrName",
"+",
"','",
"+",
"JSON",
".",
"stringify",
"(",
"attrValue",
")",
"+",
"')'",
")",
";",
"}",
"}"
] |
Mixed argument methods - END
|
[
"Mixed",
"argument",
"methods",
"-",
"END"
] |
f9af95d7bedd83cdfde9cca9c8c2d560c0222065
|
https://github.com/webgme/webgme-engine/blob/f9af95d7bedd83cdfde9cca9c8c2d560c0222065/src/client/gmeNodeSetter.js#L468-L477
|
train
|
webgme/webgme-engine
|
src/bin/blob_fs_clean_up.js
|
cleanUp
|
function cleanUp(options) {
var BlobClient = require('../server/middleware/blob/BlobClientWithFSBackend'),
blobClient,
logger,
gmeAuth,
error,
storage;
if (options && options.env) {
process.env.NODE_ENV = options.env;
}
gmeConfig = require(path.join(process.cwd(), 'config'));
webgme.addToRequireJsPaths(gmeConfig);
logger = webgme.Logger.create('clean_up', gmeConfig.bin.log, false);
blobClient = new BlobClient(gmeConfig, logger);
options = options || {};
return webgme.getGmeAuth(gmeConfig)
.then(function (gmeAuth_) {
gmeAuth = gmeAuth_;
storage = webgme.getStorage(logger, gmeConfig, gmeAuth);
return storage.openDatabase();
})
.then(function () {
if (options.input) {
return getInputHashes(options.input);
} else {
return getUnusedMetaHashes(blobClient, gmeAuth.metadataStorage, storage);
}
})
.then(function (unusedMetaHashes) {
if (options.del !== true && !options.input) {
console.log('The following metaDataHashes are unused:');
console.log(unusedMetaHashes);
return null;
} else {
return removeBasedOnMetaHashes(blobClient, unusedMetaHashes);
}
})
.then(function (removals) {
if (removals) {
console.log('The following items were removed:');
console.log(JSON.stringify(removals, null, 2));
}
})
.catch(function (err_) {
error = err_;
})
.finally(function () {
logger.debug('Closing database connections...');
return Q.allSettled([storage.closeDatabase(), gmeAuth.unload()])
.finally(function () {
logger.debug('Closed.');
if (error) {
throw error;
}
});
});
}
|
javascript
|
function cleanUp(options) {
var BlobClient = require('../server/middleware/blob/BlobClientWithFSBackend'),
blobClient,
logger,
gmeAuth,
error,
storage;
if (options && options.env) {
process.env.NODE_ENV = options.env;
}
gmeConfig = require(path.join(process.cwd(), 'config'));
webgme.addToRequireJsPaths(gmeConfig);
logger = webgme.Logger.create('clean_up', gmeConfig.bin.log, false);
blobClient = new BlobClient(gmeConfig, logger);
options = options || {};
return webgme.getGmeAuth(gmeConfig)
.then(function (gmeAuth_) {
gmeAuth = gmeAuth_;
storage = webgme.getStorage(logger, gmeConfig, gmeAuth);
return storage.openDatabase();
})
.then(function () {
if (options.input) {
return getInputHashes(options.input);
} else {
return getUnusedMetaHashes(blobClient, gmeAuth.metadataStorage, storage);
}
})
.then(function (unusedMetaHashes) {
if (options.del !== true && !options.input) {
console.log('The following metaDataHashes are unused:');
console.log(unusedMetaHashes);
return null;
} else {
return removeBasedOnMetaHashes(blobClient, unusedMetaHashes);
}
})
.then(function (removals) {
if (removals) {
console.log('The following items were removed:');
console.log(JSON.stringify(removals, null, 2));
}
})
.catch(function (err_) {
error = err_;
})
.finally(function () {
logger.debug('Closing database connections...');
return Q.allSettled([storage.closeDatabase(), gmeAuth.unload()])
.finally(function () {
logger.debug('Closed.');
if (error) {
throw error;
}
});
});
}
|
[
"function",
"cleanUp",
"(",
"options",
")",
"{",
"var",
"BlobClient",
"=",
"require",
"(",
"'../server/middleware/blob/BlobClientWithFSBackend'",
")",
",",
"blobClient",
",",
"logger",
",",
"gmeAuth",
",",
"error",
",",
"storage",
";",
"if",
"(",
"options",
"&&",
"options",
".",
"env",
")",
"{",
"process",
".",
"env",
".",
"NODE_ENV",
"=",
"options",
".",
"env",
";",
"}",
"gmeConfig",
"=",
"require",
"(",
"path",
".",
"join",
"(",
"process",
".",
"cwd",
"(",
")",
",",
"'config'",
")",
")",
";",
"webgme",
".",
"addToRequireJsPaths",
"(",
"gmeConfig",
")",
";",
"logger",
"=",
"webgme",
".",
"Logger",
".",
"create",
"(",
"'clean_up'",
",",
"gmeConfig",
".",
"bin",
".",
"log",
",",
"false",
")",
";",
"blobClient",
"=",
"new",
"BlobClient",
"(",
"gmeConfig",
",",
"logger",
")",
";",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"return",
"webgme",
".",
"getGmeAuth",
"(",
"gmeConfig",
")",
".",
"then",
"(",
"function",
"(",
"gmeAuth_",
")",
"{",
"gmeAuth",
"=",
"gmeAuth_",
";",
"storage",
"=",
"webgme",
".",
"getStorage",
"(",
"logger",
",",
"gmeConfig",
",",
"gmeAuth",
")",
";",
"return",
"storage",
".",
"openDatabase",
"(",
")",
";",
"}",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"if",
"(",
"options",
".",
"input",
")",
"{",
"return",
"getInputHashes",
"(",
"options",
".",
"input",
")",
";",
"}",
"else",
"{",
"return",
"getUnusedMetaHashes",
"(",
"blobClient",
",",
"gmeAuth",
".",
"metadataStorage",
",",
"storage",
")",
";",
"}",
"}",
")",
".",
"then",
"(",
"function",
"(",
"unusedMetaHashes",
")",
"{",
"if",
"(",
"options",
".",
"del",
"!==",
"true",
"&&",
"!",
"options",
".",
"input",
")",
"{",
"console",
".",
"log",
"(",
"'The following metaDataHashes are unused:'",
")",
";",
"console",
".",
"log",
"(",
"unusedMetaHashes",
")",
";",
"return",
"null",
";",
"}",
"else",
"{",
"return",
"removeBasedOnMetaHashes",
"(",
"blobClient",
",",
"unusedMetaHashes",
")",
";",
"}",
"}",
")",
".",
"then",
"(",
"function",
"(",
"removals",
")",
"{",
"if",
"(",
"removals",
")",
"{",
"console",
".",
"log",
"(",
"'The following items were removed:'",
")",
";",
"console",
".",
"log",
"(",
"JSON",
".",
"stringify",
"(",
"removals",
",",
"null",
",",
"2",
")",
")",
";",
"}",
"}",
")",
".",
"catch",
"(",
"function",
"(",
"err_",
")",
"{",
"error",
"=",
"err_",
";",
"}",
")",
".",
"finally",
"(",
"function",
"(",
")",
"{",
"logger",
".",
"debug",
"(",
"'Closing database connections...'",
")",
";",
"return",
"Q",
".",
"allSettled",
"(",
"[",
"storage",
".",
"closeDatabase",
"(",
")",
",",
"gmeAuth",
".",
"unload",
"(",
")",
"]",
")",
".",
"finally",
"(",
"function",
"(",
")",
"{",
"logger",
".",
"debug",
"(",
"'Closed.'",
")",
";",
"if",
"(",
"error",
")",
"{",
"throw",
"error",
";",
"}",
"}",
")",
";",
"}",
")",
";",
"}"
] |
Lists and optionally deletes the unused data from file-system based Blob-storage.
@param {object} [options]
@param {bool} [options.del=false] - If true will do the deletion.
@param {string} [options.env] - If given it will set the NODE_ENV environment variable.
@param {string} [options.input] - Input JSON array file, that contains MetaDataHashes that needs to be removed.
|
[
"Lists",
"and",
"optionally",
"deletes",
"the",
"unused",
"data",
"from",
"file",
"-",
"system",
"based",
"Blob",
"-",
"storage",
"."
] |
f9af95d7bedd83cdfde9cca9c8c2d560c0222065
|
https://github.com/webgme/webgme-engine/blob/f9af95d7bedd83cdfde9cca9c8c2d560c0222065/src/bin/blob_fs_clean_up.js#L274-L334
|
train
|
webgme/webgme-engine
|
src/common/core/users/metarules.js
|
loadNode
|
function loadNode(core, rootNode, nodePath) {
return core.loadByPath(rootNode, nodePath)
.then(function (node) {
if (node === null) {
throw new Error('Given nodePath does not exist "' + nodePath + '"!');
} else {
return node;
}
});
}
|
javascript
|
function loadNode(core, rootNode, nodePath) {
return core.loadByPath(rootNode, nodePath)
.then(function (node) {
if (node === null) {
throw new Error('Given nodePath does not exist "' + nodePath + '"!');
} else {
return node;
}
});
}
|
[
"function",
"loadNode",
"(",
"core",
",",
"rootNode",
",",
"nodePath",
")",
"{",
"return",
"core",
".",
"loadByPath",
"(",
"rootNode",
",",
"nodePath",
")",
".",
"then",
"(",
"function",
"(",
"node",
")",
"{",
"if",
"(",
"node",
"===",
"null",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Given nodePath does not exist \"'",
"+",
"nodePath",
"+",
"'\"!'",
")",
";",
"}",
"else",
"{",
"return",
"node",
";",
"}",
"}",
")",
";",
"}"
] |
Helper functions.
|
[
"Helper",
"functions",
"."
] |
f9af95d7bedd83cdfde9cca9c8c2d560c0222065
|
https://github.com/webgme/webgme-engine/blob/f9af95d7bedd83cdfde9cca9c8c2d560c0222065/src/common/core/users/metarules.js#L13-L22
|
train
|
webgme/webgme-engine
|
src/common/core/users/metarules.js
|
checkPointerRules
|
function checkPointerRules(meta, core, node, callback) {
var result = {
hasViolation: false,
messages: []
},
metaPointers = filterPointerRules(meta).pointers,
checkPromises = [],
pointerNames = core.getPointerNames(node);
checkPromises = pointerNames.map(function (pointerName) {
var metaPointer = metaPointers[pointerName],
pointerPath,
pointerPaths = [];
if (!metaPointer) {
if (pointerName === 'base') {
return {hasViolation: false};
} else {
return Q({
hasViolation: true,
messages: ['Illegal pointer "' + pointerName + '".']
});
}
} else {
pointerPath = core.getPointerPath(node, pointerName);
if (pointerPath !== null) {
pointerPaths.push(pointerPath);
}
return loadNodes(core, node, pointerPaths)
.then(function (nodes) {
return checkNodeTypesAndCardinality(core, node, nodes, metaPointer,
'"' + pointerName + '" target', true);
});
}
});
return Q.all(checkPromises)
.then(function (results) {
results.forEach(function (res) {
if (res.hasViolation) {
result.hasViolation = true;
result.messages = result.messages.concat(res.messages);
}
});
return result;
}).nodeify(callback);
}
|
javascript
|
function checkPointerRules(meta, core, node, callback) {
var result = {
hasViolation: false,
messages: []
},
metaPointers = filterPointerRules(meta).pointers,
checkPromises = [],
pointerNames = core.getPointerNames(node);
checkPromises = pointerNames.map(function (pointerName) {
var metaPointer = metaPointers[pointerName],
pointerPath,
pointerPaths = [];
if (!metaPointer) {
if (pointerName === 'base') {
return {hasViolation: false};
} else {
return Q({
hasViolation: true,
messages: ['Illegal pointer "' + pointerName + '".']
});
}
} else {
pointerPath = core.getPointerPath(node, pointerName);
if (pointerPath !== null) {
pointerPaths.push(pointerPath);
}
return loadNodes(core, node, pointerPaths)
.then(function (nodes) {
return checkNodeTypesAndCardinality(core, node, nodes, metaPointer,
'"' + pointerName + '" target', true);
});
}
});
return Q.all(checkPromises)
.then(function (results) {
results.forEach(function (res) {
if (res.hasViolation) {
result.hasViolation = true;
result.messages = result.messages.concat(res.messages);
}
});
return result;
}).nodeify(callback);
}
|
[
"function",
"checkPointerRules",
"(",
"meta",
",",
"core",
",",
"node",
",",
"callback",
")",
"{",
"var",
"result",
"=",
"{",
"hasViolation",
":",
"false",
",",
"messages",
":",
"[",
"]",
"}",
",",
"metaPointers",
"=",
"filterPointerRules",
"(",
"meta",
")",
".",
"pointers",
",",
"checkPromises",
"=",
"[",
"]",
",",
"pointerNames",
"=",
"core",
".",
"getPointerNames",
"(",
"node",
")",
";",
"checkPromises",
"=",
"pointerNames",
".",
"map",
"(",
"function",
"(",
"pointerName",
")",
"{",
"var",
"metaPointer",
"=",
"metaPointers",
"[",
"pointerName",
"]",
",",
"pointerPath",
",",
"pointerPaths",
"=",
"[",
"]",
";",
"if",
"(",
"!",
"metaPointer",
")",
"{",
"if",
"(",
"pointerName",
"===",
"'base'",
")",
"{",
"return",
"{",
"hasViolation",
":",
"false",
"}",
";",
"}",
"else",
"{",
"return",
"Q",
"(",
"{",
"hasViolation",
":",
"true",
",",
"messages",
":",
"[",
"'Illegal pointer \"'",
"+",
"pointerName",
"+",
"'\".'",
"]",
"}",
")",
";",
"}",
"}",
"else",
"{",
"pointerPath",
"=",
"core",
".",
"getPointerPath",
"(",
"node",
",",
"pointerName",
")",
";",
"if",
"(",
"pointerPath",
"!==",
"null",
")",
"{",
"pointerPaths",
".",
"push",
"(",
"pointerPath",
")",
";",
"}",
"return",
"loadNodes",
"(",
"core",
",",
"node",
",",
"pointerPaths",
")",
".",
"then",
"(",
"function",
"(",
"nodes",
")",
"{",
"return",
"checkNodeTypesAndCardinality",
"(",
"core",
",",
"node",
",",
"nodes",
",",
"metaPointer",
",",
"'\"'",
"+",
"pointerName",
"+",
"'\" target'",
",",
"true",
")",
";",
"}",
")",
";",
"}",
"}",
")",
";",
"return",
"Q",
".",
"all",
"(",
"checkPromises",
")",
".",
"then",
"(",
"function",
"(",
"results",
")",
"{",
"results",
".",
"forEach",
"(",
"function",
"(",
"res",
")",
"{",
"if",
"(",
"res",
".",
"hasViolation",
")",
"{",
"result",
".",
"hasViolation",
"=",
"true",
";",
"result",
".",
"messages",
"=",
"result",
".",
"messages",
".",
"concat",
"(",
"res",
".",
"messages",
")",
";",
"}",
"}",
")",
";",
"return",
"result",
";",
"}",
")",
".",
"nodeify",
"(",
"callback",
")",
";",
"}"
] |
Checker functions for pointers, sets, containment and attributes.
|
[
"Checker",
"functions",
"for",
"pointers",
"sets",
"containment",
"and",
"attributes",
"."
] |
f9af95d7bedd83cdfde9cca9c8c2d560c0222065
|
https://github.com/webgme/webgme-engine/blob/f9af95d7bedd83cdfde9cca9c8c2d560c0222065/src/common/core/users/metarules.js#L142-L189
|
train
|
webgme/webgme-engine
|
src/server/worker/workerrequests.js
|
_extractProjectJsonAndAddAssets
|
function _extractProjectJsonAndAddAssets(filenameOrBuffer, blobClient, callback) {
var zip = new AdmZip(filenameOrBuffer),
artifact = blobClient.createArtifact('files'),
projectStr;
return Q.all(zip.getEntries()
.map(function (entry) {
var entryName = entry.entryName;
if (entryName === 'project.json') {
projectStr = zip.readAsText(entry);
} else {
return artifact.addFileAsSoftLink(entryName, zip.readFile(entry));
}
})
)
.then(function () {
var metadata = artifact.descriptor;
return blobUtil.addAssetsFromExportedProject(logger, blobClient, metadata);
})
.then(function () {
return JSON.parse(projectStr);
})
.nodeify(callback);
}
|
javascript
|
function _extractProjectJsonAndAddAssets(filenameOrBuffer, blobClient, callback) {
var zip = new AdmZip(filenameOrBuffer),
artifact = blobClient.createArtifact('files'),
projectStr;
return Q.all(zip.getEntries()
.map(function (entry) {
var entryName = entry.entryName;
if (entryName === 'project.json') {
projectStr = zip.readAsText(entry);
} else {
return artifact.addFileAsSoftLink(entryName, zip.readFile(entry));
}
})
)
.then(function () {
var metadata = artifact.descriptor;
return blobUtil.addAssetsFromExportedProject(logger, blobClient, metadata);
})
.then(function () {
return JSON.parse(projectStr);
})
.nodeify(callback);
}
|
[
"function",
"_extractProjectJsonAndAddAssets",
"(",
"filenameOrBuffer",
",",
"blobClient",
",",
"callback",
")",
"{",
"var",
"zip",
"=",
"new",
"AdmZip",
"(",
"filenameOrBuffer",
")",
",",
"artifact",
"=",
"blobClient",
".",
"createArtifact",
"(",
"'files'",
")",
",",
"projectStr",
";",
"return",
"Q",
".",
"all",
"(",
"zip",
".",
"getEntries",
"(",
")",
".",
"map",
"(",
"function",
"(",
"entry",
")",
"{",
"var",
"entryName",
"=",
"entry",
".",
"entryName",
";",
"if",
"(",
"entryName",
"===",
"'project.json'",
")",
"{",
"projectStr",
"=",
"zip",
".",
"readAsText",
"(",
"entry",
")",
";",
"}",
"else",
"{",
"return",
"artifact",
".",
"addFileAsSoftLink",
"(",
"entryName",
",",
"zip",
".",
"readFile",
"(",
"entry",
")",
")",
";",
"}",
"}",
")",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"var",
"metadata",
"=",
"artifact",
".",
"descriptor",
";",
"return",
"blobUtil",
".",
"addAssetsFromExportedProject",
"(",
"logger",
",",
"blobClient",
",",
"metadata",
")",
";",
"}",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"return",
"JSON",
".",
"parse",
"(",
"projectStr",
")",
";",
"}",
")",
".",
"nodeify",
"(",
"callback",
")",
";",
"}"
] |
Extracts the exported zip file and adds the contained files to the blob using
the import-part of ExportImport Plugin.
@param {string|Buffer} filenameOrBuffer
@param {BlobClient} blobClient
@param function [callback]
@returns {string} - The project json as a string
@private
|
[
"Extracts",
"the",
"exported",
"zip",
"file",
"and",
"adds",
"the",
"contained",
"files",
"to",
"the",
"blob",
"using",
"the",
"import",
"-",
"part",
"of",
"ExportImport",
"Plugin",
"."
] |
f9af95d7bedd83cdfde9cca9c8c2d560c0222065
|
https://github.com/webgme/webgme-engine/blob/f9af95d7bedd83cdfde9cca9c8c2d560c0222065/src/server/worker/workerrequests.js#L308-L331
|
train
|
webgme/webgme-engine
|
src/server/worker/workerrequests.js
|
changeAttributeMeta
|
function changeAttributeMeta(webgmeToken, parameters, callback) {
var storage,
context,
finish = function (err, result) {
if (err) {
err = err instanceof Error ? err : new Error(err);
logger.error('changeAttributeMeta failed with error', err);
} else {
logger.debug('changeAttributeMeta completed');
}
if (storage) {
storage.close(function (closeErr) {
callback(err || closeErr, result);
});
} else {
callback(err, result);
}
};
getConnectedStorage(webgmeToken)
.then(function (storage_) {
storage = storage_;
storage.addEventListener(storage.CONSTANTS.NETWORK_STATUS_CHANGED,
getNetworkStatusChangeHandler(finish));
return _getCoreAndRootNode(storage, parameters.projectId, parameters.commitHash,
parameters.branchName, parameters.tagName);
})
.then(function (context_) {
context = context_;
return context.core.loadByPath(context.rootNode, parameters.nodePath);
})
.then(function (node) {
context.core.renameAttributeMeta(node, parameters.oldName, parameters.newName);
context.core.setAttributeMeta(node, parameters.newName, parameters.meta);
parameters.excludeOriginNode = true;
parameters.type = 'attribute';
return metaRename.propagateMetaDefinitionRename(context.core, node, parameters);
})
.then(function () {
var persisted = context.core.persist(context.rootNode);
return context.project.makeCommit(
parameters.branchName,
[context.commitObject._id],
persisted.rootHash,
persisted.objects,
'rename attribute definition [' + parameters.oldName + '->' + parameters.newName +
'] of [' + parameters.nodePath + ']');
})
.nodeify(finish);
}
|
javascript
|
function changeAttributeMeta(webgmeToken, parameters, callback) {
var storage,
context,
finish = function (err, result) {
if (err) {
err = err instanceof Error ? err : new Error(err);
logger.error('changeAttributeMeta failed with error', err);
} else {
logger.debug('changeAttributeMeta completed');
}
if (storage) {
storage.close(function (closeErr) {
callback(err || closeErr, result);
});
} else {
callback(err, result);
}
};
getConnectedStorage(webgmeToken)
.then(function (storage_) {
storage = storage_;
storage.addEventListener(storage.CONSTANTS.NETWORK_STATUS_CHANGED,
getNetworkStatusChangeHandler(finish));
return _getCoreAndRootNode(storage, parameters.projectId, parameters.commitHash,
parameters.branchName, parameters.tagName);
})
.then(function (context_) {
context = context_;
return context.core.loadByPath(context.rootNode, parameters.nodePath);
})
.then(function (node) {
context.core.renameAttributeMeta(node, parameters.oldName, parameters.newName);
context.core.setAttributeMeta(node, parameters.newName, parameters.meta);
parameters.excludeOriginNode = true;
parameters.type = 'attribute';
return metaRename.propagateMetaDefinitionRename(context.core, node, parameters);
})
.then(function () {
var persisted = context.core.persist(context.rootNode);
return context.project.makeCommit(
parameters.branchName,
[context.commitObject._id],
persisted.rootHash,
persisted.objects,
'rename attribute definition [' + parameters.oldName + '->' + parameters.newName +
'] of [' + parameters.nodePath + ']');
})
.nodeify(finish);
}
|
[
"function",
"changeAttributeMeta",
"(",
"webgmeToken",
",",
"parameters",
",",
"callback",
")",
"{",
"var",
"storage",
",",
"context",
",",
"finish",
"=",
"function",
"(",
"err",
",",
"result",
")",
"{",
"if",
"(",
"err",
")",
"{",
"err",
"=",
"err",
"instanceof",
"Error",
"?",
"err",
":",
"new",
"Error",
"(",
"err",
")",
";",
"logger",
".",
"error",
"(",
"'changeAttributeMeta failed with error'",
",",
"err",
")",
";",
"}",
"else",
"{",
"logger",
".",
"debug",
"(",
"'changeAttributeMeta completed'",
")",
";",
"}",
"if",
"(",
"storage",
")",
"{",
"storage",
".",
"close",
"(",
"function",
"(",
"closeErr",
")",
"{",
"callback",
"(",
"err",
"||",
"closeErr",
",",
"result",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"callback",
"(",
"err",
",",
"result",
")",
";",
"}",
"}",
";",
"getConnectedStorage",
"(",
"webgmeToken",
")",
".",
"then",
"(",
"function",
"(",
"storage_",
")",
"{",
"storage",
"=",
"storage_",
";",
"storage",
".",
"addEventListener",
"(",
"storage",
".",
"CONSTANTS",
".",
"NETWORK_STATUS_CHANGED",
",",
"getNetworkStatusChangeHandler",
"(",
"finish",
")",
")",
";",
"return",
"_getCoreAndRootNode",
"(",
"storage",
",",
"parameters",
".",
"projectId",
",",
"parameters",
".",
"commitHash",
",",
"parameters",
".",
"branchName",
",",
"parameters",
".",
"tagName",
")",
";",
"}",
")",
".",
"then",
"(",
"function",
"(",
"context_",
")",
"{",
"context",
"=",
"context_",
";",
"return",
"context",
".",
"core",
".",
"loadByPath",
"(",
"context",
".",
"rootNode",
",",
"parameters",
".",
"nodePath",
")",
";",
"}",
")",
".",
"then",
"(",
"function",
"(",
"node",
")",
"{",
"context",
".",
"core",
".",
"renameAttributeMeta",
"(",
"node",
",",
"parameters",
".",
"oldName",
",",
"parameters",
".",
"newName",
")",
";",
"context",
".",
"core",
".",
"setAttributeMeta",
"(",
"node",
",",
"parameters",
".",
"newName",
",",
"parameters",
".",
"meta",
")",
";",
"parameters",
".",
"excludeOriginNode",
"=",
"true",
";",
"parameters",
".",
"type",
"=",
"'attribute'",
";",
"return",
"metaRename",
".",
"propagateMetaDefinitionRename",
"(",
"context",
".",
"core",
",",
"node",
",",
"parameters",
")",
";",
"}",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"var",
"persisted",
"=",
"context",
".",
"core",
".",
"persist",
"(",
"context",
".",
"rootNode",
")",
";",
"return",
"context",
".",
"project",
".",
"makeCommit",
"(",
"parameters",
".",
"branchName",
",",
"[",
"context",
".",
"commitObject",
".",
"_id",
"]",
",",
"persisted",
".",
"rootHash",
",",
"persisted",
".",
"objects",
",",
"'rename attribute definition ['",
"+",
"parameters",
".",
"oldName",
"+",
"'->'",
"+",
"parameters",
".",
"newName",
"+",
"'] of ['",
"+",
"parameters",
".",
"nodePath",
"+",
"']'",
")",
";",
"}",
")",
".",
"nodeify",
"(",
"finish",
")",
";",
"}"
] |
Renames the given attribute definition and propagates the change throughout the whole project.
@param {string} webgmeToken
@param {object} parameters
@param {string} parameters.projectId
@param {string} parameters.branchName
@param {string} parameters.nodePath - the starting meta node's path.
@param {string} parameters.oldName - the current name of the attribute definition.
@param {string} parameters.newName - the new name of the attribute definition.
@param {function} callback
|
[
"Renames",
"the",
"given",
"attribute",
"definition",
"and",
"propagates",
"the",
"change",
"throughout",
"the",
"whole",
"project",
"."
] |
f9af95d7bedd83cdfde9cca9c8c2d560c0222065
|
https://github.com/webgme/webgme-engine/blob/f9af95d7bedd83cdfde9cca9c8c2d560c0222065/src/server/worker/workerrequests.js#L1323-L1374
|
train
|
webgme/webgme-engine
|
src/server/worker/workerrequests.js
|
renameMetaPointerTarget
|
function renameMetaPointerTarget(webgmeToken, parameters, callback) {
var storage,
context,
finish = function (err, result) {
if (err) {
err = err instanceof Error ? err : new Error(err);
logger.error('changeAttributeMeta failed with error', err);
} else {
logger.debug('changeAttributeMeta completed');
}
if (storage) {
storage.close(function (closeErr) {
callback(err || closeErr, result);
});
} else {
callback(err, result);
}
};
getConnectedStorage(webgmeToken)
.then(function (storage_) {
storage = storage_;
storage.addEventListener(storage.CONSTANTS.NETWORK_STATUS_CHANGED,
getNetworkStatusChangeHandler(finish));
return _getCoreAndRootNode(storage, parameters.projectId, parameters.commitHash,
parameters.branchName, parameters.tagName);
})
.then(function (context_) {
context = context_;
return Q.all([context.core.loadByPath(context.rootNode, parameters.nodePath),
context.core.loadByPath(context.rootNode, parameters.targetPath)]);
})
.then(function (nodes) {
context.core.movePointerMetaTarget(nodes[0], nodes[1], parameters.oldName, parameters.newName);
return metaRename.propagateMetaDefinitionRename(context.core, nodes[0], parameters);
})
.then(function () {
var persisted = context.core.persist(context.rootNode);
return context.project.makeCommit(
parameters.branchName,
[context.commitObject._id],
persisted.rootHash,
persisted.objects,
'rename pointer definition [' + parameters.oldName + '->' +
parameters.newName + '] of [' + parameters.nodePath + '] regarding target [' +
parameters.targetPath + ']');
})
.nodeify(finish);
}
|
javascript
|
function renameMetaPointerTarget(webgmeToken, parameters, callback) {
var storage,
context,
finish = function (err, result) {
if (err) {
err = err instanceof Error ? err : new Error(err);
logger.error('changeAttributeMeta failed with error', err);
} else {
logger.debug('changeAttributeMeta completed');
}
if (storage) {
storage.close(function (closeErr) {
callback(err || closeErr, result);
});
} else {
callback(err, result);
}
};
getConnectedStorage(webgmeToken)
.then(function (storage_) {
storage = storage_;
storage.addEventListener(storage.CONSTANTS.NETWORK_STATUS_CHANGED,
getNetworkStatusChangeHandler(finish));
return _getCoreAndRootNode(storage, parameters.projectId, parameters.commitHash,
parameters.branchName, parameters.tagName);
})
.then(function (context_) {
context = context_;
return Q.all([context.core.loadByPath(context.rootNode, parameters.nodePath),
context.core.loadByPath(context.rootNode, parameters.targetPath)]);
})
.then(function (nodes) {
context.core.movePointerMetaTarget(nodes[0], nodes[1], parameters.oldName, parameters.newName);
return metaRename.propagateMetaDefinitionRename(context.core, nodes[0], parameters);
})
.then(function () {
var persisted = context.core.persist(context.rootNode);
return context.project.makeCommit(
parameters.branchName,
[context.commitObject._id],
persisted.rootHash,
persisted.objects,
'rename pointer definition [' + parameters.oldName + '->' +
parameters.newName + '] of [' + parameters.nodePath + '] regarding target [' +
parameters.targetPath + ']');
})
.nodeify(finish);
}
|
[
"function",
"renameMetaPointerTarget",
"(",
"webgmeToken",
",",
"parameters",
",",
"callback",
")",
"{",
"var",
"storage",
",",
"context",
",",
"finish",
"=",
"function",
"(",
"err",
",",
"result",
")",
"{",
"if",
"(",
"err",
")",
"{",
"err",
"=",
"err",
"instanceof",
"Error",
"?",
"err",
":",
"new",
"Error",
"(",
"err",
")",
";",
"logger",
".",
"error",
"(",
"'changeAttributeMeta failed with error'",
",",
"err",
")",
";",
"}",
"else",
"{",
"logger",
".",
"debug",
"(",
"'changeAttributeMeta completed'",
")",
";",
"}",
"if",
"(",
"storage",
")",
"{",
"storage",
".",
"close",
"(",
"function",
"(",
"closeErr",
")",
"{",
"callback",
"(",
"err",
"||",
"closeErr",
",",
"result",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"callback",
"(",
"err",
",",
"result",
")",
";",
"}",
"}",
";",
"getConnectedStorage",
"(",
"webgmeToken",
")",
".",
"then",
"(",
"function",
"(",
"storage_",
")",
"{",
"storage",
"=",
"storage_",
";",
"storage",
".",
"addEventListener",
"(",
"storage",
".",
"CONSTANTS",
".",
"NETWORK_STATUS_CHANGED",
",",
"getNetworkStatusChangeHandler",
"(",
"finish",
")",
")",
";",
"return",
"_getCoreAndRootNode",
"(",
"storage",
",",
"parameters",
".",
"projectId",
",",
"parameters",
".",
"commitHash",
",",
"parameters",
".",
"branchName",
",",
"parameters",
".",
"tagName",
")",
";",
"}",
")",
".",
"then",
"(",
"function",
"(",
"context_",
")",
"{",
"context",
"=",
"context_",
";",
"return",
"Q",
".",
"all",
"(",
"[",
"context",
".",
"core",
".",
"loadByPath",
"(",
"context",
".",
"rootNode",
",",
"parameters",
".",
"nodePath",
")",
",",
"context",
".",
"core",
".",
"loadByPath",
"(",
"context",
".",
"rootNode",
",",
"parameters",
".",
"targetPath",
")",
"]",
")",
";",
"}",
")",
".",
"then",
"(",
"function",
"(",
"nodes",
")",
"{",
"context",
".",
"core",
".",
"movePointerMetaTarget",
"(",
"nodes",
"[",
"0",
"]",
",",
"nodes",
"[",
"1",
"]",
",",
"parameters",
".",
"oldName",
",",
"parameters",
".",
"newName",
")",
";",
"return",
"metaRename",
".",
"propagateMetaDefinitionRename",
"(",
"context",
".",
"core",
",",
"nodes",
"[",
"0",
"]",
",",
"parameters",
")",
";",
"}",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"var",
"persisted",
"=",
"context",
".",
"core",
".",
"persist",
"(",
"context",
".",
"rootNode",
")",
";",
"return",
"context",
".",
"project",
".",
"makeCommit",
"(",
"parameters",
".",
"branchName",
",",
"[",
"context",
".",
"commitObject",
".",
"_id",
"]",
",",
"persisted",
".",
"rootHash",
",",
"persisted",
".",
"objects",
",",
"'rename pointer definition ['",
"+",
"parameters",
".",
"oldName",
"+",
"'->'",
"+",
"parameters",
".",
"newName",
"+",
"'] of ['",
"+",
"parameters",
".",
"nodePath",
"+",
"'] regarding target ['",
"+",
"parameters",
".",
"targetPath",
"+",
"']'",
")",
";",
"}",
")",
".",
"nodeify",
"(",
"finish",
")",
";",
"}"
] |
Renames the given pointer relation definitions and propagates the change throughout the whole project.
@param {string} webgmeToken
@param {object} parameters
@param {string} parameters.projectId
@param {string} parameters.branchName
@param {string} parameters.type - the type of the relation ['pointer'|'set'].
@param {string} parameters.nodePath - the starting meta node's path.
@param {string} parameters.targetPath - the path of the meta node that is the target of
the relationship definition.
@param {string} parameters.oldName - the current name of the concept.
@param {string} parameters.newName - the new name of the concept.
@param {function} callback
|
[
"Renames",
"the",
"given",
"pointer",
"relation",
"definitions",
"and",
"propagates",
"the",
"change",
"throughout",
"the",
"whole",
"project",
"."
] |
f9af95d7bedd83cdfde9cca9c8c2d560c0222065
|
https://github.com/webgme/webgme-engine/blob/f9af95d7bedd83cdfde9cca9c8c2d560c0222065/src/server/worker/workerrequests.js#L1390-L1440
|
train
|
webgme/webgme-engine
|
src/server/util/ensureDir.js
|
ensureDir
|
function ensureDir(dir, mode, callback) {
var deferred = Q.defer();
if (mode && typeof mode === 'function') {
callback = mode;
mode = null;
}
mode = mode || parseInt('0777', 8) & (~process.umask());
_ensureDir(dir, mode, function (err) {
if (err) {
deferred.reject(err);
} else {
deferred.resolve();
}
});
return deferred.promise.nodeify(callback);
}
|
javascript
|
function ensureDir(dir, mode, callback) {
var deferred = Q.defer();
if (mode && typeof mode === 'function') {
callback = mode;
mode = null;
}
mode = mode || parseInt('0777', 8) & (~process.umask());
_ensureDir(dir, mode, function (err) {
if (err) {
deferred.reject(err);
} else {
deferred.resolve();
}
});
return deferred.promise.nodeify(callback);
}
|
[
"function",
"ensureDir",
"(",
"dir",
",",
"mode",
",",
"callback",
")",
"{",
"var",
"deferred",
"=",
"Q",
".",
"defer",
"(",
")",
";",
"if",
"(",
"mode",
"&&",
"typeof",
"mode",
"===",
"'function'",
")",
"{",
"callback",
"=",
"mode",
";",
"mode",
"=",
"null",
";",
"}",
"mode",
"=",
"mode",
"||",
"parseInt",
"(",
"'0777'",
",",
"8",
")",
"&",
"(",
"~",
"process",
".",
"umask",
"(",
")",
")",
";",
"_ensureDir",
"(",
"dir",
",",
"mode",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"deferred",
".",
"reject",
"(",
"err",
")",
";",
"}",
"else",
"{",
"deferred",
".",
"resolve",
"(",
")",
";",
"}",
"}",
")",
";",
"return",
"deferred",
".",
"promise",
".",
"nodeify",
"(",
"callback",
")",
";",
"}"
] |
ensure a directory exists, create it recursively if not.
@param dir The directory you want to ensure it exists
@param mode Refer to fs.mkdir()
@param callback
|
[
"ensure",
"a",
"directory",
"exists",
"create",
"it",
"recursively",
"if",
"not",
"."
] |
f9af95d7bedd83cdfde9cca9c8c2d560c0222065
|
https://github.com/webgme/webgme-engine/blob/f9af95d7bedd83cdfde9cca9c8c2d560c0222065/src/server/util/ensureDir.js#L57-L77
|
train
|
webgme/webgme-engine
|
src/utils.js
|
requestWebGMEToken
|
function requestWebGMEToken(gmeConfig, userId, password, serverUrl, callback) {
var deferred,
req;
if (gmeConfig.authentication.enable === false) {
return Q().nodeify(callback);
}
if (!serverUrl) {
serverUrl = 'http://localhost:' + gmeConfig.server.port;
}
req = superagent.get(serverUrl + '/api/v1/user/token');
if (gmeConfig.authentication.guestAccount !== userId) {
if (!password) {
return Q.reject(new Error('password was not provided!'));
}
req.set('Authorization', 'Basic ' + Buffer.from(userId + ':' + password).toString('base64'));
}
deferred = Q.defer();
req.end(function (err, res) {
if (err) {
deferred.reject(err);
} else {
deferred.resolve(res.body.webgmeToken);
}
});
return deferred.promise.nodeify(callback);
}
|
javascript
|
function requestWebGMEToken(gmeConfig, userId, password, serverUrl, callback) {
var deferred,
req;
if (gmeConfig.authentication.enable === false) {
return Q().nodeify(callback);
}
if (!serverUrl) {
serverUrl = 'http://localhost:' + gmeConfig.server.port;
}
req = superagent.get(serverUrl + '/api/v1/user/token');
if (gmeConfig.authentication.guestAccount !== userId) {
if (!password) {
return Q.reject(new Error('password was not provided!'));
}
req.set('Authorization', 'Basic ' + Buffer.from(userId + ':' + password).toString('base64'));
}
deferred = Q.defer();
req.end(function (err, res) {
if (err) {
deferred.reject(err);
} else {
deferred.resolve(res.body.webgmeToken);
}
});
return deferred.promise.nodeify(callback);
}
|
[
"function",
"requestWebGMEToken",
"(",
"gmeConfig",
",",
"userId",
",",
"password",
",",
"serverUrl",
",",
"callback",
")",
"{",
"var",
"deferred",
",",
"req",
";",
"if",
"(",
"gmeConfig",
".",
"authentication",
".",
"enable",
"===",
"false",
")",
"{",
"return",
"Q",
"(",
")",
".",
"nodeify",
"(",
"callback",
")",
";",
"}",
"if",
"(",
"!",
"serverUrl",
")",
"{",
"serverUrl",
"=",
"'http://localhost:'",
"+",
"gmeConfig",
".",
"server",
".",
"port",
";",
"}",
"req",
"=",
"superagent",
".",
"get",
"(",
"serverUrl",
"+",
"'/api/v1/user/token'",
")",
";",
"if",
"(",
"gmeConfig",
".",
"authentication",
".",
"guestAccount",
"!==",
"userId",
")",
"{",
"if",
"(",
"!",
"password",
")",
"{",
"return",
"Q",
".",
"reject",
"(",
"new",
"Error",
"(",
"'password was not provided!'",
")",
")",
";",
"}",
"req",
".",
"set",
"(",
"'Authorization'",
",",
"'Basic '",
"+",
"Buffer",
".",
"from",
"(",
"userId",
"+",
"':'",
"+",
"password",
")",
".",
"toString",
"(",
"'base64'",
")",
")",
";",
"}",
"deferred",
"=",
"Q",
".",
"defer",
"(",
")",
";",
"req",
".",
"end",
"(",
"function",
"(",
"err",
",",
"res",
")",
"{",
"if",
"(",
"err",
")",
"{",
"deferred",
".",
"reject",
"(",
"err",
")",
";",
"}",
"else",
"{",
"deferred",
".",
"resolve",
"(",
"res",
".",
"body",
".",
"webgmeToken",
")",
";",
"}",
"}",
")",
";",
"return",
"deferred",
".",
"promise",
".",
"nodeify",
"(",
"callback",
")",
";",
"}"
] |
Request a token for the user via the webgme server.
If authentication is turned off it will resolve with undefined.
@param {object} gmeConfig
@param {string} userId - User to get token for.
@param {string} [password] - Must be provided if userId is not the guestAccount.
@param {string} [serverUrl='http://127.0.0.1:<gmeConfig.server.port>'] - Url of webgme server.
@param [callback] - If not provided will return a promise.
@returns {Promise}
|
[
"Request",
"a",
"token",
"for",
"the",
"user",
"via",
"the",
"webgme",
"server",
".",
"If",
"authentication",
"is",
"turned",
"off",
"it",
"will",
"resolve",
"with",
"undefined",
"."
] |
f9af95d7bedd83cdfde9cca9c8c2d560c0222065
|
https://github.com/webgme/webgme-engine/blob/f9af95d7bedd83cdfde9cca9c8c2d560c0222065/src/utils.js#L30-L63
|
train
|
webgme/webgme-engine
|
src/utils.js
|
getSVGMap
|
function getSVGMap(gmeConfig, logger, callback) {
var svgAssetDir = gmeConfig.visualization.svgDirs[0],
//path.join(__dirname, 'client', 'assets', 'DecoratorSVG'),
svgMap;
if (!svgAssetDir) {
return Q.resolve({});
}
function joinPath(paths) {
return '/' + paths.join('/');
}
function walkExtraDir(svgDir) {
return walkDir(svgDir)
.then(function (extraSvgFiles) {
extraSvgFiles.forEach(function (fname) {
var dirName = path.parse(svgDir).name,
relativeFilePath = path.relative(svgDir, fname),
p = joinPath(['assets', 'DecoratorSVG', dirName].concat(relativeFilePath.split(path.sep)));
if (svgMap.hasOwnProperty(p)) {
logger.warn('Colliding SVG paths [', p, '] between [', svgMap[p], '] and [',
fname, ']. Will proceed and use the latter...');
}
fname = path.isAbsolute(fname) ? fname : path.join(process.cwd(), fname);
svgMap[p] = fname;
});
});
}
if (SVGMapDeffered) {
return SVGMapDeffered.promise.nodeify(callback);
}
SVGMapDeffered = Q.defer();
svgMap = {};
walkDir(svgAssetDir)
.then(function (svgFiles) {
var extraDirs = gmeConfig.visualization.svgDirs.slice(1);
svgFiles.forEach(function (fname) {
var p = joinPath(['assets', 'DecoratorSVG', path.basename(fname)]);
svgMap[p] = fname;
});
return Q.all(extraDirs.map(function (svgDir) {
return walkExtraDir(svgDir);
}));
})
.then(function () {
SVGMapDeffered.resolve(svgMap);
})
.catch(SVGMapDeffered.reject);
return SVGMapDeffered.promise.nodeify(callback);
}
|
javascript
|
function getSVGMap(gmeConfig, logger, callback) {
var svgAssetDir = gmeConfig.visualization.svgDirs[0],
//path.join(__dirname, 'client', 'assets', 'DecoratorSVG'),
svgMap;
if (!svgAssetDir) {
return Q.resolve({});
}
function joinPath(paths) {
return '/' + paths.join('/');
}
function walkExtraDir(svgDir) {
return walkDir(svgDir)
.then(function (extraSvgFiles) {
extraSvgFiles.forEach(function (fname) {
var dirName = path.parse(svgDir).name,
relativeFilePath = path.relative(svgDir, fname),
p = joinPath(['assets', 'DecoratorSVG', dirName].concat(relativeFilePath.split(path.sep)));
if (svgMap.hasOwnProperty(p)) {
logger.warn('Colliding SVG paths [', p, '] between [', svgMap[p], '] and [',
fname, ']. Will proceed and use the latter...');
}
fname = path.isAbsolute(fname) ? fname : path.join(process.cwd(), fname);
svgMap[p] = fname;
});
});
}
if (SVGMapDeffered) {
return SVGMapDeffered.promise.nodeify(callback);
}
SVGMapDeffered = Q.defer();
svgMap = {};
walkDir(svgAssetDir)
.then(function (svgFiles) {
var extraDirs = gmeConfig.visualization.svgDirs.slice(1);
svgFiles.forEach(function (fname) {
var p = joinPath(['assets', 'DecoratorSVG', path.basename(fname)]);
svgMap[p] = fname;
});
return Q.all(extraDirs.map(function (svgDir) {
return walkExtraDir(svgDir);
}));
})
.then(function () {
SVGMapDeffered.resolve(svgMap);
})
.catch(SVGMapDeffered.reject);
return SVGMapDeffered.promise.nodeify(callback);
}
|
[
"function",
"getSVGMap",
"(",
"gmeConfig",
",",
"logger",
",",
"callback",
")",
"{",
"var",
"svgAssetDir",
"=",
"gmeConfig",
".",
"visualization",
".",
"svgDirs",
"[",
"0",
"]",
",",
"svgMap",
";",
"if",
"(",
"!",
"svgAssetDir",
")",
"{",
"return",
"Q",
".",
"resolve",
"(",
"{",
"}",
")",
";",
"}",
"function",
"joinPath",
"(",
"paths",
")",
"{",
"return",
"'/'",
"+",
"paths",
".",
"join",
"(",
"'/'",
")",
";",
"}",
"function",
"walkExtraDir",
"(",
"svgDir",
")",
"{",
"return",
"walkDir",
"(",
"svgDir",
")",
".",
"then",
"(",
"function",
"(",
"extraSvgFiles",
")",
"{",
"extraSvgFiles",
".",
"forEach",
"(",
"function",
"(",
"fname",
")",
"{",
"var",
"dirName",
"=",
"path",
".",
"parse",
"(",
"svgDir",
")",
".",
"name",
",",
"relativeFilePath",
"=",
"path",
".",
"relative",
"(",
"svgDir",
",",
"fname",
")",
",",
"p",
"=",
"joinPath",
"(",
"[",
"'assets'",
",",
"'DecoratorSVG'",
",",
"dirName",
"]",
".",
"concat",
"(",
"relativeFilePath",
".",
"split",
"(",
"path",
".",
"sep",
")",
")",
")",
";",
"if",
"(",
"svgMap",
".",
"hasOwnProperty",
"(",
"p",
")",
")",
"{",
"logger",
".",
"warn",
"(",
"'Colliding SVG paths ['",
",",
"p",
",",
"'] between ['",
",",
"svgMap",
"[",
"p",
"]",
",",
"'] and ['",
",",
"fname",
",",
"']. Will proceed and use the latter...'",
")",
";",
"}",
"fname",
"=",
"path",
".",
"isAbsolute",
"(",
"fname",
")",
"?",
"fname",
":",
"path",
".",
"join",
"(",
"process",
".",
"cwd",
"(",
")",
",",
"fname",
")",
";",
"svgMap",
"[",
"p",
"]",
"=",
"fname",
";",
"}",
")",
";",
"}",
")",
";",
"}",
"if",
"(",
"SVGMapDeffered",
")",
"{",
"return",
"SVGMapDeffered",
".",
"promise",
".",
"nodeify",
"(",
"callback",
")",
";",
"}",
"SVGMapDeffered",
"=",
"Q",
".",
"defer",
"(",
")",
";",
"svgMap",
"=",
"{",
"}",
";",
"walkDir",
"(",
"svgAssetDir",
")",
".",
"then",
"(",
"function",
"(",
"svgFiles",
")",
"{",
"var",
"extraDirs",
"=",
"gmeConfig",
".",
"visualization",
".",
"svgDirs",
".",
"slice",
"(",
"1",
")",
";",
"svgFiles",
".",
"forEach",
"(",
"function",
"(",
"fname",
")",
"{",
"var",
"p",
"=",
"joinPath",
"(",
"[",
"'assets'",
",",
"'DecoratorSVG'",
",",
"path",
".",
"basename",
"(",
"fname",
")",
"]",
")",
";",
"svgMap",
"[",
"p",
"]",
"=",
"fname",
";",
"}",
")",
";",
"return",
"Q",
".",
"all",
"(",
"extraDirs",
".",
"map",
"(",
"function",
"(",
"svgDir",
")",
"{",
"return",
"walkExtraDir",
"(",
"svgDir",
")",
";",
"}",
")",
")",
";",
"}",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"SVGMapDeffered",
".",
"resolve",
"(",
"svgMap",
")",
";",
"}",
")",
".",
"catch",
"(",
"SVGMapDeffered",
".",
"reject",
")",
";",
"return",
"SVGMapDeffered",
".",
"promise",
".",
"nodeify",
"(",
"callback",
")",
";",
"}"
] |
Note, the svgs in the first directory in gmeConfig.visualization.svgDirs will be added without
the dirname prefix for the svg.
With the following file structure:
./icons/svg1.svg
./icons2/svg2.svg
./icons3/svg3.svg
and gmeConfig.visualization.svgDirs = ['./icons', './icons2', './icons3'];
then the svgMap will have keys as follows:
{
'svg1.svg' : '...',
'icons2/svg2.svg': '...',
'icons3/svg3.svg': '...'
}
@param gmeConfig
@param logger
@param callback
@returns {*}
|
[
"Note",
"the",
"svgs",
"in",
"the",
"first",
"directory",
"in",
"gmeConfig",
".",
"visualization",
".",
"svgDirs",
"will",
"be",
"added",
"without",
"the",
"dirname",
"prefix",
"for",
"the",
"svg",
"."
] |
f9af95d7bedd83cdfde9cca9c8c2d560c0222065
|
https://github.com/webgme/webgme-engine/blob/f9af95d7bedd83cdfde9cca9c8c2d560c0222065/src/utils.js#L166-L223
|
train
|
webgme/webgme-engine
|
src/common/core/corediff.js
|
function (containerGuid, relativePath) {
var usedDiff, path, containerDiff, baseGuids, i, baseDiff, dataKnownInExtension;
containerDiff = getNodeByGuid(diffExtension, containerGuid);
if (containerDiff === null) {
containerDiff = getNodeByGuid(diffBase, containerGuid);
usedDiff = diffBase;
path = getPathOfGuid(usedDiff, containerGuid);
} else {
dataKnownInExtension = true;
usedDiff = diffExtension;
path = getPathOfGuid(usedDiff, containerGuid);
}
baseGuids = Object.keys(containerDiff.oBaseGuids || {})
.concat(Object.keys(containerDiff.ooBaseGuids || {}));
for (i = 0; i < baseGuids.length; i += 1) {
baseDiff = getPathOfDiff(getNodeByGuid(diffExtension, baseGuids[i]) || {}, relativePath);
if (baseDiff.removed === false || typeof baseDiff.movedFrom === 'string') {
//the base exists / changed and new at the given path
return true;
}
}
if (dataKnownInExtension &&
containerDiff.pointer &&
typeof containerDiff.pointer.base === 'string') {
// the container changed its base
return true;
}
//this parent was fine, so let's go to the next one - except the root, that we do not have to check
relativePath = CONSTANTS.PATH_SEP + getRelidFromPath(path) + relativePath;
if (getParentPath(path)) {
// we should stop before the ROOT
return checkContainer(getParentGuid(diffExtension, path), relativePath);
}
return false;
}
|
javascript
|
function (containerGuid, relativePath) {
var usedDiff, path, containerDiff, baseGuids, i, baseDiff, dataKnownInExtension;
containerDiff = getNodeByGuid(diffExtension, containerGuid);
if (containerDiff === null) {
containerDiff = getNodeByGuid(diffBase, containerGuid);
usedDiff = diffBase;
path = getPathOfGuid(usedDiff, containerGuid);
} else {
dataKnownInExtension = true;
usedDiff = diffExtension;
path = getPathOfGuid(usedDiff, containerGuid);
}
baseGuids = Object.keys(containerDiff.oBaseGuids || {})
.concat(Object.keys(containerDiff.ooBaseGuids || {}));
for (i = 0; i < baseGuids.length; i += 1) {
baseDiff = getPathOfDiff(getNodeByGuid(diffExtension, baseGuids[i]) || {}, relativePath);
if (baseDiff.removed === false || typeof baseDiff.movedFrom === 'string') {
//the base exists / changed and new at the given path
return true;
}
}
if (dataKnownInExtension &&
containerDiff.pointer &&
typeof containerDiff.pointer.base === 'string') {
// the container changed its base
return true;
}
//this parent was fine, so let's go to the next one - except the root, that we do not have to check
relativePath = CONSTANTS.PATH_SEP + getRelidFromPath(path) + relativePath;
if (getParentPath(path)) {
// we should stop before the ROOT
return checkContainer(getParentGuid(diffExtension, path), relativePath);
}
return false;
}
|
[
"function",
"(",
"containerGuid",
",",
"relativePath",
")",
"{",
"var",
"usedDiff",
",",
"path",
",",
"containerDiff",
",",
"baseGuids",
",",
"i",
",",
"baseDiff",
",",
"dataKnownInExtension",
";",
"containerDiff",
"=",
"getNodeByGuid",
"(",
"diffExtension",
",",
"containerGuid",
")",
";",
"if",
"(",
"containerDiff",
"===",
"null",
")",
"{",
"containerDiff",
"=",
"getNodeByGuid",
"(",
"diffBase",
",",
"containerGuid",
")",
";",
"usedDiff",
"=",
"diffBase",
";",
"path",
"=",
"getPathOfGuid",
"(",
"usedDiff",
",",
"containerGuid",
")",
";",
"}",
"else",
"{",
"dataKnownInExtension",
"=",
"true",
";",
"usedDiff",
"=",
"diffExtension",
";",
"path",
"=",
"getPathOfGuid",
"(",
"usedDiff",
",",
"containerGuid",
")",
";",
"}",
"baseGuids",
"=",
"Object",
".",
"keys",
"(",
"containerDiff",
".",
"oBaseGuids",
"||",
"{",
"}",
")",
".",
"concat",
"(",
"Object",
".",
"keys",
"(",
"containerDiff",
".",
"ooBaseGuids",
"||",
"{",
"}",
")",
")",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"baseGuids",
".",
"length",
";",
"i",
"+=",
"1",
")",
"{",
"baseDiff",
"=",
"getPathOfDiff",
"(",
"getNodeByGuid",
"(",
"diffExtension",
",",
"baseGuids",
"[",
"i",
"]",
")",
"||",
"{",
"}",
",",
"relativePath",
")",
";",
"if",
"(",
"baseDiff",
".",
"removed",
"===",
"false",
"||",
"typeof",
"baseDiff",
".",
"movedFrom",
"===",
"'string'",
")",
"{",
"return",
"true",
";",
"}",
"}",
"if",
"(",
"dataKnownInExtension",
"&&",
"containerDiff",
".",
"pointer",
"&&",
"typeof",
"containerDiff",
".",
"pointer",
".",
"base",
"===",
"'string'",
")",
"{",
"return",
"true",
";",
"}",
"relativePath",
"=",
"CONSTANTS",
".",
"PATH_SEP",
"+",
"getRelidFromPath",
"(",
"path",
")",
"+",
"relativePath",
";",
"if",
"(",
"getParentPath",
"(",
"path",
")",
")",
"{",
"return",
"checkContainer",
"(",
"getParentGuid",
"(",
"diffExtension",
",",
"path",
")",
",",
"relativePath",
")",
";",
"}",
"return",
"false",
";",
"}"
] |
a generic approach to check for complex collisions, when the same path is being created by changes in the base of some container and inside the container by either move or creation also it moves new nodes whenever any of its container changed base - not necessarily able to figure out, so it is safer to reallocate relid in this rare case
|
[
"a",
"generic",
"approach",
"to",
"check",
"for",
"complex",
"collisions",
"when",
"the",
"same",
"path",
"is",
"being",
"created",
"by",
"changes",
"in",
"the",
"base",
"of",
"some",
"container",
"and",
"inside",
"the",
"container",
"by",
"either",
"move",
"or",
"creation",
"also",
"it",
"moves",
"new",
"nodes",
"whenever",
"any",
"of",
"its",
"container",
"changed",
"base",
"-",
"not",
"necessarily",
"able",
"to",
"figure",
"out",
"so",
"it",
"is",
"safer",
"to",
"reallocate",
"relid",
"in",
"this",
"rare",
"case"
] |
f9af95d7bedd83cdfde9cca9c8c2d560c0222065
|
https://github.com/webgme/webgme-engine/blob/f9af95d7bedd83cdfde9cca9c8c2d560c0222065/src/common/core/corediff.js#L935-L974
|
train
|
|
webgme/webgme-engine
|
src/common/storage/storageclasses/editorstorage.js
|
extractSWMContext
|
function extractSWMContext(swmParams) {
var result = {};
if (swmParams.projectId) {
result.projectId = swmParams.projectId;
if (swmParams.branchName || swmParams.branch || swmParams.commitHash || swmParams.commit) {
// Add any of these.
result.branchName = swmParams.branchName || swmParams.branch;
result.commitHash = swmParams.commitHash || swmParams.commit;
}
} else if (swmParams.context &&
swmParams.context.managerConfig &&
swmParams.context.managerConfig.project) {
// This is a plugin request..
result.projectId = swmParams.context.managerConfig.project;
result.commitHash = swmParams.context.managerConfig.commitHash;
result.branchName = swmParams.context.managerConfig.branchName;
}
return result;
}
|
javascript
|
function extractSWMContext(swmParams) {
var result = {};
if (swmParams.projectId) {
result.projectId = swmParams.projectId;
if (swmParams.branchName || swmParams.branch || swmParams.commitHash || swmParams.commit) {
// Add any of these.
result.branchName = swmParams.branchName || swmParams.branch;
result.commitHash = swmParams.commitHash || swmParams.commit;
}
} else if (swmParams.context &&
swmParams.context.managerConfig &&
swmParams.context.managerConfig.project) {
// This is a plugin request..
result.projectId = swmParams.context.managerConfig.project;
result.commitHash = swmParams.context.managerConfig.commitHash;
result.branchName = swmParams.context.managerConfig.branchName;
}
return result;
}
|
[
"function",
"extractSWMContext",
"(",
"swmParams",
")",
"{",
"var",
"result",
"=",
"{",
"}",
";",
"if",
"(",
"swmParams",
".",
"projectId",
")",
"{",
"result",
".",
"projectId",
"=",
"swmParams",
".",
"projectId",
";",
"if",
"(",
"swmParams",
".",
"branchName",
"||",
"swmParams",
".",
"branch",
"||",
"swmParams",
".",
"commitHash",
"||",
"swmParams",
".",
"commit",
")",
"{",
"result",
".",
"branchName",
"=",
"swmParams",
".",
"branchName",
"||",
"swmParams",
".",
"branch",
";",
"result",
".",
"commitHash",
"=",
"swmParams",
".",
"commitHash",
"||",
"swmParams",
".",
"commit",
";",
"}",
"}",
"else",
"if",
"(",
"swmParams",
".",
"context",
"&&",
"swmParams",
".",
"context",
".",
"managerConfig",
"&&",
"swmParams",
".",
"context",
".",
"managerConfig",
".",
"project",
")",
"{",
"result",
".",
"projectId",
"=",
"swmParams",
".",
"context",
".",
"managerConfig",
".",
"project",
";",
"result",
".",
"commitHash",
"=",
"swmParams",
".",
"context",
".",
"managerConfig",
".",
"commitHash",
";",
"result",
".",
"branchName",
"=",
"swmParams",
".",
"context",
".",
"managerConfig",
".",
"branchName",
";",
"}",
"return",
"result",
";",
"}"
] |
Dig out the context for the server-worker request. Needed to determine if
the request needs be queued on the current commit-queue.
@param {object} swmParams
@returns {object} If the request contains a projectId and (branchName and/or commitHash). It
will return an object with projectId and (branchName and/or commitHash).
|
[
"Dig",
"out",
"the",
"context",
"for",
"the",
"server",
"-",
"worker",
"request",
".",
"Needed",
"to",
"determine",
"if",
"the",
"request",
"needs",
"be",
"queued",
"on",
"the",
"current",
"commit",
"-",
"queue",
"."
] |
f9af95d7bedd83cdfde9cca9c8c2d560c0222065
|
https://github.com/webgme/webgme-engine/blob/f9af95d7bedd83cdfde9cca9c8c2d560c0222065/src/common/storage/storageclasses/editorstorage.js#L60-L80
|
train
|
webgme/webgme-engine
|
src/server/middleware/auth/gmeauth.js
|
updateUserComponentSettings
|
function updateUserComponentSettings(userId, componentId, settings, overwrite, callback) {
return _updateUserObjectField(userId, ['settings', componentId], settings, overwrite)
.then(function (userData) {
return userData.settings[componentId];
})
.nodeify(callback);
}
|
javascript
|
function updateUserComponentSettings(userId, componentId, settings, overwrite, callback) {
return _updateUserObjectField(userId, ['settings', componentId], settings, overwrite)
.then(function (userData) {
return userData.settings[componentId];
})
.nodeify(callback);
}
|
[
"function",
"updateUserComponentSettings",
"(",
"userId",
",",
"componentId",
",",
"settings",
",",
"overwrite",
",",
"callback",
")",
"{",
"return",
"_updateUserObjectField",
"(",
"userId",
",",
"[",
"'settings'",
",",
"componentId",
"]",
",",
"settings",
",",
"overwrite",
")",
".",
"then",
"(",
"function",
"(",
"userData",
")",
"{",
"return",
"userData",
".",
"settings",
"[",
"componentId",
"]",
";",
"}",
")",
".",
"nodeify",
"(",
"callback",
")",
";",
"}"
] |
Updates the provided fields in the settings stored at given componentId.
@param {string} userId
@param {string} componentId
@param {object} settings
@param {boolean} [overwrite] - if true the settings for the key will be overwritten.
@param {function} [callback]
@returns {*}
|
[
"Updates",
"the",
"provided",
"fields",
"in",
"the",
"settings",
"stored",
"at",
"given",
"componentId",
"."
] |
f9af95d7bedd83cdfde9cca9c8c2d560c0222065
|
https://github.com/webgme/webgme-engine/blob/f9af95d7bedd83cdfde9cca9c8c2d560c0222065/src/server/middleware/auth/gmeauth.js#L610-L616
|
train
|
webgme/webgme-engine
|
src/server/middleware/auth/gmeauth.js
|
updateUserSettings
|
function updateUserSettings(userId, settings, overwrite, callback) {
return _updateUserObjectField(userId, ['settings'], settings, overwrite)
.then(function (userData) {
return userData.settings;
})
.nodeify(callback);
}
|
javascript
|
function updateUserSettings(userId, settings, overwrite, callback) {
return _updateUserObjectField(userId, ['settings'], settings, overwrite)
.then(function (userData) {
return userData.settings;
})
.nodeify(callback);
}
|
[
"function",
"updateUserSettings",
"(",
"userId",
",",
"settings",
",",
"overwrite",
",",
"callback",
")",
"{",
"return",
"_updateUserObjectField",
"(",
"userId",
",",
"[",
"'settings'",
"]",
",",
"settings",
",",
"overwrite",
")",
".",
"then",
"(",
"function",
"(",
"userData",
")",
"{",
"return",
"userData",
".",
"settings",
";",
"}",
")",
".",
"nodeify",
"(",
"callback",
")",
";",
"}"
] |
Updates the provided fields in the settings.
@param {string} userId
@param {object} settings
@param {boolean} [overwrite] - if true the settings for the key will be overwritten.
@param {function} [callback]
@returns {*}
|
[
"Updates",
"the",
"provided",
"fields",
"in",
"the",
"settings",
"."
] |
f9af95d7bedd83cdfde9cca9c8c2d560c0222065
|
https://github.com/webgme/webgme-engine/blob/f9af95d7bedd83cdfde9cca9c8c2d560c0222065/src/server/middleware/auth/gmeauth.js#L626-L632
|
train
|
webgme/webgme-engine
|
src/plugin/climanager.js
|
PluginCliManager
|
function PluginCliManager(project, mainLogger, gmeConfig, opts) {
var blobClient = new BlobClientWithFSBackend(gmeConfig, mainLogger, opts);
PluginManagerBase.call(this, blobClient, project, mainLogger, gmeConfig);
}
|
javascript
|
function PluginCliManager(project, mainLogger, gmeConfig, opts) {
var blobClient = new BlobClientWithFSBackend(gmeConfig, mainLogger, opts);
PluginManagerBase.call(this, blobClient, project, mainLogger, gmeConfig);
}
|
[
"function",
"PluginCliManager",
"(",
"project",
",",
"mainLogger",
",",
"gmeConfig",
",",
"opts",
")",
"{",
"var",
"blobClient",
"=",
"new",
"BlobClientWithFSBackend",
"(",
"gmeConfig",
",",
"mainLogger",
",",
"opts",
")",
";",
"PluginManagerBase",
".",
"call",
"(",
"this",
",",
"blobClient",
",",
"project",
",",
"mainLogger",
",",
"gmeConfig",
")",
";",
"}"
] |
Creates a new instance of PluginCliManager
@param {UserProject} [project] - optional default project, can be passed during initialization of plugin too.
@param {object} - mainLogger - logger for manager, plugin-logger will fork from this logger.
@param {object} gmeConfig - global configuration
@param {object} [opts] - Optional options
@param {object} [opts.writeBlobFilesDir] - If defined will put blob files with their
name inside %cwd%/%writeBlobFilesDir%
@constructor
@ignore
|
[
"Creates",
"a",
"new",
"instance",
"of",
"PluginCliManager"
] |
f9af95d7bedd83cdfde9cca9c8c2d560c0222065
|
https://github.com/webgme/webgme-engine/blob/f9af95d7bedd83cdfde9cca9c8c2d560c0222065/src/plugin/climanager.js#L22-L26
|
train
|
webgme/webgme-engine
|
src/server/storage/storage.js
|
loadRootAndCommitObject
|
function loadRootAndCommitObject(project) {
var deferred = Q.defer();
if (data.newHash !== '') {
project.loadObject(data.newHash)
.then(function (commitObject) {
fullEventData.commitObject = commitObject;
return project.loadObject(commitObject.root);
})
.then(function (rootObject) {
fullEventData.coreObjects.push(rootObject);
deferred.resolve(project);
})
.catch(function (err) {
self.logger.error(err.message);
deferred.reject(new Error('Tried to setBranchHash to invalid or non-existing commit, err: ' +
err.message));
});
} else {
// When deleting a branch there no need to ensure this.
deferred.resolve(project);
}
return deferred.promise;
}
|
javascript
|
function loadRootAndCommitObject(project) {
var deferred = Q.defer();
if (data.newHash !== '') {
project.loadObject(data.newHash)
.then(function (commitObject) {
fullEventData.commitObject = commitObject;
return project.loadObject(commitObject.root);
})
.then(function (rootObject) {
fullEventData.coreObjects.push(rootObject);
deferred.resolve(project);
})
.catch(function (err) {
self.logger.error(err.message);
deferred.reject(new Error('Tried to setBranchHash to invalid or non-existing commit, err: ' +
err.message));
});
} else {
// When deleting a branch there no need to ensure this.
deferred.resolve(project);
}
return deferred.promise;
}
|
[
"function",
"loadRootAndCommitObject",
"(",
"project",
")",
"{",
"var",
"deferred",
"=",
"Q",
".",
"defer",
"(",
")",
";",
"if",
"(",
"data",
".",
"newHash",
"!==",
"''",
")",
"{",
"project",
".",
"loadObject",
"(",
"data",
".",
"newHash",
")",
".",
"then",
"(",
"function",
"(",
"commitObject",
")",
"{",
"fullEventData",
".",
"commitObject",
"=",
"commitObject",
";",
"return",
"project",
".",
"loadObject",
"(",
"commitObject",
".",
"root",
")",
";",
"}",
")",
".",
"then",
"(",
"function",
"(",
"rootObject",
")",
"{",
"fullEventData",
".",
"coreObjects",
".",
"push",
"(",
"rootObject",
")",
";",
"deferred",
".",
"resolve",
"(",
"project",
")",
";",
"}",
")",
".",
"catch",
"(",
"function",
"(",
"err",
")",
"{",
"self",
".",
"logger",
".",
"error",
"(",
"err",
".",
"message",
")",
";",
"deferred",
".",
"reject",
"(",
"new",
"Error",
"(",
"'Tried to setBranchHash to invalid or non-existing commit, err: '",
"+",
"err",
".",
"message",
")",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"deferred",
".",
"resolve",
"(",
"project",
")",
";",
"}",
"return",
"deferred",
".",
"promise",
";",
"}"
] |
This will also ensure that the new commit does indeed point to a commitObject with an existing root.
|
[
"This",
"will",
"also",
"ensure",
"that",
"the",
"new",
"commit",
"does",
"indeed",
"point",
"to",
"a",
"commitObject",
"with",
"an",
"existing",
"root",
"."
] |
f9af95d7bedd83cdfde9cca9c8c2d560c0222065
|
https://github.com/webgme/webgme-engine/blob/f9af95d7bedd83cdfde9cca9c8c2d560c0222065/src/server/storage/storage.js#L649-L672
|
train
|
webgme/webgme-engine
|
src/common/storage/util.js
|
function (project, projectJson, options, callback) {
var deferred = Q.defer(),
toPersist = {},
rootHash = projectJson.rootHash,
defaultCommitMessage = 'Importing contents of [' +
projectJson.projectId + '@' + rootHash + ']',
objects = projectJson.objects,
i;
for (i = 0; i < objects.length; i += 1) {
// we have to patch the object right before import, for smoother usage experience
toPersist[objects[i]._id] = objects[i];
}
options = options || {};
options.branch = options.branch || null;
options.parentCommit = options.parentCommit || [];
project.makeCommit(options.branch, options.parentCommit,
rootHash, toPersist, options.commitMessage || defaultCommitMessage)
.then(function (commitResult) {
deferred.resolve(commitResult);
})
.catch(deferred.reject);
return deferred.promise.nodeify(callback);
}
|
javascript
|
function (project, projectJson, options, callback) {
var deferred = Q.defer(),
toPersist = {},
rootHash = projectJson.rootHash,
defaultCommitMessage = 'Importing contents of [' +
projectJson.projectId + '@' + rootHash + ']',
objects = projectJson.objects,
i;
for (i = 0; i < objects.length; i += 1) {
// we have to patch the object right before import, for smoother usage experience
toPersist[objects[i]._id] = objects[i];
}
options = options || {};
options.branch = options.branch || null;
options.parentCommit = options.parentCommit || [];
project.makeCommit(options.branch, options.parentCommit,
rootHash, toPersist, options.commitMessage || defaultCommitMessage)
.then(function (commitResult) {
deferred.resolve(commitResult);
})
.catch(deferred.reject);
return deferred.promise.nodeify(callback);
}
|
[
"function",
"(",
"project",
",",
"projectJson",
",",
"options",
",",
"callback",
")",
"{",
"var",
"deferred",
"=",
"Q",
".",
"defer",
"(",
")",
",",
"toPersist",
"=",
"{",
"}",
",",
"rootHash",
"=",
"projectJson",
".",
"rootHash",
",",
"defaultCommitMessage",
"=",
"'Importing contents of ['",
"+",
"projectJson",
".",
"projectId",
"+",
"'@'",
"+",
"rootHash",
"+",
"']'",
",",
"objects",
"=",
"projectJson",
".",
"objects",
",",
"i",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"objects",
".",
"length",
";",
"i",
"+=",
"1",
")",
"{",
"toPersist",
"[",
"objects",
"[",
"i",
"]",
".",
"_id",
"]",
"=",
"objects",
"[",
"i",
"]",
";",
"}",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"options",
".",
"branch",
"=",
"options",
".",
"branch",
"||",
"null",
";",
"options",
".",
"parentCommit",
"=",
"options",
".",
"parentCommit",
"||",
"[",
"]",
";",
"project",
".",
"makeCommit",
"(",
"options",
".",
"branch",
",",
"options",
".",
"parentCommit",
",",
"rootHash",
",",
"toPersist",
",",
"options",
".",
"commitMessage",
"||",
"defaultCommitMessage",
")",
".",
"then",
"(",
"function",
"(",
"commitResult",
")",
"{",
"deferred",
".",
"resolve",
"(",
"commitResult",
")",
";",
"}",
")",
".",
"catch",
"(",
"deferred",
".",
"reject",
")",
";",
"return",
"deferred",
".",
"promise",
".",
"nodeify",
"(",
"callback",
")",
";",
"}"
] |
Inserts a serialized project tree into the storage and associates it with a commitHash.
@param {ProjectInterface} project
@param {object} [options]
@param {string} [options.branch] - Name of branch to update
@param {string} [options.parentCommit] - Array of parents for new commit
@param {string} [options.commitMessage=%defaultCommitMessage%] information about the insertion
@param {function(Error, hashes)} callback
|
[
"Inserts",
"a",
"serialized",
"project",
"tree",
"into",
"the",
"storage",
"and",
"associates",
"it",
"with",
"a",
"commitHash",
"."
] |
f9af95d7bedd83cdfde9cca9c8c2d560c0222065
|
https://github.com/webgme/webgme-engine/blob/f9af95d7bedd83cdfde9cca9c8c2d560c0222065/src/common/storage/util.js#L300-L327
|
train
|
|
webgme/webgme-engine
|
src/client/client.js
|
fitsInPatternTypes
|
function fitsInPatternTypes(path, pattern) {
var i;
if (pattern.items && pattern.items.length > 0) {
for (i = 0; i < pattern.items.length; i += 1) {
if (self.isTypeOf(path, pattern.items[i])) {
return true;
}
}
return false;
} else {
return true;
}
}
|
javascript
|
function fitsInPatternTypes(path, pattern) {
var i;
if (pattern.items && pattern.items.length > 0) {
for (i = 0; i < pattern.items.length; i += 1) {
if (self.isTypeOf(path, pattern.items[i])) {
return true;
}
}
return false;
} else {
return true;
}
}
|
[
"function",
"fitsInPatternTypes",
"(",
"path",
",",
"pattern",
")",
"{",
"var",
"i",
";",
"if",
"(",
"pattern",
".",
"items",
"&&",
"pattern",
".",
"items",
".",
"length",
">",
"0",
")",
"{",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"pattern",
".",
"items",
".",
"length",
";",
"i",
"+=",
"1",
")",
"{",
"if",
"(",
"self",
".",
"isTypeOf",
"(",
"path",
",",
"pattern",
".",
"items",
"[",
"i",
"]",
")",
")",
"{",
"return",
"true",
";",
"}",
"}",
"return",
"false",
";",
"}",
"else",
"{",
"return",
"true",
";",
"}",
"}"
] |
this is just a first brute implementation it needs serious optimization!!!
|
[
"this",
"is",
"just",
"a",
"first",
"brute",
"implementation",
"it",
"needs",
"serious",
"optimization!!!"
] |
f9af95d7bedd83cdfde9cca9c8c2d560c0222065
|
https://github.com/webgme/webgme-engine/blob/f9af95d7bedd83cdfde9cca9c8c2d560c0222065/src/client/client.js#L213-L226
|
train
|
webgme/webgme-engine
|
src/client/client.js
|
reLaunchUsers
|
function reLaunchUsers() {
var i;
for (i in state.users) {
if (state.users.hasOwnProperty(i)) {
if (state.users[i].UI && typeof state.users[i].UI === 'object' &&
typeof state.users[i].UI.reLaunch === 'function') {
state.users[i].UI.reLaunch();
}
}
}
}
|
javascript
|
function reLaunchUsers() {
var i;
for (i in state.users) {
if (state.users.hasOwnProperty(i)) {
if (state.users[i].UI && typeof state.users[i].UI === 'object' &&
typeof state.users[i].UI.reLaunch === 'function') {
state.users[i].UI.reLaunch();
}
}
}
}
|
[
"function",
"reLaunchUsers",
"(",
")",
"{",
"var",
"i",
";",
"for",
"(",
"i",
"in",
"state",
".",
"users",
")",
"{",
"if",
"(",
"state",
".",
"users",
".",
"hasOwnProperty",
"(",
"i",
")",
")",
"{",
"if",
"(",
"state",
".",
"users",
"[",
"i",
"]",
".",
"UI",
"&&",
"typeof",
"state",
".",
"users",
"[",
"i",
"]",
".",
"UI",
"===",
"'object'",
"&&",
"typeof",
"state",
".",
"users",
"[",
"i",
"]",
".",
"UI",
".",
"reLaunch",
"===",
"'function'",
")",
"{",
"state",
".",
"users",
"[",
"i",
"]",
".",
"UI",
".",
"reLaunch",
"(",
")",
";",
"}",
"}",
"}",
"}"
] |
magic number could be fine-tuned
|
[
"magic",
"number",
"could",
"be",
"fine",
"-",
"tuned"
] |
f9af95d7bedd83cdfde9cca9c8c2d560c0222065
|
https://github.com/webgme/webgme-engine/blob/f9af95d7bedd83cdfde9cca9c8c2d560c0222065/src/client/client.js#L407-L417
|
train
|
webgme/webgme-engine
|
src/plugin/coreplugins/GuidCollider/GuidCollider.js
|
function (node, next) {
var oldGuid = self.core.getGuid(node),
newGuid;
if (guids.hasOwnProperty(oldGuid)) {
hasCollision = true;
if (currentConfiguration.checkOnly) {
self.createMessage(node, 'guid collision with: ' + guids[oldGuid]);
} else {
newGuid = GUID();
self.core.setGuid(node, newGuid);
self.createMessage(node, 'guid changed [' + oldGuid + ']->[' + newGuid + ']');
guids[newGuid] = self.core.getPath(node);
}
} else {
guids[oldGuid] = self.core.getPath(node);
}
next(null);
}
|
javascript
|
function (node, next) {
var oldGuid = self.core.getGuid(node),
newGuid;
if (guids.hasOwnProperty(oldGuid)) {
hasCollision = true;
if (currentConfiguration.checkOnly) {
self.createMessage(node, 'guid collision with: ' + guids[oldGuid]);
} else {
newGuid = GUID();
self.core.setGuid(node, newGuid);
self.createMessage(node, 'guid changed [' + oldGuid + ']->[' + newGuid + ']');
guids[newGuid] = self.core.getPath(node);
}
} else {
guids[oldGuid] = self.core.getPath(node);
}
next(null);
}
|
[
"function",
"(",
"node",
",",
"next",
")",
"{",
"var",
"oldGuid",
"=",
"self",
".",
"core",
".",
"getGuid",
"(",
"node",
")",
",",
"newGuid",
";",
"if",
"(",
"guids",
".",
"hasOwnProperty",
"(",
"oldGuid",
")",
")",
"{",
"hasCollision",
"=",
"true",
";",
"if",
"(",
"currentConfiguration",
".",
"checkOnly",
")",
"{",
"self",
".",
"createMessage",
"(",
"node",
",",
"'guid collision with: '",
"+",
"guids",
"[",
"oldGuid",
"]",
")",
";",
"}",
"else",
"{",
"newGuid",
"=",
"GUID",
"(",
")",
";",
"self",
".",
"core",
".",
"setGuid",
"(",
"node",
",",
"newGuid",
")",
";",
"self",
".",
"createMessage",
"(",
"node",
",",
"'guid changed ['",
"+",
"oldGuid",
"+",
"']->['",
"+",
"newGuid",
"+",
"']'",
")",
";",
"guids",
"[",
"newGuid",
"]",
"=",
"self",
".",
"core",
".",
"getPath",
"(",
"node",
")",
";",
"}",
"}",
"else",
"{",
"guids",
"[",
"oldGuid",
"]",
"=",
"self",
".",
"core",
".",
"getPath",
"(",
"node",
")",
";",
"}",
"next",
"(",
"null",
")",
";",
"}"
] |
Use self to access core, project, result, logger etc from PluginBase. These are all instantiated at this point.
|
[
"Use",
"self",
"to",
"access",
"core",
"project",
"result",
"logger",
"etc",
"from",
"PluginBase",
".",
"These",
"are",
"all",
"instantiated",
"at",
"this",
"point",
"."
] |
f9af95d7bedd83cdfde9cca9c8c2d560c0222065
|
https://github.com/webgme/webgme-engine/blob/f9af95d7bedd83cdfde9cca9c8c2d560c0222065/src/plugin/coreplugins/GuidCollider/GuidCollider.js#L59-L76
|
train
|
|
webgme/webgme-engine
|
src/common/util/uint.js
|
uint8ArrayToString
|
function uint8ArrayToString(uintArray) {
var resultString = '',
i;
for (i = 0; i < uintArray.byteLength; i++) {
resultString += String.fromCharCode(uintArray[i]);
}
return decodeURIComponent(escape(resultString));
}
|
javascript
|
function uint8ArrayToString(uintArray) {
var resultString = '',
i;
for (i = 0; i < uintArray.byteLength; i++) {
resultString += String.fromCharCode(uintArray[i]);
}
return decodeURIComponent(escape(resultString));
}
|
[
"function",
"uint8ArrayToString",
"(",
"uintArray",
")",
"{",
"var",
"resultString",
"=",
"''",
",",
"i",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"uintArray",
".",
"byteLength",
";",
"i",
"++",
")",
"{",
"resultString",
"+=",
"String",
".",
"fromCharCode",
"(",
"uintArray",
"[",
"i",
"]",
")",
";",
"}",
"return",
"decodeURIComponent",
"(",
"escape",
"(",
"resultString",
")",
")",
";",
"}"
] |
this helper function is necessary as in case of large json objects, the library standard function causes stack overflow
|
[
"this",
"helper",
"function",
"is",
"necessary",
"as",
"in",
"case",
"of",
"large",
"json",
"objects",
"the",
"library",
"standard",
"function",
"causes",
"stack",
"overflow"
] |
f9af95d7bedd83cdfde9cca9c8c2d560c0222065
|
https://github.com/webgme/webgme-engine/blob/f9af95d7bedd83cdfde9cca9c8c2d560c0222065/src/common/util/uint.js#L13-L20
|
train
|
webgme/webgme-engine
|
src/server/storage/storagehelpers.js
|
loadObject
|
function loadObject(dbProject, nodeHash) {
var deferred = Q.defer(),
node;
dbProject.loadObject(nodeHash)
.then(function (node_) {
var shardLoads = [],
shardId;
node = node_;
if (node && node.ovr && node.ovr.sharded === true) {
for (shardId in node.ovr) {
if (REGEXP.DB_HASH.test(node.ovr[shardId]) === true) {
shardLoads.push(dbProject.loadObject(node.ovr[shardId]));
}
}
return Q.allSettled(shardLoads);
} else {
deferred.resolve(node);
return;
}
})
.then(function (overlayShardResults) {
var i,
response = {
multipleObjects: true,
objects: {}
};
response.objects[nodeHash] = node;
for (i = 0; i < overlayShardResults.length; i += 1) {
if (overlayShardResults[i].state === 'rejected') {
throw new Error('Loading overlay shard of node [' + nodeHash + '] failed');
} else if (overlayShardResults[i].value._id) {
response.objects[overlayShardResults[i].value._id] = overlayShardResults[i].value;
}
}
deferred.resolve(response);
})
.catch(deferred.reject);
return deferred.promise;
}
|
javascript
|
function loadObject(dbProject, nodeHash) {
var deferred = Q.defer(),
node;
dbProject.loadObject(nodeHash)
.then(function (node_) {
var shardLoads = [],
shardId;
node = node_;
if (node && node.ovr && node.ovr.sharded === true) {
for (shardId in node.ovr) {
if (REGEXP.DB_HASH.test(node.ovr[shardId]) === true) {
shardLoads.push(dbProject.loadObject(node.ovr[shardId]));
}
}
return Q.allSettled(shardLoads);
} else {
deferred.resolve(node);
return;
}
})
.then(function (overlayShardResults) {
var i,
response = {
multipleObjects: true,
objects: {}
};
response.objects[nodeHash] = node;
for (i = 0; i < overlayShardResults.length; i += 1) {
if (overlayShardResults[i].state === 'rejected') {
throw new Error('Loading overlay shard of node [' + nodeHash + '] failed');
} else if (overlayShardResults[i].value._id) {
response.objects[overlayShardResults[i].value._id] = overlayShardResults[i].value;
}
}
deferred.resolve(response);
})
.catch(deferred.reject);
return deferred.promise;
}
|
[
"function",
"loadObject",
"(",
"dbProject",
",",
"nodeHash",
")",
"{",
"var",
"deferred",
"=",
"Q",
".",
"defer",
"(",
")",
",",
"node",
";",
"dbProject",
".",
"loadObject",
"(",
"nodeHash",
")",
".",
"then",
"(",
"function",
"(",
"node_",
")",
"{",
"var",
"shardLoads",
"=",
"[",
"]",
",",
"shardId",
";",
"node",
"=",
"node_",
";",
"if",
"(",
"node",
"&&",
"node",
".",
"ovr",
"&&",
"node",
".",
"ovr",
".",
"sharded",
"===",
"true",
")",
"{",
"for",
"(",
"shardId",
"in",
"node",
".",
"ovr",
")",
"{",
"if",
"(",
"REGEXP",
".",
"DB_HASH",
".",
"test",
"(",
"node",
".",
"ovr",
"[",
"shardId",
"]",
")",
"===",
"true",
")",
"{",
"shardLoads",
".",
"push",
"(",
"dbProject",
".",
"loadObject",
"(",
"node",
".",
"ovr",
"[",
"shardId",
"]",
")",
")",
";",
"}",
"}",
"return",
"Q",
".",
"allSettled",
"(",
"shardLoads",
")",
";",
"}",
"else",
"{",
"deferred",
".",
"resolve",
"(",
"node",
")",
";",
"return",
";",
"}",
"}",
")",
".",
"then",
"(",
"function",
"(",
"overlayShardResults",
")",
"{",
"var",
"i",
",",
"response",
"=",
"{",
"multipleObjects",
":",
"true",
",",
"objects",
":",
"{",
"}",
"}",
";",
"response",
".",
"objects",
"[",
"nodeHash",
"]",
"=",
"node",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"overlayShardResults",
".",
"length",
";",
"i",
"+=",
"1",
")",
"{",
"if",
"(",
"overlayShardResults",
"[",
"i",
"]",
".",
"state",
"===",
"'rejected'",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Loading overlay shard of node ['",
"+",
"nodeHash",
"+",
"'] failed'",
")",
";",
"}",
"else",
"if",
"(",
"overlayShardResults",
"[",
"i",
"]",
".",
"value",
".",
"_id",
")",
"{",
"response",
".",
"objects",
"[",
"overlayShardResults",
"[",
"i",
"]",
".",
"value",
".",
"_id",
"]",
"=",
"overlayShardResults",
"[",
"i",
"]",
".",
"value",
";",
"}",
"}",
"deferred",
".",
"resolve",
"(",
"response",
")",
";",
"}",
")",
".",
"catch",
"(",
"deferred",
".",
"reject",
")",
";",
"return",
"deferred",
".",
"promise",
";",
"}"
] |
Loads the specific object, and if that object represents a node with sharded overlays,
then it loads those objects as well, and pack it into a single response.
@param {object} dbProject
@param {string} nodeHash
@returns {function|promise}
@ignore
|
[
"Loads",
"the",
"specific",
"object",
"and",
"if",
"that",
"object",
"represents",
"a",
"node",
"with",
"sharded",
"overlays",
"then",
"it",
"loads",
"those",
"objects",
"as",
"well",
"and",
"pack",
"it",
"into",
"a",
"single",
"response",
"."
] |
f9af95d7bedd83cdfde9cca9c8c2d560c0222065
|
https://github.com/webgme/webgme-engine/blob/f9af95d7bedd83cdfde9cca9c8c2d560c0222065/src/server/storage/storagehelpers.js#L87-L130
|
train
|
webgme/webgme-engine
|
src/server/storage/storagehelpers.js
|
loadPath
|
function loadPath(dbProject, rootHash, loadedObjects, path, excludeParents) {
var deferred = Q.defer(),
pathArray = path.split('/');
function processLoadResult(hash, result) {
var subHash;
if (result.multipleObjects === true) {
for (subHash in result.objects) {
loadedObjects[subHash] = result.objects[subHash];
}
} else {
loadedObjects[hash] = result;
}
}
function loadParent(parentHash, relPath) {
var hash;
if (loadedObjects[parentHash]) {
// Object was already loaded.
if (relPath) {
hash = loadedObjects[parentHash][relPath];
loadParent(hash, pathArray.shift());
} else {
deferred.resolve();
}
} else {
loadObject(dbProject, parentHash)
.then(function (object) {
if (relPath) {
hash = object[relPath];
if (!excludeParents) {
processLoadResult(parentHash, object);
}
loadParent(hash, pathArray.shift());
} else {
processLoadResult(parentHash, object);
deferred.resolve();
}
})
.catch(function (err) {
deferred.reject(err);
});
}
}
// Remove the root-path
pathArray.shift();
loadParent(rootHash, pathArray.shift());
return deferred.promise;
}
|
javascript
|
function loadPath(dbProject, rootHash, loadedObjects, path, excludeParents) {
var deferred = Q.defer(),
pathArray = path.split('/');
function processLoadResult(hash, result) {
var subHash;
if (result.multipleObjects === true) {
for (subHash in result.objects) {
loadedObjects[subHash] = result.objects[subHash];
}
} else {
loadedObjects[hash] = result;
}
}
function loadParent(parentHash, relPath) {
var hash;
if (loadedObjects[parentHash]) {
// Object was already loaded.
if (relPath) {
hash = loadedObjects[parentHash][relPath];
loadParent(hash, pathArray.shift());
} else {
deferred.resolve();
}
} else {
loadObject(dbProject, parentHash)
.then(function (object) {
if (relPath) {
hash = object[relPath];
if (!excludeParents) {
processLoadResult(parentHash, object);
}
loadParent(hash, pathArray.shift());
} else {
processLoadResult(parentHash, object);
deferred.resolve();
}
})
.catch(function (err) {
deferred.reject(err);
});
}
}
// Remove the root-path
pathArray.shift();
loadParent(rootHash, pathArray.shift());
return deferred.promise;
}
|
[
"function",
"loadPath",
"(",
"dbProject",
",",
"rootHash",
",",
"loadedObjects",
",",
"path",
",",
"excludeParents",
")",
"{",
"var",
"deferred",
"=",
"Q",
".",
"defer",
"(",
")",
",",
"pathArray",
"=",
"path",
".",
"split",
"(",
"'/'",
")",
";",
"function",
"processLoadResult",
"(",
"hash",
",",
"result",
")",
"{",
"var",
"subHash",
";",
"if",
"(",
"result",
".",
"multipleObjects",
"===",
"true",
")",
"{",
"for",
"(",
"subHash",
"in",
"result",
".",
"objects",
")",
"{",
"loadedObjects",
"[",
"subHash",
"]",
"=",
"result",
".",
"objects",
"[",
"subHash",
"]",
";",
"}",
"}",
"else",
"{",
"loadedObjects",
"[",
"hash",
"]",
"=",
"result",
";",
"}",
"}",
"function",
"loadParent",
"(",
"parentHash",
",",
"relPath",
")",
"{",
"var",
"hash",
";",
"if",
"(",
"loadedObjects",
"[",
"parentHash",
"]",
")",
"{",
"if",
"(",
"relPath",
")",
"{",
"hash",
"=",
"loadedObjects",
"[",
"parentHash",
"]",
"[",
"relPath",
"]",
";",
"loadParent",
"(",
"hash",
",",
"pathArray",
".",
"shift",
"(",
")",
")",
";",
"}",
"else",
"{",
"deferred",
".",
"resolve",
"(",
")",
";",
"}",
"}",
"else",
"{",
"loadObject",
"(",
"dbProject",
",",
"parentHash",
")",
".",
"then",
"(",
"function",
"(",
"object",
")",
"{",
"if",
"(",
"relPath",
")",
"{",
"hash",
"=",
"object",
"[",
"relPath",
"]",
";",
"if",
"(",
"!",
"excludeParents",
")",
"{",
"processLoadResult",
"(",
"parentHash",
",",
"object",
")",
";",
"}",
"loadParent",
"(",
"hash",
",",
"pathArray",
".",
"shift",
"(",
")",
")",
";",
"}",
"else",
"{",
"processLoadResult",
"(",
"parentHash",
",",
"object",
")",
";",
"deferred",
".",
"resolve",
"(",
")",
";",
"}",
"}",
")",
".",
"catch",
"(",
"function",
"(",
"err",
")",
"{",
"deferred",
".",
"reject",
"(",
"err",
")",
";",
"}",
")",
";",
"}",
"}",
"pathArray",
".",
"shift",
"(",
")",
";",
"loadParent",
"(",
"rootHash",
",",
"pathArray",
".",
"shift",
"(",
")",
")",
";",
"return",
"deferred",
".",
"promise",
";",
"}"
] |
Loads the entire composition chain up till the rootNode for the provided path. And stores the nodes
in the loadedObjects. If the any of the objects already exists in loadedObjects - it does not load it
from the database.
@param {object} dbProject
@param {string} rootHash
@param {Object<string, object>} loadedObjects
@param {string} path
@param {boolean} excludeParents - if true will only include the node at the path
@returns {function|promise}
@ignore
|
[
"Loads",
"the",
"entire",
"composition",
"chain",
"up",
"till",
"the",
"rootNode",
"for",
"the",
"provided",
"path",
".",
"And",
"stores",
"the",
"nodes",
"in",
"the",
"loadedObjects",
".",
"If",
"the",
"any",
"of",
"the",
"objects",
"already",
"exists",
"in",
"loadedObjects",
"-",
"it",
"does",
"not",
"load",
"it",
"from",
"the",
"database",
"."
] |
f9af95d7bedd83cdfde9cca9c8c2d560c0222065
|
https://github.com/webgme/webgme-engine/blob/f9af95d7bedd83cdfde9cca9c8c2d560c0222065/src/server/storage/storagehelpers.js#L145-L195
|
train
|
webgme/webgme-engine
|
src/client/gmeServerRequests.js
|
checkMetaRules
|
function checkMetaRules(nodePaths, includeChildren, callback) {
var parameters = {
command: CONSTANTS.SERVER_WORKER_REQUESTS.CHECK_CONSTRAINTS,
checkType: 'META', //TODO this should come from a constant
includeChildren: includeChildren,
nodePaths: nodePaths,
commitHash: state.commitHash,
projectId: state.project.projectId
};
storage.simpleRequest(parameters, function (err, result) {
if (err) {
logger.error(err);
}
if (result) {
client.dispatchEvent(client.CONSTANTS.META_RULES_RESULT, result);
} else {
client.notifyUser({
severity: 'error',
message: 'Evaluating Meta rules failed with error.'
});
}
if (callback) {
callback(err, result);
}
});
}
|
javascript
|
function checkMetaRules(nodePaths, includeChildren, callback) {
var parameters = {
command: CONSTANTS.SERVER_WORKER_REQUESTS.CHECK_CONSTRAINTS,
checkType: 'META', //TODO this should come from a constant
includeChildren: includeChildren,
nodePaths: nodePaths,
commitHash: state.commitHash,
projectId: state.project.projectId
};
storage.simpleRequest(parameters, function (err, result) {
if (err) {
logger.error(err);
}
if (result) {
client.dispatchEvent(client.CONSTANTS.META_RULES_RESULT, result);
} else {
client.notifyUser({
severity: 'error',
message: 'Evaluating Meta rules failed with error.'
});
}
if (callback) {
callback(err, result);
}
});
}
|
[
"function",
"checkMetaRules",
"(",
"nodePaths",
",",
"includeChildren",
",",
"callback",
")",
"{",
"var",
"parameters",
"=",
"{",
"command",
":",
"CONSTANTS",
".",
"SERVER_WORKER_REQUESTS",
".",
"CHECK_CONSTRAINTS",
",",
"checkType",
":",
"'META'",
",",
"includeChildren",
":",
"includeChildren",
",",
"nodePaths",
":",
"nodePaths",
",",
"commitHash",
":",
"state",
".",
"commitHash",
",",
"projectId",
":",
"state",
".",
"project",
".",
"projectId",
"}",
";",
"storage",
".",
"simpleRequest",
"(",
"parameters",
",",
"function",
"(",
"err",
",",
"result",
")",
"{",
"if",
"(",
"err",
")",
"{",
"logger",
".",
"error",
"(",
"err",
")",
";",
"}",
"if",
"(",
"result",
")",
"{",
"client",
".",
"dispatchEvent",
"(",
"client",
".",
"CONSTANTS",
".",
"META_RULES_RESULT",
",",
"result",
")",
";",
"}",
"else",
"{",
"client",
".",
"notifyUser",
"(",
"{",
"severity",
":",
"'error'",
",",
"message",
":",
"'Evaluating Meta rules failed with error.'",
"}",
")",
";",
"}",
"if",
"(",
"callback",
")",
"{",
"callback",
"(",
"err",
",",
"result",
")",
";",
"}",
"}",
")",
";",
"}"
] |
meta rules checking
@param {string[]} nodePaths - Paths to nodes of which to check.
@param includeChildren
@param callback
|
[
"meta",
"rules",
"checking"
] |
f9af95d7bedd83cdfde9cca9c8c2d560c0222065
|
https://github.com/webgme/webgme-engine/blob/f9af95d7bedd83cdfde9cca9c8c2d560c0222065/src/client/gmeServerRequests.js#L212-L240
|
train
|
webgme/webgme-engine
|
src/common/storage/project/cache.js
|
deepFreeze
|
function deepFreeze(obj) {
Object.freeze(obj);
if (obj instanceof Array) {
for (var i = 0; i < obj.length; i += 1) {
if (obj[i] !== null && typeof obj[i] === 'object') {
deepFreeze(obj[i]);
}
}
} else {
for (var key in obj) {
if (obj[key] !== null && typeof obj[key] === 'object') {
deepFreeze(obj[key]);
}
}
}
}
|
javascript
|
function deepFreeze(obj) {
Object.freeze(obj);
if (obj instanceof Array) {
for (var i = 0; i < obj.length; i += 1) {
if (obj[i] !== null && typeof obj[i] === 'object') {
deepFreeze(obj[i]);
}
}
} else {
for (var key in obj) {
if (obj[key] !== null && typeof obj[key] === 'object') {
deepFreeze(obj[key]);
}
}
}
}
|
[
"function",
"deepFreeze",
"(",
"obj",
")",
"{",
"Object",
".",
"freeze",
"(",
"obj",
")",
";",
"if",
"(",
"obj",
"instanceof",
"Array",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"obj",
".",
"length",
";",
"i",
"+=",
"1",
")",
"{",
"if",
"(",
"obj",
"[",
"i",
"]",
"!==",
"null",
"&&",
"typeof",
"obj",
"[",
"i",
"]",
"===",
"'object'",
")",
"{",
"deepFreeze",
"(",
"obj",
"[",
"i",
"]",
")",
";",
"}",
"}",
"}",
"else",
"{",
"for",
"(",
"var",
"key",
"in",
"obj",
")",
"{",
"if",
"(",
"obj",
"[",
"key",
"]",
"!==",
"null",
"&&",
"typeof",
"obj",
"[",
"key",
"]",
"===",
"'object'",
")",
"{",
"deepFreeze",
"(",
"obj",
"[",
"key",
"]",
")",
";",
"}",
"}",
"}",
"}"
] |
Useful for debugging potential mutations, but not good for performance.
|
[
"Useful",
"for",
"debugging",
"potential",
"mutations",
"but",
"not",
"good",
"for",
"performance",
"."
] |
f9af95d7bedd83cdfde9cca9c8c2d560c0222065
|
https://github.com/webgme/webgme-engine/blob/f9af95d7bedd83cdfde9cca9c8c2d560c0222065/src/common/storage/project/cache.js#L32-L48
|
train
|
webgme/webgme-engine
|
src/addon/AddOnBase.js
|
AddOnBase
|
function AddOnBase(logger, gmeConfig) {
/**
* @type {GmeConfig}
*/
this.gmeConfig = gmeConfig;
/**
* @type {GmeLogger}
*/
this.logger = logger;
// Set at configure
/**
* @type {Core}
*/
this.core = null;
/**
* @type {Project}
*/
this.project = null;
/**
* @type {string}
*/
this.branchName = null;
/**
* @type {BlobClient}
*/
this.blobClient = null;
this.initialized = false;
/**
* @type {AddOnUpdateResult}
*/
this.updateResult = null;
this.currentlyWorking = false;
this.lifespan = 0;
this.logger.debug('ctor');
}
|
javascript
|
function AddOnBase(logger, gmeConfig) {
/**
* @type {GmeConfig}
*/
this.gmeConfig = gmeConfig;
/**
* @type {GmeLogger}
*/
this.logger = logger;
// Set at configure
/**
* @type {Core}
*/
this.core = null;
/**
* @type {Project}
*/
this.project = null;
/**
* @type {string}
*/
this.branchName = null;
/**
* @type {BlobClient}
*/
this.blobClient = null;
this.initialized = false;
/**
* @type {AddOnUpdateResult}
*/
this.updateResult = null;
this.currentlyWorking = false;
this.lifespan = 0;
this.logger.debug('ctor');
}
|
[
"function",
"AddOnBase",
"(",
"logger",
",",
"gmeConfig",
")",
"{",
"this",
".",
"gmeConfig",
"=",
"gmeConfig",
";",
"this",
".",
"logger",
"=",
"logger",
";",
"this",
".",
"core",
"=",
"null",
";",
"this",
".",
"project",
"=",
"null",
";",
"this",
".",
"branchName",
"=",
"null",
";",
"this",
".",
"blobClient",
"=",
"null",
";",
"this",
".",
"initialized",
"=",
"false",
";",
"this",
".",
"updateResult",
"=",
"null",
";",
"this",
".",
"currentlyWorking",
"=",
"false",
";",
"this",
".",
"lifespan",
"=",
"0",
";",
"this",
".",
"logger",
".",
"debug",
"(",
"'ctor'",
")",
";",
"}"
] |
BaseClass for AddOns which run on the server and act upon changes in a branch.
Use the AddOnGenerator to generate a new AddOn that implements this class.
@param {GmeLogger} logger
@param {GmeConfig} gmeConfig
@constructor
@alias AddOnBase
|
[
"BaseClass",
"for",
"AddOns",
"which",
"run",
"on",
"the",
"server",
"and",
"act",
"upon",
"changes",
"in",
"a",
"branch",
".",
"Use",
"the",
"AddOnGenerator",
"to",
"generate",
"a",
"new",
"AddOn",
"that",
"implements",
"this",
"class",
"."
] |
f9af95d7bedd83cdfde9cca9c8c2d560c0222065
|
https://github.com/webgme/webgme-engine/blob/f9af95d7bedd83cdfde9cca9c8c2d560c0222065/src/addon/AddOnBase.js#L24-L67
|
train
|
webgme/webgme-engine
|
src/bin/serialize_to_xml.js
|
connectionToJson
|
function connectionToJson(object) {
var pointerNames = theCore.getPointerNames(object);
var src = null;
var dst = null;
if (pointerNames.indexOf('source') !== -1) {
src = theCore.loadPointer(object, 'source');
}
if (pointerNames.indexOf('target') !== -1) {
dst = theCore.loadPointer(object, 'target');
}
return TASYNC.call(function (s, d) {
var jsonObject = initJsonObject(object);
if (s !== null) {
if (theCore.getRegistry(s, 'metameta') === 'refport') {
var sA = theCore.getParent(s);
jsonObject._children.push({
_type: 'connpoint',
_empty: true,
_attr: {
role: "src",
target: theCore.getRegistry(s, 'id'),
refs: theCore.getRegistry(sA, 'id')
}
});
} else {
jsonObject._children.push({
_type: 'connpoint',
_empty: true,
_attr: {
role: "src",
target: theCore.getRegistry(s, 'id')
}
});
}
}
if (d !== null) {
if (theCore.getRegistry(d, 'metameta') === 'refport') {
var dA = theCore.getParent(d);
jsonObject._children.push({
_type: 'connpoint',
_empty: true,
_attr: {
role: "dst",
target: theCore.getRegistry(d, 'id'),
refs: theCore.getRegistry(dA, 'id')
}
});
} else {
jsonObject._children.push({
_type: 'connpoint',
_empty: true,
_attr: {
role: "dst",
target: theCore.getRegistry(d, 'id')
}
});
}
}
return jsonObject;
}, src, dst);
}
|
javascript
|
function connectionToJson(object) {
var pointerNames = theCore.getPointerNames(object);
var src = null;
var dst = null;
if (pointerNames.indexOf('source') !== -1) {
src = theCore.loadPointer(object, 'source');
}
if (pointerNames.indexOf('target') !== -1) {
dst = theCore.loadPointer(object, 'target');
}
return TASYNC.call(function (s, d) {
var jsonObject = initJsonObject(object);
if (s !== null) {
if (theCore.getRegistry(s, 'metameta') === 'refport') {
var sA = theCore.getParent(s);
jsonObject._children.push({
_type: 'connpoint',
_empty: true,
_attr: {
role: "src",
target: theCore.getRegistry(s, 'id'),
refs: theCore.getRegistry(sA, 'id')
}
});
} else {
jsonObject._children.push({
_type: 'connpoint',
_empty: true,
_attr: {
role: "src",
target: theCore.getRegistry(s, 'id')
}
});
}
}
if (d !== null) {
if (theCore.getRegistry(d, 'metameta') === 'refport') {
var dA = theCore.getParent(d);
jsonObject._children.push({
_type: 'connpoint',
_empty: true,
_attr: {
role: "dst",
target: theCore.getRegistry(d, 'id'),
refs: theCore.getRegistry(dA, 'id')
}
});
} else {
jsonObject._children.push({
_type: 'connpoint',
_empty: true,
_attr: {
role: "dst",
target: theCore.getRegistry(d, 'id')
}
});
}
}
return jsonObject;
}, src, dst);
}
|
[
"function",
"connectionToJson",
"(",
"object",
")",
"{",
"var",
"pointerNames",
"=",
"theCore",
".",
"getPointerNames",
"(",
"object",
")",
";",
"var",
"src",
"=",
"null",
";",
"var",
"dst",
"=",
"null",
";",
"if",
"(",
"pointerNames",
".",
"indexOf",
"(",
"'source'",
")",
"!==",
"-",
"1",
")",
"{",
"src",
"=",
"theCore",
".",
"loadPointer",
"(",
"object",
",",
"'source'",
")",
";",
"}",
"if",
"(",
"pointerNames",
".",
"indexOf",
"(",
"'target'",
")",
"!==",
"-",
"1",
")",
"{",
"dst",
"=",
"theCore",
".",
"loadPointer",
"(",
"object",
",",
"'target'",
")",
";",
"}",
"return",
"TASYNC",
".",
"call",
"(",
"function",
"(",
"s",
",",
"d",
")",
"{",
"var",
"jsonObject",
"=",
"initJsonObject",
"(",
"object",
")",
";",
"if",
"(",
"s",
"!==",
"null",
")",
"{",
"if",
"(",
"theCore",
".",
"getRegistry",
"(",
"s",
",",
"'metameta'",
")",
"===",
"'refport'",
")",
"{",
"var",
"sA",
"=",
"theCore",
".",
"getParent",
"(",
"s",
")",
";",
"jsonObject",
".",
"_children",
".",
"push",
"(",
"{",
"_type",
":",
"'connpoint'",
",",
"_empty",
":",
"true",
",",
"_attr",
":",
"{",
"role",
":",
"\"src\"",
",",
"target",
":",
"theCore",
".",
"getRegistry",
"(",
"s",
",",
"'id'",
")",
",",
"refs",
":",
"theCore",
".",
"getRegistry",
"(",
"sA",
",",
"'id'",
")",
"}",
"}",
")",
";",
"}",
"else",
"{",
"jsonObject",
".",
"_children",
".",
"push",
"(",
"{",
"_type",
":",
"'connpoint'",
",",
"_empty",
":",
"true",
",",
"_attr",
":",
"{",
"role",
":",
"\"src\"",
",",
"target",
":",
"theCore",
".",
"getRegistry",
"(",
"s",
",",
"'id'",
")",
"}",
"}",
")",
";",
"}",
"}",
"if",
"(",
"d",
"!==",
"null",
")",
"{",
"if",
"(",
"theCore",
".",
"getRegistry",
"(",
"d",
",",
"'metameta'",
")",
"===",
"'refport'",
")",
"{",
"var",
"dA",
"=",
"theCore",
".",
"getParent",
"(",
"d",
")",
";",
"jsonObject",
".",
"_children",
".",
"push",
"(",
"{",
"_type",
":",
"'connpoint'",
",",
"_empty",
":",
"true",
",",
"_attr",
":",
"{",
"role",
":",
"\"dst\"",
",",
"target",
":",
"theCore",
".",
"getRegistry",
"(",
"d",
",",
"'id'",
")",
",",
"refs",
":",
"theCore",
".",
"getRegistry",
"(",
"dA",
",",
"'id'",
")",
"}",
"}",
")",
";",
"}",
"else",
"{",
"jsonObject",
".",
"_children",
".",
"push",
"(",
"{",
"_type",
":",
"'connpoint'",
",",
"_empty",
":",
"true",
",",
"_attr",
":",
"{",
"role",
":",
"\"dst\"",
",",
"target",
":",
"theCore",
".",
"getRegistry",
"(",
"d",
",",
"'id'",
")",
"}",
"}",
")",
";",
"}",
"}",
"return",
"jsonObject",
";",
"}",
",",
"src",
",",
"dst",
")",
";",
"}"
] |
new TASYNC compatible functions
|
[
"new",
"TASYNC",
"compatible",
"functions"
] |
f9af95d7bedd83cdfde9cca9c8c2d560c0222065
|
https://github.com/webgme/webgme-engine/blob/f9af95d7bedd83cdfde9cca9c8c2d560c0222065/src/bin/serialize_to_xml.js#L419-L479
|
train
|
webgme/webgme-engine
|
src/common/core/metacore.js
|
isOnMetaSheet
|
function isOnMetaSheet(node) {
//MetaAspectSet
var sets = self.isMemberOf(node);
if (sets && sets[''] && sets[''].indexOf(CONSTANTS.META_SET_NAME) !== -1) {
return true;
}
return false;
}
|
javascript
|
function isOnMetaSheet(node) {
//MetaAspectSet
var sets = self.isMemberOf(node);
if (sets && sets[''] && sets[''].indexOf(CONSTANTS.META_SET_NAME) !== -1) {
return true;
}
return false;
}
|
[
"function",
"isOnMetaSheet",
"(",
"node",
")",
"{",
"var",
"sets",
"=",
"self",
".",
"isMemberOf",
"(",
"node",
")",
";",
"if",
"(",
"sets",
"&&",
"sets",
"[",
"''",
"]",
"&&",
"sets",
"[",
"''",
"]",
".",
"indexOf",
"(",
"CONSTANTS",
".",
"META_SET_NAME",
")",
"!==",
"-",
"1",
")",
"{",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}"
] |
type related extra query functions
|
[
"type",
"related",
"extra",
"query",
"functions"
] |
f9af95d7bedd83cdfde9cca9c8c2d560c0222065
|
https://github.com/webgme/webgme-engine/blob/f9af95d7bedd83cdfde9cca9c8c2d560c0222065/src/common/core/metacore.js#L78-L86
|
train
|
webgme/webgme-engine
|
src/common/EventDispatcher.js
|
function (sender, args) {
for (var i = 0; i < evt.length; i++) {
evt[i](sender, args);
}
}
|
javascript
|
function (sender, args) {
for (var i = 0; i < evt.length; i++) {
evt[i](sender, args);
}
}
|
[
"function",
"(",
"sender",
",",
"args",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"evt",
".",
"length",
";",
"i",
"++",
")",
"{",
"evt",
"[",
"i",
"]",
"(",
"sender",
",",
"args",
")",
";",
"}",
"}"
] |
Create the Handler method that will use currying to call all the Events Handlers internally
|
[
"Create",
"the",
"Handler",
"method",
"that",
"will",
"use",
"currying",
"to",
"call",
"all",
"the",
"Events",
"Handlers",
"internally"
] |
f9af95d7bedd83cdfde9cca9c8c2d560c0222065
|
https://github.com/webgme/webgme-engine/blob/f9af95d7bedd83cdfde9cca9c8c2d560c0222065/src/common/EventDispatcher.js#L99-L103
|
train
|
|
webgme/webgme-engine
|
src/server/standalone.js
|
getUrl
|
function getUrl() {
if (!self.serverUrl) {
// use the cached version if we already built the string
self.serverUrl = 'http://127.0.0.1:' + gmeConfig.server.port;
}
return self.serverUrl;
}
|
javascript
|
function getUrl() {
if (!self.serverUrl) {
// use the cached version if we already built the string
self.serverUrl = 'http://127.0.0.1:' + gmeConfig.server.port;
}
return self.serverUrl;
}
|
[
"function",
"getUrl",
"(",
")",
"{",
"if",
"(",
"!",
"self",
".",
"serverUrl",
")",
"{",
"self",
".",
"serverUrl",
"=",
"'http://127.0.0.1:'",
"+",
"gmeConfig",
".",
"server",
".",
"port",
";",
"}",
"return",
"self",
".",
"serverUrl",
";",
"}"
] |
Gets the server's url based on the gmeConfig that was given to the constructor.
@returns {string}
|
[
"Gets",
"the",
"server",
"s",
"url",
"based",
"on",
"the",
"gmeConfig",
"that",
"was",
"given",
"to",
"the",
"constructor",
"."
] |
f9af95d7bedd83cdfde9cca9c8c2d560c0222065
|
https://github.com/webgme/webgme-engine/blob/f9af95d7bedd83cdfde9cca9c8c2d560c0222065/src/server/standalone.js#L147-L154
|
train
|
webgme/webgme-engine
|
src/common/core/corerel.js
|
shouldHaveShardedOverlays
|
function shouldHaveShardedOverlays(node) {
return Object.keys(self.getProperty(node, CONSTANTS.OVERLAYS_PROPERTY) || {}).length >=
_shardingLimit && self.getPath(node).indexOf('_') === -1;
}
|
javascript
|
function shouldHaveShardedOverlays(node) {
return Object.keys(self.getProperty(node, CONSTANTS.OVERLAYS_PROPERTY) || {}).length >=
_shardingLimit && self.getPath(node).indexOf('_') === -1;
}
|
[
"function",
"shouldHaveShardedOverlays",
"(",
"node",
")",
"{",
"return",
"Object",
".",
"keys",
"(",
"self",
".",
"getProperty",
"(",
"node",
",",
"CONSTANTS",
".",
"OVERLAYS_PROPERTY",
")",
"||",
"{",
"}",
")",
".",
"length",
">=",
"_shardingLimit",
"&&",
"self",
".",
"getPath",
"(",
"node",
")",
".",
"indexOf",
"(",
"'_'",
")",
"===",
"-",
"1",
";",
"}"
] |
We only shard regular GME nodes, technical sub-nodes do not get sharded
|
[
"We",
"only",
"shard",
"regular",
"GME",
"nodes",
"technical",
"sub",
"-",
"nodes",
"do",
"not",
"get",
"sharded"
] |
f9af95d7bedd83cdfde9cca9c8c2d560c0222065
|
https://github.com/webgme/webgme-engine/blob/f9af95d7bedd83cdfde9cca9c8c2d560c0222065/src/common/core/corerel.js#L188-L191
|
train
|
webgme/webgme-engine
|
src/common/core/coretype.js
|
getInheritedCollectionPaths
|
function getInheritedCollectionPaths(node, name) {
var paths = [],
startNode = node,
actualNode = node,
endNode,
prefixNode,
i,
inverseOverlays,
target;
while (startNode) {
actualNode = self.getBase(startNode);
endNode = self.getBase(getInstanceRoot(startNode));
target = '';
if (actualNode && endNode) {
prefixNode = node;
while (actualNode && actualNode !== self.getParent(endNode)) {
inverseOverlays = innerCore.getInverseOverlayOfNode(actualNode);
if (inverseOverlays[target] && inverseOverlays[target][name]) {
for (i = 0; i < inverseOverlays[target][name].length; i += 1) {
paths.push(self.joinPaths(self.getPath(prefixNode), inverseOverlays[target][name][i]));
}
}
target = CONSTANTS.PATH_SEP + self.getRelid(actualNode) + target;
actualNode = self.getParent(actualNode);
prefixNode = self.getParent(prefixNode);
}
}
startNode = self.getBase(startNode);
}
return paths;
}
|
javascript
|
function getInheritedCollectionPaths(node, name) {
var paths = [],
startNode = node,
actualNode = node,
endNode,
prefixNode,
i,
inverseOverlays,
target;
while (startNode) {
actualNode = self.getBase(startNode);
endNode = self.getBase(getInstanceRoot(startNode));
target = '';
if (actualNode && endNode) {
prefixNode = node;
while (actualNode && actualNode !== self.getParent(endNode)) {
inverseOverlays = innerCore.getInverseOverlayOfNode(actualNode);
if (inverseOverlays[target] && inverseOverlays[target][name]) {
for (i = 0; i < inverseOverlays[target][name].length; i += 1) {
paths.push(self.joinPaths(self.getPath(prefixNode), inverseOverlays[target][name][i]));
}
}
target = CONSTANTS.PATH_SEP + self.getRelid(actualNode) + target;
actualNode = self.getParent(actualNode);
prefixNode = self.getParent(prefixNode);
}
}
startNode = self.getBase(startNode);
}
return paths;
}
|
[
"function",
"getInheritedCollectionPaths",
"(",
"node",
",",
"name",
")",
"{",
"var",
"paths",
"=",
"[",
"]",
",",
"startNode",
"=",
"node",
",",
"actualNode",
"=",
"node",
",",
"endNode",
",",
"prefixNode",
",",
"i",
",",
"inverseOverlays",
",",
"target",
";",
"while",
"(",
"startNode",
")",
"{",
"actualNode",
"=",
"self",
".",
"getBase",
"(",
"startNode",
")",
";",
"endNode",
"=",
"self",
".",
"getBase",
"(",
"getInstanceRoot",
"(",
"startNode",
")",
")",
";",
"target",
"=",
"''",
";",
"if",
"(",
"actualNode",
"&&",
"endNode",
")",
"{",
"prefixNode",
"=",
"node",
";",
"while",
"(",
"actualNode",
"&&",
"actualNode",
"!==",
"self",
".",
"getParent",
"(",
"endNode",
")",
")",
"{",
"inverseOverlays",
"=",
"innerCore",
".",
"getInverseOverlayOfNode",
"(",
"actualNode",
")",
";",
"if",
"(",
"inverseOverlays",
"[",
"target",
"]",
"&&",
"inverseOverlays",
"[",
"target",
"]",
"[",
"name",
"]",
")",
"{",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"inverseOverlays",
"[",
"target",
"]",
"[",
"name",
"]",
".",
"length",
";",
"i",
"+=",
"1",
")",
"{",
"paths",
".",
"push",
"(",
"self",
".",
"joinPaths",
"(",
"self",
".",
"getPath",
"(",
"prefixNode",
")",
",",
"inverseOverlays",
"[",
"target",
"]",
"[",
"name",
"]",
"[",
"i",
"]",
")",
")",
";",
"}",
"}",
"target",
"=",
"CONSTANTS",
".",
"PATH_SEP",
"+",
"self",
".",
"getRelid",
"(",
"actualNode",
")",
"+",
"target",
";",
"actualNode",
"=",
"self",
".",
"getParent",
"(",
"actualNode",
")",
";",
"prefixNode",
"=",
"self",
".",
"getParent",
"(",
"prefixNode",
")",
";",
"}",
"}",
"startNode",
"=",
"self",
".",
"getBase",
"(",
"startNode",
")",
";",
"}",
"return",
"paths",
";",
"}"
] |
This function gathers the paths of the nodes that are pointing to the questioned node. The set of relations
that are checked is the 'inherited' inverse relations.
The method of this function is identical to getInheritedCollectionNames, except this function collects the
sources of the given relations and not just the name of all such relation. To return a correct path (as
the data exists in some bases of the actual nodes) the function always convert it back to the place of
inquiry.
@param node - the node in question
@param name - name of the relation that we are interested in
@returns {Array} - list of paths of sources of inherited relations by the given name
|
[
"This",
"function",
"gathers",
"the",
"paths",
"of",
"the",
"nodes",
"that",
"are",
"pointing",
"to",
"the",
"questioned",
"node",
".",
"The",
"set",
"of",
"relations",
"that",
"are",
"checked",
"is",
"the",
"inherited",
"inverse",
"relations",
"."
] |
f9af95d7bedd83cdfde9cca9c8c2d560c0222065
|
https://github.com/webgme/webgme-engine/blob/f9af95d7bedd83cdfde9cca9c8c2d560c0222065/src/common/core/coretype.js#L245-L277
|
train
|
webgme/webgme-engine
|
src/server/storage/metadatastorage.js
|
updateProjectHooks
|
function updateProjectHooks(projectId, hooks, callback) {
return self.projectCollection.findOne({_id: projectId})
.then(function (projectData) {
if (!projectData) {
throw new Error('no such project [' + projectId + ']');
}
// always update webhook information as a whole to allow remove and create and update as well
projectData.hooks = hooks;
return self.projectCollection.updateOne({_id: projectId}, projectData, {upsert: true});
})
.then(function () {
return getProject(projectId);
})
.nodeify(callback);
}
|
javascript
|
function updateProjectHooks(projectId, hooks, callback) {
return self.projectCollection.findOne({_id: projectId})
.then(function (projectData) {
if (!projectData) {
throw new Error('no such project [' + projectId + ']');
}
// always update webhook information as a whole to allow remove and create and update as well
projectData.hooks = hooks;
return self.projectCollection.updateOne({_id: projectId}, projectData, {upsert: true});
})
.then(function () {
return getProject(projectId);
})
.nodeify(callback);
}
|
[
"function",
"updateProjectHooks",
"(",
"projectId",
",",
"hooks",
",",
"callback",
")",
"{",
"return",
"self",
".",
"projectCollection",
".",
"findOne",
"(",
"{",
"_id",
":",
"projectId",
"}",
")",
".",
"then",
"(",
"function",
"(",
"projectData",
")",
"{",
"if",
"(",
"!",
"projectData",
")",
"{",
"throw",
"new",
"Error",
"(",
"'no such project ['",
"+",
"projectId",
"+",
"']'",
")",
";",
"}",
"projectData",
".",
"hooks",
"=",
"hooks",
";",
"return",
"self",
".",
"projectCollection",
".",
"updateOne",
"(",
"{",
"_id",
":",
"projectId",
"}",
",",
"projectData",
",",
"{",
"upsert",
":",
"true",
"}",
")",
";",
"}",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"return",
"getProject",
"(",
"projectId",
")",
";",
"}",
")",
".",
"nodeify",
"(",
"callback",
")",
";",
"}"
] |
This method isn't safe and should only be used privately or for removing all hooks.
@param projectId
@param hooks
@param callback
@returns {*}
|
[
"This",
"method",
"isn",
"t",
"safe",
"and",
"should",
"only",
"be",
"used",
"privately",
"or",
"for",
"removing",
"all",
"hooks",
"."
] |
f9af95d7bedd83cdfde9cca9c8c2d560c0222065
|
https://github.com/webgme/webgme-engine/blob/f9af95d7bedd83cdfde9cca9c8c2d560c0222065/src/server/storage/metadatastorage.js#L242-L258
|
train
|
webgme/webgme-engine
|
utils/postinstall.js
|
resolveJSDocConfigPath
|
function resolveJSDocConfigPath() {
var jsdocConfJson = require('../jsdoc_conf.json'),
jsdocConfPath;
try {
fs.statSync(jsdocConfJson.opts.template);
console.log('jsdoc template from default config exists');
} catch (err) {
if (err.code === 'ENOENT') {
jsdocConfJson.opts.template = path.join(process.cwd(), '../ink-docstrap/template');
console.log('jsdoc template from default config did NOT exist! Testing alternative location',
jsdocConfJson.opts.template);
try {
fs.statSync(jsdocConfJson.opts.template);
jsdocConfPath = path.join(process.cwd(), 'jsdoc_alt_conf.json');
console.log('alternative location existed, generating alternative configuration', jsdocConfPath);
fs.writeFileSync(jsdocConfPath, JSON.stringify(jsdocConfJson), 'utf8');
} catch (err2) {
if (err.code === 'ENOENT') {
console.error('Will not generate source code documentation files!');
jsdocConfPath = false;
} else {
console.error(err);
}
}
} else {
console.error(err);
}
}
return jsdocConfPath;
}
|
javascript
|
function resolveJSDocConfigPath() {
var jsdocConfJson = require('../jsdoc_conf.json'),
jsdocConfPath;
try {
fs.statSync(jsdocConfJson.opts.template);
console.log('jsdoc template from default config exists');
} catch (err) {
if (err.code === 'ENOENT') {
jsdocConfJson.opts.template = path.join(process.cwd(), '../ink-docstrap/template');
console.log('jsdoc template from default config did NOT exist! Testing alternative location',
jsdocConfJson.opts.template);
try {
fs.statSync(jsdocConfJson.opts.template);
jsdocConfPath = path.join(process.cwd(), 'jsdoc_alt_conf.json');
console.log('alternative location existed, generating alternative configuration', jsdocConfPath);
fs.writeFileSync(jsdocConfPath, JSON.stringify(jsdocConfJson), 'utf8');
} catch (err2) {
if (err.code === 'ENOENT') {
console.error('Will not generate source code documentation files!');
jsdocConfPath = false;
} else {
console.error(err);
}
}
} else {
console.error(err);
}
}
return jsdocConfPath;
}
|
[
"function",
"resolveJSDocConfigPath",
"(",
")",
"{",
"var",
"jsdocConfJson",
"=",
"require",
"(",
"'../jsdoc_conf.json'",
")",
",",
"jsdocConfPath",
";",
"try",
"{",
"fs",
".",
"statSync",
"(",
"jsdocConfJson",
".",
"opts",
".",
"template",
")",
";",
"console",
".",
"log",
"(",
"'jsdoc template from default config exists'",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"if",
"(",
"err",
".",
"code",
"===",
"'ENOENT'",
")",
"{",
"jsdocConfJson",
".",
"opts",
".",
"template",
"=",
"path",
".",
"join",
"(",
"process",
".",
"cwd",
"(",
")",
",",
"'../ink-docstrap/template'",
")",
";",
"console",
".",
"log",
"(",
"'jsdoc template from default config did NOT exist! Testing alternative location'",
",",
"jsdocConfJson",
".",
"opts",
".",
"template",
")",
";",
"try",
"{",
"fs",
".",
"statSync",
"(",
"jsdocConfJson",
".",
"opts",
".",
"template",
")",
";",
"jsdocConfPath",
"=",
"path",
".",
"join",
"(",
"process",
".",
"cwd",
"(",
")",
",",
"'jsdoc_alt_conf.json'",
")",
";",
"console",
".",
"log",
"(",
"'alternative location existed, generating alternative configuration'",
",",
"jsdocConfPath",
")",
";",
"fs",
".",
"writeFileSync",
"(",
"jsdocConfPath",
",",
"JSON",
".",
"stringify",
"(",
"jsdocConfJson",
")",
",",
"'utf8'",
")",
";",
"}",
"catch",
"(",
"err2",
")",
"{",
"if",
"(",
"err",
".",
"code",
"===",
"'ENOENT'",
")",
"{",
"console",
".",
"error",
"(",
"'Will not generate source code documentation files!'",
")",
";",
"jsdocConfPath",
"=",
"false",
";",
"}",
"else",
"{",
"console",
".",
"error",
"(",
"err",
")",
";",
"}",
"}",
"}",
"else",
"{",
"console",
".",
"error",
"(",
"err",
")",
";",
"}",
"}",
"return",
"jsdocConfPath",
";",
"}"
] |
The path to the template in the jsdoc.json does not match for npm > 3 when webgme
is installed in another repo. I these cases we need to generate an alternative config
with the resolved path to the template.
@return {string} Path to jsdoc that should be used.
|
[
"The",
"path",
"to",
"the",
"template",
"in",
"the",
"jsdoc",
".",
"json",
"does",
"not",
"match",
"for",
"npm",
">",
"3",
"when",
"webgme",
"is",
"installed",
"in",
"another",
"repo",
".",
"I",
"these",
"cases",
"we",
"need",
"to",
"generate",
"an",
"alternative",
"config",
"with",
"the",
"resolved",
"path",
"to",
"the",
"template",
"."
] |
f9af95d7bedd83cdfde9cca9c8c2d560c0222065
|
https://github.com/webgme/webgme-engine/blob/f9af95d7bedd83cdfde9cca9c8c2d560c0222065/utils/postinstall.js#L49-L82
|
train
|
browserstack/browserstack-runner
|
lib/_patch/browserstack.js
|
function (url, json, cb) {
var req;
if (window.ActiveXObject)
req = new ActiveXObject('Microsoft.XMLHTTP');
else if (window.XMLHttpRequest)
req = new XMLHttpRequest();
else
throw "Strider: No ajax"
req.onreadystatechange = function () {
if (req.readyState==4)
cb(req.responseText);
};
var data;
if(window.CircularJSON) {
data = window.CircularJSON.stringify(json);
} else {
data = JSON.stringify(json);
}
req.open("POST", url, true);
req.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
req.setRequestHeader('X-Browser-String', BrowserStack.browser_string);
req.setRequestHeader('X-Worker-UUID', BrowserStack.worker_uuid);
req.setRequestHeader('Content-type', 'application/json');
req.send(data);
}
|
javascript
|
function (url, json, cb) {
var req;
if (window.ActiveXObject)
req = new ActiveXObject('Microsoft.XMLHTTP');
else if (window.XMLHttpRequest)
req = new XMLHttpRequest();
else
throw "Strider: No ajax"
req.onreadystatechange = function () {
if (req.readyState==4)
cb(req.responseText);
};
var data;
if(window.CircularJSON) {
data = window.CircularJSON.stringify(json);
} else {
data = JSON.stringify(json);
}
req.open("POST", url, true);
req.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
req.setRequestHeader('X-Browser-String', BrowserStack.browser_string);
req.setRequestHeader('X-Worker-UUID', BrowserStack.worker_uuid);
req.setRequestHeader('Content-type', 'application/json');
req.send(data);
}
|
[
"function",
"(",
"url",
",",
"json",
",",
"cb",
")",
"{",
"var",
"req",
";",
"if",
"(",
"window",
".",
"ActiveXObject",
")",
"req",
"=",
"new",
"ActiveXObject",
"(",
"'Microsoft.XMLHTTP'",
")",
";",
"else",
"if",
"(",
"window",
".",
"XMLHttpRequest",
")",
"req",
"=",
"new",
"XMLHttpRequest",
"(",
")",
";",
"else",
"throw",
"\"Strider: No ajax\"",
"req",
".",
"onreadystatechange",
"=",
"function",
"(",
")",
"{",
"if",
"(",
"req",
".",
"readyState",
"==",
"4",
")",
"cb",
"(",
"req",
".",
"responseText",
")",
";",
"}",
";",
"var",
"data",
";",
"if",
"(",
"window",
".",
"CircularJSON",
")",
"{",
"data",
"=",
"window",
".",
"CircularJSON",
".",
"stringify",
"(",
"json",
")",
";",
"}",
"else",
"{",
"data",
"=",
"JSON",
".",
"stringify",
"(",
"json",
")",
";",
"}",
"req",
".",
"open",
"(",
"\"POST\"",
",",
"url",
",",
"true",
")",
";",
"req",
".",
"setRequestHeader",
"(",
"'X-Requested-With'",
",",
"'XMLHttpRequest'",
")",
";",
"req",
".",
"setRequestHeader",
"(",
"'X-Browser-String'",
",",
"BrowserStack",
".",
"browser_string",
")",
";",
"req",
".",
"setRequestHeader",
"(",
"'X-Worker-UUID'",
",",
"BrowserStack",
".",
"worker_uuid",
")",
";",
"req",
".",
"setRequestHeader",
"(",
"'Content-type'",
",",
"'application/json'",
")",
";",
"req",
".",
"send",
"(",
"data",
")",
";",
"}"
] |
Tiny Ajax Post
|
[
"Tiny",
"Ajax",
"Post"
] |
52b23f060a19c3a5d9d31db4b0cfa65334d926cc
|
https://github.com/browserstack/browserstack-runner/blob/52b23f060a19c3a5d9d31db4b0cfa65334d926cc/lib/_patch/browserstack.js#L12-L38
|
train
|
|
browserstack/browserstack-runner
|
lib/_patch/jasmine-jsreporter.js
|
round
|
function round (amount, numOfDecDigits) {
numOfDecDigits = numOfDecDigits || 2;
return Math.round(amount * Math.pow(10, numOfDecDigits)) / Math.pow(10, numOfDecDigits);
}
|
javascript
|
function round (amount, numOfDecDigits) {
numOfDecDigits = numOfDecDigits || 2;
return Math.round(amount * Math.pow(10, numOfDecDigits)) / Math.pow(10, numOfDecDigits);
}
|
[
"function",
"round",
"(",
"amount",
",",
"numOfDecDigits",
")",
"{",
"numOfDecDigits",
"=",
"numOfDecDigits",
"||",
"2",
";",
"return",
"Math",
".",
"round",
"(",
"amount",
"*",
"Math",
".",
"pow",
"(",
"10",
",",
"numOfDecDigits",
")",
")",
"/",
"Math",
".",
"pow",
"(",
"10",
",",
"numOfDecDigits",
")",
";",
"}"
] |
Round an amount to the given number of Digits.
If no number of digits is given, than '2' is assumed.
@param amount Amount to round
@param numOfDecDigits Number of Digits to round to. Default value is '2'.
@return Rounded amount
|
[
"Round",
"an",
"amount",
"to",
"the",
"given",
"number",
"of",
"Digits",
".",
"If",
"no",
"number",
"of",
"digits",
"is",
"given",
"than",
"2",
"is",
"assumed",
"."
] |
52b23f060a19c3a5d9d31db4b0cfa65334d926cc
|
https://github.com/browserstack/browserstack-runner/blob/52b23f060a19c3a5d9d31db4b0cfa65334d926cc/lib/_patch/jasmine-jsreporter.js#L51-L54
|
train
|
browserstack/browserstack-runner
|
lib/_patch/jasmine-jsreporter.js
|
getSuiteData
|
function getSuiteData (suite) {
var suiteData = {
description : suite.description,
durationSec : 0,
specs: [],
suites: [],
passed: true
},
specs = suite.specs(),
suites = suite.suites(),
i, ilen;
// Loop over all the Suite's Specs
for (i = 0, ilen = specs.length; i < ilen; ++i) {
suiteData.specs[i] = {
description : specs[i].description,
durationSec : specs[i].durationSec,
passed : specs[i].results().passedCount === specs[i].results().totalCount,
results : specs[i].results()
};
suiteData.passed = !suiteData.specs[i].passed ? false : suiteData.passed;
suiteData.durationSec += suiteData.specs[i].durationSec;
}
// Loop over all the Suite's sub-Suites
for (i = 0, ilen = suites.length; i < ilen; ++i) {
suiteData.suites[i] = getSuiteData(suites[i]); //< recursive population
suiteData.passed = !suiteData.suites[i].passed ? false : suiteData.passed;
suiteData.durationSec += suiteData.suites[i].durationSec;
}
// Rounding duration numbers to 3 decimal digits
suiteData.durationSec = round(suiteData.durationSec, 4);
return suiteData;
}
|
javascript
|
function getSuiteData (suite) {
var suiteData = {
description : suite.description,
durationSec : 0,
specs: [],
suites: [],
passed: true
},
specs = suite.specs(),
suites = suite.suites(),
i, ilen;
// Loop over all the Suite's Specs
for (i = 0, ilen = specs.length; i < ilen; ++i) {
suiteData.specs[i] = {
description : specs[i].description,
durationSec : specs[i].durationSec,
passed : specs[i].results().passedCount === specs[i].results().totalCount,
results : specs[i].results()
};
suiteData.passed = !suiteData.specs[i].passed ? false : suiteData.passed;
suiteData.durationSec += suiteData.specs[i].durationSec;
}
// Loop over all the Suite's sub-Suites
for (i = 0, ilen = suites.length; i < ilen; ++i) {
suiteData.suites[i] = getSuiteData(suites[i]); //< recursive population
suiteData.passed = !suiteData.suites[i].passed ? false : suiteData.passed;
suiteData.durationSec += suiteData.suites[i].durationSec;
}
// Rounding duration numbers to 3 decimal digits
suiteData.durationSec = round(suiteData.durationSec, 4);
return suiteData;
}
|
[
"function",
"getSuiteData",
"(",
"suite",
")",
"{",
"var",
"suiteData",
"=",
"{",
"description",
":",
"suite",
".",
"description",
",",
"durationSec",
":",
"0",
",",
"specs",
":",
"[",
"]",
",",
"suites",
":",
"[",
"]",
",",
"passed",
":",
"true",
"}",
",",
"specs",
"=",
"suite",
".",
"specs",
"(",
")",
",",
"suites",
"=",
"suite",
".",
"suites",
"(",
")",
",",
"i",
",",
"ilen",
";",
"for",
"(",
"i",
"=",
"0",
",",
"ilen",
"=",
"specs",
".",
"length",
";",
"i",
"<",
"ilen",
";",
"++",
"i",
")",
"{",
"suiteData",
".",
"specs",
"[",
"i",
"]",
"=",
"{",
"description",
":",
"specs",
"[",
"i",
"]",
".",
"description",
",",
"durationSec",
":",
"specs",
"[",
"i",
"]",
".",
"durationSec",
",",
"passed",
":",
"specs",
"[",
"i",
"]",
".",
"results",
"(",
")",
".",
"passedCount",
"===",
"specs",
"[",
"i",
"]",
".",
"results",
"(",
")",
".",
"totalCount",
",",
"results",
":",
"specs",
"[",
"i",
"]",
".",
"results",
"(",
")",
"}",
";",
"suiteData",
".",
"passed",
"=",
"!",
"suiteData",
".",
"specs",
"[",
"i",
"]",
".",
"passed",
"?",
"false",
":",
"suiteData",
".",
"passed",
";",
"suiteData",
".",
"durationSec",
"+=",
"suiteData",
".",
"specs",
"[",
"i",
"]",
".",
"durationSec",
";",
"}",
"for",
"(",
"i",
"=",
"0",
",",
"ilen",
"=",
"suites",
".",
"length",
";",
"i",
"<",
"ilen",
";",
"++",
"i",
")",
"{",
"suiteData",
".",
"suites",
"[",
"i",
"]",
"=",
"getSuiteData",
"(",
"suites",
"[",
"i",
"]",
")",
";",
"suiteData",
".",
"passed",
"=",
"!",
"suiteData",
".",
"suites",
"[",
"i",
"]",
".",
"passed",
"?",
"false",
":",
"suiteData",
".",
"passed",
";",
"suiteData",
".",
"durationSec",
"+=",
"suiteData",
".",
"suites",
"[",
"i",
"]",
".",
"durationSec",
";",
"}",
"suiteData",
".",
"durationSec",
"=",
"round",
"(",
"suiteData",
".",
"durationSec",
",",
"4",
")",
";",
"return",
"suiteData",
";",
"}"
] |
Collect information about a Suite, recursively, and return a JSON result.
@param suite The Jasmine Suite to get data from
|
[
"Collect",
"information",
"about",
"a",
"Suite",
"recursively",
"and",
"return",
"a",
"JSON",
"result",
"."
] |
52b23f060a19c3a5d9d31db4b0cfa65334d926cc
|
https://github.com/browserstack/browserstack-runner/blob/52b23f060a19c3a5d9d31db4b0cfa65334d926cc/lib/_patch/jasmine-jsreporter.js#L60-L95
|
train
|
angular-translate/grunt-angular-translate
|
tasks/angular-translate.js
|
function (translationKey, translationDefaultValue) {
if (regexName !== "JavascriptServiceArraySimpleQuote" &&
regexName !== "JavascriptServiceArrayDoubleQuote") {
if (keyAsText === true && translationDefaultValue.length === 0) {
results[translationKey] = translationKey;
} else {
results[translationKey] = translationDefaultValue;
}
}
}
|
javascript
|
function (translationKey, translationDefaultValue) {
if (regexName !== "JavascriptServiceArraySimpleQuote" &&
regexName !== "JavascriptServiceArrayDoubleQuote") {
if (keyAsText === true && translationDefaultValue.length === 0) {
results[translationKey] = translationKey;
} else {
results[translationKey] = translationDefaultValue;
}
}
}
|
[
"function",
"(",
"translationKey",
",",
"translationDefaultValue",
")",
"{",
"if",
"(",
"regexName",
"!==",
"\"JavascriptServiceArraySimpleQuote\"",
"&&",
"regexName",
"!==",
"\"JavascriptServiceArrayDoubleQuote\"",
")",
"{",
"if",
"(",
"keyAsText",
"===",
"true",
"&&",
"translationDefaultValue",
".",
"length",
"===",
"0",
")",
"{",
"results",
"[",
"translationKey",
"]",
"=",
"translationKey",
";",
"}",
"else",
"{",
"results",
"[",
"translationKey",
"]",
"=",
"translationDefaultValue",
";",
"}",
"}",
"}"
] |
Store the translationKey with the value into results
|
[
"Store",
"the",
"translationKey",
"with",
"the",
"value",
"into",
"results"
] |
a3988c3850a3970a048c1a0a1ae5d2d14f0793f7
|
https://github.com/angular-translate/grunt-angular-translate/blob/a3988c3850a3970a048c1a0a1ae5d2d14f0793f7/tasks/angular-translate.js#L140-L149
|
train
|
|
phonegap/connect-phonegap
|
res/middleware/cordova/3.4.0/android/plugins/org.apache.cordova.device-orientation/www/compass.js
|
function(successCallback, errorCallback, options) {
argscheck.checkArgs('fFO', 'compass.getCurrentHeading', arguments);
var win = function(result) {
var ch = new CompassHeading(result.magneticHeading, result.trueHeading, result.headingAccuracy, result.timestamp);
successCallback(ch);
};
var fail = errorCallback && function(code) {
var ce = new CompassError(code);
errorCallback(ce);
};
// Get heading
exec(win, fail, "Compass", "getHeading", [options]);
}
|
javascript
|
function(successCallback, errorCallback, options) {
argscheck.checkArgs('fFO', 'compass.getCurrentHeading', arguments);
var win = function(result) {
var ch = new CompassHeading(result.magneticHeading, result.trueHeading, result.headingAccuracy, result.timestamp);
successCallback(ch);
};
var fail = errorCallback && function(code) {
var ce = new CompassError(code);
errorCallback(ce);
};
// Get heading
exec(win, fail, "Compass", "getHeading", [options]);
}
|
[
"function",
"(",
"successCallback",
",",
"errorCallback",
",",
"options",
")",
"{",
"argscheck",
".",
"checkArgs",
"(",
"'fFO'",
",",
"'compass.getCurrentHeading'",
",",
"arguments",
")",
";",
"var",
"win",
"=",
"function",
"(",
"result",
")",
"{",
"var",
"ch",
"=",
"new",
"CompassHeading",
"(",
"result",
".",
"magneticHeading",
",",
"result",
".",
"trueHeading",
",",
"result",
".",
"headingAccuracy",
",",
"result",
".",
"timestamp",
")",
";",
"successCallback",
"(",
"ch",
")",
";",
"}",
";",
"var",
"fail",
"=",
"errorCallback",
"&&",
"function",
"(",
"code",
")",
"{",
"var",
"ce",
"=",
"new",
"CompassError",
"(",
"code",
")",
";",
"errorCallback",
"(",
"ce",
")",
";",
"}",
";",
"exec",
"(",
"win",
",",
"fail",
",",
"\"Compass\"",
",",
"\"getHeading\"",
",",
"[",
"options",
"]",
")",
";",
"}"
] |
Asynchronously acquires the current heading.
@param {Function} successCallback The function to call when the heading
data is available
@param {Function} errorCallback The function to call when there is an error
getting the heading data.
@param {CompassOptions} options The options for getting the heading data (not used).
|
[
"Asynchronously",
"acquires",
"the",
"current",
"heading",
"."
] |
720ed8c8341a67a7a622aaeb83e153883f3fcb2c
|
https://github.com/phonegap/connect-phonegap/blob/720ed8c8341a67a7a622aaeb83e153883f3fcb2c/res/middleware/cordova/3.4.0/android/plugins/org.apache.cordova.device-orientation/www/compass.js#L38-L52
|
train
|
|
phonegap/connect-phonegap
|
res/middleware/cordova/3.4.0/android/plugins/org.apache.cordova.device-orientation/www/compass.js
|
function(successCallback, errorCallback, options) {
argscheck.checkArgs('fFO', 'compass.watchHeading', arguments);
// Default interval (100 msec)
var frequency = (options !== undefined && options.frequency !== undefined) ? options.frequency : 100;
var filter = (options !== undefined && options.filter !== undefined) ? options.filter : 0;
var id = utils.createUUID();
if (filter > 0) {
// is an iOS request for watch by filter, no timer needed
timers[id] = "iOS";
compass.getCurrentHeading(successCallback, errorCallback, options);
} else {
// Start watch timer to get headings
timers[id] = window.setInterval(function() {
compass.getCurrentHeading(successCallback, errorCallback);
}, frequency);
}
return id;
}
|
javascript
|
function(successCallback, errorCallback, options) {
argscheck.checkArgs('fFO', 'compass.watchHeading', arguments);
// Default interval (100 msec)
var frequency = (options !== undefined && options.frequency !== undefined) ? options.frequency : 100;
var filter = (options !== undefined && options.filter !== undefined) ? options.filter : 0;
var id = utils.createUUID();
if (filter > 0) {
// is an iOS request for watch by filter, no timer needed
timers[id] = "iOS";
compass.getCurrentHeading(successCallback, errorCallback, options);
} else {
// Start watch timer to get headings
timers[id] = window.setInterval(function() {
compass.getCurrentHeading(successCallback, errorCallback);
}, frequency);
}
return id;
}
|
[
"function",
"(",
"successCallback",
",",
"errorCallback",
",",
"options",
")",
"{",
"argscheck",
".",
"checkArgs",
"(",
"'fFO'",
",",
"'compass.watchHeading'",
",",
"arguments",
")",
";",
"var",
"frequency",
"=",
"(",
"options",
"!==",
"undefined",
"&&",
"options",
".",
"frequency",
"!==",
"undefined",
")",
"?",
"options",
".",
"frequency",
":",
"100",
";",
"var",
"filter",
"=",
"(",
"options",
"!==",
"undefined",
"&&",
"options",
".",
"filter",
"!==",
"undefined",
")",
"?",
"options",
".",
"filter",
":",
"0",
";",
"var",
"id",
"=",
"utils",
".",
"createUUID",
"(",
")",
";",
"if",
"(",
"filter",
">",
"0",
")",
"{",
"timers",
"[",
"id",
"]",
"=",
"\"iOS\"",
";",
"compass",
".",
"getCurrentHeading",
"(",
"successCallback",
",",
"errorCallback",
",",
"options",
")",
";",
"}",
"else",
"{",
"timers",
"[",
"id",
"]",
"=",
"window",
".",
"setInterval",
"(",
"function",
"(",
")",
"{",
"compass",
".",
"getCurrentHeading",
"(",
"successCallback",
",",
"errorCallback",
")",
";",
"}",
",",
"frequency",
")",
";",
"}",
"return",
"id",
";",
"}"
] |
Asynchronously acquires the heading repeatedly at a given interval.
@param {Function} successCallback The function to call each time the heading
data is available
@param {Function} errorCallback The function to call when there is an error
getting the heading data.
@param {HeadingOptions} options The options for getting the heading data
such as timeout and the frequency of the watch. For iOS, filter parameter
specifies to watch via a distance filter rather than time.
|
[
"Asynchronously",
"acquires",
"the",
"heading",
"repeatedly",
"at",
"a",
"given",
"interval",
"."
] |
720ed8c8341a67a7a622aaeb83e153883f3fcb2c
|
https://github.com/phonegap/connect-phonegap/blob/720ed8c8341a67a7a622aaeb83e153883f3fcb2c/res/middleware/cordova/3.4.0/android/plugins/org.apache.cordova.device-orientation/www/compass.js#L64-L83
|
train
|
|
phonegap/connect-phonegap
|
res/middleware/cordova/3.4.0/android/plugins/org.apache.cordova.contacts/www/Contact.js
|
convertOut
|
function convertOut(contact) {
var value = contact.birthday;
if (value !== null) {
// try to make it a Date object if it is not already
if (!utils.isDate(value)){
try {
value = new Date(value);
} catch(exception){
value = null;
}
}
if (utils.isDate(value)){
value = value.valueOf(); // convert to milliseconds
}
contact.birthday = value;
}
return contact;
}
|
javascript
|
function convertOut(contact) {
var value = contact.birthday;
if (value !== null) {
// try to make it a Date object if it is not already
if (!utils.isDate(value)){
try {
value = new Date(value);
} catch(exception){
value = null;
}
}
if (utils.isDate(value)){
value = value.valueOf(); // convert to milliseconds
}
contact.birthday = value;
}
return contact;
}
|
[
"function",
"convertOut",
"(",
"contact",
")",
"{",
"var",
"value",
"=",
"contact",
".",
"birthday",
";",
"if",
"(",
"value",
"!==",
"null",
")",
"{",
"if",
"(",
"!",
"utils",
".",
"isDate",
"(",
"value",
")",
")",
"{",
"try",
"{",
"value",
"=",
"new",
"Date",
"(",
"value",
")",
";",
"}",
"catch",
"(",
"exception",
")",
"{",
"value",
"=",
"null",
";",
"}",
"}",
"if",
"(",
"utils",
".",
"isDate",
"(",
"value",
")",
")",
"{",
"value",
"=",
"value",
".",
"valueOf",
"(",
")",
";",
"}",
"contact",
".",
"birthday",
"=",
"value",
";",
"}",
"return",
"contact",
";",
"}"
] |
Converts Complex objects into primitives
Only conversion at present is for Dates.
|
[
"Converts",
"Complex",
"objects",
"into",
"primitives",
"Only",
"conversion",
"at",
"present",
"is",
"for",
"Dates",
"."
] |
720ed8c8341a67a7a622aaeb83e153883f3fcb2c
|
https://github.com/phonegap/connect-phonegap/blob/720ed8c8341a67a7a622aaeb83e153883f3fcb2c/res/middleware/cordova/3.4.0/android/plugins/org.apache.cordova.contacts/www/Contact.js#L46-L63
|
train
|
phonegap/connect-phonegap
|
res/middleware/cordova/3.4.0/android/plugins/org.apache.cordova.contacts/www/Contact.js
|
function (id, displayName, name, nickname, phoneNumbers, emails, addresses,
ims, organizations, birthday, note, photos, categories, urls) {
this.id = id || null;
this.rawId = null;
this.displayName = displayName || null;
this.name = name || null; // ContactName
this.nickname = nickname || null;
this.phoneNumbers = phoneNumbers || null; // ContactField[]
this.emails = emails || null; // ContactField[]
this.addresses = addresses || null; // ContactAddress[]
this.ims = ims || null; // ContactField[]
this.organizations = organizations || null; // ContactOrganization[]
this.birthday = birthday || null;
this.note = note || null;
this.photos = photos || null; // ContactField[]
this.categories = categories || null; // ContactField[]
this.urls = urls || null; // ContactField[]
}
|
javascript
|
function (id, displayName, name, nickname, phoneNumbers, emails, addresses,
ims, organizations, birthday, note, photos, categories, urls) {
this.id = id || null;
this.rawId = null;
this.displayName = displayName || null;
this.name = name || null; // ContactName
this.nickname = nickname || null;
this.phoneNumbers = phoneNumbers || null; // ContactField[]
this.emails = emails || null; // ContactField[]
this.addresses = addresses || null; // ContactAddress[]
this.ims = ims || null; // ContactField[]
this.organizations = organizations || null; // ContactOrganization[]
this.birthday = birthday || null;
this.note = note || null;
this.photos = photos || null; // ContactField[]
this.categories = categories || null; // ContactField[]
this.urls = urls || null; // ContactField[]
}
|
[
"function",
"(",
"id",
",",
"displayName",
",",
"name",
",",
"nickname",
",",
"phoneNumbers",
",",
"emails",
",",
"addresses",
",",
"ims",
",",
"organizations",
",",
"birthday",
",",
"note",
",",
"photos",
",",
"categories",
",",
"urls",
")",
"{",
"this",
".",
"id",
"=",
"id",
"||",
"null",
";",
"this",
".",
"rawId",
"=",
"null",
";",
"this",
".",
"displayName",
"=",
"displayName",
"||",
"null",
";",
"this",
".",
"name",
"=",
"name",
"||",
"null",
";",
"this",
".",
"nickname",
"=",
"nickname",
"||",
"null",
";",
"this",
".",
"phoneNumbers",
"=",
"phoneNumbers",
"||",
"null",
";",
"this",
".",
"emails",
"=",
"emails",
"||",
"null",
";",
"this",
".",
"addresses",
"=",
"addresses",
"||",
"null",
";",
"this",
".",
"ims",
"=",
"ims",
"||",
"null",
";",
"this",
".",
"organizations",
"=",
"organizations",
"||",
"null",
";",
"this",
".",
"birthday",
"=",
"birthday",
"||",
"null",
";",
"this",
".",
"note",
"=",
"note",
"||",
"null",
";",
"this",
".",
"photos",
"=",
"photos",
"||",
"null",
";",
"this",
".",
"categories",
"=",
"categories",
"||",
"null",
";",
"this",
".",
"urls",
"=",
"urls",
"||",
"null",
";",
"}"
] |
Contains information about a single contact.
@constructor
@param {DOMString} id unique identifier
@param {DOMString} displayName
@param {ContactName} name
@param {DOMString} nickname
@param {Array.<ContactField>} phoneNumbers array of phone numbers
@param {Array.<ContactField>} emails array of email addresses
@param {Array.<ContactAddress>} addresses array of addresses
@param {Array.<ContactField>} ims instant messaging user ids
@param {Array.<ContactOrganization>} organizations
@param {DOMString} birthday contact's birthday
@param {DOMString} note user notes about contact
@param {Array.<ContactField>} photos
@param {Array.<ContactField>} categories
@param {Array.<ContactField>} urls contact's web sites
|
[
"Contains",
"information",
"about",
"a",
"single",
"contact",
"."
] |
720ed8c8341a67a7a622aaeb83e153883f3fcb2c
|
https://github.com/phonegap/connect-phonegap/blob/720ed8c8341a67a7a622aaeb83e153883f3fcb2c/res/middleware/cordova/3.4.0/android/plugins/org.apache.cordova.contacts/www/Contact.js#L83-L100
|
train
|
|
phonegap/connect-phonegap
|
res/middleware/cordova/3.4.0/android/plugins/org.apache.cordova.file/www/Entry.js
|
Entry
|
function Entry(isFile, isDirectory, name, fullPath, fileSystem) {
this.isFile = !!isFile;
this.isDirectory = !!isDirectory;
this.name = name || '';
this.fullPath = fullPath || '';
this.filesystem = fileSystem || null;
}
|
javascript
|
function Entry(isFile, isDirectory, name, fullPath, fileSystem) {
this.isFile = !!isFile;
this.isDirectory = !!isDirectory;
this.name = name || '';
this.fullPath = fullPath || '';
this.filesystem = fileSystem || null;
}
|
[
"function",
"Entry",
"(",
"isFile",
",",
"isDirectory",
",",
"name",
",",
"fullPath",
",",
"fileSystem",
")",
"{",
"this",
".",
"isFile",
"=",
"!",
"!",
"isFile",
";",
"this",
".",
"isDirectory",
"=",
"!",
"!",
"isDirectory",
";",
"this",
".",
"name",
"=",
"name",
"||",
"''",
";",
"this",
".",
"fullPath",
"=",
"fullPath",
"||",
"''",
";",
"this",
".",
"filesystem",
"=",
"fileSystem",
"||",
"null",
";",
"}"
] |
Represents a file or directory on the local file system.
@param isFile
{boolean} true if Entry is a file (readonly)
@param isDirectory
{boolean} true if Entry is a directory (readonly)
@param name
{DOMString} name of the file or directory, excluding the path
leading to it (readonly)
@param fullPath
{DOMString} the absolute full path to the file or directory
(readonly)
@param fileSystem
{FileSystem} the filesystem on which this entry resides
(readonly)
|
[
"Represents",
"a",
"file",
"or",
"directory",
"on",
"the",
"local",
"file",
"system",
"."
] |
720ed8c8341a67a7a622aaeb83e153883f3fcb2c
|
https://github.com/phonegap/connect-phonegap/blob/720ed8c8341a67a7a622aaeb83e153883f3fcb2c/res/middleware/cordova/3.4.0/android/plugins/org.apache.cordova.file/www/Entry.js#L44-L50
|
train
|
phonegap/connect-phonegap
|
res/middleware/cordova/3.4.0/android/plugins/org.apache.cordova.geolocation/www/geolocation.js
|
parseParameters
|
function parseParameters(options) {
var opt = {
maximumAge: 0,
enableHighAccuracy: false,
timeout: Infinity
};
if (options) {
if (options.maximumAge !== undefined && !isNaN(options.maximumAge) && options.maximumAge > 0) {
opt.maximumAge = options.maximumAge;
}
if (options.enableHighAccuracy !== undefined) {
opt.enableHighAccuracy = options.enableHighAccuracy;
}
if (options.timeout !== undefined && !isNaN(options.timeout)) {
if (options.timeout < 0) {
opt.timeout = 0;
} else {
opt.timeout = options.timeout;
}
}
}
return opt;
}
|
javascript
|
function parseParameters(options) {
var opt = {
maximumAge: 0,
enableHighAccuracy: false,
timeout: Infinity
};
if (options) {
if (options.maximumAge !== undefined && !isNaN(options.maximumAge) && options.maximumAge > 0) {
opt.maximumAge = options.maximumAge;
}
if (options.enableHighAccuracy !== undefined) {
opt.enableHighAccuracy = options.enableHighAccuracy;
}
if (options.timeout !== undefined && !isNaN(options.timeout)) {
if (options.timeout < 0) {
opt.timeout = 0;
} else {
opt.timeout = options.timeout;
}
}
}
return opt;
}
|
[
"function",
"parseParameters",
"(",
"options",
")",
"{",
"var",
"opt",
"=",
"{",
"maximumAge",
":",
"0",
",",
"enableHighAccuracy",
":",
"false",
",",
"timeout",
":",
"Infinity",
"}",
";",
"if",
"(",
"options",
")",
"{",
"if",
"(",
"options",
".",
"maximumAge",
"!==",
"undefined",
"&&",
"!",
"isNaN",
"(",
"options",
".",
"maximumAge",
")",
"&&",
"options",
".",
"maximumAge",
">",
"0",
")",
"{",
"opt",
".",
"maximumAge",
"=",
"options",
".",
"maximumAge",
";",
"}",
"if",
"(",
"options",
".",
"enableHighAccuracy",
"!==",
"undefined",
")",
"{",
"opt",
".",
"enableHighAccuracy",
"=",
"options",
".",
"enableHighAccuracy",
";",
"}",
"if",
"(",
"options",
".",
"timeout",
"!==",
"undefined",
"&&",
"!",
"isNaN",
"(",
"options",
".",
"timeout",
")",
")",
"{",
"if",
"(",
"options",
".",
"timeout",
"<",
"0",
")",
"{",
"opt",
".",
"timeout",
"=",
"0",
";",
"}",
"else",
"{",
"opt",
".",
"timeout",
"=",
"options",
".",
"timeout",
";",
"}",
"}",
"}",
"return",
"opt",
";",
"}"
] |
list of timers in use Returns default params, overrides if provided with values
|
[
"list",
"of",
"timers",
"in",
"use",
"Returns",
"default",
"params",
"overrides",
"if",
"provided",
"with",
"values"
] |
720ed8c8341a67a7a622aaeb83e153883f3fcb2c
|
https://github.com/phonegap/connect-phonegap/blob/720ed8c8341a67a7a622aaeb83e153883f3fcb2c/res/middleware/cordova/3.4.0/android/plugins/org.apache.cordova.geolocation/www/geolocation.js#L31-L55
|
train
|
phonegap/connect-phonegap
|
res/middleware/cordova/3.4.0/android/plugins/org.apache.cordova.geolocation/www/geolocation.js
|
createTimeout
|
function createTimeout(errorCallback, timeout) {
var t = setTimeout(function() {
clearTimeout(t);
t = null;
errorCallback({
code:PositionError.TIMEOUT,
message:"Position retrieval timed out."
});
}, timeout);
return t;
}
|
javascript
|
function createTimeout(errorCallback, timeout) {
var t = setTimeout(function() {
clearTimeout(t);
t = null;
errorCallback({
code:PositionError.TIMEOUT,
message:"Position retrieval timed out."
});
}, timeout);
return t;
}
|
[
"function",
"createTimeout",
"(",
"errorCallback",
",",
"timeout",
")",
"{",
"var",
"t",
"=",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"clearTimeout",
"(",
"t",
")",
";",
"t",
"=",
"null",
";",
"errorCallback",
"(",
"{",
"code",
":",
"PositionError",
".",
"TIMEOUT",
",",
"message",
":",
"\"Position retrieval timed out.\"",
"}",
")",
";",
"}",
",",
"timeout",
")",
";",
"return",
"t",
";",
"}"
] |
Returns a timeout failure, closed over a specified timeout value and error callback.
|
[
"Returns",
"a",
"timeout",
"failure",
"closed",
"over",
"a",
"specified",
"timeout",
"value",
"and",
"error",
"callback",
"."
] |
720ed8c8341a67a7a622aaeb83e153883f3fcb2c
|
https://github.com/phonegap/connect-phonegap/blob/720ed8c8341a67a7a622aaeb83e153883f3fcb2c/res/middleware/cordova/3.4.0/android/plugins/org.apache.cordova.geolocation/www/geolocation.js#L58-L68
|
train
|
phonegap/connect-phonegap
|
res/middleware/cordova/3.4.0/android/plugins/org.apache.cordova.contacts/www/contacts.js
|
function(fields, successCB, errorCB, options) {
argscheck.checkArgs('afFO', 'contacts.find', arguments);
if (!fields.length) {
errorCB && errorCB(new ContactError(ContactError.INVALID_ARGUMENT_ERROR));
} else {
var win = function(result) {
var cs = [];
for (var i = 0, l = result.length; i < l; i++) {
cs.push(contacts.create(result[i]));
}
successCB(cs);
};
exec(win, errorCB, "Contacts", "search", [fields, options]);
}
}
|
javascript
|
function(fields, successCB, errorCB, options) {
argscheck.checkArgs('afFO', 'contacts.find', arguments);
if (!fields.length) {
errorCB && errorCB(new ContactError(ContactError.INVALID_ARGUMENT_ERROR));
} else {
var win = function(result) {
var cs = [];
for (var i = 0, l = result.length; i < l; i++) {
cs.push(contacts.create(result[i]));
}
successCB(cs);
};
exec(win, errorCB, "Contacts", "search", [fields, options]);
}
}
|
[
"function",
"(",
"fields",
",",
"successCB",
",",
"errorCB",
",",
"options",
")",
"{",
"argscheck",
".",
"checkArgs",
"(",
"'afFO'",
",",
"'contacts.find'",
",",
"arguments",
")",
";",
"if",
"(",
"!",
"fields",
".",
"length",
")",
"{",
"errorCB",
"&&",
"errorCB",
"(",
"new",
"ContactError",
"(",
"ContactError",
".",
"INVALID_ARGUMENT_ERROR",
")",
")",
";",
"}",
"else",
"{",
"var",
"win",
"=",
"function",
"(",
"result",
")",
"{",
"var",
"cs",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"l",
"=",
"result",
".",
"length",
";",
"i",
"<",
"l",
";",
"i",
"++",
")",
"{",
"cs",
".",
"push",
"(",
"contacts",
".",
"create",
"(",
"result",
"[",
"i",
"]",
")",
")",
";",
"}",
"successCB",
"(",
"cs",
")",
";",
"}",
";",
"exec",
"(",
"win",
",",
"errorCB",
",",
"\"Contacts\"",
",",
"\"search\"",
",",
"[",
"fields",
",",
"options",
"]",
")",
";",
"}",
"}"
] |
Returns an array of Contacts matching the search criteria.
@param fields that should be searched
@param successCB success callback
@param errorCB error callback
@param {ContactFindOptions} options that can be applied to contact searching
@return array of Contacts matching search criteria
|
[
"Returns",
"an",
"array",
"of",
"Contacts",
"matching",
"the",
"search",
"criteria",
"."
] |
720ed8c8341a67a7a622aaeb83e153883f3fcb2c
|
https://github.com/phonegap/connect-phonegap/blob/720ed8c8341a67a7a622aaeb83e153883f3fcb2c/res/middleware/cordova/3.4.0/android/plugins/org.apache.cordova.contacts/www/contacts.js#L41-L55
|
train
|
|
phonegap/connect-phonegap
|
res/middleware/cordova/3.4.0/android/plugins/org.apache.cordova.file/www/DirectoryEntry.js
|
function(name, fullPath, fileSystem) {
DirectoryEntry.__super__.constructor.call(this, false, true, name, fullPath, fileSystem);
}
|
javascript
|
function(name, fullPath, fileSystem) {
DirectoryEntry.__super__.constructor.call(this, false, true, name, fullPath, fileSystem);
}
|
[
"function",
"(",
"name",
",",
"fullPath",
",",
"fileSystem",
")",
"{",
"DirectoryEntry",
".",
"__super__",
".",
"constructor",
".",
"call",
"(",
"this",
",",
"false",
",",
"true",
",",
"name",
",",
"fullPath",
",",
"fileSystem",
")",
";",
"}"
] |
An interface representing a directory on the file system.
{boolean} isFile always false (readonly)
{boolean} isDirectory always true (readonly)
{DOMString} name of the directory, excluding the path leading to it (readonly)
{DOMString} fullPath the absolute full path to the directory (readonly)
{FileSystem} filesystem on which the directory resides (readonly)
|
[
"An",
"interface",
"representing",
"a",
"directory",
"on",
"the",
"file",
"system",
"."
] |
720ed8c8341a67a7a622aaeb83e153883f3fcb2c
|
https://github.com/phonegap/connect-phonegap/blob/720ed8c8341a67a7a622aaeb83e153883f3fcb2c/res/middleware/cordova/3.4.0/android/plugins/org.apache.cordova.file/www/DirectoryEntry.js#L38-L40
|
train
|
|
jasongin/noble-uwp
|
lib/rt-utils.js
|
using
|
function using(ns) {
let nsParts = ns.split('.');
let parentObj = global;
// Build an object tree as necessary for the namespace hierarchy.
for (let i = 0; i < nsParts.length - 1; i++) {
let nsObj = parentObj[nsParts[i]];
if (!nsObj) {
nsObj = {};
parentObj[nsParts[i]] = nsObj;
}
parentObj = nsObj;
}
let lastNsPart = nsParts[nsParts.length - 1];
let nsPackage = require(uwpRoot + ns.toLowerCase());
// Merge in any already-loaded sub-namespaces.
// This allows loading in non-hierarchical order.
let nsObj = parentObj[lastNsPart];
if (nsObj) {
Object.keys(nsObj).forEach(key => {
nsPackage[key] = nsObj[key];
})
}
parentObj[lastNsPart] = nsPackage;
}
|
javascript
|
function using(ns) {
let nsParts = ns.split('.');
let parentObj = global;
// Build an object tree as necessary for the namespace hierarchy.
for (let i = 0; i < nsParts.length - 1; i++) {
let nsObj = parentObj[nsParts[i]];
if (!nsObj) {
nsObj = {};
parentObj[nsParts[i]] = nsObj;
}
parentObj = nsObj;
}
let lastNsPart = nsParts[nsParts.length - 1];
let nsPackage = require(uwpRoot + ns.toLowerCase());
// Merge in any already-loaded sub-namespaces.
// This allows loading in non-hierarchical order.
let nsObj = parentObj[lastNsPart];
if (nsObj) {
Object.keys(nsObj).forEach(key => {
nsPackage[key] = nsObj[key];
})
}
parentObj[lastNsPart] = nsPackage;
}
|
[
"function",
"using",
"(",
"ns",
")",
"{",
"let",
"nsParts",
"=",
"ns",
".",
"split",
"(",
"'.'",
")",
";",
"let",
"parentObj",
"=",
"global",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"nsParts",
".",
"length",
"-",
"1",
";",
"i",
"++",
")",
"{",
"let",
"nsObj",
"=",
"parentObj",
"[",
"nsParts",
"[",
"i",
"]",
"]",
";",
"if",
"(",
"!",
"nsObj",
")",
"{",
"nsObj",
"=",
"{",
"}",
";",
"parentObj",
"[",
"nsParts",
"[",
"i",
"]",
"]",
"=",
"nsObj",
";",
"}",
"parentObj",
"=",
"nsObj",
";",
"}",
"let",
"lastNsPart",
"=",
"nsParts",
"[",
"nsParts",
".",
"length",
"-",
"1",
"]",
";",
"let",
"nsPackage",
"=",
"require",
"(",
"uwpRoot",
"+",
"ns",
".",
"toLowerCase",
"(",
")",
")",
";",
"let",
"nsObj",
"=",
"parentObj",
"[",
"lastNsPart",
"]",
";",
"if",
"(",
"nsObj",
")",
"{",
"Object",
".",
"keys",
"(",
"nsObj",
")",
".",
"forEach",
"(",
"key",
"=>",
"{",
"nsPackage",
"[",
"key",
"]",
"=",
"nsObj",
"[",
"key",
"]",
";",
"}",
")",
"}",
"parentObj",
"[",
"lastNsPart",
"]",
"=",
"nsPackage",
";",
"}"
] |
Require a NodeRt namespace package and load it into the global namespace.
|
[
"Require",
"a",
"NodeRt",
"namespace",
"package",
"and",
"load",
"it",
"into",
"the",
"global",
"namespace",
"."
] |
a76c6230720f768615faccf5b5dfb41cc0b8ed33
|
https://github.com/jasongin/noble-uwp/blob/a76c6230720f768615faccf5b5dfb41cc0b8ed33/lib/rt-utils.js#L11-L37
|
train
|
jasongin/noble-uwp
|
lib/rt-utils.js
|
toArray
|
function toArray(o) {
let a = new Array(o.length);
for (let i = 0; i < a.length; i++) {
a[i] = o[i];
}
return a;
}
|
javascript
|
function toArray(o) {
let a = new Array(o.length);
for (let i = 0; i < a.length; i++) {
a[i] = o[i];
}
return a;
}
|
[
"function",
"toArray",
"(",
"o",
")",
"{",
"let",
"a",
"=",
"new",
"Array",
"(",
"o",
".",
"length",
")",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"a",
".",
"length",
";",
"i",
"++",
")",
"{",
"a",
"[",
"i",
"]",
"=",
"o",
"[",
"i",
"]",
";",
"}",
"return",
"a",
";",
"}"
] |
Convert a WinRT IVectorView to a JS Array.
|
[
"Convert",
"a",
"WinRT",
"IVectorView",
"to",
"a",
"JS",
"Array",
"."
] |
a76c6230720f768615faccf5b5dfb41cc0b8ed33
|
https://github.com/jasongin/noble-uwp/blob/a76c6230720f768615faccf5b5dfb41cc0b8ed33/lib/rt-utils.js#L52-L58
|
train
|
jasongin/noble-uwp
|
lib/rt-utils.js
|
toMap
|
function toMap(o) {
let m = new Map();
for (let i = o.first(); i.hasCurrent; i.moveNext()) {
m.set(i.current.key, i.current.value);
}
return m;
}
|
javascript
|
function toMap(o) {
let m = new Map();
for (let i = o.first(); i.hasCurrent; i.moveNext()) {
m.set(i.current.key, i.current.value);
}
return m;
}
|
[
"function",
"toMap",
"(",
"o",
")",
"{",
"let",
"m",
"=",
"new",
"Map",
"(",
")",
";",
"for",
"(",
"let",
"i",
"=",
"o",
".",
"first",
"(",
")",
";",
"i",
".",
"hasCurrent",
";",
"i",
".",
"moveNext",
"(",
")",
")",
"{",
"m",
".",
"set",
"(",
"i",
".",
"current",
".",
"key",
",",
"i",
".",
"current",
".",
"value",
")",
";",
"}",
"return",
"m",
";",
"}"
] |
Convert a WinRT IMap to a JS Map.
|
[
"Convert",
"a",
"WinRT",
"IMap",
"to",
"a",
"JS",
"Map",
"."
] |
a76c6230720f768615faccf5b5dfb41cc0b8ed33
|
https://github.com/jasongin/noble-uwp/blob/a76c6230720f768615faccf5b5dfb41cc0b8ed33/lib/rt-utils.js#L61-L67
|
train
|
jasongin/noble-uwp
|
lib/rt-utils.js
|
toBuffer
|
function toBuffer(b) {
// TODO: Use nodert-streams to more efficiently convert the buffer?
let len = b.length;
const DataReader = Windows.Storage.Streams.DataReader;
let r = DataReader.fromBuffer(b);
let a = new Uint8Array(len);
for (let i = 0; i < len; i++) {
a[i] = r.readByte();
}
return Buffer.from(a.buffer);
}
|
javascript
|
function toBuffer(b) {
// TODO: Use nodert-streams to more efficiently convert the buffer?
let len = b.length;
const DataReader = Windows.Storage.Streams.DataReader;
let r = DataReader.fromBuffer(b);
let a = new Uint8Array(len);
for (let i = 0; i < len; i++) {
a[i] = r.readByte();
}
return Buffer.from(a.buffer);
}
|
[
"function",
"toBuffer",
"(",
"b",
")",
"{",
"let",
"len",
"=",
"b",
".",
"length",
";",
"const",
"DataReader",
"=",
"Windows",
".",
"Storage",
".",
"Streams",
".",
"DataReader",
";",
"let",
"r",
"=",
"DataReader",
".",
"fromBuffer",
"(",
"b",
")",
";",
"let",
"a",
"=",
"new",
"Uint8Array",
"(",
"len",
")",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"a",
"[",
"i",
"]",
"=",
"r",
".",
"readByte",
"(",
")",
";",
"}",
"return",
"Buffer",
".",
"from",
"(",
"a",
".",
"buffer",
")",
";",
"}"
] |
Convert a WinRT IBuffer to a JS Buffer.
|
[
"Convert",
"a",
"WinRT",
"IBuffer",
"to",
"a",
"JS",
"Buffer",
"."
] |
a76c6230720f768615faccf5b5dfb41cc0b8ed33
|
https://github.com/jasongin/noble-uwp/blob/a76c6230720f768615faccf5b5dfb41cc0b8ed33/lib/rt-utils.js#L70-L80
|
train
|
jasongin/noble-uwp
|
lib/rt-utils.js
|
fromBuffer
|
function fromBuffer(b) {
// TODO: Use nodert-streams to more efficiently convert the buffer?
let len = b.length;
const DataWriter = Windows.Storage.Streams.DataWriter;
let w = new DataWriter();
for (let i = 0; i < len; i++) {
w.writeByte(b[i]);
}
return w.detachBuffer();
}
|
javascript
|
function fromBuffer(b) {
// TODO: Use nodert-streams to more efficiently convert the buffer?
let len = b.length;
const DataWriter = Windows.Storage.Streams.DataWriter;
let w = new DataWriter();
for (let i = 0; i < len; i++) {
w.writeByte(b[i]);
}
return w.detachBuffer();
}
|
[
"function",
"fromBuffer",
"(",
"b",
")",
"{",
"let",
"len",
"=",
"b",
".",
"length",
";",
"const",
"DataWriter",
"=",
"Windows",
".",
"Storage",
".",
"Streams",
".",
"DataWriter",
";",
"let",
"w",
"=",
"new",
"DataWriter",
"(",
")",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"w",
".",
"writeByte",
"(",
"b",
"[",
"i",
"]",
")",
";",
"}",
"return",
"w",
".",
"detachBuffer",
"(",
")",
";",
"}"
] |
Convert a JS Buffer to a WinRT IBuffer.
|
[
"Convert",
"a",
"JS",
"Buffer",
"to",
"a",
"WinRT",
"IBuffer",
"."
] |
a76c6230720f768615faccf5b5dfb41cc0b8ed33
|
https://github.com/jasongin/noble-uwp/blob/a76c6230720f768615faccf5b5dfb41cc0b8ed33/lib/rt-utils.js#L83-L92
|
train
|
jasongin/noble-uwp
|
lib/rt-utils.js
|
keepAlive
|
function keepAlive(k) {
if (k) {
if (++keepAliveIntervalCount === 1) {
// The actual duration doesn't really matter: it should be large but not too large.
keepAliveIntervalId = setInterval(() => { }, 24 * 60 * 60 * 1000);
}
} else {
if (--keepAliveIntervalCount === 0) {
clearInterval(keepAliveIntervalId);
}
}
debug(`keepAlive(${k}) => ${keepAliveIntervalCount}`);
}
|
javascript
|
function keepAlive(k) {
if (k) {
if (++keepAliveIntervalCount === 1) {
// The actual duration doesn't really matter: it should be large but not too large.
keepAliveIntervalId = setInterval(() => { }, 24 * 60 * 60 * 1000);
}
} else {
if (--keepAliveIntervalCount === 0) {
clearInterval(keepAliveIntervalId);
}
}
debug(`keepAlive(${k}) => ${keepAliveIntervalCount}`);
}
|
[
"function",
"keepAlive",
"(",
"k",
")",
"{",
"if",
"(",
"k",
")",
"{",
"if",
"(",
"++",
"keepAliveIntervalCount",
"===",
"1",
")",
"{",
"keepAliveIntervalId",
"=",
"setInterval",
"(",
"(",
")",
"=>",
"{",
"}",
",",
"24",
"*",
"60",
"*",
"60",
"*",
"1000",
")",
";",
"}",
"}",
"else",
"{",
"if",
"(",
"--",
"keepAliveIntervalCount",
"===",
"0",
")",
"{",
"clearInterval",
"(",
"keepAliveIntervalId",
")",
";",
"}",
"}",
"debug",
"(",
"`",
"${",
"k",
"}",
"${",
"keepAliveIntervalCount",
"}",
"`",
")",
";",
"}"
] |
Increment or decrement the count of WinRT async tasks. While the count is non-zero an interval is used to keep the JS engine alive.
|
[
"Increment",
"or",
"decrement",
"the",
"count",
"of",
"WinRT",
"async",
"tasks",
".",
"While",
"the",
"count",
"is",
"non",
"-",
"zero",
"an",
"interval",
"is",
"used",
"to",
"keep",
"the",
"JS",
"engine",
"alive",
"."
] |
a76c6230720f768615faccf5b5dfb41cc0b8ed33
|
https://github.com/jasongin/noble-uwp/blob/a76c6230720f768615faccf5b5dfb41cc0b8ed33/lib/rt-utils.js#L99-L111
|
train
|
Prinzhorn/skrollr-stylesheets
|
src/skrollr.stylesheets.js
|
function(input, output) {
rxAnimation.lastIndex = 0;
var animation;
var rawKeyframes;
var keyframe;
var curAnimation;
while((animation = rxAnimation.exec(input)) !== null) {
//Grab the keyframes inside this animation.
rxKeyframes.lastIndex = rxAnimation.lastIndex;
rawKeyframes = rxKeyframes.exec(input);
//Grab the single keyframes with their CSS properties.
rxSingleKeyframe.lastIndex = 0;
//Save the animation in an object using it's name as key.
curAnimation = output[animation[1]] = {};
while((keyframe = rxSingleKeyframe.exec(rawKeyframes[1])) !== null) {
//Put all keyframes inside the animation using the keyframe (like botttom-top, or 100) as key
//and the properties as value (just the raw string, newline stripped).
curAnimation[keyframe[1]] = keyframe[2].replace(/[\n\r\t]/g, '');
}
}
}
|
javascript
|
function(input, output) {
rxAnimation.lastIndex = 0;
var animation;
var rawKeyframes;
var keyframe;
var curAnimation;
while((animation = rxAnimation.exec(input)) !== null) {
//Grab the keyframes inside this animation.
rxKeyframes.lastIndex = rxAnimation.lastIndex;
rawKeyframes = rxKeyframes.exec(input);
//Grab the single keyframes with their CSS properties.
rxSingleKeyframe.lastIndex = 0;
//Save the animation in an object using it's name as key.
curAnimation = output[animation[1]] = {};
while((keyframe = rxSingleKeyframe.exec(rawKeyframes[1])) !== null) {
//Put all keyframes inside the animation using the keyframe (like botttom-top, or 100) as key
//and the properties as value (just the raw string, newline stripped).
curAnimation[keyframe[1]] = keyframe[2].replace(/[\n\r\t]/g, '');
}
}
}
|
[
"function",
"(",
"input",
",",
"output",
")",
"{",
"rxAnimation",
".",
"lastIndex",
"=",
"0",
";",
"var",
"animation",
";",
"var",
"rawKeyframes",
";",
"var",
"keyframe",
";",
"var",
"curAnimation",
";",
"while",
"(",
"(",
"animation",
"=",
"rxAnimation",
".",
"exec",
"(",
"input",
")",
")",
"!==",
"null",
")",
"{",
"rxKeyframes",
".",
"lastIndex",
"=",
"rxAnimation",
".",
"lastIndex",
";",
"rawKeyframes",
"=",
"rxKeyframes",
".",
"exec",
"(",
"input",
")",
";",
"rxSingleKeyframe",
".",
"lastIndex",
"=",
"0",
";",
"curAnimation",
"=",
"output",
"[",
"animation",
"[",
"1",
"]",
"]",
"=",
"{",
"}",
";",
"while",
"(",
"(",
"keyframe",
"=",
"rxSingleKeyframe",
".",
"exec",
"(",
"rawKeyframes",
"[",
"1",
"]",
")",
")",
"!==",
"null",
")",
"{",
"curAnimation",
"[",
"keyframe",
"[",
"1",
"]",
"]",
"=",
"keyframe",
"[",
"2",
"]",
".",
"replace",
"(",
"/",
"[\\n\\r\\t]",
"/",
"g",
",",
"''",
")",
";",
"}",
"}",
"}"
] |
Finds animation declarations and puts them into the output map.
|
[
"Finds",
"animation",
"declarations",
"and",
"puts",
"them",
"into",
"the",
"output",
"map",
"."
] |
f6a339e128a69e7d25e7caa4bdf38b5235cf29c6
|
https://github.com/Prinzhorn/skrollr-stylesheets/blob/f6a339e128a69e7d25e7caa4bdf38b5235cf29c6/src/skrollr.stylesheets.js#L109-L134
|
train
|
|
Prinzhorn/skrollr-stylesheets
|
src/skrollr.stylesheets.js
|
function(input, startIndex) {
var begin;
var end = startIndex;
//First find the curly bracket that opens this block.
while(end-- && input.charAt(end) !== '{') {}
//The end is now fixed to the right of the selector.
//Now start there to find the begin of the selector.
begin = end;
//Now walk farther backwards until we grabbed the whole selector.
//This either ends at beginning of string or at end of next block.
while(begin-- && input.charAt(begin - 1) !== '}') {}
//Return the cleaned selector.
return input.substring(begin, end).replace(/[\n\r\t]/g, '');
}
|
javascript
|
function(input, startIndex) {
var begin;
var end = startIndex;
//First find the curly bracket that opens this block.
while(end-- && input.charAt(end) !== '{') {}
//The end is now fixed to the right of the selector.
//Now start there to find the begin of the selector.
begin = end;
//Now walk farther backwards until we grabbed the whole selector.
//This either ends at beginning of string or at end of next block.
while(begin-- && input.charAt(begin - 1) !== '}') {}
//Return the cleaned selector.
return input.substring(begin, end).replace(/[\n\r\t]/g, '');
}
|
[
"function",
"(",
"input",
",",
"startIndex",
")",
"{",
"var",
"begin",
";",
"var",
"end",
"=",
"startIndex",
";",
"while",
"(",
"end",
"--",
"&&",
"input",
".",
"charAt",
"(",
"end",
")",
"!==",
"'{'",
")",
"{",
"}",
"begin",
"=",
"end",
";",
"while",
"(",
"begin",
"--",
"&&",
"input",
".",
"charAt",
"(",
"begin",
"-",
"1",
")",
"!==",
"'}'",
")",
"{",
"}",
"return",
"input",
".",
"substring",
"(",
"begin",
",",
"end",
")",
".",
"replace",
"(",
"/",
"[\\n\\r\\t]",
"/",
"g",
",",
"''",
")",
";",
"}"
] |
Extracts the selector of the given block by walking backwards to the start of the block.
|
[
"Extracts",
"the",
"selector",
"of",
"the",
"given",
"block",
"by",
"walking",
"backwards",
"to",
"the",
"start",
"of",
"the",
"block",
"."
] |
f6a339e128a69e7d25e7caa4bdf38b5235cf29c6
|
https://github.com/Prinzhorn/skrollr-stylesheets/blob/f6a339e128a69e7d25e7caa4bdf38b5235cf29c6/src/skrollr.stylesheets.js#L137-L154
|
train
|
|
Prinzhorn/skrollr-stylesheets
|
src/skrollr.stylesheets.js
|
function(input, output) {
var match;
var selector;
rxAttributeSetter.lastIndex = 0;
while((match = rxAttributeSetter.exec(input)) !== null) {
//Extract the selector of the block we found the animation in.
selector = extractSelector(input, rxAttributeSetter.lastIndex);
//Associate this selector with the attribute name and value.
output.push([selector, match[1], match[2]]);
}
}
|
javascript
|
function(input, output) {
var match;
var selector;
rxAttributeSetter.lastIndex = 0;
while((match = rxAttributeSetter.exec(input)) !== null) {
//Extract the selector of the block we found the animation in.
selector = extractSelector(input, rxAttributeSetter.lastIndex);
//Associate this selector with the attribute name and value.
output.push([selector, match[1], match[2]]);
}
}
|
[
"function",
"(",
"input",
",",
"output",
")",
"{",
"var",
"match",
";",
"var",
"selector",
";",
"rxAttributeSetter",
".",
"lastIndex",
"=",
"0",
";",
"while",
"(",
"(",
"match",
"=",
"rxAttributeSetter",
".",
"exec",
"(",
"input",
")",
")",
"!==",
"null",
")",
"{",
"selector",
"=",
"extractSelector",
"(",
"input",
",",
"rxAttributeSetter",
".",
"lastIndex",
")",
";",
"output",
".",
"push",
"(",
"[",
"selector",
",",
"match",
"[",
"1",
"]",
",",
"match",
"[",
"2",
"]",
"]",
")",
";",
"}",
"}"
] |
Finds usage of attribute setters and puts the selector and attribute data into the output array.
|
[
"Finds",
"usage",
"of",
"attribute",
"setters",
"and",
"puts",
"the",
"selector",
"and",
"attribute",
"data",
"into",
"the",
"output",
"array",
"."
] |
f6a339e128a69e7d25e7caa4bdf38b5235cf29c6
|
https://github.com/Prinzhorn/skrollr-stylesheets/blob/f6a339e128a69e7d25e7caa4bdf38b5235cf29c6/src/skrollr.stylesheets.js#L173-L186
|
train
|
|
travishorn/jquery-sessionTimeout
|
jquery.sessionTimeout.js
|
function () {
$(this).dialog('close');
$.ajax({
type: o.keepAliveAjaxRequestType,
url: o.appendTime ? updateQueryStringParameter(o.keepAliveUrl, "_", new Date().getTime()) : o.keepAliveUrl
});
// Stop redirect timer and restart warning timer
controlRedirTimer('stop');
controlDialogTimer('start');
}
|
javascript
|
function () {
$(this).dialog('close');
$.ajax({
type: o.keepAliveAjaxRequestType,
url: o.appendTime ? updateQueryStringParameter(o.keepAliveUrl, "_", new Date().getTime()) : o.keepAliveUrl
});
// Stop redirect timer and restart warning timer
controlRedirTimer('stop');
controlDialogTimer('start');
}
|
[
"function",
"(",
")",
"{",
"$",
"(",
"this",
")",
".",
"dialog",
"(",
"'close'",
")",
";",
"$",
".",
"ajax",
"(",
"{",
"type",
":",
"o",
".",
"keepAliveAjaxRequestType",
",",
"url",
":",
"o",
".",
"appendTime",
"?",
"updateQueryStringParameter",
"(",
"o",
".",
"keepAliveUrl",
",",
"\"_\"",
",",
"new",
"Date",
"(",
")",
".",
"getTime",
"(",
")",
")",
":",
"o",
".",
"keepAliveUrl",
"}",
")",
";",
"controlRedirTimer",
"(",
"'stop'",
")",
";",
"controlDialogTimer",
"(",
"'start'",
")",
";",
"}"
] |
Button two - closes dialog and makes call to keep-alive URL
|
[
"Button",
"two",
"-",
"closes",
"dialog",
"and",
"makes",
"call",
"to",
"keep",
"-",
"alive",
"URL"
] |
b9027365ca616b16008cddd0068f2aabf387ed12
|
https://github.com/travishorn/jquery-sessionTimeout/blob/b9027365ca616b16008cddd0068f2aabf387ed12/jquery.sessionTimeout.js#L90-L101
|
train
|
|
gustavohenke/toposort
|
build/toposort.js
|
visit
|
function visit( node, predecessors ) {
//check if a node is dependent of itself
if( predecessors.length !== 0 && predecessors.indexOf( node ) !== -1 ) {
throw new Error( "Cyclic dependency found. " + node + " is dependent of itself.\nDependency chain: "
+ predecessors.join( " -> " ) + " => " + node );
}
var index = nodes.indexOf( node );
//if the node still exists, traverse its dependencies
if( index !== -1 ) {
var copy = false;
//mark the node as false to exclude it from future iterations
nodes[index] = false;
//loop through all edges and follow dependencies of the current node
for( var _iterator4 = _this.edges, _isArray4 = Array.isArray( _iterator4 ), _i4 = 0, _iterator4 = _isArray4 ?
_iterator4 :
_iterator4[Symbol.iterator](); ; ) {
var _ref4;
if( _isArray4 ) {
if( _i4 >= _iterator4.length ) {
break;
}
_ref4 = _iterator4[_i4++];
} else {
_i4 = _iterator4.next();
if( _i4.done ) {
break;
}
_ref4 = _i4.value;
}
var edge = _ref4;
if( edge[0] === node ) {
//lazily create a copy of predecessors with the current node concatenated onto it
copy = copy || predecessors.concat( [node] );
//recurse to node dependencies
visit( edge[1], copy );
}
}
//add the node to the next place in the sorted array
sorted[--place] = node;
}
}
|
javascript
|
function visit( node, predecessors ) {
//check if a node is dependent of itself
if( predecessors.length !== 0 && predecessors.indexOf( node ) !== -1 ) {
throw new Error( "Cyclic dependency found. " + node + " is dependent of itself.\nDependency chain: "
+ predecessors.join( " -> " ) + " => " + node );
}
var index = nodes.indexOf( node );
//if the node still exists, traverse its dependencies
if( index !== -1 ) {
var copy = false;
//mark the node as false to exclude it from future iterations
nodes[index] = false;
//loop through all edges and follow dependencies of the current node
for( var _iterator4 = _this.edges, _isArray4 = Array.isArray( _iterator4 ), _i4 = 0, _iterator4 = _isArray4 ?
_iterator4 :
_iterator4[Symbol.iterator](); ; ) {
var _ref4;
if( _isArray4 ) {
if( _i4 >= _iterator4.length ) {
break;
}
_ref4 = _iterator4[_i4++];
} else {
_i4 = _iterator4.next();
if( _i4.done ) {
break;
}
_ref4 = _i4.value;
}
var edge = _ref4;
if( edge[0] === node ) {
//lazily create a copy of predecessors with the current node concatenated onto it
copy = copy || predecessors.concat( [node] );
//recurse to node dependencies
visit( edge[1], copy );
}
}
//add the node to the next place in the sorted array
sorted[--place] = node;
}
}
|
[
"function",
"visit",
"(",
"node",
",",
"predecessors",
")",
"{",
"if",
"(",
"predecessors",
".",
"length",
"!==",
"0",
"&&",
"predecessors",
".",
"indexOf",
"(",
"node",
")",
"!==",
"-",
"1",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"Cyclic dependency found. \"",
"+",
"node",
"+",
"\" is dependent of itself.\\nDependency chain: \"",
"+",
"\\n",
"+",
"predecessors",
".",
"join",
"(",
"\" -> \"",
")",
"+",
"\" => \"",
")",
";",
"}",
"node",
"var",
"index",
"=",
"nodes",
".",
"indexOf",
"(",
"node",
")",
";",
"}"
] |
define a visitor function that recursively traverses dependencies.
|
[
"define",
"a",
"visitor",
"function",
"that",
"recursively",
"traverses",
"dependencies",
"."
] |
fe0ca2afb366a115e6f8068b1f67bfd701bfd3d8
|
https://github.com/gustavohenke/toposort/blob/fe0ca2afb366a115e6f8068b1f67bfd701bfd3d8/build/toposort.js#L170-L219
|
train
|
ssbc/ssb-ws
|
json-api.js
|
function (req, res, next) {
var id
try { id = decodeURIComponent(req.url.substring(5)) }
catch (_) { id = req.url.substring(5) }
if(req.url.substring(0, 5) !== '/msg/' || !ref.isMsg(id)) return next()
sbot.get(id, function (err, msg) {
if(err) return next(err)
send(res, {key: id, value: msg})
})
}
|
javascript
|
function (req, res, next) {
var id
try { id = decodeURIComponent(req.url.substring(5)) }
catch (_) { id = req.url.substring(5) }
if(req.url.substring(0, 5) !== '/msg/' || !ref.isMsg(id)) return next()
sbot.get(id, function (err, msg) {
if(err) return next(err)
send(res, {key: id, value: msg})
})
}
|
[
"function",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"var",
"id",
"try",
"{",
"id",
"=",
"decodeURIComponent",
"(",
"req",
".",
"url",
".",
"substring",
"(",
"5",
")",
")",
"}",
"catch",
"(",
"_",
")",
"{",
"id",
"=",
"req",
".",
"url",
".",
"substring",
"(",
"5",
")",
"}",
"if",
"(",
"req",
".",
"url",
".",
"substring",
"(",
"0",
",",
"5",
")",
"!==",
"'/msg/'",
"||",
"!",
"ref",
".",
"isMsg",
"(",
"id",
")",
")",
"return",
"next",
"(",
")",
"sbot",
".",
"get",
"(",
"id",
",",
"function",
"(",
"err",
",",
"msg",
")",
"{",
"if",
"(",
"err",
")",
"return",
"next",
"(",
"err",
")",
"send",
"(",
"res",
",",
"{",
"key",
":",
"id",
",",
"value",
":",
"msg",
"}",
")",
"}",
")",
"}"
] |
blobs are served over CORS, so you can get blobs from any pub.
|
[
"blobs",
"are",
"served",
"over",
"CORS",
"so",
"you",
"can",
"get",
"blobs",
"from",
"any",
"pub",
"."
] |
d839f9abdd5d58d9fb244b8e49ff221f161e7845
|
https://github.com/ssbc/ssb-ws/blob/d839f9abdd5d58d9fb244b8e49ff221f161e7845/json-api.js#L19-L29
|
train
|
|
cozy/cozy-calendar
|
build/client/public/javascripts/vendor-d0a31592.js
|
function(dt, inc) {
var args = {
dt: dt,
inc: inc
},
result = this._cacheGet('before', args);
if (result === false) {
result = this._iter(new IterResult('before', args));
this._cacheAdd('before', result, args);
}
return result;
}
|
javascript
|
function(dt, inc) {
var args = {
dt: dt,
inc: inc
},
result = this._cacheGet('before', args);
if (result === false) {
result = this._iter(new IterResult('before', args));
this._cacheAdd('before', result, args);
}
return result;
}
|
[
"function",
"(",
"dt",
",",
"inc",
")",
"{",
"var",
"args",
"=",
"{",
"dt",
":",
"dt",
",",
"inc",
":",
"inc",
"}",
",",
"result",
"=",
"this",
".",
"_cacheGet",
"(",
"'before'",
",",
"args",
")",
";",
"if",
"(",
"result",
"===",
"false",
")",
"{",
"result",
"=",
"this",
".",
"_iter",
"(",
"new",
"IterResult",
"(",
"'before'",
",",
"args",
")",
")",
";",
"this",
".",
"_cacheAdd",
"(",
"'before'",
",",
"result",
",",
"args",
")",
";",
"}",
"return",
"result",
";",
"}"
] |
Returns the last recurrence before the given datetime instance.
The inc keyword defines what happens if dt is an occurrence.
With inc == True, if dt itself is an occurrence, it will be returned.
@return Date or null
|
[
"Returns",
"the",
"last",
"recurrence",
"before",
"the",
"given",
"datetime",
"instance",
".",
"The",
"inc",
"keyword",
"defines",
"what",
"happens",
"if",
"dt",
"is",
"an",
"occurrence",
".",
"With",
"inc",
"==",
"True",
"if",
"dt",
"itself",
"is",
"an",
"occurrence",
"it",
"will",
"be",
"returned",
"."
] |
786b1f6070cc3382db72dc473b45a8abf496fe16
|
https://github.com/cozy/cozy-calendar/blob/786b1f6070cc3382db72dc473b45a8abf496fe16/build/client/public/javascripts/vendor-d0a31592.js#L22650-L22661
|
train
|
|
cozy/cozy-calendar
|
build/client/public/javascripts/vendor-d0a31592.js
|
function(date) {
var tooEarly = this.minDate && date < this.minDate,
tooLate = this.maxDate && date > this.maxDate;
if (this.method == 'between') {
if (tooEarly)
return true;
if (tooLate)
return false;
} else if (this.method == 'before') {
if (tooLate)
return false;
} else if (this.method == 'after') {
if (tooEarly)
return true;
this.add(date);
return false;
}
return this.add(date);
}
|
javascript
|
function(date) {
var tooEarly = this.minDate && date < this.minDate,
tooLate = this.maxDate && date > this.maxDate;
if (this.method == 'between') {
if (tooEarly)
return true;
if (tooLate)
return false;
} else if (this.method == 'before') {
if (tooLate)
return false;
} else if (this.method == 'after') {
if (tooEarly)
return true;
this.add(date);
return false;
}
return this.add(date);
}
|
[
"function",
"(",
"date",
")",
"{",
"var",
"tooEarly",
"=",
"this",
".",
"minDate",
"&&",
"date",
"<",
"this",
".",
"minDate",
",",
"tooLate",
"=",
"this",
".",
"maxDate",
"&&",
"date",
">",
"this",
".",
"maxDate",
";",
"if",
"(",
"this",
".",
"method",
"==",
"'between'",
")",
"{",
"if",
"(",
"tooEarly",
")",
"return",
"true",
";",
"if",
"(",
"tooLate",
")",
"return",
"false",
";",
"}",
"else",
"if",
"(",
"this",
".",
"method",
"==",
"'before'",
")",
"{",
"if",
"(",
"tooLate",
")",
"return",
"false",
";",
"}",
"else",
"if",
"(",
"this",
".",
"method",
"==",
"'after'",
")",
"{",
"if",
"(",
"tooEarly",
")",
"return",
"true",
";",
"this",
".",
"add",
"(",
"date",
")",
";",
"return",
"false",
";",
"}",
"return",
"this",
".",
"add",
"(",
"date",
")",
";",
"}"
] |
Possibly adds a date into the result.
@param {Date} date - the date isn't necessarly added to the result
list (if it is too late/too early)
@return {Boolean} true if it makes sense to continue the iteration;
false if we're done.
|
[
"Possibly",
"adds",
"a",
"date",
"into",
"the",
"result",
"."
] |
786b1f6070cc3382db72dc473b45a8abf496fe16
|
https://github.com/cozy/cozy-calendar/blob/786b1f6070cc3382db72dc473b45a8abf496fe16/build/client/public/javascripts/vendor-d0a31592.js#L23588-L23609
|
train
|
|
cozy/cozy-calendar
|
build/client/public/javascripts/vendor-d0a31592.js
|
function(method, args, iterator) {
var allowedMethods = ['all', 'between'];
if (!_.include(allowedMethods, method)) {
throw 'Invalid method "' + method
+ '". Only all and between works with iterator.'
}
this.add = function(date) {
if (iterator(date, this._result.length)) {
this._result.push(date);
return true;
}
return false;
};
this.init(method, args);
}
|
javascript
|
function(method, args, iterator) {
var allowedMethods = ['all', 'between'];
if (!_.include(allowedMethods, method)) {
throw 'Invalid method "' + method
+ '". Only all and between works with iterator.'
}
this.add = function(date) {
if (iterator(date, this._result.length)) {
this._result.push(date);
return true;
}
return false;
};
this.init(method, args);
}
|
[
"function",
"(",
"method",
",",
"args",
",",
"iterator",
")",
"{",
"var",
"allowedMethods",
"=",
"[",
"'all'",
",",
"'between'",
"]",
";",
"if",
"(",
"!",
"_",
".",
"include",
"(",
"allowedMethods",
",",
"method",
")",
")",
"{",
"throw",
"'Invalid method \"'",
"+",
"method",
"+",
"'\". Only all and between works with iterator.'",
"}",
"this",
".",
"add",
"=",
"function",
"(",
"date",
")",
"{",
"if",
"(",
"iterator",
"(",
"date",
",",
"this",
".",
"_result",
".",
"length",
")",
")",
"{",
"this",
".",
"_result",
".",
"push",
"(",
"date",
")",
";",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}",
";",
"this",
".",
"init",
"(",
"method",
",",
"args",
")",
";",
"}"
] |
IterResult subclass that calls a callback function on each add,
and stops iterating when the callback returns false.
|
[
"IterResult",
"subclass",
"that",
"calls",
"a",
"callback",
"function",
"on",
"each",
"add",
"and",
"stops",
"iterating",
"when",
"the",
"callback",
"returns",
"false",
"."
] |
786b1f6070cc3382db72dc473b45a8abf496fe16
|
https://github.com/cozy/cozy-calendar/blob/786b1f6070cc3382db72dc473b45a8abf496fe16/build/client/public/javascripts/vendor-d0a31592.js#L23646-L23663
|
train
|
|
cozy/cozy-calendar
|
build/client/public/javascripts/vendor-d0a31592.js
|
function(channel, subscription, context, once) {
if (!channels[channel]) channels[channel] = [];
channels[channel].push({fn: subscription, context: context || this, once: once});
}
|
javascript
|
function(channel, subscription, context, once) {
if (!channels[channel]) channels[channel] = [];
channels[channel].push({fn: subscription, context: context || this, once: once});
}
|
[
"function",
"(",
"channel",
",",
"subscription",
",",
"context",
",",
"once",
")",
"{",
"if",
"(",
"!",
"channels",
"[",
"channel",
"]",
")",
"channels",
"[",
"channel",
"]",
"=",
"[",
"]",
";",
"channels",
"[",
"channel",
"]",
".",
"push",
"(",
"{",
"fn",
":",
"subscription",
",",
"context",
":",
"context",
"||",
"this",
",",
"once",
":",
"once",
"}",
")",
";",
"}"
] |
Subscribe to a channel
@param channel
|
[
"Subscribe",
"to",
"a",
"channel"
] |
786b1f6070cc3382db72dc473b45a8abf496fe16
|
https://github.com/cozy/cozy-calendar/blob/786b1f6070cc3382db72dc473b45a8abf496fe16/build/client/public/javascripts/vendor-d0a31592.js#L29019-L29022
|
train
|
|
cozy/cozy-calendar
|
build/client/public/javascripts/vendor-d0a31592.js
|
function(channel) {
if (!channels[channel]) return;
var args = [].slice.call(arguments, 1),
subscription;
for (var i = 0; i < channels[channel].length; i++) {
subscription = channels[channel][i];
subscription.fn.apply(subscription.context, args);
if (subscription.once) {
Backbone.Mediator.unsubscribe(channel, subscription.fn, subscription.context);
i--;
}
}
}
|
javascript
|
function(channel) {
if (!channels[channel]) return;
var args = [].slice.call(arguments, 1),
subscription;
for (var i = 0; i < channels[channel].length; i++) {
subscription = channels[channel][i];
subscription.fn.apply(subscription.context, args);
if (subscription.once) {
Backbone.Mediator.unsubscribe(channel, subscription.fn, subscription.context);
i--;
}
}
}
|
[
"function",
"(",
"channel",
")",
"{",
"if",
"(",
"!",
"channels",
"[",
"channel",
"]",
")",
"return",
";",
"var",
"args",
"=",
"[",
"]",
".",
"slice",
".",
"call",
"(",
"arguments",
",",
"1",
")",
",",
"subscription",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"channels",
"[",
"channel",
"]",
".",
"length",
";",
"i",
"++",
")",
"{",
"subscription",
"=",
"channels",
"[",
"channel",
"]",
"[",
"i",
"]",
";",
"subscription",
".",
"fn",
".",
"apply",
"(",
"subscription",
".",
"context",
",",
"args",
")",
";",
"if",
"(",
"subscription",
".",
"once",
")",
"{",
"Backbone",
".",
"Mediator",
".",
"unsubscribe",
"(",
"channel",
",",
"subscription",
".",
"fn",
",",
"subscription",
".",
"context",
")",
";",
"i",
"--",
";",
"}",
"}",
"}"
] |
Trigger all callbacks for a channel
@param channel
@params N Extra parametter to pass to handler
|
[
"Trigger",
"all",
"callbacks",
"for",
"a",
"channel"
] |
786b1f6070cc3382db72dc473b45a8abf496fe16
|
https://github.com/cozy/cozy-calendar/blob/786b1f6070cc3382db72dc473b45a8abf496fe16/build/client/public/javascripts/vendor-d0a31592.js#L29030-L29044
|
train
|
|
cozy/cozy-calendar
|
build/client/public/javascripts/vendor-d0a31592.js
|
function (channel, subscription, context) {
Backbone.Mediator.subscribe(channel, subscription, context, true);
}
|
javascript
|
function (channel, subscription, context) {
Backbone.Mediator.subscribe(channel, subscription, context, true);
}
|
[
"function",
"(",
"channel",
",",
"subscription",
",",
"context",
")",
"{",
"Backbone",
".",
"Mediator",
".",
"subscribe",
"(",
"channel",
",",
"subscription",
",",
"context",
",",
"true",
")",
";",
"}"
] |
Subscribing to one event only
@param channel
@param subscription
@param context
|
[
"Subscribing",
"to",
"one",
"event",
"only"
] |
786b1f6070cc3382db72dc473b45a8abf496fe16
|
https://github.com/cozy/cozy-calendar/blob/786b1f6070cc3382db72dc473b45a8abf496fe16/build/client/public/javascripts/vendor-d0a31592.js#L29074-L29076
|
train
|
|
cozy/cozy-calendar
|
build/client/public/javascripts/vendor-d0a31592.js
|
function(subscriptions){
if (subscriptions) _.extend(this.subscriptions || {}, subscriptions);
subscriptions = subscriptions || this.subscriptions;
if (!subscriptions || _.isEmpty(subscriptions)) return;
// Just to be sure we don't set duplicate
this.unsetSubscriptions(subscriptions);
_.each(subscriptions, function(subscription, channel){
var once;
if (subscription.$once) {
subscription = subscription.$once;
once = true;
}
if (_.isString(subscription)) {
subscription = this[subscription];
}
Backbone.Mediator.subscribe(channel, subscription, this, once);
}, this);
}
|
javascript
|
function(subscriptions){
if (subscriptions) _.extend(this.subscriptions || {}, subscriptions);
subscriptions = subscriptions || this.subscriptions;
if (!subscriptions || _.isEmpty(subscriptions)) return;
// Just to be sure we don't set duplicate
this.unsetSubscriptions(subscriptions);
_.each(subscriptions, function(subscription, channel){
var once;
if (subscription.$once) {
subscription = subscription.$once;
once = true;
}
if (_.isString(subscription)) {
subscription = this[subscription];
}
Backbone.Mediator.subscribe(channel, subscription, this, once);
}, this);
}
|
[
"function",
"(",
"subscriptions",
")",
"{",
"if",
"(",
"subscriptions",
")",
"_",
".",
"extend",
"(",
"this",
".",
"subscriptions",
"||",
"{",
"}",
",",
"subscriptions",
")",
";",
"subscriptions",
"=",
"subscriptions",
"||",
"this",
".",
"subscriptions",
";",
"if",
"(",
"!",
"subscriptions",
"||",
"_",
".",
"isEmpty",
"(",
"subscriptions",
")",
")",
"return",
";",
"this",
".",
"unsetSubscriptions",
"(",
"subscriptions",
")",
";",
"_",
".",
"each",
"(",
"subscriptions",
",",
"function",
"(",
"subscription",
",",
"channel",
")",
"{",
"var",
"once",
";",
"if",
"(",
"subscription",
".",
"$once",
")",
"{",
"subscription",
"=",
"subscription",
".",
"$once",
";",
"once",
"=",
"true",
";",
"}",
"if",
"(",
"_",
".",
"isString",
"(",
"subscription",
")",
")",
"{",
"subscription",
"=",
"this",
"[",
"subscription",
"]",
";",
"}",
"Backbone",
".",
"Mediator",
".",
"subscribe",
"(",
"channel",
",",
"subscription",
",",
"this",
",",
"once",
")",
";",
"}",
",",
"this",
")",
";",
"}"
] |
Subscribe to each subscription
@param {Object} [subscriptions] An optional hash of subscription to add
|
[
"Subscribe",
"to",
"each",
"subscription"
] |
786b1f6070cc3382db72dc473b45a8abf496fe16
|
https://github.com/cozy/cozy-calendar/blob/786b1f6070cc3382db72dc473b45a8abf496fe16/build/client/public/javascripts/vendor-d0a31592.js#L29115-L29133
|
train
|
|
cozy/cozy-calendar
|
build/client/public/javascripts/vendor-d0a31592.js
|
function(subscriptions){
subscriptions = subscriptions || this.subscriptions;
if (!subscriptions || _.isEmpty(subscriptions)) return;
_.each(subscriptions, function(subscription, channel){
if (_.isString(subscription)) {
subscription = this[subscription];
}
Backbone.Mediator.unsubscribe(channel, subscription.$once || subscription, this);
}, this);
}
|
javascript
|
function(subscriptions){
subscriptions = subscriptions || this.subscriptions;
if (!subscriptions || _.isEmpty(subscriptions)) return;
_.each(subscriptions, function(subscription, channel){
if (_.isString(subscription)) {
subscription = this[subscription];
}
Backbone.Mediator.unsubscribe(channel, subscription.$once || subscription, this);
}, this);
}
|
[
"function",
"(",
"subscriptions",
")",
"{",
"subscriptions",
"=",
"subscriptions",
"||",
"this",
".",
"subscriptions",
";",
"if",
"(",
"!",
"subscriptions",
"||",
"_",
".",
"isEmpty",
"(",
"subscriptions",
")",
")",
"return",
";",
"_",
".",
"each",
"(",
"subscriptions",
",",
"function",
"(",
"subscription",
",",
"channel",
")",
"{",
"if",
"(",
"_",
".",
"isString",
"(",
"subscription",
")",
")",
"{",
"subscription",
"=",
"this",
"[",
"subscription",
"]",
";",
"}",
"Backbone",
".",
"Mediator",
".",
"unsubscribe",
"(",
"channel",
",",
"subscription",
".",
"$once",
"||",
"subscription",
",",
"this",
")",
";",
"}",
",",
"this",
")",
";",
"}"
] |
Unsubscribe to each subscription
@param {Object} [subscriptions] An optional hash of subscription to remove
|
[
"Unsubscribe",
"to",
"each",
"subscription"
] |
786b1f6070cc3382db72dc473b45a8abf496fe16
|
https://github.com/cozy/cozy-calendar/blob/786b1f6070cc3382db72dc473b45a8abf496fe16/build/client/public/javascripts/vendor-d0a31592.js#L29139-L29148
|
train
|
|
cozy/cozy-calendar
|
build/client/public/javascripts/vendor-d0a31592.js
|
choosePluralForm
|
function choosePluralForm(text, locale, count){
var ret, texts, chosenText;
if (count != null && text) {
texts = text.split(delimeter);
chosenText = texts[pluralTypeIndex(locale, count)] || texts[0];
ret = trim(chosenText);
} else {
ret = text;
}
return ret;
}
|
javascript
|
function choosePluralForm(text, locale, count){
var ret, texts, chosenText;
if (count != null && text) {
texts = text.split(delimeter);
chosenText = texts[pluralTypeIndex(locale, count)] || texts[0];
ret = trim(chosenText);
} else {
ret = text;
}
return ret;
}
|
[
"function",
"choosePluralForm",
"(",
"text",
",",
"locale",
",",
"count",
")",
"{",
"var",
"ret",
",",
"texts",
",",
"chosenText",
";",
"if",
"(",
"count",
"!=",
"null",
"&&",
"text",
")",
"{",
"texts",
"=",
"text",
".",
"split",
"(",
"delimeter",
")",
";",
"chosenText",
"=",
"texts",
"[",
"pluralTypeIndex",
"(",
"locale",
",",
"count",
")",
"]",
"||",
"texts",
"[",
"0",
"]",
";",
"ret",
"=",
"trim",
"(",
"chosenText",
")",
";",
"}",
"else",
"{",
"ret",
"=",
"text",
";",
"}",
"return",
"ret",
";",
"}"
] |
Based on a phrase text that contains `n` plural forms separated by `delimeter`, a `locale`, and a `count`, choose the correct plural form, or none if `count` is `null`.
|
[
"Based",
"on",
"a",
"phrase",
"text",
"that",
"contains",
"n",
"plural",
"forms",
"separated",
"by",
"delimeter",
"a",
"locale",
"and",
"a",
"count",
"choose",
"the",
"correct",
"plural",
"form",
"or",
"none",
"if",
"count",
"is",
"null",
"."
] |
786b1f6070cc3382db72dc473b45a8abf496fe16
|
https://github.com/cozy/cozy-calendar/blob/786b1f6070cc3382db72dc473b45a8abf496fe16/build/client/public/javascripts/vendor-d0a31592.js#L31928-L31938
|
train
|
cozy/cozy-calendar
|
build/client/public/javascripts/vendor-d0a31592.js
|
encodeAsBinary
|
function encodeAsBinary(obj, callback) {
function writeEncoding(bloblessData) {
var deconstruction = binary.deconstructPacket(bloblessData);
var pack = encodeAsString(deconstruction.packet);
var buffers = deconstruction.buffers;
buffers.unshift(pack); // add packet info to beginning of data list
callback(buffers); // write all the buffers
}
binary.removeBlobs(obj, writeEncoding);
}
|
javascript
|
function encodeAsBinary(obj, callback) {
function writeEncoding(bloblessData) {
var deconstruction = binary.deconstructPacket(bloblessData);
var pack = encodeAsString(deconstruction.packet);
var buffers = deconstruction.buffers;
buffers.unshift(pack); // add packet info to beginning of data list
callback(buffers); // write all the buffers
}
binary.removeBlobs(obj, writeEncoding);
}
|
[
"function",
"encodeAsBinary",
"(",
"obj",
",",
"callback",
")",
"{",
"function",
"writeEncoding",
"(",
"bloblessData",
")",
"{",
"var",
"deconstruction",
"=",
"binary",
".",
"deconstructPacket",
"(",
"bloblessData",
")",
";",
"var",
"pack",
"=",
"encodeAsString",
"(",
"deconstruction",
".",
"packet",
")",
";",
"var",
"buffers",
"=",
"deconstruction",
".",
"buffers",
";",
"buffers",
".",
"unshift",
"(",
"pack",
")",
";",
"callback",
"(",
"buffers",
")",
";",
"}",
"binary",
".",
"removeBlobs",
"(",
"obj",
",",
"writeEncoding",
")",
";",
"}"
] |
Encode packet as 'buffer sequence' by removing blobs, and
deconstructing packet into object with placeholders and
a list of buffers.
@param {Object} packet
@return {Buffer} encoded
@api private
|
[
"Encode",
"packet",
"as",
"buffer",
"sequence",
"by",
"removing",
"blobs",
"and",
"deconstructing",
"packet",
"into",
"object",
"with",
"placeholders",
"and",
"a",
"list",
"of",
"buffers",
"."
] |
786b1f6070cc3382db72dc473b45a8abf496fe16
|
https://github.com/cozy/cozy-calendar/blob/786b1f6070cc3382db72dc473b45a8abf496fe16/build/client/public/javascripts/vendor-d0a31592.js#L38889-L38901
|
train
|
words/n-gram
|
index.js
|
nGram
|
function nGram(n) {
if (typeof n !== 'number' || isNaN(n) || n < 1 || n === Infinity) {
throw new Error('`' + n + '` is not a valid argument for n-gram')
}
return grams
// Create n-grams from a given value.
function grams(value) {
var nGrams = []
var index
if (value === null || value === undefined) {
return nGrams
}
value = value.slice ? value : String(value)
index = value.length - n + 1
if (index < 1) {
return nGrams
}
while (index--) {
nGrams[index] = value.slice(index, index + n)
}
return nGrams
}
}
|
javascript
|
function nGram(n) {
if (typeof n !== 'number' || isNaN(n) || n < 1 || n === Infinity) {
throw new Error('`' + n + '` is not a valid argument for n-gram')
}
return grams
// Create n-grams from a given value.
function grams(value) {
var nGrams = []
var index
if (value === null || value === undefined) {
return nGrams
}
value = value.slice ? value : String(value)
index = value.length - n + 1
if (index < 1) {
return nGrams
}
while (index--) {
nGrams[index] = value.slice(index, index + n)
}
return nGrams
}
}
|
[
"function",
"nGram",
"(",
"n",
")",
"{",
"if",
"(",
"typeof",
"n",
"!==",
"'number'",
"||",
"isNaN",
"(",
"n",
")",
"||",
"n",
"<",
"1",
"||",
"n",
"===",
"Infinity",
")",
"{",
"throw",
"new",
"Error",
"(",
"'`'",
"+",
"n",
"+",
"'` is not a valid argument for n-gram'",
")",
"}",
"return",
"grams",
"function",
"grams",
"(",
"value",
")",
"{",
"var",
"nGrams",
"=",
"[",
"]",
"var",
"index",
"if",
"(",
"value",
"===",
"null",
"||",
"value",
"===",
"undefined",
")",
"{",
"return",
"nGrams",
"}",
"value",
"=",
"value",
".",
"slice",
"?",
"value",
":",
"String",
"(",
"value",
")",
"index",
"=",
"value",
".",
"length",
"-",
"n",
"+",
"1",
"if",
"(",
"index",
"<",
"1",
")",
"{",
"return",
"nGrams",
"}",
"while",
"(",
"index",
"--",
")",
"{",
"nGrams",
"[",
"index",
"]",
"=",
"value",
".",
"slice",
"(",
"index",
",",
"index",
"+",
"n",
")",
"}",
"return",
"nGrams",
"}",
"}"
] |
Factory returning a function that converts a value string to n-grams.
|
[
"Factory",
"returning",
"a",
"function",
"that",
"converts",
"a",
"value",
"string",
"to",
"n",
"-",
"grams",
"."
] |
006bfc965e118805ed6692854e854e925f75dcfc
|
https://github.com/words/n-gram/blob/006bfc965e118805ed6692854e854e925f75dcfc/index.js#L9-L38
|
train
|
words/n-gram
|
index.js
|
grams
|
function grams(value) {
var nGrams = []
var index
if (value === null || value === undefined) {
return nGrams
}
value = value.slice ? value : String(value)
index = value.length - n + 1
if (index < 1) {
return nGrams
}
while (index--) {
nGrams[index] = value.slice(index, index + n)
}
return nGrams
}
|
javascript
|
function grams(value) {
var nGrams = []
var index
if (value === null || value === undefined) {
return nGrams
}
value = value.slice ? value : String(value)
index = value.length - n + 1
if (index < 1) {
return nGrams
}
while (index--) {
nGrams[index] = value.slice(index, index + n)
}
return nGrams
}
|
[
"function",
"grams",
"(",
"value",
")",
"{",
"var",
"nGrams",
"=",
"[",
"]",
"var",
"index",
"if",
"(",
"value",
"===",
"null",
"||",
"value",
"===",
"undefined",
")",
"{",
"return",
"nGrams",
"}",
"value",
"=",
"value",
".",
"slice",
"?",
"value",
":",
"String",
"(",
"value",
")",
"index",
"=",
"value",
".",
"length",
"-",
"n",
"+",
"1",
"if",
"(",
"index",
"<",
"1",
")",
"{",
"return",
"nGrams",
"}",
"while",
"(",
"index",
"--",
")",
"{",
"nGrams",
"[",
"index",
"]",
"=",
"value",
".",
"slice",
"(",
"index",
",",
"index",
"+",
"n",
")",
"}",
"return",
"nGrams",
"}"
] |
Create n-grams from a given value.
|
[
"Create",
"n",
"-",
"grams",
"from",
"a",
"given",
"value",
"."
] |
006bfc965e118805ed6692854e854e925f75dcfc
|
https://github.com/words/n-gram/blob/006bfc965e118805ed6692854e854e925f75dcfc/index.js#L17-L37
|
train
|
briankircho/mongoose-schema-extend
|
Gruntfile.js
|
pathsort
|
function pathsort(paths, sep, algorithm) {
sep = sep || '/'
return paths.map(function(el) {
return el.split(sep)
}).sort(algorithm || levelSorter).map(function(el) {
return el.join(sep)
})
}
|
javascript
|
function pathsort(paths, sep, algorithm) {
sep = sep || '/'
return paths.map(function(el) {
return el.split(sep)
}).sort(algorithm || levelSorter).map(function(el) {
return el.join(sep)
})
}
|
[
"function",
"pathsort",
"(",
"paths",
",",
"sep",
",",
"algorithm",
")",
"{",
"sep",
"=",
"sep",
"||",
"'/'",
"return",
"paths",
".",
"map",
"(",
"function",
"(",
"el",
")",
"{",
"return",
"el",
".",
"split",
"(",
"sep",
")",
"}",
")",
".",
"sort",
"(",
"algorithm",
"||",
"levelSorter",
")",
".",
"map",
"(",
"function",
"(",
"el",
")",
"{",
"return",
"el",
".",
"join",
"(",
"sep",
")",
"}",
")",
"}"
] |
Sort a list of paths
|
[
"Sort",
"a",
"list",
"of",
"paths"
] |
de17899ff3c326ba6db3c35a91721e4751affc9c
|
https://github.com/briankircho/mongoose-schema-extend/blob/de17899ff3c326ba6db3c35a91721e4751affc9c/Gruntfile.js#L17-L25
|
train
|
briankircho/mongoose-schema-extend
|
Gruntfile.js
|
levelSorter
|
function levelSorter(a, b) {
var l = Math.max(a.length, b.length)
for (var i = 0; i < l; i += 1) {
if (!(i in a)) return +1
if (!(i in b)) return -1
if (a.length < b.length) return +1
if (a.length > b.length) return -1
}
}
|
javascript
|
function levelSorter(a, b) {
var l = Math.max(a.length, b.length)
for (var i = 0; i < l; i += 1) {
if (!(i in a)) return +1
if (!(i in b)) return -1
if (a.length < b.length) return +1
if (a.length > b.length) return -1
}
}
|
[
"function",
"levelSorter",
"(",
"a",
",",
"b",
")",
"{",
"var",
"l",
"=",
"Math",
".",
"max",
"(",
"a",
".",
"length",
",",
"b",
".",
"length",
")",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"l",
";",
"i",
"+=",
"1",
")",
"{",
"if",
"(",
"!",
"(",
"i",
"in",
"a",
")",
")",
"return",
"+",
"1",
"if",
"(",
"!",
"(",
"i",
"in",
"b",
")",
")",
"return",
"-",
"1",
"if",
"(",
"a",
".",
"length",
"<",
"b",
".",
"length",
")",
"return",
"+",
"1",
"if",
"(",
"a",
".",
"length",
">",
"b",
".",
"length",
")",
"return",
"-",
"1",
"}",
"}"
] |
Level-order sort of a list of paths
|
[
"Level",
"-",
"order",
"sort",
"of",
"a",
"list",
"of",
"paths"
] |
de17899ff3c326ba6db3c35a91721e4751affc9c
|
https://github.com/briankircho/mongoose-schema-extend/blob/de17899ff3c326ba6db3c35a91721e4751affc9c/Gruntfile.js#L30-L39
|
train
|
meteorhacks/npm
|
plugin/init_npm.js
|
canProceed
|
function canProceed() {
var unAcceptableCommands = {'test-packages': 1, 'publish': 1};
if(process.argv.length > 2) {
var command = process.argv[2];
if(unAcceptableCommands[command]) {
return false;
}
}
return true;
}
|
javascript
|
function canProceed() {
var unAcceptableCommands = {'test-packages': 1, 'publish': 1};
if(process.argv.length > 2) {
var command = process.argv[2];
if(unAcceptableCommands[command]) {
return false;
}
}
return true;
}
|
[
"function",
"canProceed",
"(",
")",
"{",
"var",
"unAcceptableCommands",
"=",
"{",
"'test-packages'",
":",
"1",
",",
"'publish'",
":",
"1",
"}",
";",
"if",
"(",
"process",
".",
"argv",
".",
"length",
">",
"2",
")",
"{",
"var",
"command",
"=",
"process",
".",
"argv",
"[",
"2",
"]",
";",
"if",
"(",
"unAcceptableCommands",
"[",
"command",
"]",
")",
"{",
"return",
"false",
";",
"}",
"}",
"return",
"true",
";",
"}"
] |
check whether is this `meteor test-packages` or not
|
[
"check",
"whether",
"is",
"this",
"meteor",
"test",
"-",
"packages",
"or",
"not"
] |
177465467a87d37ec283d127d877a1a5ce97f818
|
https://github.com/meteorhacks/npm/blob/177465467a87d37ec283d127d877a1a5ce97f818/plugin/init_npm.js#L44-L54
|
train
|
meteorhacks/npm
|
plugin/init_npm.js
|
getContent
|
function getContent(func) {
var lines = func.toString().split('\n');
// Drop the function declaration and closing bracket
var onlyBody = lines.slice(1, lines.length -1);
// Drop line number comments generated by Meteor, trim whitespace, make string
onlyBody = _.map(onlyBody, function(line) {
return line.slice(0, line.lastIndexOf("//")).trim();
}).join('\n');
// Make it look normal
return beautify(onlyBody, { indent_size: 2 });
}
|
javascript
|
function getContent(func) {
var lines = func.toString().split('\n');
// Drop the function declaration and closing bracket
var onlyBody = lines.slice(1, lines.length -1);
// Drop line number comments generated by Meteor, trim whitespace, make string
onlyBody = _.map(onlyBody, function(line) {
return line.slice(0, line.lastIndexOf("//")).trim();
}).join('\n');
// Make it look normal
return beautify(onlyBody, { indent_size: 2 });
}
|
[
"function",
"getContent",
"(",
"func",
")",
"{",
"var",
"lines",
"=",
"func",
".",
"toString",
"(",
")",
".",
"split",
"(",
"'\\n'",
")",
";",
"\\n",
"var",
"onlyBody",
"=",
"lines",
".",
"slice",
"(",
"1",
",",
"lines",
".",
"length",
"-",
"1",
")",
";",
"onlyBody",
"=",
"_",
".",
"map",
"(",
"onlyBody",
",",
"function",
"(",
"line",
")",
"{",
"return",
"line",
".",
"slice",
"(",
"0",
",",
"line",
".",
"lastIndexOf",
"(",
"\"//\"",
")",
")",
".",
"trim",
"(",
")",
";",
"}",
")",
".",
"join",
"(",
"'\\n'",
")",
";",
"}"
] |
getContent inside a function
|
[
"getContent",
"inside",
"a",
"function"
] |
177465467a87d37ec283d127d877a1a5ce97f818
|
https://github.com/meteorhacks/npm/blob/177465467a87d37ec283d127d877a1a5ce97f818/plugin/init_npm.js#L57-L67
|
train
|
meteorhacks/npm
|
plugin/init_npm.js
|
_indexJsContent
|
function _indexJsContent() {
Meteor.npmRequire = function(moduleName) {
var module = Npm.require(moduleName);
return module;
};
Meteor.require = function(moduleName) {
console.warn('Meteor.require is deprecated. Please use Meteor.npmRequire instead!');
return Meteor.npmRequire(moduleName);
};
}
|
javascript
|
function _indexJsContent() {
Meteor.npmRequire = function(moduleName) {
var module = Npm.require(moduleName);
return module;
};
Meteor.require = function(moduleName) {
console.warn('Meteor.require is deprecated. Please use Meteor.npmRequire instead!');
return Meteor.npmRequire(moduleName);
};
}
|
[
"function",
"_indexJsContent",
"(",
")",
"{",
"Meteor",
".",
"npmRequire",
"=",
"function",
"(",
"moduleName",
")",
"{",
"var",
"module",
"=",
"Npm",
".",
"require",
"(",
"moduleName",
")",
";",
"return",
"module",
";",
"}",
";",
"Meteor",
".",
"require",
"=",
"function",
"(",
"moduleName",
")",
"{",
"console",
".",
"warn",
"(",
"'Meteor.require is deprecated. Please use Meteor.npmRequire instead!'",
")",
";",
"return",
"Meteor",
".",
"npmRequire",
"(",
"moduleName",
")",
";",
"}",
";",
"}"
] |
Following function has been defined to just get the content inside them They are not executables
|
[
"Following",
"function",
"has",
"been",
"defined",
"to",
"just",
"get",
"the",
"content",
"inside",
"them",
"They",
"are",
"not",
"executables"
] |
177465467a87d37ec283d127d877a1a5ce97f818
|
https://github.com/meteorhacks/npm/blob/177465467a87d37ec283d127d877a1a5ce97f818/plugin/init_npm.js#L71-L81
|
train
|
IdentityModel/oidc-token-manager
|
sample/vs/Sample/oidc-token-manager.js
|
_rsapem_readPrivateKeyFromASN1HexString
|
function _rsapem_readPrivateKeyFromASN1HexString(keyHex) {
var a = _rsapem_getHexValueArrayOfChildrenFromHex(keyHex);
this.setPrivateEx(a[1],a[2],a[3],a[4],a[5],a[6],a[7],a[8]);
}
|
javascript
|
function _rsapem_readPrivateKeyFromASN1HexString(keyHex) {
var a = _rsapem_getHexValueArrayOfChildrenFromHex(keyHex);
this.setPrivateEx(a[1],a[2],a[3],a[4],a[5],a[6],a[7],a[8]);
}
|
[
"function",
"_rsapem_readPrivateKeyFromASN1HexString",
"(",
"keyHex",
")",
"{",
"var",
"a",
"=",
"_rsapem_getHexValueArrayOfChildrenFromHex",
"(",
"keyHex",
")",
";",
"this",
".",
"setPrivateEx",
"(",
"a",
"[",
"1",
"]",
",",
"a",
"[",
"2",
"]",
",",
"a",
"[",
"3",
"]",
",",
"a",
"[",
"4",
"]",
",",
"a",
"[",
"5",
"]",
",",
"a",
"[",
"6",
"]",
",",
"a",
"[",
"7",
"]",
",",
"a",
"[",
"8",
"]",
")",
";",
"}"
] |
read RSA private key from a ASN.1 hexadecimal string
@name readPrivateKeyFromASN1HexString
@memberOf RSAKey#
@function
@param {String} keyHex ASN.1 hexadecimal string of PKCS#1 private key.
@since 1.1.1
|
[
"read",
"RSA",
"private",
"key",
"from",
"a",
"ASN",
".",
"1",
"hexadecimal",
"string"
] |
92998b8c3713975d98dc41cec4de2fff2c23e102
|
https://github.com/IdentityModel/oidc-token-manager/blob/92998b8c3713975d98dc41cec4de2fff2c23e102/sample/vs/Sample/oidc-token-manager.js#L3455-L3458
|
train
|
IdentityModel/oidc-token-manager
|
sample/vs/Sample/oidc-token-manager.js
|
BAtos
|
function BAtos(a) {
var s = "";
for (var i = 0; i < a.length; i++) {
s = s + String.fromCharCode(a[i]);
}
return s;
}
|
javascript
|
function BAtos(a) {
var s = "";
for (var i = 0; i < a.length; i++) {
s = s + String.fromCharCode(a[i]);
}
return s;
}
|
[
"function",
"BAtos",
"(",
"a",
")",
"{",
"var",
"s",
"=",
"\"\"",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"a",
".",
"length",
";",
"i",
"++",
")",
"{",
"s",
"=",
"s",
"+",
"String",
".",
"fromCharCode",
"(",
"a",
"[",
"i",
"]",
")",
";",
"}",
"return",
"s",
";",
"}"
] |
convert an array of character codes to a string
@param {Array of Numbers} a array of character codes
@return {String} s
|
[
"convert",
"an",
"array",
"of",
"character",
"codes",
"to",
"a",
"string"
] |
92998b8c3713975d98dc41cec4de2fff2c23e102
|
https://github.com/IdentityModel/oidc-token-manager/blob/92998b8c3713975d98dc41cec4de2fff2c23e102/sample/vs/Sample/oidc-token-manager.js#L5391-L5397
|
train
|
koajs/koa-hbs
|
index.js
|
merge
|
function merge (obj1, obj2) {
var c = {},
keys = Object.keys(obj2),
i;
for (i = 0; i !== keys.length; i++) {
c[keys[i]] = obj2[keys[i]];
}
keys = Object.keys(obj1);
for (i = 0; i !== keys.length; i++) {
if (!c.hasOwnProperty(keys[i])) {
c[keys[i]] = obj1[keys[i]];
}
}
return c;
}
|
javascript
|
function merge (obj1, obj2) {
var c = {},
keys = Object.keys(obj2),
i;
for (i = 0; i !== keys.length; i++) {
c[keys[i]] = obj2[keys[i]];
}
keys = Object.keys(obj1);
for (i = 0; i !== keys.length; i++) {
if (!c.hasOwnProperty(keys[i])) {
c[keys[i]] = obj1[keys[i]];
}
}
return c;
}
|
[
"function",
"merge",
"(",
"obj1",
",",
"obj2",
")",
"{",
"var",
"c",
"=",
"{",
"}",
",",
"keys",
"=",
"Object",
".",
"keys",
"(",
"obj2",
")",
",",
"i",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"!==",
"keys",
".",
"length",
";",
"i",
"++",
")",
"{",
"c",
"[",
"keys",
"[",
"i",
"]",
"]",
"=",
"obj2",
"[",
"keys",
"[",
"i",
"]",
"]",
";",
"}",
"keys",
"=",
"Object",
".",
"keys",
"(",
"obj1",
")",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"!==",
"keys",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"!",
"c",
".",
"hasOwnProperty",
"(",
"keys",
"[",
"i",
"]",
")",
")",
"{",
"c",
"[",
"keys",
"[",
"i",
"]",
"]",
"=",
"obj1",
"[",
"keys",
"[",
"i",
"]",
"]",
";",
"}",
"}",
"return",
"c",
";",
"}"
] |
Shallow copy two objects into a new object
Objects are merged from left to right. Thus, properties in objects further
to the right are preferred over those on the left.
@param {object} obj1
@param {object} obj2
@returns {object}
@api private
|
[
"Shallow",
"copy",
"two",
"objects",
"into",
"a",
"new",
"object"
] |
7a505cb9d1030ecd059ba8dd98c6a3edff8376d4
|
https://github.com/koajs/koa-hbs/blob/7a505cb9d1030ecd059ba8dd98c6a3edff8376d4/index.js#L23-L40
|
train
|
koajs/koa-hbs
|
index.js
|
Hbs
|
function Hbs () {
if (!(this instanceof Hbs)) {
return new Hbs();
}
this.handlebars = require('handlebars').create();
this.Utils = this.handlebars.Utils;
this.SafeString = this.handlebars.SafeString;
}
|
javascript
|
function Hbs () {
if (!(this instanceof Hbs)) {
return new Hbs();
}
this.handlebars = require('handlebars').create();
this.Utils = this.handlebars.Utils;
this.SafeString = this.handlebars.SafeString;
}
|
[
"function",
"Hbs",
"(",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"Hbs",
")",
")",
"{",
"return",
"new",
"Hbs",
"(",
")",
";",
"}",
"this",
".",
"handlebars",
"=",
"require",
"(",
"'handlebars'",
")",
".",
"create",
"(",
")",
";",
"this",
".",
"Utils",
"=",
"this",
".",
"handlebars",
".",
"Utils",
";",
"this",
".",
"SafeString",
"=",
"this",
".",
"handlebars",
".",
"SafeString",
";",
"}"
] |
Create new instance of `Hbs`
@api public
|
[
"Create",
"new",
"instance",
"of",
"Hbs"
] |
7a505cb9d1030ecd059ba8dd98c6a3edff8376d4
|
https://github.com/koajs/koa-hbs/blob/7a505cb9d1030ecd059ba8dd98c6a3edff8376d4/index.js#L100-L109
|
train
|
jonschlinkert/array-sort
|
index.js
|
arraySort
|
function arraySort(arr, props, opts) {
if (arr == null) {
return [];
}
if (!Array.isArray(arr)) {
throw new TypeError('array-sort expects an array.');
}
if (arguments.length === 1) {
return arr.sort();
}
var args = flatten([].slice.call(arguments, 1));
// if the last argument appears to be a plain object,
// it's not a valid `compare` arg, so it must be options.
if (typeOf(args[args.length - 1]) === 'object') {
opts = args.pop();
}
return arr.sort(sortBy(args, opts));
}
|
javascript
|
function arraySort(arr, props, opts) {
if (arr == null) {
return [];
}
if (!Array.isArray(arr)) {
throw new TypeError('array-sort expects an array.');
}
if (arguments.length === 1) {
return arr.sort();
}
var args = flatten([].slice.call(arguments, 1));
// if the last argument appears to be a plain object,
// it's not a valid `compare` arg, so it must be options.
if (typeOf(args[args.length - 1]) === 'object') {
opts = args.pop();
}
return arr.sort(sortBy(args, opts));
}
|
[
"function",
"arraySort",
"(",
"arr",
",",
"props",
",",
"opts",
")",
"{",
"if",
"(",
"arr",
"==",
"null",
")",
"{",
"return",
"[",
"]",
";",
"}",
"if",
"(",
"!",
"Array",
".",
"isArray",
"(",
"arr",
")",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'array-sort expects an array.'",
")",
";",
"}",
"if",
"(",
"arguments",
".",
"length",
"===",
"1",
")",
"{",
"return",
"arr",
".",
"sort",
"(",
")",
";",
"}",
"var",
"args",
"=",
"flatten",
"(",
"[",
"]",
".",
"slice",
".",
"call",
"(",
"arguments",
",",
"1",
")",
")",
";",
"if",
"(",
"typeOf",
"(",
"args",
"[",
"args",
".",
"length",
"-",
"1",
"]",
")",
"===",
"'object'",
")",
"{",
"opts",
"=",
"args",
".",
"pop",
"(",
")",
";",
"}",
"return",
"arr",
".",
"sort",
"(",
"sortBy",
"(",
"args",
",",
"opts",
")",
")",
";",
"}"
] |
Sort an array of objects by one or more properties.
@param {Array} `arr` The Array to sort.
@param {String|Array|Function} `props` One or more object paths or comparison functions.
@param {Object} `opts` Pass `{ reverse: true }` to reverse the sort order.
@return {Array} Returns a sorted array.
@api public
|
[
"Sort",
"an",
"array",
"of",
"objects",
"by",
"one",
"or",
"more",
"properties",
"."
] |
055c178975547166c3c78602e6dc134d3dc450f5
|
https://github.com/jonschlinkert/array-sort/blob/055c178975547166c3c78602e6dc134d3dc450f5/index.js#L24-L45
|
train
|
jonschlinkert/array-sort
|
index.js
|
sortBy
|
function sortBy(props, opts) {
opts = opts || {};
return function compareFn(a, b) {
var len = props.length, i = -1;
var result;
while (++i < len) {
result = compare(props[i], a, b);
if (result !== 0) {
break;
}
}
if (opts.reverse === true) {
return result * -1;
}
return result;
};
}
|
javascript
|
function sortBy(props, opts) {
opts = opts || {};
return function compareFn(a, b) {
var len = props.length, i = -1;
var result;
while (++i < len) {
result = compare(props[i], a, b);
if (result !== 0) {
break;
}
}
if (opts.reverse === true) {
return result * -1;
}
return result;
};
}
|
[
"function",
"sortBy",
"(",
"props",
",",
"opts",
")",
"{",
"opts",
"=",
"opts",
"||",
"{",
"}",
";",
"return",
"function",
"compareFn",
"(",
"a",
",",
"b",
")",
"{",
"var",
"len",
"=",
"props",
".",
"length",
",",
"i",
"=",
"-",
"1",
";",
"var",
"result",
";",
"while",
"(",
"++",
"i",
"<",
"len",
")",
"{",
"result",
"=",
"compare",
"(",
"props",
"[",
"i",
"]",
",",
"a",
",",
"b",
")",
";",
"if",
"(",
"result",
"!==",
"0",
")",
"{",
"break",
";",
"}",
"}",
"if",
"(",
"opts",
".",
"reverse",
"===",
"true",
")",
"{",
"return",
"result",
"*",
"-",
"1",
";",
"}",
"return",
"result",
";",
"}",
";",
"}"
] |
Iterate over each comparison property or function until `1` or `-1`
is returned.
@param {String|Array|Function} `props` One or more object paths or comparison functions.
@param {Object} `opts` Pass `{ reverse: true }` to reverse the sort order.
@return {Array}
|
[
"Iterate",
"over",
"each",
"comparison",
"property",
"or",
"function",
"until",
"1",
"or",
"-",
"1",
"is",
"returned",
"."
] |
055c178975547166c3c78602e6dc134d3dc450f5
|
https://github.com/jonschlinkert/array-sort/blob/055c178975547166c3c78602e6dc134d3dc450f5/index.js#L56-L74
|
train
|
gruntjs/grunt-contrib-handlebars
|
tasks/handlebars.js
|
function(filepath) {
var pieces = _.last(filepath.split('/')).split('.');
var name = _(pieces).without(_.last(pieces)).join('.'); // strips file extension
if (name.charAt(0) === '_') {
name = name.substr(1, name.length); // strips leading _ character
}
return name;
}
|
javascript
|
function(filepath) {
var pieces = _.last(filepath.split('/')).split('.');
var name = _(pieces).without(_.last(pieces)).join('.'); // strips file extension
if (name.charAt(0) === '_') {
name = name.substr(1, name.length); // strips leading _ character
}
return name;
}
|
[
"function",
"(",
"filepath",
")",
"{",
"var",
"pieces",
"=",
"_",
".",
"last",
"(",
"filepath",
".",
"split",
"(",
"'/'",
")",
")",
".",
"split",
"(",
"'.'",
")",
";",
"var",
"name",
"=",
"_",
"(",
"pieces",
")",
".",
"without",
"(",
"_",
".",
"last",
"(",
"pieces",
")",
")",
".",
"join",
"(",
"'.'",
")",
";",
"if",
"(",
"name",
".",
"charAt",
"(",
"0",
")",
"===",
"'_'",
")",
"{",
"name",
"=",
"name",
".",
"substr",
"(",
"1",
",",
"name",
".",
"length",
")",
";",
"}",
"return",
"name",
";",
"}"
] |
filename conversion for partials
|
[
"filename",
"conversion",
"for",
"partials"
] |
84e9d9e533cb600828998e93de30cf40e157a595
|
https://github.com/gruntjs/grunt-contrib-handlebars/blob/84e9d9e533cb600828998e93de30cf40e157a595/tasks/handlebars.js#L26-L33
|
train
|
|
indieisaconcept/grunt-styleguide
|
tasks/styleguide.js
|
function(/* Array */ files) {
var preprocessor;
if (_.isEmpty(files)) {
return preprocessor;
}
// collect all the possible extensions
// and remove duplicates
files = _.chain(files).map(function (/* string */ file) {
var ext = path.extname(file).split('.');
return ext[ext.length - 1];
}).uniq().value();
preprocessor = _.find(Object.keys(plugin.preprocessors), function (/* String */ key) {
var value = plugin.preprocessors[key],
exts = value.split(/[,\s]+/),
matches = _.filter(files, function (/* String */ ext) {
return exts.indexOf(ext) !== -1;
});
return !_.isEmpty(matches);
});
return preprocessor;
}
|
javascript
|
function(/* Array */ files) {
var preprocessor;
if (_.isEmpty(files)) {
return preprocessor;
}
// collect all the possible extensions
// and remove duplicates
files = _.chain(files).map(function (/* string */ file) {
var ext = path.extname(file).split('.');
return ext[ext.length - 1];
}).uniq().value();
preprocessor = _.find(Object.keys(plugin.preprocessors), function (/* String */ key) {
var value = plugin.preprocessors[key],
exts = value.split(/[,\s]+/),
matches = _.filter(files, function (/* String */ ext) {
return exts.indexOf(ext) !== -1;
});
return !_.isEmpty(matches);
});
return preprocessor;
}
|
[
"function",
"(",
"files",
")",
"{",
"var",
"preprocessor",
";",
"if",
"(",
"_",
".",
"isEmpty",
"(",
"files",
")",
")",
"{",
"return",
"preprocessor",
";",
"}",
"files",
"=",
"_",
".",
"chain",
"(",
"files",
")",
".",
"map",
"(",
"function",
"(",
"file",
")",
"{",
"var",
"ext",
"=",
"path",
".",
"extname",
"(",
"file",
")",
".",
"split",
"(",
"'.'",
")",
";",
"return",
"ext",
"[",
"ext",
".",
"length",
"-",
"1",
"]",
";",
"}",
")",
".",
"uniq",
"(",
")",
".",
"value",
"(",
")",
";",
"preprocessor",
"=",
"_",
".",
"find",
"(",
"Object",
".",
"keys",
"(",
"plugin",
".",
"preprocessors",
")",
",",
"function",
"(",
"key",
")",
"{",
"var",
"value",
"=",
"plugin",
".",
"preprocessors",
"[",
"key",
"]",
",",
"exts",
"=",
"value",
".",
"split",
"(",
"/",
"[,\\s]+",
"/",
")",
",",
"matches",
"=",
"_",
".",
"filter",
"(",
"files",
",",
"function",
"(",
"ext",
")",
"{",
"return",
"exts",
".",
"indexOf",
"(",
"ext",
")",
"!==",
"-",
"1",
";",
"}",
")",
";",
"return",
"!",
"_",
".",
"isEmpty",
"(",
"matches",
")",
";",
"}",
")",
";",
"return",
"preprocessor",
";",
"}"
] |
processor Determine the CSS processor to use based on an array of files
|
[
"processor",
"Determine",
"the",
"CSS",
"processor",
"to",
"use",
"based",
"on",
"an",
"array",
"of",
"files"
] |
0447f9e099eade810b61f71ad057d7ce79774095
|
https://github.com/indieisaconcept/grunt-styleguide/blob/0447f9e099eade810b61f71ad057d7ce79774095/tasks/styleguide.js#L109-L142
|
train
|
|
luciotato/waitfor
|
waitfor.js
|
function(err,data){
if (fiber.callbackAlreadyCalled)
throw new Error("Callback for function "+fnName+" called twice. Wait.for already resumed the execution.");
fiber.callbackAlreadyCalled = true;
fiber.err=err; //store err on fiber object
fiber.data=data; //store data on fiber object
if (!fiber.yielded) {//when callback is called *before* async function returns
// no need to "resume" because we never got the chance to "yield"
return;
}
else {
//resume fiber after "yield"
fiber.run();
}
}
|
javascript
|
function(err,data){
if (fiber.callbackAlreadyCalled)
throw new Error("Callback for function "+fnName+" called twice. Wait.for already resumed the execution.");
fiber.callbackAlreadyCalled = true;
fiber.err=err; //store err on fiber object
fiber.data=data; //store data on fiber object
if (!fiber.yielded) {//when callback is called *before* async function returns
// no need to "resume" because we never got the chance to "yield"
return;
}
else {
//resume fiber after "yield"
fiber.run();
}
}
|
[
"function",
"(",
"err",
",",
"data",
")",
"{",
"if",
"(",
"fiber",
".",
"callbackAlreadyCalled",
")",
"throw",
"new",
"Error",
"(",
"\"Callback for function \"",
"+",
"fnName",
"+",
"\" called twice. Wait.for already resumed the execution.\"",
")",
";",
"fiber",
".",
"callbackAlreadyCalled",
"=",
"true",
";",
"fiber",
".",
"err",
"=",
"err",
";",
"fiber",
".",
"data",
"=",
"data",
";",
"if",
"(",
"!",
"fiber",
".",
"yielded",
")",
"{",
"return",
";",
"}",
"else",
"{",
"fiber",
".",
"run",
"(",
")",
";",
"}",
"}"
] |
create a closure to resume on callback
|
[
"create",
"a",
"closure",
"to",
"resume",
"on",
"callback"
] |
4a5e155084dab3dbdbc42ed585b16c0600d20f3e
|
https://github.com/luciotato/waitfor/blob/4a5e155084dab3dbdbc42ed585b16c0600d20f3e/waitfor.js#L26-L40
|
train
|
|
luciotato/waitfor
|
examples/waitfor-demo.js
|
handler
|
function handler(req,res){
try{
res.writeHead(200, {'Content-Type': 'text/html'});
var start = new Date().getTime();
//console.log(start);
//read css, wait.for syntax:
var css = wait.for(fs.readFile,'style.css','utf8');
//read post, fancy syntax:
var content = wait.for(fs.readFile,'blogPost.txt','utf8');
//compose template, fancy syntax, as parameter:
var template = composeTemplate ( css, wait.for(fs.readFile,'blogTemplate.html','utf8') );
console.log('about to call hardToGetData...');
//call async, wait.for syntax, in a expression
var hardToGetData = "\n" + start.toString().substr(-5) +"<br>" + ( wait.for(longAsyncFn,'some data') );
console.log('hardToGetData=',hardToGetData);
var end = new Date().getTime();
hardToGetData += ', after '+(end-start)+' ms<br>';
hardToGetData += end.toString().substr(-5);
res.end( applyTemplate(template, formatPost ( content + hardToGetData) ) );
}
catch(err){
res.end('ERROR: '+err.message);
}
}
|
javascript
|
function handler(req,res){
try{
res.writeHead(200, {'Content-Type': 'text/html'});
var start = new Date().getTime();
//console.log(start);
//read css, wait.for syntax:
var css = wait.for(fs.readFile,'style.css','utf8');
//read post, fancy syntax:
var content = wait.for(fs.readFile,'blogPost.txt','utf8');
//compose template, fancy syntax, as parameter:
var template = composeTemplate ( css, wait.for(fs.readFile,'blogTemplate.html','utf8') );
console.log('about to call hardToGetData...');
//call async, wait.for syntax, in a expression
var hardToGetData = "\n" + start.toString().substr(-5) +"<br>" + ( wait.for(longAsyncFn,'some data') );
console.log('hardToGetData=',hardToGetData);
var end = new Date().getTime();
hardToGetData += ', after '+(end-start)+' ms<br>';
hardToGetData += end.toString().substr(-5);
res.end( applyTemplate(template, formatPost ( content + hardToGetData) ) );
}
catch(err){
res.end('ERROR: '+err.message);
}
}
|
[
"function",
"handler",
"(",
"req",
",",
"res",
")",
"{",
"try",
"{",
"res",
".",
"writeHead",
"(",
"200",
",",
"{",
"'Content-Type'",
":",
"'text/html'",
"}",
")",
";",
"var",
"start",
"=",
"new",
"Date",
"(",
")",
".",
"getTime",
"(",
")",
";",
"var",
"css",
"=",
"wait",
".",
"for",
"(",
"fs",
".",
"readFile",
",",
"'style.css'",
",",
"'utf8'",
")",
";",
"var",
"content",
"=",
"wait",
".",
"for",
"(",
"fs",
".",
"readFile",
",",
"'blogPost.txt'",
",",
"'utf8'",
")",
";",
"var",
"template",
"=",
"composeTemplate",
"(",
"css",
",",
"wait",
".",
"for",
"(",
"fs",
".",
"readFile",
",",
"'blogTemplate.html'",
",",
"'utf8'",
")",
")",
";",
"console",
".",
"log",
"(",
"'about to call hardToGetData...'",
")",
";",
"var",
"hardToGetData",
"=",
"\"\\n\"",
"+",
"\\n",
"+",
"start",
".",
"toString",
"(",
")",
".",
"substr",
"(",
"-",
"5",
")",
"+",
"\"<br>\"",
";",
"(",
"wait",
".",
"for",
"(",
"longAsyncFn",
",",
"'some data'",
")",
")",
"console",
".",
"log",
"(",
"'hardToGetData='",
",",
"hardToGetData",
")",
";",
"var",
"end",
"=",
"new",
"Date",
"(",
")",
".",
"getTime",
"(",
")",
";",
"hardToGetData",
"+=",
"', after '",
"+",
"(",
"end",
"-",
"start",
")",
"+",
"' ms<br>'",
";",
"hardToGetData",
"+=",
"end",
".",
"toString",
"(",
")",
".",
"substr",
"(",
"-",
"5",
")",
";",
"}",
"res",
".",
"end",
"(",
"applyTemplate",
"(",
"template",
",",
"formatPost",
"(",
"content",
"+",
"hardToGetData",
")",
")",
")",
";",
"}"
] |
handle request in a fiber
|
[
"handle",
"request",
"in",
"a",
"fiber"
] |
4a5e155084dab3dbdbc42ed585b16c0600d20f3e
|
https://github.com/luciotato/waitfor/blob/4a5e155084dab3dbdbc42ed585b16c0600d20f3e/examples/waitfor-demo.js#L40-L73
|
train
|
Mangopay/mangopay2-nodejs-sdk
|
lib/api.js
|
function(callback, options, params) {
var options = options || ((_.isObject(callback) && !_.isFunction(callback)) ? callback : {});
if (params) {
options = _.extend({}, options, params);
}
return options
}
|
javascript
|
function(callback, options, params) {
var options = options || ((_.isObject(callback) && !_.isFunction(callback)) ? callback : {});
if (params) {
options = _.extend({}, options, params);
}
return options
}
|
[
"function",
"(",
"callback",
",",
"options",
",",
"params",
")",
"{",
"var",
"options",
"=",
"options",
"||",
"(",
"(",
"_",
".",
"isObject",
"(",
"callback",
")",
"&&",
"!",
"_",
".",
"isFunction",
"(",
"callback",
")",
")",
"?",
"callback",
":",
"{",
"}",
")",
";",
"if",
"(",
"params",
")",
"{",
"options",
"=",
"_",
".",
"extend",
"(",
"{",
"}",
",",
"options",
",",
"params",
")",
";",
"}",
"return",
"options",
"}"
] |
Checks if callback is a function or not, and passes the options
@param {Object, Function} callback
@param {Object} options
@param {Object} params Additional params that extend options
|
[
"Checks",
"if",
"callback",
"is",
"a",
"function",
"or",
"not",
"and",
"passes",
"the",
"options"
] |
73c0699835877b3d2851c1fcd8fefb6a457b6e06
|
https://github.com/Mangopay/mangopay2-nodejs-sdk/blob/73c0699835877b3d2851c1fcd8fefb6a457b6e06/lib/api.js#L80-L87
|
train
|
|
Mangopay/mangopay2-nodejs-sdk
|
lib/api.js
|
function(method, callback, options) {
options = this._getOptions(callback, options);
if (this.config.debugMode) {
this.config.logClass(method, options);
}
/**
* If data has parse method, call it before passing data
*/
if (options.data && options.data instanceof this.models.EntityBase) {
options.data = this.buildRequestData(options.data);
} else if (options.data && options.data.toJSON) {
options.data = options.data.toJSON();
}
var self = this;
/**
* If there's no OAuthKey, request one
*/
if (!this.requestOptions.headers.Authorization || this.isExpired()) {
return new Promise(function(resolve, reject){
self.authorize()
.then(function(){
self.method.call(self, method, function(data, response){
// Check if we have to wrap data into a model
if (_.isFunction(callback)) {
callback(data, response);
}
}, options)
.then(resolve)
.catch(reject)
})
.catch(reject);
});
}
/**
* Extend default request options with custom ones, if present
*/
var requestOptions = _.extend({}, this.requestOptions, options);
/**
* If we have custom headers, we have to prevent them to override Authentication header
*/
if (options && options.headers) {
_.extend(requestOptions.headers, this.requestOptions.headers, options.headers);
}
/**
* Append the path placeholders in order to build the proper url for the request
*/
if (options && options.path) {
_.extend(requestOptions.path, this.requestOptions.path, options.path);
}
return this._requestApi(requestOptions, method, callback);
}
|
javascript
|
function(method, callback, options) {
options = this._getOptions(callback, options);
if (this.config.debugMode) {
this.config.logClass(method, options);
}
/**
* If data has parse method, call it before passing data
*/
if (options.data && options.data instanceof this.models.EntityBase) {
options.data = this.buildRequestData(options.data);
} else if (options.data && options.data.toJSON) {
options.data = options.data.toJSON();
}
var self = this;
/**
* If there's no OAuthKey, request one
*/
if (!this.requestOptions.headers.Authorization || this.isExpired()) {
return new Promise(function(resolve, reject){
self.authorize()
.then(function(){
self.method.call(self, method, function(data, response){
// Check if we have to wrap data into a model
if (_.isFunction(callback)) {
callback(data, response);
}
}, options)
.then(resolve)
.catch(reject)
})
.catch(reject);
});
}
/**
* Extend default request options with custom ones, if present
*/
var requestOptions = _.extend({}, this.requestOptions, options);
/**
* If we have custom headers, we have to prevent them to override Authentication header
*/
if (options && options.headers) {
_.extend(requestOptions.headers, this.requestOptions.headers, options.headers);
}
/**
* Append the path placeholders in order to build the proper url for the request
*/
if (options && options.path) {
_.extend(requestOptions.path, this.requestOptions.path, options.path);
}
return this._requestApi(requestOptions, method, callback);
}
|
[
"function",
"(",
"method",
",",
"callback",
",",
"options",
")",
"{",
"options",
"=",
"this",
".",
"_getOptions",
"(",
"callback",
",",
"options",
")",
";",
"if",
"(",
"this",
".",
"config",
".",
"debugMode",
")",
"{",
"this",
".",
"config",
".",
"logClass",
"(",
"method",
",",
"options",
")",
";",
"}",
"if",
"(",
"options",
".",
"data",
"&&",
"options",
".",
"data",
"instanceof",
"this",
".",
"models",
".",
"EntityBase",
")",
"{",
"options",
".",
"data",
"=",
"this",
".",
"buildRequestData",
"(",
"options",
".",
"data",
")",
";",
"}",
"else",
"if",
"(",
"options",
".",
"data",
"&&",
"options",
".",
"data",
".",
"toJSON",
")",
"{",
"options",
".",
"data",
"=",
"options",
".",
"data",
".",
"toJSON",
"(",
")",
";",
"}",
"var",
"self",
"=",
"this",
";",
"if",
"(",
"!",
"this",
".",
"requestOptions",
".",
"headers",
".",
"Authorization",
"||",
"this",
".",
"isExpired",
"(",
")",
")",
"{",
"return",
"new",
"Promise",
"(",
"function",
"(",
"resolve",
",",
"reject",
")",
"{",
"self",
".",
"authorize",
"(",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"self",
".",
"method",
".",
"call",
"(",
"self",
",",
"method",
",",
"function",
"(",
"data",
",",
"response",
")",
"{",
"if",
"(",
"_",
".",
"isFunction",
"(",
"callback",
")",
")",
"{",
"callback",
"(",
"data",
",",
"response",
")",
";",
"}",
"}",
",",
"options",
")",
".",
"then",
"(",
"resolve",
")",
".",
"catch",
"(",
"reject",
")",
"}",
")",
".",
"catch",
"(",
"reject",
")",
";",
"}",
")",
";",
"}",
"var",
"requestOptions",
"=",
"_",
".",
"extend",
"(",
"{",
"}",
",",
"this",
".",
"requestOptions",
",",
"options",
")",
";",
"if",
"(",
"options",
"&&",
"options",
".",
"headers",
")",
"{",
"_",
".",
"extend",
"(",
"requestOptions",
".",
"headers",
",",
"this",
".",
"requestOptions",
".",
"headers",
",",
"options",
".",
"headers",
")",
";",
"}",
"if",
"(",
"options",
"&&",
"options",
".",
"path",
")",
"{",
"_",
".",
"extend",
"(",
"requestOptions",
".",
"path",
",",
"this",
".",
"requestOptions",
".",
"path",
",",
"options",
".",
"path",
")",
";",
"}",
"return",
"this",
".",
"_requestApi",
"(",
"requestOptions",
",",
"method",
",",
"callback",
")",
";",
"}"
] |
Main API resource request method
@param {string} method Mangopay API method to be called
@param {function} callback Callback function
@param {object} options Hash of configuration to be passed to request
@returns {object} request promise
|
[
"Main",
"API",
"resource",
"request",
"method"
] |
73c0699835877b3d2851c1fcd8fefb6a457b6e06
|
https://github.com/Mangopay/mangopay2-nodejs-sdk/blob/73c0699835877b3d2851c1fcd8fefb6a457b6e06/lib/api.js#L96-L153
|
train
|
|
Mangopay/mangopay2-nodejs-sdk
|
lib/api.js
|
function(callback) {
var self = this;
var auth_post_data = querystring.stringify({
'grant_type': 'client_credentials'
});
return new Promise(function(resolve, reject){
self.client.methods.authentication_oauth(_.extend({}, self.requestOptions, {
data: auth_post_data,
headers: _.extend({}, self.requestOptions.headers, {
'Authorization': _getBasicAuthHash(self.config.clientId, self.config.clientApiKey),
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(auth_post_data)
})
}), function(data) {
// Authorization succeeded
if (data.token_type && data.access_token) {
_.extend(self.requestOptions.headers, {
'Authorization': data.token_type + ' ' + data.access_token
});
// Multiplying expires_in (seconds) by 1000 since JS getTime() is expressed in ms
self.authorizationExpireTime = new Date().getTime() + ( data.expires_in * 1000 );
resolve(data);
if (_.isFunction(callback)) {
callback(data);
}
} else {
reject(data);
}
}).on('error', function (err) { reject(err.message) });
});
}
|
javascript
|
function(callback) {
var self = this;
var auth_post_data = querystring.stringify({
'grant_type': 'client_credentials'
});
return new Promise(function(resolve, reject){
self.client.methods.authentication_oauth(_.extend({}, self.requestOptions, {
data: auth_post_data,
headers: _.extend({}, self.requestOptions.headers, {
'Authorization': _getBasicAuthHash(self.config.clientId, self.config.clientApiKey),
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(auth_post_data)
})
}), function(data) {
// Authorization succeeded
if (data.token_type && data.access_token) {
_.extend(self.requestOptions.headers, {
'Authorization': data.token_type + ' ' + data.access_token
});
// Multiplying expires_in (seconds) by 1000 since JS getTime() is expressed in ms
self.authorizationExpireTime = new Date().getTime() + ( data.expires_in * 1000 );
resolve(data);
if (_.isFunction(callback)) {
callback(data);
}
} else {
reject(data);
}
}).on('error', function (err) { reject(err.message) });
});
}
|
[
"function",
"(",
"callback",
")",
"{",
"var",
"self",
"=",
"this",
";",
"var",
"auth_post_data",
"=",
"querystring",
".",
"stringify",
"(",
"{",
"'grant_type'",
":",
"'client_credentials'",
"}",
")",
";",
"return",
"new",
"Promise",
"(",
"function",
"(",
"resolve",
",",
"reject",
")",
"{",
"self",
".",
"client",
".",
"methods",
".",
"authentication_oauth",
"(",
"_",
".",
"extend",
"(",
"{",
"}",
",",
"self",
".",
"requestOptions",
",",
"{",
"data",
":",
"auth_post_data",
",",
"headers",
":",
"_",
".",
"extend",
"(",
"{",
"}",
",",
"self",
".",
"requestOptions",
".",
"headers",
",",
"{",
"'Authorization'",
":",
"_getBasicAuthHash",
"(",
"self",
".",
"config",
".",
"clientId",
",",
"self",
".",
"config",
".",
"clientApiKey",
")",
",",
"'Content-Type'",
":",
"'application/x-www-form-urlencoded'",
",",
"'Content-Length'",
":",
"Buffer",
".",
"byteLength",
"(",
"auth_post_data",
")",
"}",
")",
"}",
")",
",",
"function",
"(",
"data",
")",
"{",
"if",
"(",
"data",
".",
"token_type",
"&&",
"data",
".",
"access_token",
")",
"{",
"_",
".",
"extend",
"(",
"self",
".",
"requestOptions",
".",
"headers",
",",
"{",
"'Authorization'",
":",
"data",
".",
"token_type",
"+",
"' '",
"+",
"data",
".",
"access_token",
"}",
")",
";",
"self",
".",
"authorizationExpireTime",
"=",
"new",
"Date",
"(",
")",
".",
"getTime",
"(",
")",
"+",
"(",
"data",
".",
"expires_in",
"*",
"1000",
")",
";",
"resolve",
"(",
"data",
")",
";",
"if",
"(",
"_",
".",
"isFunction",
"(",
"callback",
")",
")",
"{",
"callback",
"(",
"data",
")",
";",
"}",
"}",
"else",
"{",
"reject",
"(",
"data",
")",
";",
"}",
"}",
")",
".",
"on",
"(",
"'error'",
",",
"function",
"(",
"err",
")",
"{",
"reject",
"(",
"err",
".",
"message",
")",
"}",
")",
";",
"}",
")",
";",
"}"
] |
OAuth2 authorization mechanism. After authorization request, calls the callback with returned authorization data
@param {function} callback
@returns {object} request promise
|
[
"OAuth2",
"authorization",
"mechanism",
".",
"After",
"authorization",
"request",
"calls",
"the",
"callback",
"with",
"returned",
"authorization",
"data"
] |
73c0699835877b3d2851c1fcd8fefb6a457b6e06
|
https://github.com/Mangopay/mangopay2-nodejs-sdk/blob/73c0699835877b3d2851c1fcd8fefb6a457b6e06/lib/api.js#L262-L294
|
train
|
|
Mangopay/mangopay2-nodejs-sdk
|
lib/api.js
|
function() {
var self = this;
// Read all files from ./services and add them to this object
// ex: services/User.js becomes mangopay.Users
var servicesRoot = path.join(__dirname, 'services');
fs.readdirSync(servicesRoot).forEach(function (file) {
var serviceName = file.match(/(.*)\.js/)[1];
var ServiceClass = require(servicesRoot + '/' + file);
self[serviceName] = new ServiceClass();
self[serviceName]._api = self;
});
// Read all files from ./models and add them to this object
// ex: models/User.js becomes mangopay.models.User
var modelsRoot = path.join(__dirname, 'models');
self.models = {};
fs.readdirSync(modelsRoot).forEach(function (file) {
var modelName = file.match(/(.*)\.js/)[1];
self.models[modelName] = require(modelsRoot + '/' + file);
});
}
|
javascript
|
function() {
var self = this;
// Read all files from ./services and add them to this object
// ex: services/User.js becomes mangopay.Users
var servicesRoot = path.join(__dirname, 'services');
fs.readdirSync(servicesRoot).forEach(function (file) {
var serviceName = file.match(/(.*)\.js/)[1];
var ServiceClass = require(servicesRoot + '/' + file);
self[serviceName] = new ServiceClass();
self[serviceName]._api = self;
});
// Read all files from ./models and add them to this object
// ex: models/User.js becomes mangopay.models.User
var modelsRoot = path.join(__dirname, 'models');
self.models = {};
fs.readdirSync(modelsRoot).forEach(function (file) {
var modelName = file.match(/(.*)\.js/)[1];
self.models[modelName] = require(modelsRoot + '/' + file);
});
}
|
[
"function",
"(",
")",
"{",
"var",
"self",
"=",
"this",
";",
"var",
"servicesRoot",
"=",
"path",
".",
"join",
"(",
"__dirname",
",",
"'services'",
")",
";",
"fs",
".",
"readdirSync",
"(",
"servicesRoot",
")",
".",
"forEach",
"(",
"function",
"(",
"file",
")",
"{",
"var",
"serviceName",
"=",
"file",
".",
"match",
"(",
"/",
"(.*)\\.js",
"/",
")",
"[",
"1",
"]",
";",
"var",
"ServiceClass",
"=",
"require",
"(",
"servicesRoot",
"+",
"'/'",
"+",
"file",
")",
";",
"self",
"[",
"serviceName",
"]",
"=",
"new",
"ServiceClass",
"(",
")",
";",
"self",
"[",
"serviceName",
"]",
".",
"_api",
"=",
"self",
";",
"}",
")",
";",
"var",
"modelsRoot",
"=",
"path",
".",
"join",
"(",
"__dirname",
",",
"'models'",
")",
";",
"self",
".",
"models",
"=",
"{",
"}",
";",
"fs",
".",
"readdirSync",
"(",
"modelsRoot",
")",
".",
"forEach",
"(",
"function",
"(",
"file",
")",
"{",
"var",
"modelName",
"=",
"file",
".",
"match",
"(",
"/",
"(.*)\\.js",
"/",
")",
"[",
"1",
"]",
";",
"self",
".",
"models",
"[",
"modelName",
"]",
"=",
"require",
"(",
"modelsRoot",
"+",
"'/'",
"+",
"file",
")",
";",
"}",
")",
";",
"}"
] |
Populates the SDK object with the services
|
[
"Populates",
"the",
"SDK",
"object",
"with",
"the",
"services"
] |
73c0699835877b3d2851c1fcd8fefb6a457b6e06
|
https://github.com/Mangopay/mangopay2-nodejs-sdk/blob/73c0699835877b3d2851c1fcd8fefb6a457b6e06/lib/api.js#L305-L325
|
train
|
|
36node/sketch
|
packages/cli/config-overrides.js
|
mockServer
|
function mockServer(app) {
const jsonRouter = jsonServer.router(db);
const shouldMockReq = req => {
return (
req.method !== "GET" ||
(req.headers.accept &&
req.headers.accept.indexOf("application/json") !== -1)
);
};
if (serverOpts.delay) {
app.use((req, res, next) => {
if (shouldMockReq(req)) {
return pause(serverOpts.delay)(req, res, next);
}
return next();
});
}
app.use(jsonServer.rewriter(rewrites));
// user defined routers
app.use(jsonServer.bodyParser);
// user query normalizr
app.use((req, res, next) => {
if (shouldMockReq(req)) {
req.query = toJsonServer(req.query);
return next();
}
return next();
});
routers.forEach(router => app.use(router));
// json server router
app.use((req, res, next) => {
if (shouldMockReq(req)) {
return jsonRouter(req, res, next);
}
return next();
});
return app;
}
|
javascript
|
function mockServer(app) {
const jsonRouter = jsonServer.router(db);
const shouldMockReq = req => {
return (
req.method !== "GET" ||
(req.headers.accept &&
req.headers.accept.indexOf("application/json") !== -1)
);
};
if (serverOpts.delay) {
app.use((req, res, next) => {
if (shouldMockReq(req)) {
return pause(serverOpts.delay)(req, res, next);
}
return next();
});
}
app.use(jsonServer.rewriter(rewrites));
// user defined routers
app.use(jsonServer.bodyParser);
// user query normalizr
app.use((req, res, next) => {
if (shouldMockReq(req)) {
req.query = toJsonServer(req.query);
return next();
}
return next();
});
routers.forEach(router => app.use(router));
// json server router
app.use((req, res, next) => {
if (shouldMockReq(req)) {
return jsonRouter(req, res, next);
}
return next();
});
return app;
}
|
[
"function",
"mockServer",
"(",
"app",
")",
"{",
"const",
"jsonRouter",
"=",
"jsonServer",
".",
"router",
"(",
"db",
")",
";",
"const",
"shouldMockReq",
"=",
"req",
"=>",
"{",
"return",
"(",
"req",
".",
"method",
"!==",
"\"GET\"",
"||",
"(",
"req",
".",
"headers",
".",
"accept",
"&&",
"req",
".",
"headers",
".",
"accept",
".",
"indexOf",
"(",
"\"application/json\"",
")",
"!==",
"-",
"1",
")",
")",
";",
"}",
";",
"if",
"(",
"serverOpts",
".",
"delay",
")",
"{",
"app",
".",
"use",
"(",
"(",
"req",
",",
"res",
",",
"next",
")",
"=>",
"{",
"if",
"(",
"shouldMockReq",
"(",
"req",
")",
")",
"{",
"return",
"pause",
"(",
"serverOpts",
".",
"delay",
")",
"(",
"req",
",",
"res",
",",
"next",
")",
";",
"}",
"return",
"next",
"(",
")",
";",
"}",
")",
";",
"}",
"app",
".",
"use",
"(",
"jsonServer",
".",
"rewriter",
"(",
"rewrites",
")",
")",
";",
"app",
".",
"use",
"(",
"jsonServer",
".",
"bodyParser",
")",
";",
"app",
".",
"use",
"(",
"(",
"req",
",",
"res",
",",
"next",
")",
"=>",
"{",
"if",
"(",
"shouldMockReq",
"(",
"req",
")",
")",
"{",
"req",
".",
"query",
"=",
"toJsonServer",
"(",
"req",
".",
"query",
")",
";",
"return",
"next",
"(",
")",
";",
"}",
"return",
"next",
"(",
")",
";",
"}",
")",
";",
"routers",
".",
"forEach",
"(",
"router",
"=>",
"app",
".",
"use",
"(",
"router",
")",
")",
";",
"app",
".",
"use",
"(",
"(",
"req",
",",
"res",
",",
"next",
")",
"=>",
"{",
"if",
"(",
"shouldMockReq",
"(",
"req",
")",
")",
"{",
"return",
"jsonRouter",
"(",
"req",
",",
"res",
",",
"next",
")",
";",
"}",
"return",
"next",
"(",
")",
";",
"}",
")",
";",
"return",
"app",
";",
"}"
] |
mock server hoc
@param {Express.Application} app
|
[
"mock",
"server",
"hoc"
] |
a4e96c4f2f1fe524357afcd31a555e0da5ee17a9
|
https://github.com/36node/sketch/blob/a4e96c4f2f1fe524357afcd31a555e0da5ee17a9/packages/cli/config-overrides.js#L101-L146
|
train
|
36node/sketch
|
packages/fastman/bin/fastman-import.js
|
importing
|
async function importing(file) {
await helpers.checkApiKey();
if (typeof file === "undefined") {
stderr("collection file not given!");
process.exit(1);
}
const collection = jsonfile.readFileSync(file);
const collections = await apis.listCollections();
const { info = {} } = collection;
const found = collections.find(c => c.name === info.name);
if (found) {
await apis.updateCollection(found.id, collection);
stdout("updated collection", info.name);
} else {
await apis.createCollection(collection);
stdout("created collection", info.name);
}
}
|
javascript
|
async function importing(file) {
await helpers.checkApiKey();
if (typeof file === "undefined") {
stderr("collection file not given!");
process.exit(1);
}
const collection = jsonfile.readFileSync(file);
const collections = await apis.listCollections();
const { info = {} } = collection;
const found = collections.find(c => c.name === info.name);
if (found) {
await apis.updateCollection(found.id, collection);
stdout("updated collection", info.name);
} else {
await apis.createCollection(collection);
stdout("created collection", info.name);
}
}
|
[
"async",
"function",
"importing",
"(",
"file",
")",
"{",
"await",
"helpers",
".",
"checkApiKey",
"(",
")",
";",
"if",
"(",
"typeof",
"file",
"===",
"\"undefined\"",
")",
"{",
"stderr",
"(",
"\"collection file not given!\"",
")",
";",
"process",
".",
"exit",
"(",
"1",
")",
";",
"}",
"const",
"collection",
"=",
"jsonfile",
".",
"readFileSync",
"(",
"file",
")",
";",
"const",
"collections",
"=",
"await",
"apis",
".",
"listCollections",
"(",
")",
";",
"const",
"{",
"info",
"=",
"{",
"}",
"}",
"=",
"collection",
";",
"const",
"found",
"=",
"collections",
".",
"find",
"(",
"c",
"=>",
"c",
".",
"name",
"===",
"info",
".",
"name",
")",
";",
"if",
"(",
"found",
")",
"{",
"await",
"apis",
".",
"updateCollection",
"(",
"found",
".",
"id",
",",
"collection",
")",
";",
"stdout",
"(",
"\"updated collection\"",
",",
"info",
".",
"name",
")",
";",
"}",
"else",
"{",
"await",
"apis",
".",
"createCollection",
"(",
"collection",
")",
";",
"stdout",
"(",
"\"created collection\"",
",",
"info",
".",
"name",
")",
";",
"}",
"}"
] |
import collection file
@param {string} file collection file path
|
[
"import",
"collection",
"file"
] |
a4e96c4f2f1fe524357afcd31a555e0da5ee17a9
|
https://github.com/36node/sketch/blob/a4e96c4f2f1fe524357afcd31a555e0da5ee17a9/packages/fastman/bin/fastman-import.js#L16-L36
|
train
|
z-hao-wang/react-native-rsa
|
lib/rsa.js
|
RSAGetPublicString
|
function RSAGetPublicString() {
var exportObj = {n: this.n.toString(16), e: this.e.toString(16)};
if (exportObj.n.length % 2 == 1) {
exportObj.n = '0' + exportObj.n; // pad them with 0
}
return JSON.stringify(exportObj);
}
|
javascript
|
function RSAGetPublicString() {
var exportObj = {n: this.n.toString(16), e: this.e.toString(16)};
if (exportObj.n.length % 2 == 1) {
exportObj.n = '0' + exportObj.n; // pad them with 0
}
return JSON.stringify(exportObj);
}
|
[
"function",
"RSAGetPublicString",
"(",
")",
"{",
"var",
"exportObj",
"=",
"{",
"n",
":",
"this",
".",
"n",
".",
"toString",
"(",
"16",
")",
",",
"e",
":",
"this",
".",
"e",
".",
"toString",
"(",
"16",
")",
"}",
";",
"if",
"(",
"exportObj",
".",
"n",
".",
"length",
"%",
"2",
"==",
"1",
")",
"{",
"exportObj",
".",
"n",
"=",
"'0'",
"+",
"exportObj",
".",
"n",
";",
"}",
"return",
"JSON",
".",
"stringify",
"(",
"exportObj",
")",
";",
"}"
] |
return modulus and public exponent as string
|
[
"return",
"modulus",
"and",
"public",
"exponent",
"as",
"string"
] |
112ecd2e78006221c579d4949d670adad3189fa5
|
https://github.com/z-hao-wang/react-native-rsa/blob/112ecd2e78006221c579d4949d670adad3189fa5/lib/rsa.js#L77-L83
|
train
|
z-hao-wang/react-native-rsa
|
lib/rsa.js
|
RSASetPrivate
|
function RSASetPrivate(N,E,D) {
if(N != null && E != null && N.length > 0 && E.length > 0) {
this.n = parseBigInt(N,16);
this.e = parseInt(E,16);
this.d = parseBigInt(D,16);
}
else
console.log("Invalid RSA private key");
}
|
javascript
|
function RSASetPrivate(N,E,D) {
if(N != null && E != null && N.length > 0 && E.length > 0) {
this.n = parseBigInt(N,16);
this.e = parseInt(E,16);
this.d = parseBigInt(D,16);
}
else
console.log("Invalid RSA private key");
}
|
[
"function",
"RSASetPrivate",
"(",
"N",
",",
"E",
",",
"D",
")",
"{",
"if",
"(",
"N",
"!=",
"null",
"&&",
"E",
"!=",
"null",
"&&",
"N",
".",
"length",
">",
"0",
"&&",
"E",
".",
"length",
">",
"0",
")",
"{",
"this",
".",
"n",
"=",
"parseBigInt",
"(",
"N",
",",
"16",
")",
";",
"this",
".",
"e",
"=",
"parseInt",
"(",
"E",
",",
"16",
")",
";",
"this",
".",
"d",
"=",
"parseBigInt",
"(",
"D",
",",
"16",
")",
";",
"}",
"else",
"console",
".",
"log",
"(",
"\"Invalid RSA private key\"",
")",
";",
"}"
] |
Set the private key fields N, e, and d from hex strings
|
[
"Set",
"the",
"private",
"key",
"fields",
"N",
"e",
"and",
"d",
"from",
"hex",
"strings"
] |
112ecd2e78006221c579d4949d670adad3189fa5
|
https://github.com/z-hao-wang/react-native-rsa/blob/112ecd2e78006221c579d4949d670adad3189fa5/lib/rsa.js#L194-L202
|
train
|
jpravetz/node-datatable
|
lib/builder.js
|
buildLimitPartial
|
function buildLimitPartial(requestQuery) {
var sLimit = "";
if (requestQuery && requestQuery.start !== undefined && self.dbType !== 'oracle') {
var start = parseInt(requestQuery.start, 10);
if (start >= 0) {
var len = parseInt(requestQuery.length, 10);
sLimit = (self.dbType === 'postgres') ? " OFFSET " + String(start) + " LIMIT " : " LIMIT " + String(start) + ", ";
sLimit += ( len > 0 ) ? String(len) : String(DEFAULT_LIMIT);
}
}
return sLimit;
}
|
javascript
|
function buildLimitPartial(requestQuery) {
var sLimit = "";
if (requestQuery && requestQuery.start !== undefined && self.dbType !== 'oracle') {
var start = parseInt(requestQuery.start, 10);
if (start >= 0) {
var len = parseInt(requestQuery.length, 10);
sLimit = (self.dbType === 'postgres') ? " OFFSET " + String(start) + " LIMIT " : " LIMIT " + String(start) + ", ";
sLimit += ( len > 0 ) ? String(len) : String(DEFAULT_LIMIT);
}
}
return sLimit;
}
|
[
"function",
"buildLimitPartial",
"(",
"requestQuery",
")",
"{",
"var",
"sLimit",
"=",
"\"\"",
";",
"if",
"(",
"requestQuery",
"&&",
"requestQuery",
".",
"start",
"!==",
"undefined",
"&&",
"self",
".",
"dbType",
"!==",
"'oracle'",
")",
"{",
"var",
"start",
"=",
"parseInt",
"(",
"requestQuery",
".",
"start",
",",
"10",
")",
";",
"if",
"(",
"start",
">=",
"0",
")",
"{",
"var",
"len",
"=",
"parseInt",
"(",
"requestQuery",
".",
"length",
",",
"10",
")",
";",
"sLimit",
"=",
"(",
"self",
".",
"dbType",
"===",
"'postgres'",
")",
"?",
"\" OFFSET \"",
"+",
"String",
"(",
"start",
")",
"+",
"\" LIMIT \"",
":",
"\" LIMIT \"",
"+",
"String",
"(",
"start",
")",
"+",
"\", \"",
";",
"sLimit",
"+=",
"(",
"len",
">",
"0",
")",
"?",
"String",
"(",
"len",
")",
":",
"String",
"(",
"DEFAULT_LIMIT",
")",
";",
"}",
"}",
"return",
"sLimit",
";",
"}"
] |
Build a LIMIT clause
@param requestQuery The Datatable query string (we look at length and start)
@return {String} The LIMIT clause
|
[
"Build",
"a",
"LIMIT",
"clause"
] |
6166ed2bc50f1bcd8e6f2b170a58fc5e75e78bd5
|
https://github.com/jpravetz/node-datatable/blob/6166ed2bc50f1bcd8e6f2b170a58fc5e75e78bd5/lib/builder.js#L234-L245
|
train
|
jpravetz/node-datatable
|
lib/builder.js
|
buildSelectPartial
|
function buildSelectPartial() {
var query = "SELECT ";
query += self.sSelectSql ? self.sSelectSql : "*";
query += " FROM ";
query += self.sFromSql ? self.sFromSql : self.sTableName;
return query;
}
|
javascript
|
function buildSelectPartial() {
var query = "SELECT ";
query += self.sSelectSql ? self.sSelectSql : "*";
query += " FROM ";
query += self.sFromSql ? self.sFromSql : self.sTableName;
return query;
}
|
[
"function",
"buildSelectPartial",
"(",
")",
"{",
"var",
"query",
"=",
"\"SELECT \"",
";",
"query",
"+=",
"self",
".",
"sSelectSql",
"?",
"self",
".",
"sSelectSql",
":",
"\"*\"",
";",
"query",
"+=",
"\" FROM \"",
";",
"query",
"+=",
"self",
".",
"sFromSql",
"?",
"self",
".",
"sFromSql",
":",
"self",
".",
"sTableName",
";",
"return",
"query",
";",
"}"
] |
Build the base SELECT statement.
@return {String} The SELECT partial
|
[
"Build",
"the",
"base",
"SELECT",
"statement",
"."
] |
6166ed2bc50f1bcd8e6f2b170a58fc5e75e78bd5
|
https://github.com/jpravetz/node-datatable/blob/6166ed2bc50f1bcd8e6f2b170a58fc5e75e78bd5/lib/builder.js#L251-L257
|
train
|
jpravetz/node-datatable
|
lib/builder.js
|
buildQuery
|
function buildQuery(requestQuery) {
var queries = {};
if (typeof requestQuery !== 'object')
return queries;
var searchString = sanitize(_u.isObject(requestQuery.search) ? requestQuery.search.value : '');
self.oRequestQuery = requestQuery;
var useStmt = buildSetDatabaseOrSchemaStatement();
if (useStmt) {
queries.changeDatabaseOrSchema = useStmt;
}
queries.recordsTotal = buildCountStatement(requestQuery);
if (searchString) {
queries.recordsFiltered = buildCountStatement(requestQuery);
}
var query = buildSelectPartial();
query += buildWherePartial(requestQuery);
query += buildGroupByPartial();
query += buildOrderingPartial(requestQuery);
query += buildLimitPartial(requestQuery);
if (self.dbType === 'oracle'){
var start = parseInt(requestQuery.start, 10);
var len = parseInt(requestQuery.length, 10);
if (len >= 0 && start >= 0) {
query = 'SELECT * FROM (SELECT a.*, ROWNUM rnum FROM (' + query + ') ';
query += 'a)' + ' WHERE rnum BETWEEN ' + (start + 1) + ' AND ' + (start + len);
}
}
queries.select = query;
return queries;
}
|
javascript
|
function buildQuery(requestQuery) {
var queries = {};
if (typeof requestQuery !== 'object')
return queries;
var searchString = sanitize(_u.isObject(requestQuery.search) ? requestQuery.search.value : '');
self.oRequestQuery = requestQuery;
var useStmt = buildSetDatabaseOrSchemaStatement();
if (useStmt) {
queries.changeDatabaseOrSchema = useStmt;
}
queries.recordsTotal = buildCountStatement(requestQuery);
if (searchString) {
queries.recordsFiltered = buildCountStatement(requestQuery);
}
var query = buildSelectPartial();
query += buildWherePartial(requestQuery);
query += buildGroupByPartial();
query += buildOrderingPartial(requestQuery);
query += buildLimitPartial(requestQuery);
if (self.dbType === 'oracle'){
var start = parseInt(requestQuery.start, 10);
var len = parseInt(requestQuery.length, 10);
if (len >= 0 && start >= 0) {
query = 'SELECT * FROM (SELECT a.*, ROWNUM rnum FROM (' + query + ') ';
query += 'a)' + ' WHERE rnum BETWEEN ' + (start + 1) + ' AND ' + (start + len);
}
}
queries.select = query;
return queries;
}
|
[
"function",
"buildQuery",
"(",
"requestQuery",
")",
"{",
"var",
"queries",
"=",
"{",
"}",
";",
"if",
"(",
"typeof",
"requestQuery",
"!==",
"'object'",
")",
"return",
"queries",
";",
"var",
"searchString",
"=",
"sanitize",
"(",
"_u",
".",
"isObject",
"(",
"requestQuery",
".",
"search",
")",
"?",
"requestQuery",
".",
"search",
".",
"value",
":",
"''",
")",
";",
"self",
".",
"oRequestQuery",
"=",
"requestQuery",
";",
"var",
"useStmt",
"=",
"buildSetDatabaseOrSchemaStatement",
"(",
")",
";",
"if",
"(",
"useStmt",
")",
"{",
"queries",
".",
"changeDatabaseOrSchema",
"=",
"useStmt",
";",
"}",
"queries",
".",
"recordsTotal",
"=",
"buildCountStatement",
"(",
"requestQuery",
")",
";",
"if",
"(",
"searchString",
")",
"{",
"queries",
".",
"recordsFiltered",
"=",
"buildCountStatement",
"(",
"requestQuery",
")",
";",
"}",
"var",
"query",
"=",
"buildSelectPartial",
"(",
")",
";",
"query",
"+=",
"buildWherePartial",
"(",
"requestQuery",
")",
";",
"query",
"+=",
"buildGroupByPartial",
"(",
")",
";",
"query",
"+=",
"buildOrderingPartial",
"(",
"requestQuery",
")",
";",
"query",
"+=",
"buildLimitPartial",
"(",
"requestQuery",
")",
";",
"if",
"(",
"self",
".",
"dbType",
"===",
"'oracle'",
")",
"{",
"var",
"start",
"=",
"parseInt",
"(",
"requestQuery",
".",
"start",
",",
"10",
")",
";",
"var",
"len",
"=",
"parseInt",
"(",
"requestQuery",
".",
"length",
",",
"10",
")",
";",
"if",
"(",
"len",
">=",
"0",
"&&",
"start",
">=",
"0",
")",
"{",
"query",
"=",
"'SELECT * FROM (SELECT a.*, ROWNUM rnum FROM ('",
"+",
"query",
"+",
"') '",
";",
"query",
"+=",
"'a)'",
"+",
"' WHERE rnum BETWEEN '",
"+",
"(",
"start",
"+",
"1",
")",
"+",
"' AND '",
"+",
"(",
"start",
"+",
"len",
")",
";",
"}",
"}",
"queries",
".",
"select",
"=",
"query",
";",
"return",
"queries",
";",
"}"
] |
Build an array of query strings based on the Datatable parameters
@param requestQuery The datatable parameters that are generated by the client
@return {Object} An array of query strings, each including a terminating semicolon.
|
[
"Build",
"an",
"array",
"of",
"query",
"strings",
"based",
"on",
"the",
"Datatable",
"parameters"
] |
6166ed2bc50f1bcd8e6f2b170a58fc5e75e78bd5
|
https://github.com/jpravetz/node-datatable/blob/6166ed2bc50f1bcd8e6f2b170a58fc5e75e78bd5/lib/builder.js#L264-L293
|
train
|
jpravetz/node-datatable
|
lib/builder.js
|
parseResponse
|
function parseResponse(queryResult) {
var oQuery = self.oRequestQuery;
var result = { recordsFiltered: 0, recordsTotal: 0 };
if (oQuery && typeof oQuery.draw === 'string') {
// Cast for security reasons, as per http://datatables.net/usage/server-side
result.draw = parseInt(oQuery.draw,10);
} else {
result.draw = 0;
}
if (_u.isObject(queryResult) && _u.keys(queryResult).length > 1) {
result.recordsFiltered = result.recordsTotal = extractResponseVal(queryResult.recordsTotal) || 0;
if (queryResult.recordsFiltered) {
result.recordsFiltered = extractResponseVal(queryResult.recordsFiltered) || 0;
}
result.data = queryResult.select;
}
return result;
}
|
javascript
|
function parseResponse(queryResult) {
var oQuery = self.oRequestQuery;
var result = { recordsFiltered: 0, recordsTotal: 0 };
if (oQuery && typeof oQuery.draw === 'string') {
// Cast for security reasons, as per http://datatables.net/usage/server-side
result.draw = parseInt(oQuery.draw,10);
} else {
result.draw = 0;
}
if (_u.isObject(queryResult) && _u.keys(queryResult).length > 1) {
result.recordsFiltered = result.recordsTotal = extractResponseVal(queryResult.recordsTotal) || 0;
if (queryResult.recordsFiltered) {
result.recordsFiltered = extractResponseVal(queryResult.recordsFiltered) || 0;
}
result.data = queryResult.select;
}
return result;
}
|
[
"function",
"parseResponse",
"(",
"queryResult",
")",
"{",
"var",
"oQuery",
"=",
"self",
".",
"oRequestQuery",
";",
"var",
"result",
"=",
"{",
"recordsFiltered",
":",
"0",
",",
"recordsTotal",
":",
"0",
"}",
";",
"if",
"(",
"oQuery",
"&&",
"typeof",
"oQuery",
".",
"draw",
"===",
"'string'",
")",
"{",
"result",
".",
"draw",
"=",
"parseInt",
"(",
"oQuery",
".",
"draw",
",",
"10",
")",
";",
"}",
"else",
"{",
"result",
".",
"draw",
"=",
"0",
";",
"}",
"if",
"(",
"_u",
".",
"isObject",
"(",
"queryResult",
")",
"&&",
"_u",
".",
"keys",
"(",
"queryResult",
")",
".",
"length",
">",
"1",
")",
"{",
"result",
".",
"recordsFiltered",
"=",
"result",
".",
"recordsTotal",
"=",
"extractResponseVal",
"(",
"queryResult",
".",
"recordsTotal",
")",
"||",
"0",
";",
"if",
"(",
"queryResult",
".",
"recordsFiltered",
")",
"{",
"result",
".",
"recordsFiltered",
"=",
"extractResponseVal",
"(",
"queryResult",
".",
"recordsFiltered",
")",
"||",
"0",
";",
"}",
"result",
".",
"data",
"=",
"queryResult",
".",
"select",
";",
"}",
"return",
"result",
";",
"}"
] |
Parse the responses from the database and build a Datatable response object.
@param queryResult An array of SQL response objects, each of which must, in order, correspond with a query string
returned by buildQuery.
@return {Object} A Datatable reply that is suitable for sending in a response to the client.
|
[
"Parse",
"the",
"responses",
"from",
"the",
"database",
"and",
"build",
"a",
"Datatable",
"response",
"object",
"."
] |
6166ed2bc50f1bcd8e6f2b170a58fc5e75e78bd5
|
https://github.com/jpravetz/node-datatable/blob/6166ed2bc50f1bcd8e6f2b170a58fc5e75e78bd5/lib/builder.js#L301-L318
|
train
|
jpravetz/node-datatable
|
lib/builder.js
|
filteredResult
|
function filteredResult(obj, count) {
if (obj) {
var result = _u.omit(obj, self.sAjaxDataProp );
result.aaLength = obj[self.sAjaxDataProp] ? obj[self.sAjaxDataProp].length : 0;
result[self.sAjaxDataProp] = [];
var count = count ? Math.min(count, result.aaLength) : result.aaLength;
for (var idx = 0; idx < count; ++idx) {
result[self.sAjaxDataProp].push(obj[self.sAjaxDataProp][idx]);
}
return result;
}
return null;
}
|
javascript
|
function filteredResult(obj, count) {
if (obj) {
var result = _u.omit(obj, self.sAjaxDataProp );
result.aaLength = obj[self.sAjaxDataProp] ? obj[self.sAjaxDataProp].length : 0;
result[self.sAjaxDataProp] = [];
var count = count ? Math.min(count, result.aaLength) : result.aaLength;
for (var idx = 0; idx < count; ++idx) {
result[self.sAjaxDataProp].push(obj[self.sAjaxDataProp][idx]);
}
return result;
}
return null;
}
|
[
"function",
"filteredResult",
"(",
"obj",
",",
"count",
")",
"{",
"if",
"(",
"obj",
")",
"{",
"var",
"result",
"=",
"_u",
".",
"omit",
"(",
"obj",
",",
"self",
".",
"sAjaxDataProp",
")",
";",
"result",
".",
"aaLength",
"=",
"obj",
"[",
"self",
".",
"sAjaxDataProp",
"]",
"?",
"obj",
"[",
"self",
".",
"sAjaxDataProp",
"]",
".",
"length",
":",
"0",
";",
"result",
"[",
"self",
".",
"sAjaxDataProp",
"]",
"=",
"[",
"]",
";",
"var",
"count",
"=",
"count",
"?",
"Math",
".",
"min",
"(",
"count",
",",
"result",
".",
"aaLength",
")",
":",
"result",
".",
"aaLength",
";",
"for",
"(",
"var",
"idx",
"=",
"0",
";",
"idx",
"<",
"count",
";",
"++",
"idx",
")",
"{",
"result",
"[",
"self",
".",
"sAjaxDataProp",
"]",
".",
"push",
"(",
"obj",
"[",
"self",
".",
"sAjaxDataProp",
"]",
"[",
"idx",
"]",
")",
";",
"}",
"return",
"result",
";",
"}",
"return",
"null",
";",
"}"
] |
Debug, reduced size object for display
@param obj
@return {*}
|
[
"Debug",
"reduced",
"size",
"object",
"for",
"display"
] |
6166ed2bc50f1bcd8e6f2b170a58fc5e75e78bd5
|
https://github.com/jpravetz/node-datatable/blob/6166ed2bc50f1bcd8e6f2b170a58fc5e75e78bd5/lib/builder.js#L340-L352
|
train
|
jpravetz/node-datatable
|
lib/builder.js
|
sanitize
|
function sanitize(str, len) {
len = len || 256;
if (!str || typeof str === 'string' && str.length < 1)
return str;
if (typeof str !== 'string' || str.length > len)
return null;
return str.replace(/[\0\x08\x09\x1a\n\r"'\\\%]/g, function (char) {
switch (char) {
case "\0":
return "\\0";
case "\x08":
return "\\b";
case "\x09":
return "\\t";
case "\x1a":
return "\\z";
case "\n":
return "\\n";
case "\r":
return "\\r";
case "\"":
case "'":
case "\\":
case "%":
return "\\" + char; // prepends a backslash to backslash, percent,
// and double/single quotes
}
});
}
|
javascript
|
function sanitize(str, len) {
len = len || 256;
if (!str || typeof str === 'string' && str.length < 1)
return str;
if (typeof str !== 'string' || str.length > len)
return null;
return str.replace(/[\0\x08\x09\x1a\n\r"'\\\%]/g, function (char) {
switch (char) {
case "\0":
return "\\0";
case "\x08":
return "\\b";
case "\x09":
return "\\t";
case "\x1a":
return "\\z";
case "\n":
return "\\n";
case "\r":
return "\\r";
case "\"":
case "'":
case "\\":
case "%":
return "\\" + char; // prepends a backslash to backslash, percent,
// and double/single quotes
}
});
}
|
[
"function",
"sanitize",
"(",
"str",
",",
"len",
")",
"{",
"len",
"=",
"len",
"||",
"256",
";",
"if",
"(",
"!",
"str",
"||",
"typeof",
"str",
"===",
"'string'",
"&&",
"str",
".",
"length",
"<",
"1",
")",
"return",
"str",
";",
"if",
"(",
"typeof",
"str",
"!==",
"'string'",
"||",
"str",
".",
"length",
">",
"len",
")",
"return",
"null",
";",
"return",
"str",
".",
"replace",
"(",
"/",
"[\\0\\x08\\x09\\x1a\\n\\r\"'\\\\\\%]",
"/",
"g",
",",
"function",
"(",
"char",
")",
"{",
"switch",
"(",
"char",
")",
"{",
"case",
"\"\\0\"",
":",
"\\0",
"return",
"\"\\\\0\"",
";",
"\\\\",
"case",
"\"\\x08\"",
":",
"\\x08",
"return",
"\"\\\\b\"",
";",
"\\\\",
"case",
"\"\\x09\"",
":",
"\\x09",
"return",
"\"\\\\t\"",
";",
"\\\\",
"case",
"\"\\x1a\"",
":",
"\\x1a",
"}",
"}",
")",
";",
"}"
] |
Sanitize to prevent SQL injections.
@param str
@return {*}
|
[
"Sanitize",
"to",
"prevent",
"SQL",
"injections",
"."
] |
6166ed2bc50f1bcd8e6f2b170a58fc5e75e78bd5
|
https://github.com/jpravetz/node-datatable/blob/6166ed2bc50f1bcd8e6f2b170a58fc5e75e78bd5/lib/builder.js#L362-L390
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.