_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q14000
relativeURI
train
function relativeURI(uri, base) { // reduce base and uri strings to just their difference string var baseParts = base.split('/'); baseParts.pop(); base = baseParts.join('/') + '/'; i = 0; while (base.substr(i, 1) == uri.substr(i, 1)) i++; while (base.substr(i, 1) != '/') i--; base = base.substr(i + 1); uri = uri.substr(i + 1); // each base folder difference is thus a backtrack baseParts = base.split('/'); var uriParts = uri.split('/'); out = ''; while (baseParts.shift()) out += '../'; // finally add uri parts while (curPart = uriParts.shift()) out += curPart + '/'; return out.substr(0, out.length - 1); }
javascript
{ "resource": "" }
q14001
partialAny
train
function partialAny(fn /* arguments */) { var appliedArgs = Array.prototype.slice.call(arguments, 1); if ( appliedArgs.length < 1 ) return fn; return function () { var args = _.deepClone(appliedArgs); var partialArgs = _.toArray(arguments); for (var i=0; i < args.length; i++) { if ( args[i] === _ ) args[i] = partialArgs.shift(); } return fn.apply(this, args.concat(partialArgs)); }; }
javascript
{ "resource": "" }
q14002
tryFn
train
function tryFn(fn, args) { try { return Promise.resolve(fn.apply(null, args)); } catch (e) { return Promise.reject(e); } }
javascript
{ "resource": "" }
q14003
train
function (key, value) { if (!supported) { try { $cookieStore.set(key, value); return value; } catch (e) { console.log('Local Storage not supported, make sure you have the $cookieStore supported.'); } } var saver = JSON.stringify(value); storage.setItem(key, saver); return privateMethods.parseValue(saver); }
javascript
{ "resource": "" }
q14004
train
function (key) { if (!supported) { try { return privateMethods.parseValue($cookieStore.get(key)); } catch (e) { return null; } } var item = storage.getItem(key); return privateMethods.parseValue(item); }
javascript
{ "resource": "" }
q14005
train
function (key) { if (!supported) { try { $cookieStore.remove(key); return true; } catch (e) { return false; } } storage.removeItem(key); return true; }
javascript
{ "resource": "" }
q14006
CanaryStore
train
function CanaryStore() { var self = this; EventEmitter.call(self); var counter = self._counter = new Counter(); counter.on('resource', self._onresource.bind(self)); self._id = 0; self._variants = {}; self._callbacks = {}; self._assigners = []; self._assignments = {}; self._overrides = {}; self._pending = 0; // create a global context for simple cases var context = this._globalContext = this.context(this.emit.bind(this, 'change')); this.get = context.get.bind(context); this.start = context.start.bind(context); this.stop = context.stop.bind(context); }
javascript
{ "resource": "" }
q14007
isModuleInstalledGlobally
train
function isModuleInstalledGlobally(name, fn) { var cmd = 'npm ls --global --json --depth=0'; exec(cmd, function(err, stdout) { if (err) { return fn(err); } var data = JSON.parse(stdout); var installed = data.dependencies[name]; fn(null, installed !== undefined); }); }
javascript
{ "resource": "" }
q14008
controllerWrap
train
function controllerWrap(ctx, ctrl, hooks, next) { let result const preHooks = [] hooks.pre.map(pre => { preHooks.push(() => pre(ctx)) }) return sequenceAndReturnOne(preHooks) .then(() => { return ctrl(ctx) }) .then(data => { if (!data && ctx.body && ctx.body.data) { data = ctx.body.data } result = data const postHooks = [] hooks.post.map(post => { // Use pre action's result for next action's data postHooks.push(preResult => post(ctx, preResult || result)) }) return sequenceAndReturnOne(postHooks) }) .then(ret => { if (!ctx.body) { ctx.body = { code: 0, data: ret || result } } next && next() }) .catch(err => { // throw errors to app error handler throw err }) }
javascript
{ "resource": "" }
q14009
train
function(arr, iterator, callback) { callback = _doOnce(callback || noop); var amount = arr.length; if (!isArray(arr)) return callback(); var completed = 0; doEach(arr, function(item) { iterator(item, doOnce(function(err) { if (err) { callback(err); callback = noop; } else { completed++; if (completed >= amount) callback(null); } })); }); }
javascript
{ "resource": "" }
q14010
train
function(tasks, callback) { var keys; var length; var i; var results; var kind; var updated_tasks = []; var is_object; var counter = 0; if (isArray(tasks)) { length = tasks.length; results = []; } else if (isObject(tasks)) { is_object = true; keys = ObjectKeys(tasks); length = keys.length; results = {}; } else { return callback(); } for (i=0; i<length; i++) { if (is_object) { updated_tasks.push({ k: keys[i], t: tasks[keys[i]] }); } else { updated_tasks.push({ k: i, t: tasks[i] }); } } updated_tasks.forEach(function(task_object) { task_object.t(function(err, result) { if (err) return callback(err); results[task_object.k] = result; counter++; if (counter == length) callback(null, results); }); }); }
javascript
{ "resource": "" }
q14011
train
function(tasks, callback) { if (!isArray(tasks)) return callback(); var length = tasks.length; var results = []; function runTask(index) { tasks[index](function(err, result) { if (err) return callback(err); results[index] = result; if (index < length - 1) return runTask(index + 1); return callback(null, results); }); } runTask(0); }
javascript
{ "resource": "" }
q14012
methodWrapper
train
function methodWrapper(fn) { return function() { var args = [].slice.call(arguments); args.unshift(this); return fn.apply(this, args); }; }
javascript
{ "resource": "" }
q14013
getNewFilename
train
function getNewFilename(list, name) { if (list.indexOf(name) === -1) { return name; } const parsed = parseFilename(name); const base = parsed.base; const ext = parsed.ext; if (!base) { const newName = getNextNumberName(ext); return getNewFilename(list, newName); } else { const basename = getNextNumberName(base); return getNewFilename(list, `${basename}${ext}`); } }
javascript
{ "resource": "" }
q14014
processDirective
train
function processDirective(list, directive) { _(options.paths).forEach(function(filepath) { _.each(list, function(item) { item = path.join(filepath, item); console.log(item); grunt.file.expand(grunt.template.process(item)).map(function(ea) { importDirectives.push('@import' + ' (' + directive + ') ' + '"' + ea + '";'); }); }); }); console.log(importDirectives); }
javascript
{ "resource": "" }
q14015
create
train
function create (config) { /** Generate each client as described. */ config.clients.forEach(function (client) { if (client.type === 'node') { /** Fork a new node process. */ fork(config.panic); } }); }
javascript
{ "resource": "" }
q14016
Multibundle
train
function Multibundle(config, components) { var tasks; if (!(this instanceof Multibundle)) { return new Multibundle(config, components); } // turn on object mode Readable.call(this, {objectMode: true}); // prepare config options this.config = lodash.merge({}, Multibundle._defaults, config); this.config.componentOptions = lodash.cloneDeep(components); // process each component in specific order tasks = this._getComponents() .map(this._processComponent.bind(this)) .map(this._prepareForRjs.bind(this)) ; // run optimize tasks asynchronously async.parallelLimit(tasks, this.config.parallelLimit, function(err) { if (err) { this.emit('error', err); return; } // be nice if (this.config.logLevel < 4) { console.log('\n-- All requirejs bundles have been processed.'); } // singal end of the stream this.push(null); }.bind(this)); }
javascript
{ "resource": "" }
q14017
train
function (tokens){ if (!this.next()) return; if (this.current.type === "heading" && this.current.depth === this.optionDepth) { return this.findDescription(this.current.text.trim()); } this.findOption(); }
javascript
{ "resource": "" }
q14018
train
function (option) { if (!this.next()) return; if (this.current.type === "paragraph") { this.results.push({ name: option, description: this.current.text.trim() }); return this.findOption(); } this.findDescription(option); }
javascript
{ "resource": "" }
q14019
LENGTH_VALIDATOR
train
function LENGTH_VALIDATOR(v) { v = (v || '').toString() var match = v.match(LENGTH_REGEXP) if (match) { var unit = match[1] if (!unit) { return {value: parseFloat(v)} } else if (SUPPORT_CSS_UNIT.indexOf(unit) > -1) { return {value: v} } else { return { value: parseFloat(v), reason: function reason(k, v, result) { return 'NOTE: unit `' + unit + '` is not supported and property value `' + v + '` is autofixed to `' + result + '`' } } } } return { value: null, reason: function reason(k, v, result) { return 'ERROR: property value `' + v + '` is not supported for `' + util.camelCaseToHyphened(k) + '` (only number and pixel values are supported)' } } }
javascript
{ "resource": "" }
q14020
NUMBER_VALIDATOR
train
function NUMBER_VALIDATOR(v) { v = (v || '').toString() var match = v.match(LENGTH_REGEXP) if (match && !match[1]) { return {value: parseFloat(v)} } return { value: null, reason: function reason(k, v, result) { return 'ERROR: property value `' + v + '` is not supported for `' + util.camelCaseToHyphened(k) + '` (only number is supported)' } } }
javascript
{ "resource": "" }
q14021
INTEGER_VALIDATOR
train
function INTEGER_VALIDATOR(v) { v = (v || '').toString() if (v.match(/^[-+]?\d+$/)) { return {value: parseInt(v, 10)} } return { value: null, reason: function reason(k, v, result) { return 'ERROR: property value `' + v + '` is not supported for `' + util.camelCaseToHyphened(k) + '` (only integer is supported)' } } }
javascript
{ "resource": "" }
q14022
genValidatorMap
train
function genValidatorMap() { var groupName, group, name for (groupName in PROP_NAME_GROUPS) { group = PROP_NAME_GROUPS[groupName] for (name in group) { validatorMap[name] = group[name] } } }
javascript
{ "resource": "" }
q14023
train
function(post) { return $http({ url : '/api/v1/posts/' + post._id, method : 'PUT', params : {access_token : authProvider.getUser().token}, data : post }).catch(authProvider.checkApiResponse); }
javascript
{ "resource": "" }
q14024
train
function(id) { return $http({ url : '/api/v1/posts/' + id, method : 'DELETE', params : {access_token : authProvider.getUser().token} }).catch(authProvider.checkApiResponse); }
javascript
{ "resource": "" }
q14025
train
function() { if (!this.routes) { return; } var routes = []; for (var route in this.routes) { if (this.routes.hasOwnProperty(route)) { routes.unshift([route, this.routes[route]]); } } for (var i = 0, l = routes.length; i < l; i++) { this.route(routes[i][0], routes[i][1], this[routes[i][1]]); } }
javascript
{ "resource": "" }
q14026
train
function( editor, element ) { // Transform the element into a CKEDITOR.dom.element instance. this.base( element.$ || element ); this.editor = editor; /** * Indicates the initialization status of the editable element. The following statuses are available: * * * **unloaded** &ndash; the initial state. The editable's instance was created but * is not fully loaded (in particular it has no data). * * **ready** &ndash; the editable is fully initialized. The `ready` status is set after * the first {@link CKEDITOR.editor#method-setData} is called. * * **detached** &ndash; the editable was detached. * * @since 4.3.3 * @readonly * @property {String} */ this.status = 'unloaded'; /** * Indicates whether the editable element gained focus. * * @property {Boolean} hasFocus */ this.hasFocus = false; // The bootstrapping logic. this.setup(); }
javascript
{ "resource": "" }
q14027
train
function( cls ) { var classes = this.getCustomData( 'classes' ); if ( !this.hasClass( cls ) ) { !classes && ( classes = [] ), classes.push( cls ); this.setCustomData( 'classes', classes ); this.addClass( cls ); } }
javascript
{ "resource": "" }
q14028
train
function( attr, val ) { var orgVal = this.getAttribute( attr ); if ( val !== orgVal ) { !this._.attrChanges && ( this._.attrChanges = {} ); // Saved the original attribute val. if ( !( attr in this._.attrChanges ) ) this._.attrChanges[ attr ] = orgVal; this.setAttribute( attr, val ); } }
javascript
{ "resource": "" }
q14029
train
function( element, range ) { var editor = this.editor, enterMode = editor.config.enterMode, elementName = element.getName(), isBlock = CKEDITOR.dtd.$block[ elementName ]; if ( range.checkReadOnly() ) return false; // Remove the original contents, merge split nodes. range.deleteContents( 1 ); // If range is placed in inermediate element (not td or th), we need to do three things: // * fill emptied <td/th>s with if browser needs them, // * remove empty text nodes so IE8 won't crash (http://dev.ckeditor.com/ticket/11183#comment:8), // * fix structure and move range into the <td/th> element. if ( range.startContainer.type == CKEDITOR.NODE_ELEMENT && range.startContainer.is( { tr: 1, table: 1, tbody: 1, thead: 1, tfoot: 1 } ) ) fixTableAfterContentsDeletion( range ); // If we're inserting a block at dtd-violated position, split // the parent blocks until we reach blockLimit. var current, dtd; if ( isBlock ) { while ( ( current = range.getCommonAncestor( 0, 1 ) ) && ( dtd = CKEDITOR.dtd[ current.getName() ] ) && !( dtd && dtd[ elementName ] ) ) { // Split up inline elements. if ( current.getName() in CKEDITOR.dtd.span ) range.splitElement( current ); // If we're in an empty block which indicate a new paragraph, // simply replace it with the inserting block.(#3664) else if ( range.checkStartOfBlock() && range.checkEndOfBlock() ) { range.setStartBefore( current ); range.collapse( true ); current.remove(); } else { range.splitBlock( enterMode == CKEDITOR.ENTER_DIV ? 'div' : 'p', editor.editable() ); } } } // Insert the new node. range.insertNode( element ); // Return true if insertion was successful. return true; }
javascript
{ "resource": "" }
q14030
train
function( element ) { // Prepare for the insertion. For example - focus editor (#11848). beforeInsert( this ); var editor = this.editor, enterMode = editor.activeEnterMode, selection = editor.getSelection(), range = selection.getRanges()[ 0 ], elementName = element.getName(), isBlock = CKEDITOR.dtd.$block[ elementName ]; // Insert element into first range only and ignore the rest (#11183). if ( this.insertElementIntoRange( element, range ) ) { range.moveToPosition( element, CKEDITOR.POSITION_AFTER_END ); // If we're inserting a block element, the new cursor position must be // optimized. (#3100,#5436,#8950) if ( isBlock ) { // Find next, meaningful element. var next = element.getNext( function( node ) { return isNotEmpty( node ) && !isBogus( node ); } ); if ( next && next.type == CKEDITOR.NODE_ELEMENT && next.is( CKEDITOR.dtd.$block ) ) { // If the next one is a text block, move cursor to the start of it's content. if ( next.getDtd()[ '#' ] ) range.moveToElementEditStart( next ); // Otherwise move cursor to the before end of the last element. else range.moveToElementEditEnd( element ); } // Open a new line if the block is inserted at the end of parent. else if ( !next && enterMode != CKEDITOR.ENTER_BR ) { next = range.fixBlock( true, enterMode == CKEDITOR.ENTER_DIV ? 'div' : 'p' ); range.moveToElementEditStart( next ); } } } // Set up the correct selection. selection.selectRanges( [ range ] ); afterInsert( this ); }
javascript
{ "resource": "" }
q14031
needsBrFiller
train
function needsBrFiller( selection, path ) { // Fake selection does not need filler, because it is fake. if ( selection.isFake ) return 0; // Ensure bogus br could help to move cursor (out of styles) to the end of block. (#7041) var pathBlock = path.block || path.blockLimit, lastNode = pathBlock && pathBlock.getLast( isNotEmpty ); // Check some specialities of the current path block: // 1. It is really displayed as block; (#7221) // 2. It doesn't end with one inner block; (#7467) // 3. It doesn't have bogus br yet. if ( pathBlock && pathBlock.isBlockBoundary() && !( lastNode && lastNode.type == CKEDITOR.NODE_ELEMENT && lastNode.isBlockBoundary() ) && !pathBlock.is( 'pre' ) && !pathBlock.getBogus() ) return pathBlock; }
javascript
{ "resource": "" }
q14032
prepareRangeToDataInsertion
train
function prepareRangeToDataInsertion( that ) { var range = that.range, mergeCandidates = that.mergeCandidates, node, marker, path, startPath, endPath, previous, bm; // If range starts in inline element then insert a marker, so empty // inline elements won't be removed while range.deleteContents // and we will be able to move range back into this element. // E.g. 'aa<b>[bb</b>]cc' -> (after deleting) 'aa<b><span/></b>cc' if ( that.type == 'text' && range.shrink( CKEDITOR.SHRINK_ELEMENT, true, false ) ) { marker = CKEDITOR.dom.element.createFromHtml( '<span>&nbsp;</span>', range.document ); range.insertNode( marker ); range.setStartAfter( marker ); } // By using path we can recover in which element was startContainer // before deleting contents. // Start and endPathElements will be used to squash selected blocks, after removing // selection contents. See rule 5. startPath = new CKEDITOR.dom.elementPath( range.startContainer ); that.endPath = endPath = new CKEDITOR.dom.elementPath( range.endContainer ); if ( !range.collapsed ) { // Anticipate the possibly empty block at the end of range after deletion. node = endPath.block || endPath.blockLimit; var ancestor = range.getCommonAncestor(); if ( node && !( node.equals( ancestor ) || node.contains( ancestor ) ) && range.checkEndOfBlock() ) { that.zombies.push( node ); } range.deleteContents(); } // Rule 4. // Move range into the previous block. while ( ( previous = getRangePrevious( range ) ) && checkIfElement( previous ) && previous.isBlockBoundary() && // Check if previousNode was parent of range's startContainer before deleteContents. startPath.contains( previous ) ) range.moveToPosition( previous, CKEDITOR.POSITION_BEFORE_END ); // Rule 5. mergeAncestorElementsOfSelectionEnds( range, that.blockLimit, startPath, endPath ); // Rule 1. if ( marker ) { // If marker was created then move collapsed range into its place. range.setEndBefore( marker ); range.collapse(); marker.remove(); } // Split inline elements so HTML will be inserted with its own styles. path = range.startPath(); if ( ( node = path.contains( isInline, false, 1 ) ) ) { range.splitElement( node ); that.inlineStylesRoot = node; that.inlineStylesPeak = path.lastElement; } // Record inline merging candidates for later cleanup in place. bm = range.createBookmark(); // 1. Inline siblings. node = bm.startNode.getPrevious( isNotEmpty ); node && checkIfElement( node ) && isInline( node ) && mergeCandidates.push( node ); node = bm.startNode.getNext( isNotEmpty ); node && checkIfElement( node ) && isInline( node ) && mergeCandidates.push( node ); // 2. Inline parents. node = bm.startNode; while ( ( node = node.getParent() ) && isInline( node ) ) mergeCandidates.push( node ); range.moveToBookmark( bm ); }
javascript
{ "resource": "" }
q14033
stripBlockTagIfSingleLine
train
function stripBlockTagIfSingleLine( dataWrapper ) { var block, children; if ( dataWrapper.getChildCount() == 1 && // Only one node bein inserted. checkIfElement( block = dataWrapper.getFirst() ) && // And it's an element. block.is( stripSingleBlockTags ) ) // That's <p> or <div> or header. { // Check children not containing block. children = block.getElementsByTag( '*' ); for ( var i = 0, child, count = children.count(); i < count; i++ ) { child = children.getItem( i ); if ( !child.is( inlineButNotBr ) ) return; } block.moveChildren( block.getParent( 1 ) ); block.remove(); } }
javascript
{ "resource": "" }
q14034
Kernel
train
function Kernel(){ this.registrations = new Registrations() this.decorators = new Decorators() this.resolvers = {} this.activators = {} this._inflight = new Inflight(this.decorators) registerSystemServices.call(this) }
javascript
{ "resource": "" }
q14035
forkWorkers
train
function forkWorkers(numWorkers, env) { var workers = []; env = env || {}; for(var i = 0; i < numWorkers; i++) { worker = cluster.fork(env); console.info("Start worker: " + worker.process.pid + ' at ' + (new Date()).toISOString()); workers.push(worker); } return workers; }
javascript
{ "resource": "" }
q14036
run
train
function run(booleanOrString, anyDataType, functionOrObject, aNumber, anArray) { /* * if expectations aren't met, args checker will throw appropriate exceptions * notifying the user regarding the errors of the arguments. * */ args.expect(arguments, ['boolean|string', '*', 'function|object', 'number', 'array']); // do something here... console.log("\n\nfunction `run` arguments passed!"); }
javascript
{ "resource": "" }
q14037
catchError
train
function catchError (stream) { return { source: pull( stream.source, pullCatch((err) => { if (err.message === 'Channel destroyed') { return } return false }) ), sink: stream.sink } }
javascript
{ "resource": "" }
q14038
datesOfToday
train
function datesOfToday () { const ret = {} ret.year = String(new Date().getFullYear()) ret.month = prefix(String(new Date().getMonth())) ret.day = prefix(String(new Date().getDate())) ret.date = [ret.year, ret.month, ret.day].join('-') return ret }
javascript
{ "resource": "" }
q14039
closureRequire
train
function closureRequire(symbol) { closure.goog.require(symbol); return closure.goog.getObjectByName(symbol); }
javascript
{ "resource": "" }
q14040
buildURL
train
function buildURL(dbName, opts) { var authentication opts.scheme = opts.scheme || 'http' opts.host = opts.host || '127.0.0.1' opts.port = opts.port || '5984' if (has(opts, 'auth')) { if (typeof opts.auth === 'object') { authentication = opts.auth.username + ':' + opts.auth.password + '@' } } return opts.scheme + '://' + authentication + opts.host + ':' + opts.port + '/' + dbName }
javascript
{ "resource": "" }
q14041
pushCouchapp
train
function pushCouchapp(dbName, opts) { opts = opts || {} if (!dbName && typeof dbName !== 'string') { throw new PluginError(PLUGIN_NAME, 'Missing database name.'); } return through.obj(function (file, enc, cb) { var ddocObj = require(file.path) var url = /^https?:\/\//.test(dbName) ? dbName : buildURL(dbName, opts); if (file.isNull()) { return cb(null, file) } if (file.isStream()) { this.emit('error', new PluginError(PLUGIN_NAME, 'Streaming not supported.')) return cb(null, file) } if (path.extname(file.path) !== '.js') { this.emit('error', new PluginError(PLUGIN_NAME, 'File extension not supported.')) return cb(null, file) } if (has(opts, 'attachments')) { var attachmentsPath = path.join(process.cwd(), path.normalize(opts.attachments)) couchapp.loadAttachments(ddocObj, attachmentsPath) } couchapp.createApp(ddocObj, url, function (app) { app.push(function () { gutil.log(PLUGIN_NAME, 'Couchapp pushed!') return cb(null, file) }) }) }) }
javascript
{ "resource": "" }
q14042
whiteOrBlack
train
function whiteOrBlack( color ) { color = color.replace( /^#/, '' ); for ( var i = 0, rgb = []; i <= 2; i++ ) rgb[ i ] = parseInt( color.substr( i * 2, 2 ), 16 ); var luma = ( 0.2126 * rgb[ 0 ] ) + ( 0.7152 * rgb[ 1 ] ) + ( 0.0722 * rgb[ 2 ] ); return '#' + ( luma >= 165 ? '000' : 'fff' ); }
javascript
{ "resource": "" }
q14043
updateHighlight
train
function updateHighlight( event ) { // Convert to event. !event.name && ( event = new CKEDITOR.event( event ) ); var isFocus = !( /mouse/ ).test( event.name ), target = event.data.getTarget(), color; if ( target.getName() == 'td' && ( color = target.getChild( 0 ).getHtml() ) ) { removeHighlight( event ); isFocus ? focused = target : hovered = target; // Apply outline style to show focus. if ( isFocus ) { target.setStyle( 'border-color', whiteOrBlack( color ) ); target.setStyle( 'border-style', 'dotted' ); } $doc.getById( hicolorId ).setStyle( 'background-color', color ); $doc.getById( hicolorTextId ).setHtml( color ); } }
javascript
{ "resource": "" }
q14044
removeHighlight
train
function removeHighlight( event ) { var isFocus = !( /mouse/ ).test( event.name ), target = isFocus && focused; if ( target ) { var color = target.getChild( 0 ).getHtml(); target.setStyle( 'border-color', color ); target.setStyle( 'border-style', 'solid' ); } if ( !( focused || hovered ) ) { $doc.getById( hicolorId ).removeStyle( 'background-color' ); $doc.getById( hicolorTextId ).setHtml( '&nbsp;' ); } }
javascript
{ "resource": "" }
q14045
num
train
function num(type, value) { var val; if(type === NUMERIC.INTEGER) { val = utils.strtoint(value); if(isNaN(val)) throw IntegerRange; }else{ val = utils.strtofloat(value); if(isNaN(val)) throw InvalidFloat; } return val; }
javascript
{ "resource": "" }
q14046
type
train
function type(cmd, args, info) { // definition provided by earlier command validation /* istanbul ignore next: currently subcommands do not type validate */ var def = info.command.sub ? info.command.sub.def : info.command.def // expected type of the value based on the supplied command , expected = TYPES[cmd] , numeric = NUMERIC[cmd] , margs = args.slice(0) // extract keys from the args list , keys = def.getKeys(args) // build up value list, when validation // passes this can be re-used by calling code , values = {} , i, k, v, nv; // numeric argument validation if(numeric && numeric.pos) { numeric.pos.forEach(function(pos) { //console.error('got value for arg at pos %s (%s)', pos, args[pos]); var val = num(numeric.type, args[pos]); margs[pos] = val; args[pos] = val; }) } // command does not operate on a type or has no keys // nothing to be done. first part of the conditional // should never match, if it does it represents a misconfiguration // of the constants, however we need to ensure we have some keys // to iterate over if(!keys || !TYPES[cmd]) return null; for(i = 0;i < keys.length;i++) { k = keys[i]; v = nv = info.db.getKey(k, {}); //console.dir(v); // numeric value validation if(numeric) { if(expected === TYPE_NAMES.STRING && numeric.value) { // update the value, allows // calling code to skip coercion // on successful validation v = num(numeric.type, v); // should have a hash // need to dig deeper to get the real // value for complex types }else if(v && expected === TYPE_NAMES.HASH && numeric.value) { nv = v.getValues(cmd, args, def); //console.error('got validate value: %s', nv); num(numeric.type, nv); } } // got an existing value if(v !== undefined) { //console.dir(v); switch(expected) { case TYPE_NAMES.STRING: // the store is allowed to save string values as // numbers and coerce to strings on get() if(typeof v !== 'string' && typeof v !== 'number' && !(v instanceof Buffer)) { throw WrongType; } break; case TYPE_NAMES.HASH: case TYPE_NAMES.LIST: case TYPE_NAMES.SET: case TYPE_NAMES.ZSET: if(v.rtype !== expected) throw WrongType; break; } } // always store regardless of whether a value is defined values[k] = v; } return {keys: keys, values: values, args: margs}; }
javascript
{ "resource": "" }
q14047
getMeasurements
train
function getMeasurements(startDate, endDate, params, callback) { params = params || {}; if(!startDate && !endDate) { startDate = new Date(); startDate.setHours(startDate.getHours() - 24); startDate = formatDate(startDate); endDate = new Date(); endDate = formatDate(endDate); } params.startdate = startDate; params.endDate = endDate; core.callApi('/AirQualityService/v1.0/Measurements', params, callback); }
javascript
{ "resource": "" }
q14048
validate
train
function validate(rules, args, cb) { try { _known(rules, args); _required(rules, args); Object.keys(args).forEach(function (arg) { var value = args[arg], ruleSet = rules[arg]; try { ruleSet.forEach(function (rule) { if (rule !== 'required') { exports.checks[rule](value || ''); } }); } catch (e) { throw new Error(util.format( 'Validation error - arg: %s, value: %s, desc: %s', arg, value, e.message)); } }); cb(); } catch (e) { cb(e); } }
javascript
{ "resource": "" }
q14049
clone
train
function clone(obj1, obj2, index) { index = index || 0; for (var i in obj2) { if ('object' == typeof i) obj1[i] = recursiveMerge(obj1[i], obj2[i], index++); else obj1[i] = obj2[i]; } return obj1; }
javascript
{ "resource": "" }
q14050
addContentsDirectoryToReaddirResultAndCallOriginalCallback
train
function addContentsDirectoryToReaddirResultAndCallOriginalCallback(err, entryNames) { if (!err && Array.isArray(entryNames)) { entryNames = ['gitFakeFs'].concat(entryNames); } cb.call(this, err, entryNames); }
javascript
{ "resource": "" }
q14051
html
train
function html(template) { var expressions = []; for (var _i = 1; _i < arguments.length; _i++) { expressions[_i - 1] = arguments[_i]; } var result = ""; var i = 0; // resolve each expression and build the result string for (var _a = 0, template_1 = template; _a < template_1.length; _a++) { var part = template_1[_a]; var expression = expressions[i++ - 1]; // this might be an array var resolvedExpression = resolveExpression(expression); result += "" + resolvedExpression + part; } // strip indentation and trim the result return strip_indent_1.default(result).trim(); }
javascript
{ "resource": "" }
q14052
validatorNum
train
function validatorNum( msg ) { return function() { var value = this.getValue(), pass = !!( CKEDITOR.dialog.validate.integer()( value ) && value > 0 ); if ( !pass ) { alert( msg ); this.select(); } return pass; }; }
javascript
{ "resource": "" }
q14053
train
function(monitor, callback) { callback = callback || function(){}; var t = this, monitorJSON = monitor.toMonitorJSON(), probeJSON = null, probeClass = monitorJSON.probeClass, startTime = Date.now(), monitorStr = probeClass + '.' + monitor.toServerString().replace(/:/g, '.'); // Class name must be set if (!probeClass) { var errStr = 'probeClass must be set'; log.error('connectMonitor', errStr); return callback(errStr); } // Determine the connection (or internal), and listen for change events t.determineConnection(monitorJSON, true, function(err, connection) { if (err) {return callback(err);} // Function to run on connection (internal or external) var onConnect = function(error, probe) { if (error) {return callback(error);} probeJSON = probe.toJSON(); probeJSON.probeId = probeJSON.id; delete probeJSON.id; monitor.probe = probe; // Perform the initial set silently. This assures the initial // probe contents are available on the connect event, // but doesn't fire a change event before connect. monitor.set(probeJSON, {silent:true}); // Watch the probe for changes. monitor.probeChange = function(){ monitor.set(probe.changedAttributes()); log.info('probeChange', {probeId: probeJSON.probeId, changed: probe.changedAttributes()}); }; probe.on('change', monitor.probeChange); // Call the callback. This calls the original caller, issues // the connect event, then fires the initial change event. callback(null); }; // Connect internally or externally if (connection) { t.connectExternal(monitorJSON, connection, onConnect); } else { t.connectInternal(monitorJSON, onConnect); } }); }
javascript
{ "resource": "" }
q14054
train
function(monitorJSON, callback) { // Build a key for this probe from the probeClass and initParams var t = this, probeKey = t.buildProbeKey(monitorJSON), probeClass = monitorJSON.probeClass, initParams = monitorJSON.initParams, probeImpl = null; var whenDone = function(error) { // Wait one tick before firing the callback. This simulates a remote // connection, making the client callback order consistent, regardless // of a local or remote connection. setTimeout(function() { // Dont connect the probe on error if (error) { if (probeImpl) { delete t.runningProbesByKey[probeKey]; delete t.runningProbesById[probeImpl.id]; try { // This may fail depending on how many resources were created // by the probe before failure. Ignore errors. probeImpl.release(); } catch (e){} } log.error('connectInternal', {error: error, probeKey: probeKey}); return callback(error); } // Probes are released based on reference count probeImpl.refCount++; log.info('connectInternal', {probeKey: probeKey, probeId: probeImpl.id}); callback(null, probeImpl); }, 0); }; // Get the probe instance probeImpl = t.runningProbesByKey[probeKey]; if (!probeImpl) { // Instantiate the probe var ProbeClass = Probe.classes[probeClass]; if (!ProbeClass) { return whenDone({msg:'Probe not available: ' + probeClass}); } var initOptions = {asyncInit: false, callback: whenDone}; try { // Deep copy the init params, because Backbone mutates them. This // is bad if the init params came in from defaults of another object, // because those defaults will get mutated. var paramCopy = Monitor.deepCopy(initParams); // Instantiate a new probe probeImpl = new ProbeClass(paramCopy, initOptions); probeImpl.set({id: Monitor.generateUniqueId()}); probeImpl.refCount = 0; probeImpl.probeKey = probeKey; t.runningProbesByKey[probeKey] = probeImpl; t.runningProbesById[probeImpl.id] = probeImpl; } catch (e) { var error = {msg: 'Error instantiating probe ' + probeClass, error: e.message}; log.error('connect', error); return whenDone(error); } // Return early if the probe constructor transferred responsibility // for calling the callback. if (initOptions.asyncInit) { return; } } // The probe impl is found, and instantiated if necessary whenDone(); }
javascript
{ "resource": "" }
q14055
connect
train
function connect() { // detect type of each argument for (var i = 0; i < arguments.length; i++) { if (arguments[i].constructor.name === 'Mongoose') { // detected Mongoose this.mongoose = arguments[i]; } else if (arguments[i].name === 'app') { // detected Express app this.app = arguments[i]; } } return this; }
javascript
{ "resource": "" }
q14056
mod
train
function mod(A, B) { var C = 1, D = 0 var _B = B if (B > A) return A //shift B right until it it's just smaller than A. while(B < A) { B<<=1; C<<=1 } //now, shift B back, while subtracting. do { B>>=1; C>>=1 //mark the bits where you could subtract. //this becomes the quotent! if(B < A) { D |= C; A = A - B } console.log('=', D.toString(2)) } while(B > _B) console.log(D, D.toString(2)) return A }
javascript
{ "resource": "" }
q14057
validate
train
function validate(json, done) { var log = [] var err try { json = JSON.parse(JSON.stringify(json)) } catch (e) { err = e json = {} } Object.keys(json).forEach(function (selector) { var declarations = json[selector] Object.keys(declarations).forEach(function (name) { var value = declarations[name] var result = validateItem(name, value) if (typeof result.value === 'number' || typeof result.value === 'string') { declarations[name] = result.value } else { delete declarations[name] } if (result.log) { log.push(result.log) } }) }) done(err, { jsonStyle: json, log: log }) }
javascript
{ "resource": "" }
q14058
qParallel
train
function qParallel(funcs, count) { var length = funcs.length; if (!length) { return q([]); } if (count == null) { count = Infinity; } count = Math.max(count, 1); count = Math.min(count, funcs.length); var promises = []; var values = []; for (var i = 0; i < count; ++i) { var promise = funcs[i](); promise = promise.then(next(i)); promises.push(promise); } return q.all(promises).then(function () { return values; }); function next(i) { return function (value) { if (i == null) { i = count++; } if (i < length) { values[i] = value; } if (count < length) { return funcs[count]().then(next()) } } } }
javascript
{ "resource": "" }
q14059
Color
train
function Color(values, spaceAlpha, space) { this.values = values; this.alpha = 1; this.space = 'rgb'; this.originalColor = null; if (space !== undefined) { this.alpha = spaceAlpha; this.space = space; } else if (spaceAlpha !== undefined) { if (typeof spaceAlpha === 'number') { this.alpha = spaceAlpha; } else { this.space = spaceAlpha; } } }
javascript
{ "resource": "" }
q14060
isCompassInstalled
train
function isCompassInstalled() { var deferred = q.defer(), cmd = 'compass'; exec(cmd, function (err) { deferred.resolve(! err); }); return deferred.promise; }
javascript
{ "resource": "" }
q14061
scino
train
function scino (num, precision, options) { if (typeof precision === 'object') { options = precision precision = undefined } if (typeof num !== 'number') { return num } var parsed = parse(num, precision) var opts = getValidOptions(options) var coefficient = parsed.coefficient var exponent = parsed.exponent.toString() var superscriptExponent = '' if (typeof coefficient === 'number' && isNaN(coefficient)) { return num } for (var i = 0; i < exponent.length; i++) { superscriptExponent += SUPERSCRIPTS[exponent[i]] } return opts.beforeCoefficient + coefficient + opts.afterCoefficient + opts.beforeMultiplicationSign + opts.multiplicationSign + opts.afterMultiplicationSign + opts.beforeBase + opts.base + opts.afterBase + opts.beforeExponent + superscriptExponent + opts.afterExponent }
javascript
{ "resource": "" }
q14062
parse
train
function parse (num, precision) { var exponent = Math.floor(Math.log10(Math.abs(num))) var coefficient = new Decimal(num) .mul(new Decimal(Math.pow(10, -1 * exponent))) return { coefficient: typeof precision === 'number' ? coefficient.toSD(precision).toNumber() : coefficient.toNumber(), exponent: exponent } }
javascript
{ "resource": "" }
q14063
render
train
function render(content, store) { var type = typeof content; var node = content; if(type === 'function') node = render(content(), store); else if(type === 'string') { node = document.createTextNode(''); bind(content, function(data) { node.nodeValue = data; }, store); } else if(content instanceof Array) node = fragment(content, store); return node; }
javascript
{ "resource": "" }
q14064
bind
train
function bind(text, fn, store) { var data = store.data; var tmpl = mouth(text, store.data); var cb = tmpl[0]; var keys = tmpl[1]; fn(cb(store.data)); for(var l = keys.length; l--;) { store.on('change ' + keys[l], function() { fn(cb(store.data)); }); } }
javascript
{ "resource": "" }
q14065
fragment
train
function fragment(arr, store) { var el = document.createDocumentFragment(); for(var i = 0, l = arr.length; i < l; i++) { el.appendChild(render(arr[i], store)); } return el; }
javascript
{ "resource": "" }
q14066
attributes
train
function attributes(el, attrs, store) { for(var key in attrs) { var value = attrs[key]; if(typeof value === 'object') value = styles(value); else if(typeof value === 'function') { var bool = key.substring(0, 2) === 'on'; if(bool) el.addEventListener(key.slice(2), value); else el.setAttribute(key, value.call(store.data)); // @not we should compute the function if it's not an event break; } bind(value, function(data) { // @note should refactor with render (too bad attribute can't append text node anymore) el.setAttribute(this, data); }.bind(key), store); } }
javascript
{ "resource": "" }
q14067
styles
train
function styles(obj) { var str = ''; for(var key in obj) { str += key + ':' + obj[key] + ';'; } return str; }
javascript
{ "resource": "" }
q14068
buildCommand
train
function buildCommand(options, dir) { var cmd = options.bin; if (options.reportFile) { cmd += ' --log-pmd ' + options.reportFile; } cmd += ' --min-lines ' + options.minLines; cmd += ' --min-tokens ' + options.minTokens; if (options.exclude instanceof Array) { for (var i = 0, l = options.exclude; i < l; i++) { cmd += ' --exclude ' + options.exclude[i]; } } else { cmd += ' --exclude ' + options.exclude; } cmd += ' --names \"' + options.names + '\"'; if (options.namesExclude) { cmd += ' --names-exclude \"' + options.namesExclude + '\"'; } if (options.quiet) { cmd += ' --quiet'; } if (options.verbose) { cmd += ' --verbose'; } return cmd + ' ' + dir; }
javascript
{ "resource": "" }
q14069
train
function(args, done) { debug('checking required files with args', args); var dir = path.resolve(args['<directory>']); var tasks = [ 'README*', 'LICENSE', '.travis.yml', '.gitignore' ].map(function requireFileExists(pattern) { return function(cb) { glob(pattern, { cwd: dir }, function(err, files) { debug('resolved %s for `%s`', files, pattern); if (err) { return cb(err); } if (files.length === 0) { return done(new Error('missing required file matching ' + pattern)); } if (files.length > 1) { return done(new Error('more than one file matched ' + pattern)); } fs.exists(files[0], function(exists) { if (!exists) { return done(new Error('missing required file matching ' + files[0])); } return cb(null, files[0]); }); }); }; }); async.parallel(tasks, done); }
javascript
{ "resource": "" }
q14070
train
function(args, done) { var dir = path.resolve(args['<directory>']); var pkg = require(path.join(dir, 'package.json')); var schema = Joi.object().keys({ name: Joi.string().min(1).max(30).regex(/^[a-zA-Z0-9][a-zA-Z0-9\.\-_]*$/).required(), version: Joi.string().regex(/^[0-9]+\.[0-9]+[0-9+a-zA-Z\.\-]+$/).required(), description: Joi.string().max(80).required(), license: Joi.string().max(20).required(), homepage: Joi.string().uri({ scheme: ['http', 'https'] }).required(), main: Joi.string().optional(), repository: Joi.object().keys({ type: Joi.string().valid('git').required(), url: Joi.string().uri({ scheme: ['git', 'https'] }).regex(/mongodb-js\/[a-zA-Z0-9\.\-_]+/).required() }), bin: Joi.object().optional(), scripts: Joi.object().optional(), bugs: Joi.alternatives().try(Joi.string(), Joi.object()).required(), author: Joi.string().required(), dependencies: Joi.object().required(), devDependencies: Joi.object().required() }); Joi.validate(pkg, schema, { abortEarly: false, allowUnknown: true }, done); }
javascript
{ "resource": "" }
q14071
train
function(args, done) { function run(cmd) { return function(cb) { debug('testing `%s`', cmd); var parts = cmd.split(' '); var bin = parts.shift(); var args = parts; var completed = false; var child = spawn(bin, args, { cwd: args['<directory>'] }) .on('error', function(err) { completed = true; done(new Error(cmd + ' failed: ' + err.message)); }); child.stderr.pipe(process.stderr); if (cmd === 'npm start') { setTimeout(function() { if (completed) { return; } completed = true; child.kill('SIGKILL'); done(); }, 5000); } child.on('close', function(code) { if (completed) { return; } completed = true; if (code === 0) { done(); return; } cb(new Error(cmd + ' failed')); }); }; } debug('checking first run'); var dir = path.resolve(args['<directory>']); var pkg = require(path.join(dir, 'package.json')); debug('clearing local node_modules to make sure install works'); rimraf(dir + '/node_modules/**/*', function(err) { if (err) { return done(err); } var tasks = [ run('npm install'), run('npm test') ]; if (pkg.scripts.start) { tasks.push(run('npm start')); } async.series(tasks, function(err, results) { if (err) { return done(err); } done(null, results); }); }); }
javascript
{ "resource": "" }
q14072
toBoolean
train
function toBoolean(str, fallback) { if (typeof str === 'boolean') { return str; } if (REGEXP_TRUE.test(str)) { return true; } if (REGEXP_FALSE.test(str)) { return false; } return fallback; }
javascript
{ "resource": "" }
q14073
hashCode
train
function hashCode(str) { var hash = 0xdeadbeef; for (var i = str.length; i >= 0; --i) { hash = (hash * 33) ^ str.charCodeAt(--i); } // turn to unsigned 32bit int return hash >>> 0; }
javascript
{ "resource": "" }
q14074
gravatarUrl
train
function gravatarUrl(email, size) { var url = 'http://www.gravatar.com/avatar/'; if (email) { url += crypto.createHash('md5').update(email.toLowerCase()).digest('hex'); } if (size) { url += '?s=' + size; } return url; }
javascript
{ "resource": "" }
q14075
placeholderUrl
train
function placeholderUrl(width, height, text) { var url = 'http://placehold.it/' + width; if (height) { url += 'x' + height; } if (text) { url += '&text=' + encodeURIComponent(text); } return url; }
javascript
{ "resource": "" }
q14076
digestPassword
train
function digestPassword(password, salt, algorithm, encoding) { var hash = (salt) ? crypto.createHmac(algorithm || 'sha1', salt) : crypto.createHash(algorithm || 'sha1'); return hash.update(password).digest(encoding || 'hex'); }
javascript
{ "resource": "" }
q14077
digestFile
train
function digestFile(file, algorithm, encoding) { return crypto.createHash(algorithm || 'md5').update(fs.readFileSync(file)).digest(encoding || 'hex'); }
javascript
{ "resource": "" }
q14078
flatten
train
function flatten(a) { return a.reduce(function(flat, val) { if (val && typeof val.flatten === 'function') { flat = flat.concat(val.flatten()); } else if (Array.isArray(val)) { flat = flat.concat(flatten(val)); } else { flat.push(val); } return flat; }); }
javascript
{ "resource": "" }
q14079
StreamClient
train
function StreamClient(options) { EventEmitter.call(this); SockJS = options.SockJS || SockJS; // Facilitate testing this.options = extend({}, options); // Clone this.options.debug = this.options.debug || false; this.options.retry = this.options.retry || 10; // Try to (re)connect 10 times before giving up this.options.retryTimeout = this.options.retryTimeout !== undefined ? this.options.retryTimeout : 500; this.options.protocol = this.options.protocol || window.location.protocol; if (this.options.protocol.slice(-1) !== ':') { this.options.protocol += ':'; } this.options.port = Number(this.options.port); if (!this.options.port) { if (this.options.protocol === "http:") { this.options.port = 80 } else if (this.options.protocol === "https:") { this.options.port = 443 } else { throw new Error("Invalid protocol and port"); } } this.options.endpoint = this.options.endpoint || '/stream'; if (!this.options.hostname && options.environment) { this.options.hostname = environments[options.environment]; } if (!this.options.hostname) { throw new Error("Stream Hostname is required"); } // SockJS - Stream Connection this.lfToken = null; this.conn = null; this.lastError = null; this.retryCount = 0; this.rebalancedTo = null; this.allProtocols = Object.keys(SockJS.getUtils().probeProtocols()); this.allProtocolsWithoutWS = this.allProtocols.slice(); this.allProtocolsWithoutWS.splice(this.allProtocols.indexOf("websocket"),1); this.streams = {}; // Stream State this.States = States; // Make accessible for testing this.state = new State(States.DISCONNECTED); this.state.on("change", this._stateChangeHandler.bind(this)); }
javascript
{ "resource": "" }
q14080
train
function (Schema, key) { if (!this.KEY_SCHEMA_REG_EXP.test(key)) { throw new Error('invalid schema key format. must be match with ' + this.KEY_SCHEMA_REG_EXP.source); } var schema = new Schema(); key.replace(this.KEY_SCHEMA_REG_EXP, this._patchFormat(schema)); return schema; }
javascript
{ "resource": "" }
q14081
train
function (Schema, fieldName, parent) { var schema = new Schema(); var name = fieldName.replace(this.KEY_FIELD_REG_EXP, this._patchFormat(schema)); return parent.field(name).like(schema); }
javascript
{ "resource": "" }
q14082
train
function(gl, vertices, uv) { var verticesBuf = createBuffer(gl, new Float32Array(vertices)) var uvBuf = createBuffer(gl, new Float32Array(uv)) var mesh = createVAO(gl, [ { buffer: verticesBuf, size: 3 }, { buffer: uvBuf, size: 2 } ]) mesh.length = vertices.length/3 return mesh }
javascript
{ "resource": "" }
q14083
parseQueryString
train
function parseQueryString(query, options) { const result = {}; let parsedQueryString = qs.parse(query); for (const key in parsedQueryString) { const value = parsedQueryString[key]; if (value === '' || value == null) { throw new MongoParseError('Incomplete key value pair for option'); } const normalizedKey = key.toLowerCase(); const parsedValue = parseQueryStringItemValue(normalizedKey, value); applyConnectionStringOption(result, normalizedKey, parsedValue, options); } // special cases for known deprecated options if (result.wtimeout && result.wtimeoutms) { delete result.wtimeout; console.warn('Unsupported option `wtimeout` specified'); } return Object.keys(result).length ? result : null; }
javascript
{ "resource": "" }
q14084
varMatchingAny
train
function varMatchingAny(varnameAtom) { return sl.list(sl.atom("::", {token: varnameAtom}), varnameAtom, sl.str("any")); }
javascript
{ "resource": "" }
q14085
train
function (url) { // *WARNING WARNING WARNING* // This method yields the most correct result we can get but it is EXPENSIVE! // In ALL browsers! When called multiple times in a sequence, as if when // we resolve dependencies for entries, it will cause garbage collection events // and overall painful slowness. This is why we try to avoid it as much as we can. // // @TODO - see if we need this fallback logic // http://stackoverflow.com/questions/470832/getting-an-absolute-url-from-a-relative-one-ie6-issue resolverEl.href = url; var ret = resolverEl.href, dc = _config.disableCachingParam, pos = dc ? ret.indexOf(dc + '=') : -1, c, end; // If we have a _dc query parameter we need to remove it from the canonical // URL. if (pos > 0 && ((c = ret.charAt(pos - 1)) === '?' || c === '&')) { end = ret.indexOf('&', pos); end = (end < 0) ? '' : ret.substring(end); if (end && c === '?') { ++pos; // keep the '?' end = end.substring(1); // remove the '&' } ret = ret.substring(0, pos - 1) + end; } return ret; }
javascript
{ "resource": "" }
q14086
train
function (name, value) { if (typeof name === 'string') { Boot.config[name] = value; } else { for (var s in name) { Boot.setConfig(s, name[s]); } } return Boot; }
javascript
{ "resource": "" }
q14087
train
function (indexMap, loadOrder) { // In older versions indexMap was an object instead of a sparse array if (!('length' in indexMap)) { var indexArray = [], index; for (index in indexMap) { if (!isNaN(+index)) { indexArray[+index] = indexMap[index]; } } indexMap = indexArray; } return Request.prototype.getPathsFromIndexes(indexMap, loadOrder); }
javascript
{ "resource": "" }
q14088
train
function ( fn, context ) { // Initialize variables this.state = Promise.STATE.INITIALIZED; this.handlers = []; this.value = fn; // Rebind control functions to be run always on this promise this.resolve = this.resolve.bind( this ); this.fulfill = this.fulfill.bind( this ); this.reject = this.reject.bind( this ); // Set fn and context if ( fn ) { if ( typeof fn !== 'function' ) throw new TypeError("fn is not a function"); this.fn = fn; this.context = context || this; this.run(); } return this; }
javascript
{ "resource": "" }
q14089
train
function ( x ) { if ( Util.is.Error( x ) ) { return this.reject( x ); } // Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure try { if ( x === this ) { throw new TypeError('A promise cannot be resolved with itself.'); } if ( Util.is.Promise( x ) || ( x !== null && Util.is.Object( x ) && Util.is.Function( x.then ) ) ) { Promise.doResolve( x.then.bind( x ), this.resolve, this.reject ); return this; } if ( Util.is.Function( x ) ) { Promise.doResolve( x, this.resolve, this.reject ); return this; } this.fulfill( x ); } catch ( error ) { return this.reject( error ); } return this; }
javascript
{ "resource": "" }
q14090
train
function ( onRejected ) { if ( onRejected && typeof onRejected !== 'function' ) throw new TypeError("onFulfilled is not a function"); var promise = this, handler = new Promise.Handler({ onRejected: onRejected, }); // Catch on entire promise chain while( promise ) { handler.handle( promise ); promise = promise.parent; } return this; }
javascript
{ "resource": "" }
q14091
resolve
train
function resolve() { return whichNativeNodish('..') .then(function (results) { var nwVersion = results.nwVersion; var asVersion = results.asVersion; debug('which-native-nodish output: %j', results); var prefix = ''; var target = ''; var debugArg = process.env.BUILD_DEBUG ? ' --debug' : ''; var builder = 'node-gyp'; var distUrl = ''; if (asVersion) { prefix = (process.platform === 'win32' ? 'SET USERPROFILE=%USERPROFILE%\\.electron-gyp&&' : 'HOME=~/.electron-gyp'); target = '--target=' + asVersion; distUrl = '--dist-url=https://atom.io/download/atom-shell'; } else if (nwVersion) { builder = 'nw-gyp'; target = '--target=' + nwVersion; } builder = '"' + path.resolve(__dirname, '..', 'node_modules', '.bin', builder) + '"'; return [prefix, builder, 'rebuild', target, debugArg, distUrl] .join(' ').trim(); }); }
javascript
{ "resource": "" }
q14092
rgba
train
function rgba(r, g, b, a) { return new RGBA(r, g, b, a); }
javascript
{ "resource": "" }
q14093
train
function(cb) { cb = cb || _.noop; const self = this; self._step = 0; if (self._stack.length<=0) return cb(); (function next() { const step = _getStep(self); if (!step) { cb(); } else if (_.isFunction(step)) { step.call(self, next); } else if (_.isFunction(step[self._exec])) { step[self._exec](next); } })(); }
javascript
{ "resource": "" }
q14094
Menu
train
function Menu(arg,opt) { if ($.isPlainObject(arg) || Array.isArray(arg)) { opt = arg; arg = null; } /** * Conteneur du menu contextuel */ if (!arg) arg = document.createElement('ul'); if (arg) this.container = $(arg)[0]; /** * Tableau d'objets MenuItem définissant la liste des éléments du menu */ this.list = []; /** * Liste des séparateurs d'éléments */ this.dividers = []; this.keyboardCtrls = new KeyboardCtrls(this); if (opt) this.set(opt); }
javascript
{ "resource": "" }
q14095
train
function() { var currentIndent = []; var i; for (i = 0; i < this._currentIndent; i++) { currentIndent[i] = this._singleIndent; } return currentIndent.join(""); }
javascript
{ "resource": "" }
q14096
train
function() { if (!this.quiet()) { var prefix = this._callerInfo() + this._getIndent() + "#".magenta.bold; var args = argsToArray(arguments).map(function(a) { if (typeof a != "string") { a = util.inspect(a); } return a.toUpperCase().magenta.bold.inverse; }).join(" "); console.log.call(console, prefix, args); } }
javascript
{ "resource": "" }
q14097
train
function() { if (!this.quiet()) { var hr = []; for (var i = 0; i < 79; i++) { hr[i] = "-"; } console.log(this._callerInfo() + this._getIndent() + hr.join("").green); } }
javascript
{ "resource": "" }
q14098
train
function(keyDownFn, keyUpFn) { var g_keyState = {}; var g_oldKeyState = {}; var updateKey = function(keyCode, state) { g_keyState[keyCode] = state; if (g_oldKeyState !== g_keyState) { g_oldKeyState = state; if (state) { keyDownFn(keyCode); } else { keyUpFn(keyCode); } } }; var keyUp = function(event) { updateKey(event.keyCode, false); }; var keyDown = function(event) { updateKey(event.keyCode, true); }; window.addEventListener("keyup", keyUp, false); window.addEventListener("keydown", keyDown, false); }
javascript
{ "resource": "" }
q14099
sinonDoublist
train
function sinonDoublist(sinon, test, disableAutoSandbox) { if (typeof test === 'string') { adapters[test](sinon, disableAutoSandbox); return; } Object.keys(mixin).forEach(function forEachKey(method) { test[method] = mixin[method].bind(test); }); if (!disableAutoSandbox) { test.createSandbox(sinon); } }
javascript
{ "resource": "" }