_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q43000
init
train
function init (directory, callback) { var source = path.join(__dirname, 'template'); ncp(source, directory, callback); }
javascript
{ "resource": "" }
q43001
start
train
function start (outputFunction) { startTime = new Date() failures = [] count = 0 stats = {success: 0, failure: 0, skipped: 0} log = outputFunction || log }
javascript
{ "resource": "" }
q43002
result
train
function result (type, error) { if (count % 40 === 0) { log('\n ') } count++ stats[type]++ log(SYMBOLS[type] + ' ') if (type === 'failure') { failures.push(error) } }
javascript
{ "resource": "" }
q43003
end
train
function end () { var diff = new Date() - startTime log('\n\n') log(' ' + SYMBOLS.success + ' ' + (stats.success + ' passing ').green) log(('(' + diff + 'ms)').grey) if (stats.skipped) { log('\n ' + SYMBOLS.skipped + ' ' + (stats.skipped + ' pending').cyan) } if (stats.failure) { log('\n ' + SYMBOLS.failure + ' ' + (stats.failure + ' failing').red) // Log all accumulated errors log('\n\n') failures.forEach(logError) } log('\n\n') }
javascript
{ "resource": "" }
q43004
logError
train
function logError (failure, index) { index = index + 1 if (index > 1) { log('\n\n') } log(' ' + index + ') ' + failure.description + ': ') if (failure.environment) { log(('(' + failure.environment + ')').grey) } log('\n\n') // Log the actual error message / stack trace / diffs var intend = 4 + String(index).length var error = formatError(failure.error, intend) if (!_empty(error.message)) { log(error.message + '\n') } if (!_empty(error.stack)) { log('\n' + error.stack.grey + '\n') } }
javascript
{ "resource": "" }
q43005
intendLines
train
function intendLines (string, trim, intend) { var intendStr = new Array(intend + 1).join(' ') return string .split('\n') .map(function (s) { return trim ? s.trim() : s }) .join('\n') .replace(/^/gm, intendStr) }
javascript
{ "resource": "" }
q43006
registerComponents
train
function registerComponents (newComponents) { var config = Vue$2.config; var newConfig = {}; if (Array.isArray(newComponents)) { newComponents.forEach(function (component) { if (!component) { return } if (typeof component === 'string') { components[component] = true; newConfig[component] = true; } else if (typeof component === 'object' && typeof component.type === 'string') { components[component.type] = component; newConfig[component.type] = true; } }); var oldIsReservedTag = config.isReservedTag; config.isReservedTag = function (name) { return newConfig[name] || oldIsReservedTag(name) }; } }
javascript
{ "resource": "" }
q43007
ensureLogsRotated
train
function ensureLogsRotated(stats){ // TODO: other writes should wait until this is done var today = new Date(), modifiedDate = new Date(stats.mtime), archivedFileName; if(!_logDatesMatch(today, modifiedDate)){ archivedFileName = _createRotatedLogName(this.config.path, modifiedDate); console.log('Log file modified previous to today, archiving to: ' + archivedFileName); return fs.renameAsync(this.config.path, archivedFileName) .bind(this) .then(this.createEmptyFile); } }
javascript
{ "resource": "" }
q43008
_logDatesMatch
train
function _logDatesMatch(d1, d2){ return ((d1.getFullYear()===d2.getFullYear())&&(d1.getMonth()===d2.getMonth())&&(d1.getDate()===d2.getDate())); }
javascript
{ "resource": "" }
q43009
_createRotatedLogName
train
function _createRotatedLogName(logPath, modifiedDate){ var logName = logPath, suffixIdx = logPath.lastIndexOf('.'), suffix = ''; if(suffixIdx > -1){ suffix = logName.substr(suffixIdx, logName.length); logName = logName.replace( suffix, ('.' + modifiedDate.getFullYear() + '-' + (modifiedDate.getMonth() + 1) + '-' + modifiedDate.getDate() ) + suffix ); } else { logName = logName + ('.' + modifiedDate.getFullYear() + '-' + (modifiedDate.getMonth() + 1) + '-' + modifiedDate.getDate()); } return logName; }
javascript
{ "resource": "" }
q43010
getStackTraceArray
train
function getStackTraceArray() { var origStackTraceLimit = Error.stackTraceLimit var origPrepareStackTrace = Error.prepareStackTrace // Collect all stack frames. Error.stackTraceLimit = Infinity // Get a structured stack trace as an `Array` of `CallSite` objects, each of which represents a stack frame, with frames for native Node functions and this file removed. Error.prepareStackTrace = function (error, structuredStackTrace) { return structuredStackTrace.filter(function (frame) { var filePath = frame.getFileName() // Skip frames from within this module (i.e., `dantil`). if (filePath === __filename) { return false } // Skip frames for native Node functions (e.g., `require()`). if (!/\//.test(filePath)) { return false } return true }) } // Collect the stack trace. var stack = Error().stack // Restore stack trace configuration after collecting stack trace. Error.stackTraceLimit = origStackTraceLimit Error.prepareStackTrace = origPrepareStackTrace return stack }
javascript
{ "resource": "" }
q43011
writeToProcessStream
train
function writeToProcessStream(processStreamName, string) { var writableStream = process[processStreamName] if (writableStream) { writableStream.write(string + '\n') } else { throw new Error('Unrecognized process stream: ' + exports.stylize(processStreamName)) } }
javascript
{ "resource": "" }
q43012
prettify
train
function prettify(args, options) { if (!options) { options = {} } var stylizeOptions = { // Number of times to recurse while formatting; defaults to 2. depth: options.depth, // Format in color if the terminal supports color. colors: exports.colors.supportsColor, } // Use `RegExp()` to get correct `reMultiLined.source`. var reMultiLined = RegExp('\n', 'g') var reWhitespaceOnly = /^\s+$/ var indent = ' ' var prevArgIsSeperateLine = false var argsArray = Array.prototype.slice.call(args) // Remove any leading newline characters in the first argument, and prepend them to the remainder of the formatted arguments instead of including the characters in the indentation of each argument (as occurs with other whitespace characters in the first argument). var firstArg = argsArray[0] var leadingNewlines = '' if (/^\n+/.test(firstArg)) { var lastNewlineIdx = firstArg.lastIndexOf('\n') if (lastNewlineIdx === firstArg.length - 1) { argsArray.shift() } else { argsArray[0] = firstArg.slice(lastNewlineIdx + 1) firstArg = firstArg.slice(0, lastNewlineIdx + 1) } leadingNewlines = firstArg } return leadingNewlines + argsArray.reduce(function (formattedArgs, arg, i, args) { var argIsString = typeof arg === 'string' // Parse numbers passed as string for styling. if (argIsString && /^\S+$/.test(arg) && !isNaN(arg)) { arg = parseFloat(arg) argIsString = false } // Do not stylize strings passed as arguments (i.e., not `Object` properties). This also preserves any already-stylized arguments. var formattedArg = !options.stylizeStings && argIsString ? arg : exports.stylize(arg, stylizeOptions) if (i === 0) { // Extend indent for remaining arguments with the first argument's leading whitespace, if any. if (argIsString) { // Get the substring of leading whitespace characters from the start of the string, up to the first non-whitespace character, if any. var firstNonWhitespaceIndex = arg.search(/[^\s]/) arg = arg.slice(0, firstNonWhitespaceIndex === -1 ? arg.length : firstNonWhitespaceIndex) // JavaScript will not properly indent if '\t' is appended to spaces (i.e., reverse order as here). // If the first argument is entirely whitespace, indent all remaining arguments with that whitespace. indent = reWhitespaceOnly.test(formattedArg) ? arg : arg + indent // If first argument is entirely whitespace, exclude from output because it serves only to set indentation of all remaining arguments. if (reWhitespaceOnly.test(formattedArg)) { // Force the next argument to be pushed to `formattedArgs` to avoid concatenating with `undefined` (because `formattedArgs` remains empty). prevArgIsSeperateLine = true } else { formattedArgs.push(formattedArg) } } else { formattedArgs.push(formattedArg) if (arg instanceof Object) { // Do not indent remaining arguments if the first argument is of a complex type. indent = '' // Format the complex type on a separate line. prevArgIsSeperateLine = true } } } else if (arg instanceof Object && (!Array.isArray(arg) || reMultiLined.test(formattedArg) || args[0] instanceof Object)) { // Format plain `Object`s, `Array`s with multi-line string representations, and `Array`s when the first argument is of a complex type on separate lines. formattedArgs.push(indent + formattedArg.replace(reMultiLined, reMultiLined.source + indent)) prevArgIsSeperateLine = true } else if (prevArgIsSeperateLine) { // Format anything that follows a multi-line string representations on a new line. formattedArgs.push(indent + formattedArg) prevArgIsSeperateLine = false } else { // Concatenate all consecutive primitive data types. formattedArgs[formattedArgs.length - 1] += ' ' + formattedArg } return formattedArgs }, []).join('\n') }
javascript
{ "resource": "" }
q43013
stringifyStackFrame
train
function stringifyStackFrame(stackFrame, label) { var frameString = stackFrame.toString() // Colorize function name (or `label`, if provided). var lastSpaceIndex = frameString.lastIndexOf(' ') if (lastSpaceIndex !== -1) { return exports.colors.cyan(label || frameString.slice(0, lastSpaceIndex)) + frameString.slice(lastSpaceIndex) } // If there is no leading function, method, or type name (e.g., then root Node call: "node.js:405:3"), and `label` was provided. if (label) { return exports.colors.cyan(label) + ' ' + frameString } return frameString }
javascript
{ "resource": "" }
q43014
ProcessWatcher
train
function ProcessWatcher(pid, parent) { var self = this; this.dead = false; // check first if process is alive if (exports.alive(pid) === false) { process.nextTick(function () { self.dead = true; self.emit('dead'); }); return self; } // use disconnect to detect parent death if (parent && exports.support.disconnect) { var listen = function() { self.dead = true; self.stop(); self.emit('dead'); } parent.once('disconnect', listen); this.stop = parent.removeListener.bind(null, 'disconnect', listen); this.on('newListener', function (eventName) { if (eventName !== 'cycle') return; process.nextTick(function () { self.emit('cycle'); }); }); return self; } // fallback to an setInterval try/catch check var timer = setInterval(function () { if (exports.alive(pid) === false) { self.dead = true; self.stop(); self.emit('dead'); } self.emit('cycle'); }); this.stop = clearInterval.bind(null, timer); }
javascript
{ "resource": "" }
q43015
validate
train
function validate (config) { /** Make sure the config object was passed. */ if (!config) { throw new TypeError('Missing configuration object.'); } /** Make sure the panic url is provided. */ if (typeof config.panic !== 'string') { throw new TypeError('Panic server URL "config.panic" not provided.'); } /** Make sure config.clients is an array. */ if (isArray(config.clients) === false) { throw new TypeError('"config.clients" is not an array.'); } var str = JSON.stringify; /** Validate the client objects. */ config.clients.forEach(function (client) { if (!client) { throw new Error('Client "' + client + '" is not an object.'); } if (!client.type) { throw new Error('Missing client.type attribute: ' + str(client)); } }); }
javascript
{ "resource": "" }
q43016
Manager
train
function Manager (remote) { /** Allow usage without `new`. */ if (!(this instanceof Manager)) { return new Manager(remote); } /** * @property {Boolean} isRemote * Whether the manager is remote. */ this.isRemote = false; /** * @property {Socket} socket * A socket.io instance, or `null` if using locally. */ this.socket = null; /** If only using locally, stop here. */ if (!remote) { return this; } /** If it's a URL, connect to it. */ if (typeof remote === 'string') { this.isRemote = true; /** Automatically postfix the manager scope. */ var url = remote + '/panic-manager'; /** Connect to the remote manager. */ this.socket = socket.client(url); return this; } /** Listen for /panic-manager connections. */ var server = socket.server(remote).of('/panic-manager'); /** Listen for connections. */ server.on('connection', function (socket) { /** Listen for start commands. */ socket.on('start', function (config) { spawn(config); }); }); this.socket = server; }
javascript
{ "resource": "" }
q43017
recent
train
function recent(views, options) { options = options || {}; var prop = options.prop || 'data.date'; var limit = options.limit || 10; var res = {}; for (var key in views) { if (views.hasOwnProperty(key)) { var date = createdDate(key, views[key], prop); res[date] = res[date] || []; res[date].push(key); } } var keys = Object.keys(res).sort(); var len = keys.length; var num = 0; var acc = {}; while (len-- && num < limit) { var arr = res[keys[len]]; for (var j = 0; j < arr.length; j++) { var key = arr[j]; acc[key] = views[key]; num++; if (num > limit) break; } } return acc; }
javascript
{ "resource": "" }
q43018
createdDate
train
function createdDate(key, value, prop) { var val = prop ? get(value, prop) : value; var str = val || key; var re = /^(\d{4})-(\d{2})-(\d{2})/; var m = re.exec(str); if (!m) return null; return String(m[1]) + String(m[2]) + String(m[3]); }
javascript
{ "resource": "" }
q43019
printError
train
function printError(error) { process.stderr.write(red); console.error(error.trace); process.stderr.write(yellow); console.error('an error occurred, please file an issue'); process.stderr.write(reset); process.exit(1); }
javascript
{ "resource": "" }
q43020
routes
train
function routes(app) { this.app = app; var seminarjs = this; app.get('/version', function (req, res) { res.setHeader('Content-Type', 'application/json'); res.send(JSON.stringify({ 'name': seminarjs.get('name'), 'seminarjsVersion': seminarjs.version })); }); return this; }
javascript
{ "resource": "" }
q43021
getSimiliarString
train
function getSimiliarString(base, relation) { var length = Math.round(base.length * relation), r = '', i, str do { str = getRandomString(base.length - length) } while (str && str[0] === base[length]) for (i = 0; i < length; i++) { r += base[i] // substr(...) seems to be optimized } return r + str }
javascript
{ "resource": "" }
q43022
compare
train
function compare(a, b, n) { var n2 = n, then = Date.now() while (n2--) { a === b } return (Date.now() - then) * 1e6 / n }
javascript
{ "resource": "" }
q43023
constantCompare
train
function constantCompare(a, b, n) { var n2 = n, then = Date.now(), eq = false, len, i while (n2--) { len = Math.max(a.length, b.length) for (i = 0; i < len; i++) { if (a.length >= i && b.length >= i && a[i] !== b[i]) { eq = false } } } return (Date.now() - then) * 1e6 / n }
javascript
{ "resource": "" }
q43024
stat
train
function stat(fn, n) { var n2 = n, times = [], sum = 0, t, avg, median while (n2--) { t = fn() sum += t times.push(t) } avg = sum / n times.sort(function (a, b) { return a - b }) median = times[Math.floor(times.length / 2)] if (times.length % 2 === 0) { median = (median + times[times.length / 2 - 1]) / 2 } return { avg: avg, median: median } }
javascript
{ "resource": "" }
q43025
merge
train
function merge() { var res = {}; for (var i = 0; i < arguments.length; i++) { if (arguments[i]) { Object.assign(res, arguments[i]); } else { if (typeof arguments[i] === 'undefined') { throw new Error('m(): argument ' + i + ' undefined'); } } } return res; }
javascript
{ "resource": "" }
q43026
publish
train
function publish(opts) { // stream options var defaults = { enableResolve: false, directory: './build', debug: false }; var options = utils.shallowMerge(opts, defaults); return through(function(file, enc, callback) { if (file.isNull()) return callback(null, file); // emit error event when pass stream if (file.isStream()) { this.emit('error', new gutil.PluginError(PLUGIN, 'Streams are not supported!')); return callback(); } // resolve the HTML files var blocks = utils.getSplitBlock(file.contents.toString()); var result = utils.resolveSourceToDestiny(blocks, options); file.contents = new Buffer(result); // resolve the files linked by tag script and link if (options.enableResolve) { var fileSource = utils.getBlockFileSource(blocks); utils.resolveFileSource(fileSource, options); } callback(null, file); }); }
javascript
{ "resource": "" }
q43027
multiple
train
function multiple(pool, fn, queries, callback) { let queryObjects = queries.map(query => { if (typeof query === 'string') { return { text: query, values: [] }; } return Object.assign({ values: [] }, query); }); if (callback && typeof callback === 'function') { return fn(pool, queryObjects, callback); } return new Promise((resolve, reject) => { fn(pool, queryObjects, (error, result) => { if (error) { return reject(error); } resolve(result); }); }); }
javascript
{ "resource": "" }
q43028
normalize
train
function normalize(args) { let result = { queries: null, callback: null }; if (args.length === 1 && Array.isArray(args[0])) { result.queries = args[0]; } else if (args.length === 2 && Array.isArray(args[0])) { result.queries = args[0]; if (typeof args[1] === 'function') { result.callback = args[1]; } } else { result.queries = args; if (typeof result.queries[result.queries.length - 1] === 'function') { result.callback = result.queries.pop(); } } return result; }
javascript
{ "resource": "" }
q43029
performParallel
train
function performParallel(pool, queries, callback) { let count = 0, results = new Array(queries.length); queries.forEach((query, index) => { pool.query(query, (error, result) => { if (error) { return callback(error, results); } results[index] = result; if (++count === queries.length) { return callback(null, results); } }); }); }
javascript
{ "resource": "" }
q43030
performTransaction
train
function performTransaction(pool, queries, callback) { pool.connect((error, client, done) => { if (error) { done(client); return callback(error, null); } client.query('BEGIN', error => { if (error) { return rollback(client, done, error, callback); } sequence(queries, (results, current, next) => { let query = current.text, params = current.values; client.query(query, params, (error, result) => { if (error) { return rollback(client, done, error, callback); } results.push(result); next(); }); }, (results) => { client.query('COMMIT', error => { if (error) { return rollback(client, done, error, callback); } done(client); return callback(null, results); }); }); }); }); }
javascript
{ "resource": "" }
q43031
rollback
train
function rollback(client, done, error, callback) { client.query('ROLLBACK', rollbackError => { done(rollbackError); return callback(rollbackError || error, null); }); }
javascript
{ "resource": "" }
q43032
flatten
train
function flatten(source, opts) { opts = opts || {}; var delimiter = opts.delimiter = opts.delimiter || '.'; var o = {}; function iterate(source, parts) { var k, v; parts = parts || []; for(k in source) { v = source[k]; if(v && typeof v === 'object' && Object.keys(v).length) { iterate(v, parts.concat(k)); }else{ o[parts.concat(k).join(delimiter)] = v; } } } iterate(source); return o; }
javascript
{ "resource": "" }
q43033
isValidLevel
train
function isValidLevel ( level ) { return reLevel.test( level ) || isFunction( level ) || Array.isArray( level ); }
javascript
{ "resource": "" }
q43034
printMsg
train
function printMsg ( msgId, data ) { var outputFn; if ( messages.hasOwnProperty( msgId) ) { switch ( msgId.match( /^[A-Z]+/ )[0] ) { case 'INFO': outputFn = grunt.log.writeln; break; case 'VERBOSE': outputFn = grunt.verbose.writeln; break; case 'DEBUG': outputFn = grunt.log.debug; break; default: outputFn = grunt.fail.warn; } // switch outputFn( grunt.template.process( messages[ msgId ], { data: data } ) ); } }
javascript
{ "resource": "" }
q43035
formatMessage
train
function formatMessage (message) { return '<error' + attr(message, 'line') + attr(message, 'column') + attr(message, 'severity') + attr(message, 'message') + ('source' in message ? attr(message, 'source') : '') + ' />' }
javascript
{ "resource": "" }
q43036
formatResult
train
function formatResult (result) { return [ '<file name="' + result.filename + '">', result.messages.map(formatMessage).join('\n'), '</file>' ].join('\n') }
javascript
{ "resource": "" }
q43037
restoreLib
train
function restoreLib(err1) { fs.move(ORIG, LIB, {clobber: true}, function(err2) { callback(err1 || err2) }) }
javascript
{ "resource": "" }
q43038
train
function(chunk) { var patsy = this; chunk = chunk.trim(); if(chunk == 'exit'){ this.scripture.print('[King Arthur]'.magenta + ': On second thought, let\'s not go to Camelot, it\'s a silly place. I am leaving you behind squire!\n'); program.prompt('[Patsy]'.cyan + ': Sire, do you really want to leave me here all alone? [Y/n] (enter for yes): ', function(proceed){ // Did he answer yes? (or DEFAULT) if (( proceed.search(/yes|y|j|ja/g) !== -1 ) || (( proceed.trim() === '' ))) { util.print('[King Arthur]'.magenta + ': I hold your oath fullfilled!\n'); patsy.die(); } // Did he answer no? else if( proceed.search(/no|n|nei/g) !== -1 ) { util.print('[King Arthur]'.magenta + ': No, I am just pulling your leg mate! \n'); util.print('[Patsy]'.cyan + ': <shrugs> \n'); } // No valid input else { util.print('[King Arthur]'.magenta + ': I can\'t do that!? It\'s to silly! I\'m leaving, come Patsy! <sound of two half coconuts banging together fading out..>\n'); process.exit(); } }); } else if(chunk == 'test') { this.scripture.print('[Patsy]'.yellow + ': Running tests!\n'); this.runTests(); } }
javascript
{ "resource": "" }
q43039
train
function(relativeProjectPath, relative){ var src = []; var complete_path; var patsy = this; if(patsy.utils.isArray(relative)){ // For each path, check if path is negated, if it is, remove negation relative.forEach(function(_path){ if(patsy.utils.isPathNegated(_path)){ _path = _path.slice(1); complete_path = '!' + relativeProjectPath + _path; } else { complete_path = relativeProjectPath + _path; } src.push(path.normalize(complete_path)); }); } else { if(patsy.utils.isPathNegated(relative)){ var _path = relative.slice(1); complete_path = '!' + relativeProjectPath + _path; } else { complete_path = relativeProjectPath + relative; } src = path.normalize(complete_path); } return src; }
javascript
{ "resource": "" }
q43040
train
function(how){ var _child, _cfg, patsy = this; var _execCmd = []; if(typeof this.project_cfg.project === 'undefined'){ /** * Require config from the library * * @var Object * @source patsy */ var config = require('./config')({ app_path : opts.app_path, verbose : opts.verbose, project_path : '' }); this.project_cfg = config.load(); } process.chdir(this.project_cfg.project.environment.abs_path); _cfg = this.project_cfg || this.config.load(); process.chdir(opts.app_path); if(patsy.utils.isWin){ _execCmd.push('cmd'); // New args will go to cmd.exe, then we append the args passed in to the list // the /c part tells it to run the command. Thanks, Windows... _execCmd.push('/c'); _execCmd.push('node_modules\\.bin\\grunt'); } else { _execCmd.push('node_modules/.bin/grunt'); } // Append needed arguments for grunt _execCmd.push('--path'); _execCmd.push(_cfg.project.environment.abs_path); _execCmd.push(opts.verbose ? '-v' : ''); _execCmd.push(opts.force ? '--force' : ''); _execCmd.push(how); _child = exec(_execCmd.join(' '), function (error, stdout, stderr) { util.print(stdout); if(stderr){ console.log(stderr); } if (error !== null) { patsy.scripture.print('\n[Patsy]'.yellow + ': The grunt died!'); if(opts.verbose){ console.log('>> ERROR'.red + ':' , error); } process.exit(1); } }); }
javascript
{ "resource": "" }
q43041
Image
train
function Image(src) { if (!(this instanceof Image)) { return new Image(src) } if (typeof src !== 'string') { throw new Error('param `src` must be a string') } var ret = reg.exec(src) if (!ret) { throw new Error('invalid param `src`') } this.src = src this.host = ret[1] || defaultHost this.version = ret[2] ? ret[2].slice(0, -1) : '' this.hash = ret[3] this.ext = ret[4] }
javascript
{ "resource": "" }
q43042
train
function ($placeholder, file, that) { $.ajax({ type: "post", url: that.options.imagesUploadScript, xhr: function () { var xhr = new XMLHttpRequest(); xhr.upload.onprogress = that.updateProgressBar; return xhr; }, cache: false, contentType: false, complete: function (jqxhr) { that.uploadCompleted(jqxhr, $placeholder); }, processData: false, data: that.options.formatData(file) }); }
javascript
{ "resource": "" }
q43043
train
function (file, that) { $.ajax({ type: "post", url: that.options.imagesDeleteScript, data: { file: file } }); }
javascript
{ "resource": "" }
q43044
train
function (options) { if (options && options.$el) { this.$el = options.$el; } this.options = $.extend(this.defaults, options); this.setImageEvents(); if (this.options.useDragAndDrop === true){ this.setDragAndDropEvents(); } this.preparePreviousImages(); }
javascript
{ "resource": "" }
q43045
train
function(buttonLabels){ var label = 'Img'; if (buttonLabels === 'fontawesome' || typeof buttonLabels === 'object' && !!(buttonLabels.fontawesome)) { label = '<i class="fa fa-picture-o"></i>'; } if (typeof buttonLabels === 'object' && buttonLabels.img) { label = buttonLabels.img; } return '<button data-addon="images" data-action="add" class="medium-editor-action mediumInsert-action">'+label+'</button>'; }
javascript
{ "resource": "" }
q43046
train
function ($placeholder) { var that = this, $selectFile, files; $selectFile = $('<input type="file" multiple="multiple">').click(); $selectFile.change(function () { files = this.files; that.uploadFiles($placeholder, files, that); }); $.fn.mediumInsert.insert.deselect(); return $selectFile; }
javascript
{ "resource": "" }
q43047
train
function (e) { var $progress = $('.progress:first', this.$el), complete; if (e.lengthComputable) { complete = e.loaded / e.total * 100; complete = complete ? complete : 0; $progress.attr('value', complete); $progress.html(complete); } }
javascript
{ "resource": "" }
q43048
train
function (jqxhr, $placeholder) { var $progress = $('.progress:first', $placeholder), $img; $progress.attr('value', 100); $progress.html(100); if (jqxhr.responseText) { $progress.before('<figure class="mediumInsert-images"><img src="'+ jqxhr.responseText +'" draggable="true" alt=""></figure>'); $img = $progress.siblings('img'); $img.load(function () { $img.parent().mouseleave().mouseenter(); }); } else { $progress.before('<div class="mediumInsert-error">There was a problem uploading the file.</div>'); setTimeout(function () { $('.mediumInsert-error:first', $placeholder).fadeOut(function () { $(this).remove(); }); }, 3000); } $progress.remove(); $placeholder.closest('[data-medium-element]').trigger('keyup').trigger('input'); }
javascript
{ "resource": "" }
q43049
train
function(key, callback) { if (key) { this.store.proxy.remove(this.prefix + key); if (callback) { callback(null, key); } } else { if (callback) { callback('missing key'); } } }
javascript
{ "resource": "" }
q43050
train
function(key, callback) { if (key) { var _data = this.store.proxy.get(this.prefix + key), data; if ('undefined' !== typeof window) { // browser try { data = JSON.parse(_data); } catch (e) { data = _data; } } else { data = _data; } callback(null, data); } else { callback('missing key'); } }
javascript
{ "resource": "" }
q43051
train
function(key, data, callback) { if (key) { if (data) { var _data = data; if ('undefined' !== typeof window && 'object' === typeof data) { _data = JSON.stringify(_data); } this.store.proxy.set(this.prefix + key, _data); callback(null); } else { callback('missing data'); } } else { callback('missing key'); } }
javascript
{ "resource": "" }
q43052
list
train
function list() { return installer.listPlugins(function(listErr, plugins) { if (listErr) { return out.error("error listing installed plugins: %s", listErr); } if (plugins.length === 0) { return out.success("no plugins found"); } var string = ""; for (var idx = 0; idx < plugins.length; idx++) { string += " " + (idx + 1) + ". " + plugins[idx].name + " - " + plugins[idx].description + "\n"; } return out.success("installed plugins:\n%s", string); }); }
javascript
{ "resource": "" }
q43053
resolveId
train
function resolveId (prop) { if (rule[prop] === null || typeof rule[prop] === 'number') return // Resolve the property to an index var j = self._getRuleIndex(rule.id) if (j < 0) self._error( new Error('Atok#_resolveRules: ' + prop + '() value not found: ' + rule.id) ) rule[prop] = i - j }
javascript
{ "resource": "" }
q43054
train
function (options) { events.EventEmitter.call(this); // this.el = el; this.options = extend(this.options, options); // console.log(this.options); this._init(); this.show = this._show; this.hide = this._hide; }
javascript
{ "resource": "" }
q43055
createFunctions
train
function createFunctions() { const result = []; for (let i = 0; i < count; i++) { result.push(number => Promise.resolve(number + 1)); } return result; }
javascript
{ "resource": "" }
q43056
train
function(filepath, req, res) { var path = require("path"), config = module.exports.config, result = false, parentdir; do { var defaultdir = path.resolve(path.join(config.responsesdefault, filepath)); parentdir = path.resolve(path.join(config.responses, filepath)); if (isValidDir(parentdir) && isValidFile(path.join(parentdir, "index.js"))) { //Parent module response handler exists. require(parentdir)(req, res); result = true; } else if (isValidDir(defaultdir) && isValidFile(path.join(defaultdir, "index.js"))) { //Default response handler require(defaultdir)(req, res); result = true; } if (filepath === path.sep) break; filepath = path.dirname(filepath); } while (result === false && parentdir !== filepath); return result; }
javascript
{ "resource": "" }
q43057
convert
train
function convert(swagger, done) { fury.parse({source: swagger}, function (parseErr, res) { if (parseErr) { return done(parseErr); } fury.serialize({api: res.api}, function (serializeErr, blueprint) { if (serializeErr) { return done(serializeErr); } done(null, blueprint); }); }); }
javascript
{ "resource": "" }
q43058
run
train
function run(argv, done) { if (!argv) { argv = parser.argv; } if (argv.h) { parser.showHelp(); return done(null); } if (!argv._.length) { return done(new Error('Requires an input argument')); } else if (argv._.length > 2) { return done(new Error('Too many arguments given!')); } var input = argv._[0]; if (input.indexOf('http://') === 0 || input.indexOf('https://') === 0) { request(input, function (err, res, body) { if (err) { return done(err); } convert(body, done); }); } else { if (!fs.existsSync(input)) { return done(new Error('`' + input + '` does not exist!')); } fs.readFile(input, 'utf-8', function (err, content) { if (err) { return done(err); } convert(content, done); }); } }
javascript
{ "resource": "" }
q43059
ModuleResource
train
function ModuleResource( pkg, config ) { // Parent constructor ModuleResource.super.call( this, pkg, config ); // Properties this.imports = config.imports || null; this.exports = config.exports || null; this.propertyNamePattern = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/; }
javascript
{ "resource": "" }
q43060
init
train
function init (done) { var node = tools.match_ext(filename, 'node') var json = tools.match_ext(filename, 'json') done(null, { content: content, json: json, node: node, // all other files are considered as javascript files. js: !node && !json, }) }
javascript
{ "resource": "" }
q43061
train
function(db, auditDb) { var dbWrapper = getDbWrapper(db); var auditDbWrapper; if (auditDb) { auditDbWrapper = getDbWrapper(auditDb); } else { auditDbWrapper = dbWrapper; } var clientWrapper = { uuids: function(count, callback) { db.newUUID.call(db, 100, function(err, id) { callback(err, {uuids: [id]}); }); } }; return log.init(appname, clientWrapper, dbWrapper, auditDbWrapper, function(callback) { session.info(function(err, result) { if (err) { return callback(err); } callback(null, result.userCtx.name); }); }); }
javascript
{ "resource": "" }
q43062
domIndexOf
train
function domIndexOf(nodes, domNode) { var index = -1; for (var i = 0; i < nodes.length; i++) { var node = nodes[i]; if (node.type !== 'TextNode' && node.type !== 'ElementNode') { continue; } else { index++; } if (node === domNode) { return index; } } return -1; }
javascript
{ "resource": "" }
q43063
parseComponentBlockParams
train
function parseComponentBlockParams(element, program) { var l = element.attributes.length; var attrNames = []; for (var i = 0; i < l; i++) { attrNames.push(element.attributes[i].name); } var asIndex = attrNames.indexOf('as'); if (asIndex !== -1 && l > asIndex && attrNames[asIndex + 1].charAt(0) === '|') { // Some basic validation, since we're doing the parsing ourselves var paramsString = attrNames.slice(asIndex).join(' '); if (paramsString.charAt(paramsString.length - 1) !== '|' || paramsString.match(/\|/g).length !== 2) { throw new Error('Invalid block parameters syntax: \'' + paramsString + '\''); } var params = []; for (i = asIndex + 1; i < l; i++) { var param = attrNames[i].replace(/\|/g, ''); if (param !== '') { if (ID_INVERSE_PATTERN.test(param)) { throw new Error('Invalid identifier for block parameters: \'' + param + '\' in \'' + paramsString + '\''); } params.push(param); } } if (params.length === 0) { throw new Error('Cannot use zero block parameters: \'' + paramsString + '\''); } element.attributes = element.attributes.slice(0, asIndex); program.blockParams = params; } }
javascript
{ "resource": "" }
q43064
onLinkClick
train
function onLinkClick(event) { // Resolve anchor link var page = url.format( url.resolve(location, this.getAttribute('href')) ); // Load new page piccolo.loadPage( page ); event.preventDefault(); return false; }
javascript
{ "resource": "" }
q43065
renderPage
train
function renderPage(state) { // Get presenter object piccolo.require(state.resolved.name, function (error, Resource) { if (error) return piccolo.emit('error', error); var presenter = new Resource(state.query.href, document); presenter[state.resolved.method].apply(presenter, state.resolved.args); }); }
javascript
{ "resource": "" }
q43066
createStateObject
train
function createStateObject(page, callback) { // This callback function will create a change table state object var create = function () { var query = url.parse(page); var presenter = piccolo.build.router.parse(query.pathname); var state = { 'resolved': presenter, 'namespace': 'piccolo', 'query': query }; callback(state); }; piccolo.once('ready.router', create); }
javascript
{ "resource": "" }
q43067
train
function () { var query = url.parse(page); var presenter = piccolo.build.router.parse(query.pathname); var state = { 'resolved': presenter, 'namespace': 'piccolo', 'query': query }; callback(state); }
javascript
{ "resource": "" }
q43068
createChain
train
function createChain(descriptor, callback) { if (typeof descriptor !== 'object') { throw new TypeError('createChain: descriptor is not an object: ' + descriptor); } //Create the Chain class. function CustomChain(callback) { if (!(this instanceof CustomChain)) { return new CustomChain(callback); } CustomChain.super_.call(this, callback); CustomChain._lists.forEach(function(listName) { this._result[listName] = []; }, this); } util.inherits(CustomChain, Chain); if (callback) { CustomChain.prototype._callback = callback; } //This will come to contain the names of all lists in the chain. CustomChain._lists = []; //Add descriptor properties to Chain prototype. var keys = Object.keys(descriptor); keys.forEach(function(key) { var property = descriptor[key]; //When a chain method is called, a number of actions need to take place. var actionList = [ //1. Decide what item to store from the arguments. getArgumentInterpreter(property.elem), //2. Decide whether to set or push the item to store to an array. getPropertySetter(CustomChain, key, property.plural), //3. End the chain or return `this` for further chaining. getChainEnder(CustomChain, property.end) ].reverse(); CustomChain.prototype[key] = _.compose.apply(null, actionList); }); return CustomChain; }
javascript
{ "resource": "" }
q43069
CustomChain
train
function CustomChain(callback) { if (!(this instanceof CustomChain)) { return new CustomChain(callback); } CustomChain.super_.call(this, callback); CustomChain._lists.forEach(function(listName) { this._result[listName] = []; }, this); }
javascript
{ "resource": "" }
q43070
includedFiles
train
function includedFiles(name){ let includes=this.getIncludes(this.getFile(name)); let ret=includes.map(include => { let ret = { absolute:path.join(name,"../",include.relPath), relative:include.relPath, match:include.match } return ret; }) return ret; }
javascript
{ "resource": "" }
q43071
SquiddioTokenError
train
function SquiddioTokenError(message, type, code, subcode) { Error.call(this); Error.captureStackTrace(this, arguments.callee); this.name = 'SquiddioTokenError'; this.message = message; this.type = type; this.code = code; this.subcode = subcode; this.status = 500; }
javascript
{ "resource": "" }
q43072
onNextTransform
train
function onNextTransform (transform, next) { // check if we should handle this filePath function shouldProcess (filePath, done) { done(!!multimatch(filePath, transform.pattern, transform.opts).length) } // transform the path function process (filePath, complete) { var filename = path.basename(filePath), pathParts = path.dirname(filePath).split(path.sep) // we'll get an empty arrary if we overslice pathParts = pathParts.slice(transform.by) pathParts.push(filename) var newPath = pathParts.join(path.sep), fileData = files[filePath] // don't need the old fileData anymore, // since we are re-adding with the new path delete files[filePath] files[newPath] = fileData complete() } // we do this for each option as the last may have modified the collection async.filter(Object.keys(files), shouldProcess, function (results) { async.each(results, process, next) }) }
javascript
{ "resource": "" }
q43073
shouldProcess
train
function shouldProcess (filePath, done) { done(!!multimatch(filePath, transform.pattern, transform.opts).length) }
javascript
{ "resource": "" }
q43074
process
train
function process (filePath, complete) { var filename = path.basename(filePath), pathParts = path.dirname(filePath).split(path.sep) // we'll get an empty arrary if we overslice pathParts = pathParts.slice(transform.by) pathParts.push(filename) var newPath = pathParts.join(path.sep), fileData = files[filePath] // don't need the old fileData anymore, // since we are re-adding with the new path delete files[filePath] files[newPath] = fileData complete() }
javascript
{ "resource": "" }
q43075
Response
train
function Response(request, key) { // define private store const store = { body: '', cookies: [], headers: {}, key: key, sent: false, statusCode: 0 }; this[STORE] = store; /** * The request that is tied to this response. * @name Response#req * @type {Request} */ Object.defineProperty(this, 'req', { configurable: false, enumerable: true, value: request }); /** * Determine if the response has already been sent. * @name Response#sent * @type {boolean} */ Object.defineProperty(this, 'sent', { enumerable: true, get: () => store.sent }); /** * Get the server instance that initialized this response. * @name Request#server * @type {SansServer} */ Object.defineProperty(this, 'server', { enumerable: true, configurable: false, value: request.server }); /** * Get a copy of the current response state. * @name Response#state * @type {ResponseState} */ Object.defineProperty(this, 'state', { configurable: false, enumerable: true, get: () => { return { body: store.body, cookies: store.cookies.concat(), headers: Object.assign({}, store.headers), rawHeaders: rawHeaders(store.headers, store.cookies), statusCode: store.statusCode } } }); /** * Get or set the status code. * @name Response#statusCode * @type {number} */ Object.defineProperty(this, 'statusCode', { configurable: false, enumerable: true, get: () => store.statusCode, set: v => this.status(v) }); /** * Produce a log event. * @param {string} message * @param {...*} [arg] * @returns {Response} * @fires Response#log */ this.log = request.logger('sans-server', 'response', this); }
javascript
{ "resource": "" }
q43076
text
train
function text(el, str) { if (el.textContent) { el.textContent = str; } else { el.innerText = str; } }
javascript
{ "resource": "" }
q43077
map
train
function map(cov) { var ret = { instrumentation: 'node-jscoverage' , sloc: 0 , hits: 0 , misses: 0 , coverage: 0 , files: [] }; for (var filename in cov) { var data = coverage(filename, cov[filename]); ret.files.push(data); ret.hits += data.hits; ret.misses += data.misses; ret.sloc += data.sloc; } ret.files.sort(function(a, b) { return a.filename.localeCompare(b.filename); }); if (ret.sloc > 0) { ret.coverage = (ret.hits / ret.sloc) * 100; } return ret; }
javascript
{ "resource": "" }
q43078
coverage
train
function coverage(filename, data) { var ret = { filename: filename, coverage: 0, hits: 0, misses: 0, sloc: 0, source: {} }; data.source.forEach(function(line, num){ num++; if (data[num] === 0) { ret.misses++; ret.sloc++; } else if (data[num] !== undefined) { ret.hits++; ret.sloc++; } ret.source[num] = { source: line , coverage: data[num] === undefined ? '' : data[num] }; }); ret.coverage = ret.hits / ret.sloc * 100; return ret; }
javascript
{ "resource": "" }
q43079
TAP
train
function TAP(runner) { Base.call(this, runner); var self = this , stats = this.stats , n = 1 , passes = 0 , failures = 0; runner.on('start', function(){ var total = runner.grepTotal(runner.suite); console.log('%d..%d', 1, total); }); runner.on('test end', function(){ ++n; }); runner.on('pending', function(test){ console.log('ok %d %s # SKIP -', n, title(test)); }); runner.on('pass', function(test){ passes++; console.log('ok %d %s', n, title(test)); }); runner.on('fail', function(test, err){ failures++; console.log('not ok %d %s', n, title(test)); if (err.stack) console.log(err.stack.replace(/^/gm, ' ')); }); runner.on('end', function(){ console.log('# tests ' + (passes + failures)); console.log('# pass ' + passes); console.log('# fail ' + failures); }); }
javascript
{ "resource": "" }
q43080
Teamcity
train
function Teamcity(runner) { Base.call(this, runner); var stats = this.stats; runner.on('start', function() { console.log("##teamcity[testSuiteStarted name='mocha.suite']"); }); runner.on('test', function(test) { console.log("##teamcity[testStarted name='" + escape(test.fullTitle()) + "']"); }); runner.on('fail', function(test, err) { console.log("##teamcity[testFailed name='" + escape(test.fullTitle()) + "' message='" + escape(err.message) + "']"); }); runner.on('pending', function(test) { console.log("##teamcity[testIgnored name='" + escape(test.fullTitle()) + "' message='pending']"); }); runner.on('test end', function(test) { console.log("##teamcity[testFinished name='" + escape(test.fullTitle()) + "' duration='" + test.duration + "']"); }); runner.on('end', function() { console.log("##teamcity[testSuiteFinished name='mocha.suite' duration='" + stats.duration + "']"); }); }
javascript
{ "resource": "" }
q43081
XUnit
train
function XUnit(runner) { Base.call(this, runner); var stats = this.stats , tests = [] , self = this; runner.on('pass', function(test){ tests.push(test); }); runner.on('fail', function(test){ tests.push(test); }); runner.on('end', function(){ console.log(tag('testsuite', { name: 'Mocha Tests' , tests: stats.tests , failures: stats.failures , errors: stats.failures , skip: stats.tests - stats.failures - stats.passes , timestamp: (new Date).toUTCString() , time: stats.duration / 1000 }, false)); tests.forEach(test); console.log('</testsuite>'); }); }
javascript
{ "resource": "" }
q43082
Runner
train
function Runner(suite) { var self = this; this._globals = []; this.suite = suite; this.total = suite.total(); this.failures = 0; this.on('test end', function(test){ self.checkGlobals(test); }); this.on('hook end', function(hook){ self.checkGlobals(hook); }); this.grep(/.*/); this.globals(this.globalProps().concat(['errno'])); }
javascript
{ "resource": "" }
q43083
train
function( filter, context ) { var comment = this.value; if ( !( comment = filter.onComment( context, comment, this ) ) ) { this.remove(); return false; } if ( typeof comment != 'string' ) { this.replaceWith( comment ); return false; } this.value = comment; return true; }
javascript
{ "resource": "" }
q43084
getExistsSync
train
function getExistsSync(path, exts) { for (var i=0,len=exts.length; i<len; i++) { if (fs.existsSync(path + exts[i])) { return path + exts[i]; } } return false; }
javascript
{ "resource": "" }
q43085
extend
train
function extend(a,b) { var c = clone(a); for (var key in b) { c[key] = b[key]; } return c; }
javascript
{ "resource": "" }
q43086
randomize
train
function randomize( obj ) { var j = 0, i = Math.floor(Math.random() * (Object.keys(obj).length)), result; for(var property in obj) { if(j === i) { result = property; break; } j++; } return result; }
javascript
{ "resource": "" }
q43087
_createEventRangeValidator
train
function _createEventRangeValidator(range) { var ctxRange = _createRangeArray(range); return function rangeValidator(range) { var leftIndex = 0; var rightIndex = 0; var left; var right; for (; leftIndex < ctxRange.length && rightIndex < range.length; ) { left = ctxRange[leftIndex]; right = range[rightIndex]; if (left.max < right.min) { ++leftIndex; } else if ((left.min <= right.min || left.max >= right.max) && ((left.min > right.min && (right.min !== Number.MIN_VALUE)) || (left.max < right.max) && (right.max !== Infinity))) { return false; } else { ++rightIndex; } } return (rightIndex >= range.length); }; }
javascript
{ "resource": "" }
q43088
sendSPrintFError
train
function sendSPrintFError(res, errorArray, code, internalCode) { var obj = { success: false }; obj[res ? 'description' : 'reason'] = errorArray; return sendError(res, obj, code, internalCode); }
javascript
{ "resource": "" }
q43089
sendStringError
train
function sendStringError(res, error, code, internalCode) { var obj = { success: false }; obj[res ? 'description' : 'reason'] = error; return sendError(res, obj, code, internalCode); }
javascript
{ "resource": "" }
q43090
Device
train
function Device(key, params) { var p = params || {}; // The primary key of the device [String] this.key = key; // Human readable name of the device [String] EG - "My Device" this.name = p.name || ""; // Indexable attributes. Useful for grouping related Devices. // EG - {location: '445-w-Erie', model: 'TX75', region: 'Southwest'} this.attributes = p.attributes || {}; this.sensors = p.sensors || []; }
javascript
{ "resource": "" }
q43091
train
function(err, httpRes, body) { if (err) _callback(err) else { try { var res = JSON.parse(body) } catch(err) { _callback(null, body) } if (httpRes && httpRes.statusCode !== 200) { maybeRetry(res, IOD, IODOpts, apiType, _callback) } else _callback(null, res) } }
javascript
{ "resource": "" }
q43092
maybeRetry
train
function maybeRetry(err, IOD, IODOpts, apiType, callback) { var retryApiReq = apiType !== IOD.TYPES.SYNC && apiType !== IOD.TYPES.RESULT && apiType !== IOD.TYPES.DISCOVERY if (IODOpts.retries == null || retryApiReq) callback(err) else if (!--IODOpts.retries) callback(err) var reqTypeDontRetry = apiType !== IOD.TYPES.SYNC && apiType !== IOD.TYPES.DISCOVERY && apiType !== IOD.TYPES.RESULT if (IODOpts.retries == null || reqTypeDontRetry) callback(err) else if (!IODOpts.retries--) callback(err) else { var errCode = err.error var errCodeList = T.maybeToArray(IODOpts.errorCodes) // Backend request failed or timed out if (errCode === 5000 || errCode === 7000 || _.contains(errCodeList, errCode)) { exports.send(IOD, IODOpts, apiType, callback) } else callback(err) } }
javascript
{ "resource": "" }
q43093
makeOptions
train
function makeOptions(IOD, IODOpts, apiType, reqOpts) { var path = IodU.makePath(IOD, IODOpts, apiType) var method = apiType === IOD.TYPES.JOB || !_.isEmpty(IODOpts.files) ? 'post' : IODOpts.method.toLowerCase() return _.defaults({ url: IOD.host + ':' + IOD.port + path, path: path, method: method, // For 'get' request use request `qs` property. qs: method === 'get' ? _.defaults({ apiKey: IOD.apiKey }, exports.prepareParams(IODOpts.params)) : undefined, // For 'post' request with no files use `form` property form: method === 'post' && !IODOpts.files ? _.defaults({ apiKey: IOD.apiKey }, exports.prepareParams(IODOpts.params)) : undefined }, reqOpts, IOD.reqOpts) }
javascript
{ "resource": "" }
q43094
addParamsToData
train
function addParamsToData(IOD, IODOpts, form) { form.append('apiKey', IOD.apiKey) _.each(exports.prepareParams(IODOpts.params), function(paramVal, paramName) { _.each(T.maybeToArray(paramVal), function(val) { form.append(paramName, val) }) }) }
javascript
{ "resource": "" }
q43095
addFilesToData
train
function addFilesToData(IOD, IODOpts, apiType, form) { _.each(T.maybeToArray(IODOpts.files), function(file) { if (apiType === IOD.TYPES.JOB) { form.append(file.name, fs.createReadStream(file.path)) } else form.append('file', fs.createReadStream(file)) }) }
javascript
{ "resource": "" }
q43096
replaceCssLength
train
function replaceCssLength( length1, length2 ) { var parts1 = cssLengthRegex.exec( length1 ), parts2 = cssLengthRegex.exec( length2 ); // Omit pixel length unit when necessary, // e.g. replaceCssLength( 10, '20px' ) -> 20 if ( parts1 ) { if ( !parts1[ 2 ] && parts2[ 2 ] == 'px' ) return parts2[ 1 ]; if ( parts1[ 2 ] == 'px' && !parts2[ 2 ] ) return parts2[ 1 ] + 'px'; } return length2; }
javascript
{ "resource": "" }
q43097
train
function() { var results = []; for (var i=0, cs=this.controls, c; c=cs[i]; i++) { if (!c.isChrome) { results.push(c); } } return results; }
javascript
{ "resource": "" }
q43098
train
function() { var c$ = this.getClientControls(); for (var i=0, c; c=c$[i]; i++) { c.destroy(); } }
javascript
{ "resource": "" }
q43099
train
function(inMessage, inPayload, inSender) { // Note: Controls will generally be both in a $ hash and a child list somewhere. // Attempt to avoid duplicated messages by sending only to components that are not // UiComponent, as those components are guaranteed not to be in a child list. // May cause a problem if there is a scenario where a UiComponent owns a pure // Component that in turn owns Controls. // // waterfall to all pure components for (var n in this.$) { if (!(this.$[n] instanceof enyo.UiComponent)) { this.$[n].waterfall(inMessage, inPayload, inSender); } } // waterfall to my children for (var i=0, cs=this.children, c; c=cs[i]; i++) { // Do not send {showingOnly: true} events to hidden controls. This flag is set for resize events // which are broadcast from within the framework. This saves a *lot* of unnecessary layout. // TODO: Maybe remember that we did this, and re-send those messages on setShowing(true)? // No obvious problems with it as-is, though if (c.showing || !(inPayload && inPayload.showingOnly)) { c.waterfall(inMessage, inPayload, inSender); } } }
javascript
{ "resource": "" }