_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q41300
train
function(webhookId, callback) { utils.debug('Webhooks get: ' + webhookId); request.get({ path: '/webhooks/' + utils.toUUID(webhookId), }, callback); }
javascript
{ "resource": "" }
q41301
xBarPadding
train
function xBarPadding() { var domain = xBar.domain(); var barSpacing = (domain.length > 1 ? (xBar(domain[1]) - xBar(domain[0])) : xBar.rangeBand()); var barPadding = (barSpacing - xBar.rangeBand()); return barPadding; }
javascript
{ "resource": "" }
q41302
trimToXDomain
train
function trimToXDomain(array) { var start = 0, len = array.length, xDomainStart = parent.x.domain()[0]; // remove any data earlier than first full range while ( start < len ) { if ( array[start].date.getTime() >= xDomainStart.getTime() ) { break; } start += 1; } return (start === 0 ? array : array.slice(start)); }
javascript
{ "resource": "" }
q41303
drawHoverHighlightBars
train
function drawHoverHighlightBars(dataArray) { var hoverBar = parent.svgHoverRoot.selectAll('rect.highlightbar').data(dataArray); hoverBar.attr('x', valueX) .attr('width', xBar.rangeBand()); hoverBar.enter().append('rect') .attr('x', valueX) .attr('y', 0) .attr('height', parent.height) .attr('width', xBar.rangeBand()) .classed('highlightbar clickable', true); hoverBar.exit().remove(); }
javascript
{ "resource": "" }
q41304
drawSelection
train
function drawSelection(dataArray) { var firstItem = (dataArray && dataArray.length > 0 ? dataArray.slice(0, 1) : []), firstItemX = (dataArray && dataArray.length > 0 ? valueX(dataArray[0]) : 0), lastItemX = (dataArray && dataArray.length > 0 ? valueX(dataArray[dataArray.length - 1]) : 0), width = (lastItemX - firstItemX) + xBar.rangeBand(); var selectBar = parent.svgHoverRoot.selectAll('rect.selectionbar').data(firstItem); selectBar.attr('x', firstItemX) .attr('width', width); selectBar.enter().append('rect') .attr('x', firstItemX) .attr('y', 0) .attr('height', parent.height) .attr('width', width) .classed('selectionbar clickable', true); selectBar.exit().remove(); }
javascript
{ "resource": "" }
q41305
mongooseify
train
function mongooseify(obj, returnValues) { applyMethods(obj); traverse(obj, (key, value) => { applyMethods(value); }); function applyMethods(value) { if(value && value.hasOwnProperty('_id')) { value.toObject = jasmine.createSpy('toObject'); value.toObject.and.returnValue(JSON.parse(JSON.stringify(value))); value.save = jasmine.createSpy('save'); value.save.and.returnValue(returnValues && returnValues.save ? returnValues.save : Promise.resolve({name : 'fooy'})); } } }
javascript
{ "resource": "" }
q41306
train
function(type, envelope, complete) { // We send the message by navigating the browser to a special URL. // The iOS library will catch the navigation, prevent the UIWebView // from continuing, and use the data in the URL to execute code // within the iOS app. var dispatcher = this; this.callbacks[envelope.id] = function() { complete(); delete dispatcher.callbacks[envelope.id]; }; var src = "jockey://" + type + "/" + envelope.id + "?" + encodeURIComponent(JSON.stringify(envelope)); var iframe = document.createElement("iframe"); iframe.setAttribute("src", src); document.documentElement.appendChild(iframe); iframe.parentNode.removeChild(iframe); iframe = null; }
javascript
{ "resource": "" }
q41307
train
function(type, messageId, json) { var self = this; var listenerList = this.listeners[type] || []; var executedCount = 0; var complete = function() { executedCount += 1; if (executedCount >= listenerList.length) { self.dispatcher.sendCallback(messageId); } }; for (var index = 0; index < listenerList.length; index++) { var listener = listenerList[index]; // If it's a "sync" listener, we'll call the complete() function // after it has finished. If it's async, we expect it to call complete(). if (listener.length <= 1) { listener(json); complete(); } else { listener(json, complete); } } }
javascript
{ "resource": "" }
q41308
buildHasteMap
train
function buildHasteMap(rootPath, prefix) { var prefix = prefix || 'haste-map-provider'; return new HasteMapBuilder({ "extensions": [ "snap", "js", "json", "jsx", "node" ], "ignorePattern": /SOME_COMPLEX_IGNORE_PATTERN_UNLIKELY_TO_HAPPEN/, "maxWorkers": 7, "name": prefix + "-" + rootPath.replace(/[\/\\]/g, '_'), "platforms": [ "ios", "android" ], "providesModuleNodeModules": [], "resetCache": false, "retainAllFiles": false, "roots": [ rootPath, ], "useWatchman": true, }).build(); }
javascript
{ "resource": "" }
q41309
train
function(to_clean) { _.map(to_clean, function(value, key, to_clean) { if (value === undefined) { delete to_clean[key]; } }); return to_clean; }
javascript
{ "resource": "" }
q41310
create
train
function create(appName, callback) { commons.post(format('/%s/apps/', deis.version), { id: appName }, callback); }
javascript
{ "resource": "" }
q41311
list
train
function list(pageSize, callback) { var limit = 100; if (!isFunction(pageSize)) { limit = pageSize; }else { callback = pageSize; } commons.get(format('/%s/apps?limit=%s', deis.version, limit), callback); }
javascript
{ "resource": "" }
q41312
info
train
function info(appName, callback) { commons.get(format('/%s/apps/%s/', deis.version, appName), callback); }
javascript
{ "resource": "" }
q41313
logs
train
function logs(appName, callback) { commons.get(format('/%s/apps/%s/logs/', deis.version, appName), callback); }
javascript
{ "resource": "" }
q41314
run
train
function run(appName, command, callback) { commons.get(format('/%s/apps/%s/run/', deis.version, appName), callback); }
javascript
{ "resource": "" }
q41315
destroy
train
function destroy(appName, callback) { commons.del(format('/%s/apps/%s/', deis.version, appName), callback); }
javascript
{ "resource": "" }
q41316
start
train
function start(basedir, connectionCompleteCallback) { var defaultConfig = require("./config/defaults.json"); var config = Config.create(basedir, defaultConfig); var globalObject = { config: config }; var loginCompleteCallback = function(bot) { globalObject.bot = bot; bot.connect(config.DubBotBase.roomName); LOG.info("Connect request sent. Waiting 5 seconds for the connection to be established."); var innerConnectionCompleteCallback = function() { StateTracker.init(globalObject, function() { // Connect before registering anything, because StateTracker depends on being connected var commands = _registerCommands(basedir, globalObject); var eventListeners = _registerEventListeners(basedir, globalObject); // Hook our own event listener in to chat, for the command framework bot.on(Event.CHAT, _createCommandHandler(commands)); if (connectionCompleteCallback) { connectionCompleteCallback(globalObject); } }); }; setTimeout(innerConnectionCompleteCallback, 5000); }; new Dubtrack.Bot({ username: config.DubBotBase.botEmail, password: config.DubBotBase.botPassword }, globalObject, loginCompleteCallback); return globalObject; }
javascript
{ "resource": "" }
q41317
_createCommandHandler
train
function _createCommandHandler(commands) { return function(chatEvent, globalObject) { if (!chatEvent.command) { return; } var commandName = chatEvent.command; if (!globalObject.config.DubBotBase.areCommandsCaseSensitive) { commandName = commandName.toLowerCase(); } for (var i = 0; i < commands.length; i++) { var command = commands[i]; if (command.triggers.indexOf(commandName) >= 0) { if (command.minimumRole && chatEvent.userRole.level < command.minimumRole.level) { // user doesn't have sufficient permissions; notify the command module if possible if (command.insufficientPermissionsHandler) { command.insufficientPermissionsHandler.call(command.context, chatEvent, globalObject); } continue; } command.handler.call(command.context, chatEvent, globalObject); } } }; }
javascript
{ "resource": "" }
q41318
_registerCommands
train
function _registerCommands(basedir, globalObject) { var commandsDir = path.resolve(basedir, "commands"); var files; try { files = Utils.getAllFilePathsUnderDirectory(commandsDir); LOG.info("Found the following potential command files: {}", files); } catch (e) { LOG.error("Unable to register commands from the base directory '{}'. Error: {}", commandsDir, e); return; } var commands = []; for (var i = 0; i < files.length; i++) { var filePath = files[i]; if (filePath.lastIndexOf(".js") !== filePath.length - 3) { LOG.info("File {} doesn't appear to be a JS module. Ignoring.", filePath); continue; } var module = require(filePath); if (!module.triggers || !module.handler) { LOG.warn("Found a module at {} but it doesn't appear to be a command handler. Ignoring.", filePath); continue; } if (typeof module.init === "function") { module.init(globalObject); } commands.push(module); LOG.info("Registered command from file {}", filePath); } return commands; }
javascript
{ "resource": "" }
q41319
_registerEventListeners
train
function _registerEventListeners(basedir, globalObject) { var bot = globalObject.bot; var eventListenerDir = path.resolve(basedir, "event_listeners"); var files; try { files = Utils.getAllFilePathsUnderDirectory(eventListenerDir); LOG.info("Found the following potential event listener files: {}", files); } catch (e) { LOG.error("Unable to register event listeners from the base directory '{}'. Error: {}", eventListenerDir, e); return; } var listeners = []; for (var i = 0; i < files.length; i++) { var filePath = files[i]; if (filePath.lastIndexOf(".js") !== filePath.length - 3) { LOG.info("File {} doesn't appear to be a JS module. Ignoring.", filePath); continue; } var module = require(filePath); /* Check each event key and look for an export in one of two forms: * * 1) EVENT_KEY : some_function * 2) EVENT_KEY : { handler: some_function, context: some_object } * * Context is optional even in the second form, but a function is always required. */ var eventHandlerFound = false; for (var eventKey in Event) { var eventValue = Event[eventKey]; var eventHandler = null; var handlerContext = null; var error = null; if (!module[eventValue]) { continue; } if (typeof module[eventValue] === "function") { eventHandler = module[eventValue]; } else if (typeof module[eventValue] === "object") { if (typeof module[eventValue].handler !== "function") { LOG.error("An error occurred while reading event listener from file {}", filePath); LOG.error("Event listener for event '{}' has an object type, but the 'handler' property does not refer to a function", eventKey); throw new Error("An error occurred while initializing event listeners. Check your logfile (or just stdout) for more details."); } eventHandler = module[eventValue].handler; handlerContext = module[eventValue].context; } else { LOG.warn("Found what looks like an event listener, but it's not an object or a function. Event: {}, from file: {}", eventKey, filePath); continue; } eventHandlerFound = true; bot.on(eventValue, eventHandler, handlerContext); } if (!eventHandlerFound) { LOG.warn("Found a module at {} but it doesn't appear to be an event handler. Ignoring.", filePath); continue; } if (typeof module.init === "function") { LOG.info("Calling init for module at {}", filePath); module.init(globalObject); } listeners.push(module); LOG.info("Registered event listener from file {}", filePath); } return listeners; }
javascript
{ "resource": "" }
q41320
getMongoHandle
train
function getMongoHandle(mongoose) { var res = { mongoose: mongoose, modelDocs: {}, modelESchemas: {}, mongoMaps: {} }; var modelES = Schemaload.getExtendedSchemaModel(mongoose); return modelES.distinct('modelname').then((modelnames) => { debuglog(() => 'here distinct modelnames ' + JSON.stringify(modelnames)); return Promise.all(modelnames.map(function (modelname) { debuglog(() => 'creating tripel for ' + modelname); return Promise.all([Schemaload.getExtendSchemaDocFromDB(mongoose, modelname), Schemaload.makeModelFromDB(mongoose, modelname), Schemaload.getModelDocFromDB(mongoose, modelname)]).then((value) => { debuglog(() => 'attempting to load ' + modelname + 'to create mongomap'); var [extendedSchema, model, modelDoc] = value; res.modelESchemas[modelname] = extendedSchema; res.modelDocs[modelname] = modelDoc; res.mongoMaps[modelname] = MongoMap.makeMongoMap(modelDoc, extendedSchema); debuglog(() => 'created mongomap for ' + modelname); }); })); }).then(() => { return res; }); //var modelDoc = Schemaload.getExtendedDocModel(mongoose); //res.modelDocs[ISchema.MongoNLQ.MODELNAME_METAMODELS] = modelDoc; //return Promise.resolve(res); }
javascript
{ "resource": "" }
q41321
getDomainsForBitField
train
function getDomainsForBitField(oModel, bitfield) { return oModel.domains.filter(domain => (getDomainBitIndex(domain, oModel) & bitfield)); }
javascript
{ "resource": "" }
q41322
loadModels
train
function loadModels(mongoose, modelPath) { if (mongoose === undefined) { throw new Error('expect a mongoose handle to be passed'); } return getMongoHandle(mongoose).then((modelHandle) => { debuglog(`got a mongo handle for ${modelPath}`); return _loadModelsFull(modelHandle, modelPath); }); }
javascript
{ "resource": "" }
q41323
difference
train
function difference(arrayA, arrayB) { var maxLength = _.max([ arrayA.length, arrayB.length ]); for (var i = 0, j = 0; i < maxLength; i += 1, j += 1) { if (arrayA[i] !== arrayB[j]) { if (arrayB[i-1] === arrayA[i]) { j -= 1; } else if (arrayB[i+1] === arrayA[i]) { j += 1; } else { return arrayA[i]; } } } }
javascript
{ "resource": "" }
q41324
decode
train
function decode(buf) { let off = 0; var i; // unpack meta const meta = buf[(off += 1)]; // const VERSION = meta >> 4; const argv = meta & 0xf; const args = new Array(argv); // unpack args for (i = 0; i < argv; i += 1) { const len = buf.readUInt32BE(off); off += 4; args[i] = buf.slice(off, (off += len)); } return args; }
javascript
{ "resource": "" }
q41325
appendListener
train
function appendListener(event, listener, once) { this.events[event] = this.events[event] || []; this.events[event].push({ "listener": listener, "once": !!once }); this.emit('newListener', event, listener); if (this.events[event].length > this.maxListeners) { console.warn('warning: possible EventEmitter memory leak detected. ', this.events[event].length, ' listeners added. ', 'Use emitter.setMaxListeners() to increase limit. ', this); } }
javascript
{ "resource": "" }
q41326
train
function(u){ var urlObj = url.parse(u) return u.replace( urlObj.search, '').replace('#', '') }
javascript
{ "resource": "" }
q41327
train
function(u){ var urlObj = url.parse(u) return urlObj.protocol + "//" + urlObj.hostname + urlObj.pathname }
javascript
{ "resource": "" }
q41328
PostEmitter
train
function PostEmitter() { var _this = this; //might be global this._listener = function(ev) { //check origin //then var data = ev.data; _this.emit.apply(_this, data instanceof Array ? data : [data]); }; window[attach](prefix + 'message', this._listener); }
javascript
{ "resource": "" }
q41329
sn_color_map
train
function sn_color_map(fillColors, keys) { var colorRange = d3.scale.ordinal().range(fillColors); var colorData = keys.map(function(el, i) { return {source:el, color:colorRange(i)}; }); // also provide a mapping of sources to corresponding colors var i, len, sourceName; for ( i = 0, len = colorData.length; i < len; i += 1 ) { // a source value might actually be a number string, which JavaScript will treat // as an array index so only set non-numbers here sourceName = colorData[i].source; if ( sourceName === '' ) { // default to Main if source not provided sourceName = 'Main'; } if ( isNaN(Number(sourceName)) ) { colorData[sourceName] = colorData[i].color; } } return colorData; }
javascript
{ "resource": "" }
q41330
sn_color_color
train
function sn_color_color(d) { var s = Number(d.source); if ( isNaN(s) ) { return sn.runtime.colorData[d.source]; } return sn.runtime.colorData.reduce(function(c, obj) { return (obj.source === d.source ? obj.color : c); }, sn.runtime.colorData[0].color); }
javascript
{ "resource": "" }
q41331
_createConsumerMessage
train
function _createConsumerMessage(consumer, message, {chanId}) { const { iterator: consumerIterator, type: requestType, payload } = consumer if (requestType === cSelectRequest) { const {selectedChanIds} = payload const i = selectedChanIds.indexOf(chanId) const response = new Array(selectedChanIds.length) response[i] = message return [consumerIterator, response] } else if (requestType === cTakeRequest) { return [consumerIterator, message] } throw new Error(`Unknown request type ${requestType}`) }
javascript
{ "resource": "" }
q41332
train
function () { var stream = new $.streamqueue({ objectMode: true }); //Optionally injected additional javascript sourcecode injectIntoStream(stream, options.injectInto.js.pre); // App files without vendor files stream.queue(gulp.src(options.files.jsNoVendor)); //Angular template files stream.queue( gulp.src(options.files.partials) .pipe($.htmlMinify()) .pipe($.angularTemplatecache(options.templateCacheOptions)) ); //Optionally injected additional javascript sourcecode injectIntoStream(stream, options.injectInto.js.post); return stream .done() .pipe($.angularFilesort()) .pipe($.concat(options.output.js.app)) .pipe($.generateOutPipe(options.paths.build, options.output.js.path, 'app.js', options.rev, $.jsMinify)()); }
javascript
{ "resource": "" }
q41333
train
function () { var stream = new $.streamqueue({ objectMode: true }); //Optionally injected additional css sourcecode injectIntoStream(stream, options.injectInto.css.pre); // App files without vendor files stream.queue(gulp.src(options.files.cssNoVendor)); //Optionally injected additional css sourcecode injectIntoStream(stream, options.injectInto.css.post); return stream .done() .pipe($.concat(options.output.css.app)) .pipe($.generateOutPipe(options.paths.build, options.output.css.path, 'app.css', options.rev, $.cssMinify)()); }
javascript
{ "resource": "" }
q41334
merge
train
function merge(target, ...sources) { let targetObject = target; if (!isObj(target)) { targetObject = {}; } // for all the sources provided merge them with // the target object sources.forEach((s) => { // before merging check the source is an object if (isObj(s)) { targetObject = mergeObject(targetObject, s); } }); return targetObject; }
javascript
{ "resource": "" }
q41335
lintStream
train
function lintStream(spec) { if (!spec || !spec.jslint) { throw new gulpUtil.PluginError(pluginName, 'The file path to jslint is required.'); } var errors = 0; function lint(source, callback) { var contents = source.contents.toString('utf8'); var result = context.jslint(contents, spec.options, spec.globals); if (result.ok) { gulpUtil.log(colors.green(source.path)); } else { gulpUtil.log(colors.red(source.path)); errors += result.warnings.length; result.warnings.forEach(logWarning); } callback(null, source); } function map(source, callback) { if (context.jslint) { lint(source, callback); return; } fs.readFile(spec.jslint, 'utf8', function (err, jslint) { if (err) { throw new gulpUtil.PluginError(pluginName, err); } vm.runInNewContext(jslint, context); lint(source, callback); }); } function onEnd() { if (errors && !spec.noFail) { var message = errors === 1 ? 'JSLint found one error.' : 'JSLint found ' + errors + ' errors.'; throw new gulpUtil.PluginError(pluginName, message); } } return eventStream .map(map) .on('end', onEnd); }
javascript
{ "resource": "" }
q41336
rejectAll
train
function rejectAll(requests, error) { for (const request of requests) { request.abort(); request.reject(error); } }
javascript
{ "resource": "" }
q41337
UnauthorizedError
train
function UnauthorizedError(message) { Error.call(this); Error.captureStackTrace(this, this.constructor); this.status = 401; this.message = 'Unauthorized: ' + message; this.name = this.constructor.name; }
javascript
{ "resource": "" }
q41338
NotFoundError
train
function NotFoundError(message) { Error.call(this); Error.captureStackTrace(this, this.constructor); this.status = 404; this.message = 'Not Found: ' + message; this.name = this.constructor.name; }
javascript
{ "resource": "" }
q41339
train
function(el) { var self = this, $el = $(el); if ($el.length > 1) { $el.each(function() { self.addElement(this); }); } else if ($el.length === 0) { throw new Error("Invalid element!"); } if (this.$el.closest($el).length) { throw new Error("Element is a child of this view. This is only for unrelated elements"); } if ($el.closest(this.$el).length) { throw new Error("Element is an ancestor of this view! Reconsider how you're using this view."); } // normalize el = $el.get(0); if (!this._trackedElements) { this._trackedElements = []; } _(this._trackedElements).each(function(otherEl) { var $otherEl = $(otherEl); if ($otherEl.closest($el).length) { throw new Error("Element is a child of another tracked element. This will cause problems."); } if ($el.closest($otherEl).length) { throw new Error("Element is an ancestor of another tracked element. This will cause problems."); } }); this._trackedElements.push(el); }
javascript
{ "resource": "" }
q41340
styler
train
function styler(...rawStyles) { const stylesBundle = buildStyles.apply(null, rawStyles); /** * Styling composer * * @param {...string} classNames - Class names of desired styles */ return function stylingComposer(classNames, error) { var parsedClassNames; const styles = []; const notFound = []; if (classNames) { const commands = stylesBundle.__runtime_commands__; parsedClassNames = findClassNames(classNames).map((classNm) => classNm ? classNm.join("") : ""); parsedClassNames.forEach((className) => { if(!stylesBundle[className]){ notFound.push(className); return; } let style = stylesBundle[className]; let factories = commands[className] ? commandsManager.getRuntimeCommands() : null; if (factories) { factories.forEach(factory => { commands[className].forEach(command => { let fn = factory(command.type); fn && (style = merge(style, fn(command))); }); }); } styles.push(style); }); } else { const commands = stylesBundle.__runtime_commands__; const factories = commandsManager.getRuntimeCommands(); styles.push(stylesBundle); // if runtime commands and command factories exist if (factories.length > 0 && commands) { // run all runtime commands of the styles Object.keys(commands).forEach(className => { commands[className].forEach(command => { factories.forEach(factory => { let style = {}; const fn = factory(command.type); fn && (style[className] = merge(stylesBundle[className], fn(command))); styles.push(style); }); }); }); } } const style = merge.apply(null, styles); if(notFound.length > 0 && error){ error(notFound.join(", ")+" cannot be found."); } /** * Styles mapper. If passed a function as the argument then return styles to the funtion or null then return style object. * * @param {?function=} [null] fn - Mapping callback function */ return function stylesComposer(fn = null) { //create deepcopy of the style if (fn) { let result = {}; // parsedClassNames.forEach((className) => { if(style){ Object.keys(style).forEach((key) => { let value = style[key] !== null && style[key] instanceof Object ? merge(style[key]) : style[key]; result[key] = fn(classNames, key, value); }); } // }); return result; }; return style; }; }; }
javascript
{ "resource": "" }
q41341
checkHasValue
train
function checkHasValue(value, message) { checkNotEmpty(message, "No error message passed to checkHasValue"); if (value === null || typeof value === "undefined") { throw new Error(message); } }
javascript
{ "resource": "" }
q41342
checkNotEmpty
train
function checkNotEmpty(string, message) { if (!message || !message.trim()) { throw new Error("No error message passed to checkNotEmpty"); } if (!string || !string.trim()) { throw new Error(message); } }
javascript
{ "resource": "" }
q41343
checkValueIsInObject
train
function checkValueIsInObject(value, object, message) { checkNotEmpty(message, "No error message passed to checkValueIsInObject"); var key = findValueInObject(value, object); if (typeof key === "undefined") { // Make sure the value's actually missing and it's not hidden behind undefined if (!(undefined in object && deepEquals(value, object[undefined]))) { throw new Error(message); } } }
javascript
{ "resource": "" }
q41344
deepEquals
train
function deepEquals(obj1, obj2) { if (typeof obj1 !== typeof obj2) { return false; } // NaN check if (obj1 !== obj1) { return obj2 !== obj2; } // Non-object types will compare correctly with === if (typeof obj1 !== "object") { return obj1 === obj2; } if (!_checkKeysFromFirstAreInSecond(obj1, obj2)) { return false; } if (!_checkKeysFromFirstAreInSecond(obj2, obj1)) { return false; } return true; }
javascript
{ "resource": "" }
q41345
findValueInObject
train
function findValueInObject(value, object) { checkHasType(object, "object", "Non-object value provided as second argument to findValueInObject"); checkHasValue(object, "Invalid null object provided as second argument to findValueInObject"); for (var key in object) { var objValue = object[key]; if (deepEquals(value, objValue)) { return key; } } return; // explicit return of undefined }
javascript
{ "resource": "" }
q41346
getAllFilePathsUnderDirectory
train
function getAllFilePathsUnderDirectory(directory) { // TODO: make this run in parallel, async var filesInBaseDir = fs.readdirSync(directory); var allFiles = []; if (!filesInBaseDir) { return allFiles; } for (var i = 0; i < filesInBaseDir.length; i++) { var filePath = path.resolve(directory, filesInBaseDir[i]); var fileStats = fs.statSync(filePath); if (fileStats.isDirectory()) { allFiles = allFiles.concat(getAllFilePathsUnderDirectory(filePath)); } else if (fileStats.isFile()) { allFiles.push(filePath); } } return allFiles; }
javascript
{ "resource": "" }
q41347
_checkKeysFromFirstAreInSecond
train
function _checkKeysFromFirstAreInSecond(first, second) { for (var key in first) { if (!(key in second)) { return false; } var value1 = first[key]; var value2 = second[key]; if (!deepEquals(value1, value2)) { return false; } } return true; }
javascript
{ "resource": "" }
q41348
getBody
train
function getBody(req) { return new Promise((resolve, reject) => { let data = ''; req .on('data', (chunk) => { data += chunk; }) .on('end', () => { resolve(data); }) .on('error', reject); }); }
javascript
{ "resource": "" }
q41349
train
function(req, res, next) { var accData = req.user.Account , newData = { name: req.body.name || accData.name, logo: req.body.logo || accData.logo, info: req.body.info || accData.info, email: req.body.email || accData.email, themeColor: req.body.themeColor || accData.themeColor }; req.body = newData; next(); }
javascript
{ "resource": "" }
q41350
train
function(req, res, next){ var subdomain = req.body.subdomain; if (!subdomain) { return res.json(400, 'Company subdomain is mandatory!'); } AccountService .find({ where: { subdomain: subdomain } }) .then(function(result){ if(result.length){ return res.json(403, 'This URL "' + subdomain + '" is already taken'); } next(); }) .catch(function(err){ return res.json(500, 'There was an error: ' + err); }); }
javascript
{ "resource": "" }
q41351
finalize
train
function finalize(base, path, patches, inversePatches) { if (isProxy(base)) { var state = base[PROXY_STATE]; if (state.modified === true) { if (state.finalized === true) return state.copy; state.finalized = true; var result = finalizeObject(useProxies ? state.copy : state.copy = shallowCopy(base), state, path, patches, inversePatches); generatePatches(state, path, patches, inversePatches, state.base, result); return result; } else { return state.base; } } finalizeNonProxiedObject(base); return base; }
javascript
{ "resource": "" }
q41352
produce
train
function produce(baseState, producer, patchListener) { // prettier-ignore if (arguments.length < 1 || arguments.length > 3) throw new Error("produce expects 1 to 3 arguments, got " + arguments.length); // curried invocation if (typeof baseState === "function") { // prettier-ignore if (typeof producer === "function") throw new Error("if first argument is a function (curried invocation), the second argument to produce cannot be a function"); var initialState = producer; var recipe = baseState; return function () { var args = arguments; var currentState = args[0] === undefined && initialState !== undefined ? initialState : args[0]; return produce(currentState, function (draft) { args[0] = draft; // blegh! return recipe.apply(draft, args); }); }; } // prettier-ignore { if (typeof producer !== "function") throw new Error("if first argument is not a function, the second argument to produce should be a function"); if (patchListener !== undefined && typeof patchListener !== "function") throw new Error("the third argument of a producer should not be set or a function"); } // if state is a primitive, don't bother proxying at all if ((typeof baseState === "undefined" ? "undefined" : _typeof(baseState)) !== "object" || baseState === null) { var returnValue = producer(baseState); return returnValue === undefined ? baseState : returnValue; } if (!isProxyable(baseState)) throw new Error("the first argument to an immer producer should be a primitive, plain object or array, got " + (typeof baseState === "undefined" ? "undefined" : _typeof(baseState)) + ": \"" + baseState + "\""); return getUseProxies() ? produceProxy(baseState, producer, patchListener) : produceEs5(baseState, producer, patchListener); }
javascript
{ "resource": "" }
q41353
mergeOptions
train
function mergeOptions(config, pass) { var _this = this; var result = loadConfig(config); var plugins = result.plugins.map(function (descriptor) { return loadPluginDescriptor(descriptor); }); var presets = result.presets.map(function (descriptor) { return loadPresetDescriptor(descriptor); }); if (config.options.passPerPreset != null && typeof config.options.passPerPreset !== "boolean") { throw new Error(".passPerPreset must be a boolean or undefined"); } var passPerPreset = config.options.passPerPreset; pass = pass || this.passes[0]; // resolve presets if (presets.length > 0) { var presetPasses = null; if (passPerPreset) { var _passes; presetPasses = presets.map(function () { return []; }); // The passes are created in the same order as the preset list, but are inserted before any // existing additional passes. (_passes = this.passes).splice.apply(_passes, [1, 0].concat((0, _toConsumableArray3.default)(presetPasses))); } presets.forEach(function (presetConfig, i) { _this.mergeOptions(presetConfig, presetPasses ? presetPasses[i] : pass); }); } // resolve plugins if (plugins.length > 0) { var _pass; (_pass = pass).unshift.apply(_pass, (0, _toConsumableArray3.default)(plugins)); } (0, _merge2.default)(this.options, result.options); }
javascript
{ "resource": "" }
q41354
loadConfig
train
function loadConfig(config) { var options = normalizeOptions(config); if (config.options.plugins != null && !Array.isArray(config.options.plugins)) { throw new Error(".plugins should be an array, null, or undefined"); } var plugins = (config.options.plugins || []).map(function (plugin, index) { var _normalizePair = normalizePair(plugin, _files.loadPlugin, config.dirname), filepath = _normalizePair.filepath, value = _normalizePair.value, options = _normalizePair.options; return { alias: filepath || config.loc + "$" + index, loc: filepath || config.loc, value: value, options: options, dirname: config.dirname }; }); if (config.options.presets != null && !Array.isArray(config.options.presets)) { throw new Error(".presets should be an array, null, or undefined"); } var presets = (config.options.presets || []).map(function (preset, index) { var _normalizePair2 = normalizePair(preset, _files.loadPreset, config.dirname), filepath = _normalizePair2.filepath, value = _normalizePair2.value, options = _normalizePair2.options; return { alias: filepath || config.loc + "$" + index, loc: filepath || config.loc, value: value, options: options, dirname: config.dirname }; }); return { options: options, plugins: plugins, presets: presets }; }
javascript
{ "resource": "" }
q41355
loadPresetDescriptor
train
function loadPresetDescriptor(descriptor) { return { type: "preset", options: loadDescriptor(descriptor).value, alias: descriptor.alias, loc: descriptor.loc, dirname: descriptor.dirname }; }
javascript
{ "resource": "" }
q41356
train
function(options) { options = options || {}; this._modelBindersMap = null; this._collectionBinder = null; this._bindingIndex = null; this._itemAlias = null; this._subviewsStruct = null; this._explicitSubviewsStruct = null; this._pendingRefresh = false; this._pendingRefreshRoot = false; this._subviewsArgs = null; this._isRunning = false; this._isSuspended = false; this._template = null; this._isolated = false; this.subviews = null; if(options.isolated) { this._isolated = true; } if(options.parentView) { this.scope = options.scope || null; this._setParentView(options.parentView); } else if(options.scope) this.scope = mixin({}, options.scope); else this.scope = {}; options.scope = null; if(options.events) { this.domEvents = options.events.slice(); } else this.domEvents = []; if(options.dispatcher) { this.dispatcher = options.dispatcher; } else this.dispatcher = null; if(options.actions) { this.actions = mixin({ set: actionSet }, options.actions); } else if((this.parentView == null || this._isolated )&& !options._clone) { this.actions = { set: actionSet }; } else this.actions = null; if(options.env) { this.env = options.env; } else this.env = { document: document, window: window }; if(options.element) { this.element = options.element options.element = null; } else this.element = this.env.document.body; this.options = options; }
javascript
{ "resource": "" }
q41357
train
function() { if(!this._modelBindersMap) this._initBinding(); if(!this._collectionBinder) { this._explicitSubviewsStruct = null; if(this._template) this.element.innerHTML = this._template; if(this.render !== noop) this.render(); this.renderSubviews(); } }
javascript
{ "resource": "" }
q41358
train
function() { if(this._isRunning && !this._isSuspended) { var shouldRefresh = true; if(typeof this.shouldRefresh === 'function') shouldRefresh = this.shouldRefresh(); if(shouldRefresh) { if(typeof this.refresh === 'function') this.refresh(); if(this._collectionBinder) { this._collectionBinder.refreshBoundViews(); this._collectionBinder.refreshAll(); } else { this._rebindCursors(); this._refreshOwnBinders(); if(this.subviews !== null) { for(var i = 0, l = this.subviews.length; i < l; i++) this.subviews[i].refreshAll(); } } } this._pendingRefresh = false; } }
javascript
{ "resource": "" }
q41359
train
function() { var view = this; while(view.parentView) { view = view.parentView; } if(view.dispatcher !== null) { view.dispatcher.trigger({ type: 'refresh' }); this._pendingRefreshRoot = false; } }
javascript
{ "resource": "" }
q41360
train
function() { this._destroyBinding(); if(this._collectionBinder) this._collectionBinder.destroyBoundViews(); this._modelBindersMap = null; this._collectionBinder = null; this._bindingIndex = null; this._itemAlias = null; this.element.removeAttribute(settings.DATA_RENDERED_ATTR); this.undelegateEvents(); this.destroySubviews(); if(this.dispatcher) { this.dispatcher.off('refresh', this.f('refreshAll')); this.dispatcher.off('refreshFromRoot', this.f('refreshFromRoot')); this.dispatcher.off('refreshRaf', this.f('requestRefreshAll')); this.dispatcher.off('refreshFromRootRaf', this.f('requestRefreshAllFromRoot')); this.dispatcher.off('dispatcher:noaction', this.f('_dispatchNoAction')); } if(this.destroy !== noop) this.destroy(); if(typeof this.afterDestroy === 'function') this.afterDestroy(); this._subviewsStruct = null; this._explicitSubviewsStruct = null; this.subviews = null; this._isRunning = false; this._isSuspended = false; }
javascript
{ "resource": "" }
q41361
train
function() { if(this._collectionBinder) { this._collectionBinder.destroyBoundViews(); } else { var subView, i, l; // Destroy subviews if(this.subviews !== null) { for(i = 0, l = this.subviews.length; i < l; i++) { subView = this.subviews[i]; subView.destroyAll(); } } this.subviews = null; this._subviewsStruct = null; } }
javascript
{ "resource": "" }
q41362
train
function(keyPath) { if(typeof keyPath === 'string') keyPath = keyPath.split('.'); var rootCursorName = keyPath[0]; keyPath = keyPath.slice(1); var rootCursor = this.scope[rootCursorName]; if(!(rootCursor instanceof Cursor)) rootCursor = new Cursor(rootCursor, keyPath); var cursor = rootCursor.refine(keyPath); return cursor; }
javascript
{ "resource": "" }
q41363
train
function(events) { if(!Array.isArray(events)) { if(arguments.length === 2 || arguments.length === 3) this.domEvents.push(Array.prototype.slice.apply(arguments)); return; } else if(!Array.isArray(events[0])) { events = Array.prototype.slice.apply(arguments); } Array.prototype.push.apply(this.domEvents, events); }
javascript
{ "resource": "" }
q41364
train
function(viewName, options) { var subView, args; if(this._subviewsArgs && Array.isArray(this._subviewsArgs[viewName])) { args = this._subviewsArgs[viewName]; if(typeof args[0] === 'object' && args[0] !== null) options = immerge(options, args[0]); } options.parentView = this; if(viewName === 'View') subView = new View(options); else if(viewName in this.scope) subView = new this.scope[viewName](options); if(subView instanceof View) { if(this.subviews === null) this.subviews = []; this.subviews.push(subView); } return subView; }
javascript
{ "resource": "" }
q41365
train
function(element, viewName, options) { if(this._explicitSubviewsStruct === null) this._explicitSubviewsStruct = []; this._explicitSubviewsStruct.push({ viewName: viewName, element: element, options: options || {} }); }
javascript
{ "resource": "" }
q41366
train
function(force) { if(this._collectionBinder) { this._collectionBinder.refreshBinders(force); } else { this._refreshOwnBinders(force); if(this.subviews !== null) { for(var i = 0, l = this.subviews.length; i < l; i++) this.subviews[i].refreshBinders(force); } } }
javascript
{ "resource": "" }
q41367
train
function() { if(this._collectionBinder) { this._collectionBinder.refreshIndexedBinders(); } else { if(this._modelBindersMap) { this._modelBindersMap.refreshIndexedBinders(); } if(this.subviews !== null) { for(var i = 0, l = this.subviews.length; i < l; i++) this.subviews[i].refreshIndexedBinders(); } } }
javascript
{ "resource": "" }
q41368
train
function() { var l; var clonedSubview; var options = this.options; options.parentView = null; options.env = this.env; options._clone = true; var clonedView = new this.constructor(options); if(this.subviews !== null) { l = this.subviews.length; clonedView.subviews = new Array(l); while(l--) { clonedSubview = this.subviews[l]._clone(); clonedView.subviews[l] = clonedSubview; } } if(this._subviewsStruct !== null) { clonedView._subviewsStruct = this._subviewsStruct.slice(); } if(this._explicitSubviewsStruct !== null) { clonedView._explicitSubviewsStruct = this._explicitSubviewsStruct.slice(); } if(this._collectionBinder) { clonedView._collectionBinder = new CollectionBinder( { view: clonedView, keyPath: this._collectionBinder.keyPath, animate: this._collectionBinder.animate, keyProp: this._collectionBinder.keyProp, collection: null, collectionPathArray: this._collectionBinder.collectionPathArray }); } if(this._modelBindersMap) { clonedView._modelBindersMap = this._modelBindersMap.clone(); clonedView._modelBindersMap.setView(clonedView); } clonedView._itemAlias = this._itemAlias; return clonedView; }
javascript
{ "resource": "" }
q41369
train
function(element) { var i, l; this.element = element; this._rebindSubViews(element, { subviewIndex: 0, subviewsStructIndex: 0, index: 0 }); if(this._modelBindersMap) { this._modelBindersMap.setView(this); } if(this._collectionBinder) { this._collectionBinder.view = this; } }
javascript
{ "resource": "" }
q41370
BinderLogReader
train
function BinderLogReader () { this.config = defaultConfig var staticLogsUrl = this.config.host + ':' + this.config.elasticsearch.port this.client = new elasticsearch.Client({ host: staticLogsUrl, log: 'error' }) }
javascript
{ "resource": "" }
q41371
train
function (config) { if (!config) { config = defaultConfig } var error = validateConfig(config) if (error) { } config = assign(defaultConfig, config) return new BinderLogReader(config) }
javascript
{ "resource": "" }
q41372
train
function(done) { var source = __dirname + '/background.js'; var dest = self.dir + '/background.js'; fs.readFile(source, 'utf8', function(err, background) { if (err) return done(err); // Make background.js connect with the websocket server on // this port background = background.replace('$PORT', self.port); fs.writeFile(dest, background, done); }); }
javascript
{ "resource": "" }
q41373
closeServer
train
function closeServer(done) { if (self.server) { self.server.close(); self.server.removeListener('error', handlers.relayError); } self.httpServer.close(done); }
javascript
{ "resource": "" }
q41374
removeExtensionDir
train
function removeExtensionDir(done) { if (!self.dir) return done(null); rimraf(self.dir, done); }
javascript
{ "resource": "" }
q41375
createAndSpawn
train
function createAndSpawn(opts) { const spawned = createSpawn(opts) const termination = spawned.spawn() return { termination, proc: spawned.proc } }
javascript
{ "resource": "" }
q41376
boolStringOption
train
function boolStringOption(value){ if(value === 'true' || value === true) return true; if(value === 'false' || value === false) return false; return value; }
javascript
{ "resource": "" }
q41377
createExpressAppServer
train
function createExpressAppServer(app, port) { return new P(function(resolve, reject) { var appServer = app.listen(port, function() { var addr = appServer.address(); resolve({ app: app, appServer: appServer, serverUrl: url.format({ protocol: 'http', hostname: addr.address, port: addr.port }) }); }); }); }
javascript
{ "resource": "" }
q41378
encode
train
function encode(args) { const argc = args.length; let len = 1; let off = 0; var i; // data length for (i = 0; i < argc; i += 1) { len += 4 + args[i].length; } // buffer const buf = Buffer.alloc(len); // pack meta buf[off += 1] = (VERSION << 4) | argc; // pack args for (i = 0; i < argc; i += 1) { const arg = args[i]; buf.writeUInt32BE(arg.length, off); off += 4; arg.copy(buf, off); off += arg.length; } return buf; }
javascript
{ "resource": "" }
q41379
proxy
train
function proxy(options, format) { var tty = options.tty , method = options.method , re = /(%[sdj])+/g , start , end; if(arguments.length === 1) { return method.apply(console, []); } var arg, i, replacing, replacements, matches, tag; replacing = (typeof format === 'string') && re.test(format) && arguments.length > 2; replacements = [].slice.call(arguments, 2); if(format instanceof AnsiColor) { replacing = true; if(!replacements.length) { replacements.unshift(format); format = '%s'; } } if(!replacing) { replacements.unshift(format); return method.apply(console, replacements); } matches = (format && (typeof format.match === 'function')) ? format.match(re) : []; if(format instanceof AnsiColor) { if(!tty) { format = format.v; }else{ tag = format.start(tty); format = format.valueOf(tty); } } //console.dir('is tty: ' + tty); if(tty) { re = /(%[sdj])/g; var fmt, result, j = 0; while((result = re.exec(format))) { if(j === replacements.length) { break; } arg = replacements[j]; //console.dir('processing ansi replacement: ' + typeof(arg)); fmt = result[1]; start = format.substr(0, result.index); end = format.substr(result.index + result[0].length); //console.dir('re format: ' + fmt); //console.dir('re start: ' + start); //console.dir('re end: ' + end); if((arg instanceof AnsiColor)) { //console.dir('update arg value: ' + typeof(arg.v)); if(fmt === '%j') { arg.v = JSON.stringify(arg.v, circular()); } format = start + '%s' + end; } j++; } } for(i = 0;i < replacements.length;i++) { arg = replacements[i]; if(arg instanceof AnsiColor) { replacements[i] = arg.valueOf(tty, tag); } } replacements.unshift(format); return method.apply(options.scope ? options.scope : console, replacements); }
javascript
{ "resource": "" }
q41380
format
train
function format(fmt) { var args = [].slice.call(arguments, 0); var tty = true; var test = (typeof fmt === 'function') ? fmt : null; if(test) { tty = test(); args.shift(); } args.unshift({scope: util, method: util.format, tty: tty}); //console.dir(args); return proxy.apply(null, args); }
javascript
{ "resource": "" }
q41381
main
train
function main(option, parser, force) { if(typeof option === 'function') { parser = option; option = null; } if(option !== false) { option = option || parse.option; parser = parser || parse; } //var mode = parse.auto; if(typeof parser === 'function') { module.exports.mode = parser(parse.modes, option, process.argv.slice(2)); } initialize(force); return module.exports; }
javascript
{ "resource": "" }
q41382
camel
train
function camel(s) { return s.replace(/_(.)/g, function(_, l) { return l.toUpperCase() }) }
javascript
{ "resource": "" }
q41383
camelize
train
function camelize(obj) { if (!obj || typeof obj === 'string') return obj if (Array.isArray(obj)) return obj.map(camelize) if (typeof obj === 'object') { return Object.keys(obj).reduce(function(camelizedObj, k) { camelizedObj[camel(k)] = camelize(obj[k]) return camelizedObj }, {}) } return obj }
javascript
{ "resource": "" }
q41384
_mainMap
train
function _mainMap(data, schema, options) { options = options || {}; var mapping = _map(data, schema, options); if (options.removeChanged) { var mappedFields = _getMappedFields(schema); mappedFields.forEach(function (field) { _removeMappedFields(mapping, field); }); mapping = _cleanArrays(mapping); } return mapping; }
javascript
{ "resource": "" }
q41385
_map
train
function _map(data, schema, options) { options = options || {}; if (!schema || data === null) { return data; } if (schema instanceof Array) { return _mapArray(data, schema, options); } if (typeof schema === 'object') { return _mapObject(data, schema, options); } return schema; }
javascript
{ "resource": "" }
q41386
_removeMappedFields
train
function _removeMappedFields(mapping, path) { if (typeof path === 'number') { delete mapping[path]; return mapping; } var keys = path.split(_separator); if (keys.length <= 1) { delete mapping[path]; return mapping; } return _removeMappedFields( mapping[path[0]], keys .slice(1) .join(_separator) ); }
javascript
{ "resource": "" }
q41387
_getMappedFields
train
function _getMappedFields(schema) { if (schema === undefined || schema === null) { return; } if (schema instanceof Array) { return schema .reduce(function (memo, key) { var mappedField = _getMappedFields(key); if (mappedField !== undefined) { memo = memo.concat(mappedField); } return memo; }, []); } if (typeof schema === 'object') { return Object .keys(schema) .reduce(function (memo, key) { var mappedField = _getMappedFields(schema[key]); if (mappedField !== undefined) { memo = memo.concat(mappedField); } return memo; }, []); } if (typeof schema === 'string' || typeof schema === 'number') { return schema; } }
javascript
{ "resource": "" }
q41388
_mapArray
train
function _mapArray(data, schema, options) { var base = []; if (data instanceof Array && options.keep) { base = _clone(data); } if (typeof data === 'object' && options.keep) { base = Object .keys(data) .map(function(key) { return data[key]; }); } return schema .reduce(function (memo, nestedSchema) { memo.push(_mapDataValue(data, nestedSchema)); return memo; }, base); }
javascript
{ "resource": "" }
q41389
_mapObject
train
function _mapObject(data, schema, options) { return Object .keys(schema) .reduce(function (memo, key) { memo[key] = _mapDataValue(data, schema[key]); return memo; }, options.keep ? _clone(data) : {}); }
javascript
{ "resource": "" }
q41390
_mapDataValue
train
function _mapDataValue(data, nestedSchema) { if (typeof nestedSchema === 'function') { return nestedSchema.apply(data); } else if (typeof nestedSchema === 'object') { return _map(data, nestedSchema); } else { return _getDataValue(data, nestedSchema); } }
javascript
{ "resource": "" }
q41391
_getDataValue
train
function _getDataValue(data, path) { if (data === undefined) { return undefined; } if (typeof path === 'number') { return data[path]; } if (typeof path === 'string') { var keys = path.split(_separator); if (keys.length <= 1) { return data[keys[0]]; } return _getDataValue( data[keys[0]], keys .slice(1) .join(_separator) ); } return undefined; }
javascript
{ "resource": "" }
q41392
train
function (app) { let p = pathUtil.getCronPath(app.getBase(), app.getServerType()); if (p) { return Loader.load(p, app); } }
javascript
{ "resource": "" }
q41393
train
function (server, app) { let env = app.get(Constants.RESERVED.ENV); let p = path.join(app.getBase(), app.get(Constants.RESERVED.SERVICE_PATH), Constants.FILEPATH.CRON); if (!fs.existsSync(p)) { p = path.join(app.getBase(), Constants.FILEPATH.CONFIG_DIR, env, path.basename(Constants.FILEPATH.CRON)); if (!fs.existsSync(p)) { return; } } app.loadConfigBaseApp(Constants.RESERVED.CRONS, app.get(Constants.RESERVED.SERVICE_PATH), Constants.FILEPATH.CRON); let crons = app.get(Constants.RESERVED.CRONS); for (let serverType in crons) { if (app.serverType === serverType) { let list = crons[serverType]; for (let i = 0; i < list.length; i++) { if (!list[i].serverId) { checkAndAdd(list[i], server.crons, server); } else { if (app.serverId === list[i].serverId) { checkAndAdd(list[i], server.crons, server); } } } } } }
javascript
{ "resource": "" }
q41394
train
function (isGlobal, server, err, msg, session, resp, opts, cb) { let fm; if (isGlobal) { fm = server.globalFilterService; } else { fm = server.filterService; } if (fm) { if (isGlobal) { fm.afterFilter(err, msg, session, resp, function () { // do nothing }); } else { fm.afterFilter(err, msg, session, resp, function (err) { cb(err, resp, opts); }); } } }
javascript
{ "resource": "" }
q41395
train
function (isGlobal, server, err, msg, session, resp, opts, cb) { let handler; if (isGlobal) { handler = server.app.get(Constants.RESERVED.GLOBAL_ERROR_HANDLER); } else { handler = server.app.get(Constants.RESERVED.ERROR_HANDLER); } if (!handler) { logger.debug('no default error handler to resolve unknown exception. ' + err.stack); utils.invokeCallback(cb, err, resp, opts); } else { if (handler.length === 5) { handler(err, msg, resp, session, cb); } else { handler(err, msg, resp, session, opts, cb); } } }
javascript
{ "resource": "" }
q41396
train
function (route) { if (!route) { return null; } let ts = route.split('.'); if (ts.length !== 3) { return null; } return { route: route, serverType: ts[0], handler: ts[1], method: ts[2] }; }
javascript
{ "resource": "" }
q41397
Metadata
train
function Metadata(resolve, reject, query, options) { this.resolve = this._wrapResolveForProfile(resolve); this.reject = reject; this.query = query; // The query in case we have to build a backtrace this.options = options || {}; this.cursor = false; }
javascript
{ "resource": "" }
q41398
start
train
function start(app, config, callback) { if (httpServer) { DEBUG && debug('***ignore*** http server is already running!'); callback && callback(false); return httpServer; } config = _.merge({}, DEF_CONFIG, config); DEBUG && debug('start http server http://' + config.host + ':' + config.port); httpServer = http.createServer(app).listen(config.port, config.host, callback); httpServer.on('close', function () { DEBUG && debug('close http server'); httpServer = null; }); process.on('exit', function () { stop(); }); if (process.env.NODE_ENV === 'production') { process.on('uncaughtException', function (err) { console.error('***uncaughtException***', err); }); } return httpServer; }
javascript
{ "resource": "" }
q41399
stop
train
function stop(callback) { if (httpServer) { DEBUG && debug('stop http server'); try { httpServer.close(); } catch (e) { } httpServer = null; } else { DEBUG && debug('***ignore*** http server is not running!'); } callback && callback(false); }
javascript
{ "resource": "" }