_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q55100
setSetAttribute
train
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
{ "resource": "" }
q55101
cleanUp
train
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
{ "resource": "" }
q55102
loadNode
train
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
{ "resource": "" }
q55103
checkPointerRules
train
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
{ "resource": "" }
q55104
_extractProjectJsonAndAddAssets
train
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
{ "resource": "" }
q55105
changeAttributeMeta
train
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
{ "resource": "" }
q55106
renameMetaPointerTarget
train
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
{ "resource": "" }
q55107
ensureDir
train
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
{ "resource": "" }
q55108
requestWebGMEToken
train
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
{ "resource": "" }
q55109
getSVGMap
train
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
{ "resource": "" }
q55110
train
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
{ "resource": "" }
q55111
extractSWMContext
train
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
{ "resource": "" }
q55112
updateUserComponentSettings
train
function updateUserComponentSettings(userId, componentId, settings, overwrite, callback) { return _updateUserObjectField(userId, ['settings', componentId], settings, overwrite) .then(function (userData) { return userData.settings[componentId]; }) .nodeify(callback); }
javascript
{ "resource": "" }
q55113
updateUserSettings
train
function updateUserSettings(userId, settings, overwrite, callback) { return _updateUserObjectField(userId, ['settings'], settings, overwrite) .then(function (userData) { return userData.settings; }) .nodeify(callback); }
javascript
{ "resource": "" }
q55114
PluginCliManager
train
function PluginCliManager(project, mainLogger, gmeConfig, opts) { var blobClient = new BlobClientWithFSBackend(gmeConfig, mainLogger, opts); PluginManagerBase.call(this, blobClient, project, mainLogger, gmeConfig); }
javascript
{ "resource": "" }
q55115
loadRootAndCommitObject
train
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
{ "resource": "" }
q55116
train
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
{ "resource": "" }
q55117
fitsInPatternTypes
train
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
{ "resource": "" }
q55118
reLaunchUsers
train
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
{ "resource": "" }
q55119
train
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
{ "resource": "" }
q55120
uint8ArrayToString
train
function uint8ArrayToString(uintArray) { var resultString = '', i; for (i = 0; i < uintArray.byteLength; i++) { resultString += String.fromCharCode(uintArray[i]); } return decodeURIComponent(escape(resultString)); }
javascript
{ "resource": "" }
q55121
loadObject
train
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
{ "resource": "" }
q55122
loadPath
train
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
{ "resource": "" }
q55123
checkMetaRules
train
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
{ "resource": "" }
q55124
deepFreeze
train
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
{ "resource": "" }
q55125
AddOnBase
train
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
{ "resource": "" }
q55126
connectionToJson
train
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
{ "resource": "" }
q55127
isOnMetaSheet
train
function isOnMetaSheet(node) { //MetaAspectSet var sets = self.isMemberOf(node); if (sets && sets[''] && sets[''].indexOf(CONSTANTS.META_SET_NAME) !== -1) { return true; } return false; }
javascript
{ "resource": "" }
q55128
train
function (sender, args) { for (var i = 0; i < evt.length; i++) { evt[i](sender, args); } }
javascript
{ "resource": "" }
q55129
getUrl
train
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
{ "resource": "" }
q55130
shouldHaveShardedOverlays
train
function shouldHaveShardedOverlays(node) { return Object.keys(self.getProperty(node, CONSTANTS.OVERLAYS_PROPERTY) || {}).length >= _shardingLimit && self.getPath(node).indexOf('_') === -1; }
javascript
{ "resource": "" }
q55131
getInheritedCollectionPaths
train
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
{ "resource": "" }
q55132
updateProjectHooks
train
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
{ "resource": "" }
q55133
resolveJSDocConfigPath
train
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
{ "resource": "" }
q55134
train
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
{ "resource": "" }
q55135
round
train
function round (amount, numOfDecDigits) { numOfDecDigits = numOfDecDigits || 2; return Math.round(amount * Math.pow(10, numOfDecDigits)) / Math.pow(10, numOfDecDigits); }
javascript
{ "resource": "" }
q55136
getSuiteData
train
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
{ "resource": "" }
q55137
train
function (translationKey, translationDefaultValue) { if (regexName !== "JavascriptServiceArraySimpleQuote" && regexName !== "JavascriptServiceArrayDoubleQuote") { if (keyAsText === true && translationDefaultValue.length === 0) { results[translationKey] = translationKey; } else { results[translationKey] = translationDefaultValue; } } }
javascript
{ "resource": "" }
q55138
train
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
{ "resource": "" }
q55139
train
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
{ "resource": "" }
q55140
convertOut
train
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
{ "resource": "" }
q55141
train
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
{ "resource": "" }
q55142
Entry
train
function Entry(isFile, isDirectory, name, fullPath, fileSystem) { this.isFile = !!isFile; this.isDirectory = !!isDirectory; this.name = name || ''; this.fullPath = fullPath || ''; this.filesystem = fileSystem || null; }
javascript
{ "resource": "" }
q55143
parseParameters
train
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
{ "resource": "" }
q55144
createTimeout
train
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
{ "resource": "" }
q55145
train
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
{ "resource": "" }
q55146
train
function(name, fullPath, fileSystem) { DirectoryEntry.__super__.constructor.call(this, false, true, name, fullPath, fileSystem); }
javascript
{ "resource": "" }
q55147
using
train
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
{ "resource": "" }
q55148
toArray
train
function toArray(o) { let a = new Array(o.length); for (let i = 0; i < a.length; i++) { a[i] = o[i]; } return a; }
javascript
{ "resource": "" }
q55149
toMap
train
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
{ "resource": "" }
q55150
toBuffer
train
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
{ "resource": "" }
q55151
fromBuffer
train
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
{ "resource": "" }
q55152
keepAlive
train
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
{ "resource": "" }
q55153
train
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
{ "resource": "" }
q55154
train
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
{ "resource": "" }
q55155
train
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
{ "resource": "" }
q55156
train
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
{ "resource": "" }
q55157
visit
train
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
{ "resource": "" }
q55158
train
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
{ "resource": "" }
q55159
train
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
{ "resource": "" }
q55160
train
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
{ "resource": "" }
q55161
train
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
{ "resource": "" }
q55162
train
function(channel, subscription, context, once) { if (!channels[channel]) channels[channel] = []; channels[channel].push({fn: subscription, context: context || this, once: once}); }
javascript
{ "resource": "" }
q55163
train
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
{ "resource": "" }
q55164
train
function (channel, subscription, context) { Backbone.Mediator.subscribe(channel, subscription, context, true); }
javascript
{ "resource": "" }
q55165
train
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
{ "resource": "" }
q55166
train
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
{ "resource": "" }
q55167
choosePluralForm
train
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
{ "resource": "" }
q55168
encodeAsBinary
train
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
{ "resource": "" }
q55169
nGram
train
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
{ "resource": "" }
q55170
grams
train
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
{ "resource": "" }
q55171
pathsort
train
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
{ "resource": "" }
q55172
levelSorter
train
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
{ "resource": "" }
q55173
canProceed
train
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
{ "resource": "" }
q55174
getContent
train
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
{ "resource": "" }
q55175
_indexJsContent
train
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
{ "resource": "" }
q55176
_rsapem_readPrivateKeyFromASN1HexString
train
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
{ "resource": "" }
q55177
BAtos
train
function BAtos(a) { var s = ""; for (var i = 0; i < a.length; i++) { s = s + String.fromCharCode(a[i]); } return s; }
javascript
{ "resource": "" }
q55178
merge
train
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
{ "resource": "" }
q55179
Hbs
train
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
{ "resource": "" }
q55180
arraySort
train
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
{ "resource": "" }
q55181
sortBy
train
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
{ "resource": "" }
q55182
train
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
{ "resource": "" }
q55183
train
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
{ "resource": "" }
q55184
train
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
{ "resource": "" }
q55185
handler
train
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
{ "resource": "" }
q55186
train
function(callback, options, params) { var options = options || ((_.isObject(callback) && !_.isFunction(callback)) ? callback : {}); if (params) { options = _.extend({}, options, params); } return options }
javascript
{ "resource": "" }
q55187
train
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
{ "resource": "" }
q55188
train
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
{ "resource": "" }
q55189
train
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
{ "resource": "" }
q55190
mockServer
train
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
{ "resource": "" }
q55191
importing
train
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
{ "resource": "" }
q55192
RSAGetPublicString
train
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
{ "resource": "" }
q55193
RSASetPrivate
train
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
{ "resource": "" }
q55194
buildLimitPartial
train
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
{ "resource": "" }
q55195
buildSelectPartial
train
function buildSelectPartial() { var query = "SELECT "; query += self.sSelectSql ? self.sSelectSql : "*"; query += " FROM "; query += self.sFromSql ? self.sFromSql : self.sTableName; return query; }
javascript
{ "resource": "" }
q55196
buildQuery
train
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
{ "resource": "" }
q55197
parseResponse
train
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
{ "resource": "" }
q55198
filteredResult
train
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
{ "resource": "" }
q55199
sanitize
train
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
{ "resource": "" }