_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q43100
train
function(path, stamp) { var name = sysPath.basename(path); var ext = sysPath.extname(name); var stub = path.slice(0, name ? (-name.length) : path.length - 1); if (ext.length) { name = name.slice(0, -ext.length); } //Ignore leading dot if ('.' === ext[0]) { ext = ext.slice(1); } return urljoin(stub, options.buildFileName(name, ext, stamp)); }
javascript
{ "resource": "" }
q43101
User
train
function User(db, username, opts) { if (typeof db !== 'object') { throw new TypeError('db must be an object'); } if (typeof username !== 'string') { throw new TypeError('username must be a string'); } opts = opts || {}; if (typeof opts !== 'object') { throw new TypeError('opts must be an object'); } var realm = '_default'; if (typeof opts.realm !== 'undefined') { if (typeof opts.realm !== 'string') { throw new TypeError('opts.realm must be a string'); } realm = opts.realm; } if (typeof opts.debug !== 'undefined' && typeof opts.debug !== 'boolean') { throw new TypeError('opts.debug must be a boolean'); } if (typeof opts.hide !== 'undefined' && typeof opts.hide !== 'boolean') { throw new TypeError('opts.hide must be a boolean'); } if (username.length < 2) { throw new Error('username must be at least 2 characters'); } if (username.length > 128) { throw new Error('username can not exceed 128 characters'); } if (realm.length < 1) { throw new Error('opts.realm must be at least 1 character'); } if (realm.length > 128) { throw new Error('opts.realm can not exceed 128 characters'); } this._db = db; this._username = username; this._realm = realm; this._debug = opts.debug || false; this._hide = opts.hide || false; // keys that should be mapped from the user object that is stored in the user db this._protectedDbKeys = { realm: true, username: true, password: true }; // keys that can not be used in the user object that is stored in the user db this._illegalDbKeys = { _protectedDbKeys: true, _illegalDbKeys: true, _db: true, _debug: true, _hide: true }; }
javascript
{ "resource": "" }
q43102
train
function(data) { var map = _map, key; if (map && data) { for (key in data) { if (key && data.hasOwnProperty(key)) { _map[key] = data[key]; } } } }
javascript
{ "resource": "" }
q43103
ScyllaDown
train
function ScyllaDown(location) { if (!(this instanceof ScyllaDown)) return new ScyllaDown(location) AbstractLevelDOWN.call(this, location) this.keyspace = null this.client = null this.table = slugify(location) this[kQuery] = { insert: null , update: null , get: null , del: null } }
javascript
{ "resource": "" }
q43104
executeGit
train
function executeGit( args, options ) { options = options || {}; return new Promise( function( resolve, reject ) { var stdo = ''; var proc = doSpawn( 'git', args, { cwd: options.cwd ? options.cwd : process.cwd(), stdio: [ 'ignore', 'pipe', 'ignore' ] } ); function unpipe() { } if ( options.captureStdout ) { proc.stdout.on( 'data', function onStdout( data ) { stdo += data.toString(); } ); } proc.on( 'error', function( err ) { unpipe(); if ( options.ignoreError ) { resolve( { out: stdo, code: 0 } ); } else { printError( err, args ); reject( err ); } } ); proc.on( 'exit', function( code ) { unpipe(); } ); proc.on( 'close', function( code ) { unpipe(); if ( code !== 0 && !options.ignoreError ) { if ( !options.quiet ) { printError( '', args ); } reject( new Error( "Error running git" ) ); } else { resolve( { out: stdo, code: code } ); } } ); } ); }
javascript
{ "resource": "" }
q43105
train
function(filepath, data){ filepath = [].concat(filepath); var buf=[].concat(filepath); function parse(fileId, refUri, data) { var filepath = id2Uri(fileId, refUri, data); if(!grunt.file.exists(filepath)){ //file not found grunt.log.warn('Source file "' + filepath + '" not found.'); return; } buf.unshift(filepath); if(filepath.indexOf('.css') != -1){ //if depend a css file buf.unshift(CSSFILE_HOLDER); return; } var dependencies = parseDependencies(grunt.file.read(filepath)); if (dependencies.length) { var i = dependencies.length; while (i--) { parse(dependencies[i], filepath, data); } } } filepath.forEach(function(filepath){ var fileContent = grunt.file.read(filepath); parseDependencies(fileContent).forEach(function(id){ parse(id, filepath, data); }) }) //filter the same file return buf.filter(function(value, index, self){ return self.indexOf(value) === index; }); }
javascript
{ "resource": "" }
q43106
and
train
function and(values, values2) { var results = []; if(values instanceof Array) { for(var i=0; i<values.length; i++) { results.push(values[i]); } } if(values2 instanceof Array) { for(var i=0; i<values2.length; i++) { results.push(values2[i]); } } return results; }
javascript
{ "resource": "" }
q43107
getMethod
train
function getMethod(methodname) { if (controllers[methodname]) { return function(call, callback) { console.log(call); return controllers[methodname](call, callback); }; } else { return function(call, callback) { // By default we print an empty response. callback(null, {}); }; } }
javascript
{ "resource": "" }
q43108
scale
train
function scale(s, v){ return Vector3(v.x*s, v.y*s, v.z*s); }
javascript
{ "resource": "" }
q43109
train
function( dialog, elementDefinition, htmlList, contentHtml ) { if ( arguments.length < 4 ) return; var _ = initPrivateObject.call( this, elementDefinition ); _.labelId = CKEDITOR.tools.getNextId() + '_label'; var children = this._.children = []; var innerHTML = function() { var html = [], requiredClass = elementDefinition.required ? ' cke_required' : ''; if ( elementDefinition.labelLayout != 'horizontal' ) { html.push( '<label class="cke_dialog_ui_labeled_label' + requiredClass + '" ', ' id="' + _.labelId + '"', ( _.inputId ? ' for="' + _.inputId + '"' : '' ), ( elementDefinition.labelStyle ? ' style="' + elementDefinition.labelStyle + '"' : '' ) + '>', elementDefinition.label, '</label>', '<div class="cke_dialog_ui_labeled_content"', ( elementDefinition.controlStyle ? ' style="' + elementDefinition.controlStyle + '"' : '' ), ' role="presentation">', contentHtml.call( this, dialog, elementDefinition ), '</div>' ); } else { var hboxDefinition = { type: 'hbox', widths: elementDefinition.widths, padding: 0, children: [ { type: 'html', html: '<label class="cke_dialog_ui_labeled_label' + requiredClass + '"' + ' id="' + _.labelId + '"' + ' for="' + _.inputId + '"' + ( elementDefinition.labelStyle ? ' style="' + elementDefinition.labelStyle + '"' : '' ) + '>' + CKEDITOR.tools.htmlEncode( elementDefinition.label ) + '</span>' }, { type: 'html', html: '<span class="cke_dialog_ui_labeled_content"' + ( elementDefinition.controlStyle ? ' style="' + elementDefinition.controlStyle + '"' : '' ) + '>' + contentHtml.call( this, dialog, elementDefinition ) + '</span>' } ] }; CKEDITOR.dialog._.uiElementBuilders.hbox.build( dialog, hboxDefinition, html ); } return html.join( '' ); }; var attributes = { role: elementDefinition.role || 'presentation' }; if ( elementDefinition.includeLabel ) attributes[ 'aria-labelledby' ] = _.labelId; CKEDITOR.ui.dialog.uiElement.call( this, dialog, elementDefinition, htmlList, 'div', null, attributes, innerHTML ); }
javascript
{ "resource": "" }
q43110
train
function( dialog, elementDefinition, htmlList ) { if ( arguments.length < 3 ) return; initPrivateObject.call( this, elementDefinition ); var domId = this._.inputId = CKEDITOR.tools.getNextId() + '_textInput', attributes = { 'class': 'cke_dialog_ui_input_' + elementDefinition.type, id: domId, type: elementDefinition.type }, i; // Set the validator, if any. if ( elementDefinition.validate ) this.validate = elementDefinition.validate; // Set the max length and size. if ( elementDefinition.maxLength ) attributes.maxlength = elementDefinition.maxLength; if ( elementDefinition.size ) attributes.size = elementDefinition.size; if ( elementDefinition.inputStyle ) attributes.style = elementDefinition.inputStyle; // If user presses Enter in a text box, it implies clicking OK for the dialog. var me = this, keyPressedOnMe = false; dialog.on( 'load', function() { me.getInputElement().on( 'keydown', function( evt ) { if ( evt.data.getKeystroke() == 13 ) keyPressedOnMe = true; } ); // Lower the priority this 'keyup' since 'ok' will close the dialog.(#3749) me.getInputElement().on( 'keyup', function( evt ) { if ( evt.data.getKeystroke() == 13 && keyPressedOnMe ) { dialog.getButton( 'ok' ) && setTimeout( function() { dialog.getButton( 'ok' ).click(); }, 0 ); keyPressedOnMe = false; } }, null, null, 1000 ); } ); var innerHTML = function() { // IE BUG: Text input fields in IE at 100% would exceed a <td> or inline // container's width, so need to wrap it inside a <div>. var html = [ '<div class="cke_dialog_ui_input_', elementDefinition.type, '" role="presentation"' ]; if ( elementDefinition.width ) html.push( 'style="width:' + elementDefinition.width + '" ' ); html.push( '><input ' ); attributes[ 'aria-labelledby' ] = this._.labelId; this._.required && ( attributes[ 'aria-required' ] = this._.required ); for ( var i in attributes ) html.push( i + '="' + attributes[ i ] + '" ' ); html.push( ' /></div>' ); return html.join( '' ); }; CKEDITOR.ui.dialog.labeledElement.call( this, dialog, elementDefinition, htmlList, innerHTML ); }
javascript
{ "resource": "" }
q43111
train
function( dialog, elementDefinition, htmlList ) { if ( arguments.length < 3 ) return; initPrivateObject.call( this, elementDefinition ); var me = this, domId = this._.inputId = CKEDITOR.tools.getNextId() + '_textarea', attributes = {}; if ( elementDefinition.validate ) this.validate = elementDefinition.validate; // Generates the essential attributes for the textarea tag. attributes.rows = elementDefinition.rows || 5; attributes.cols = elementDefinition.cols || 20; attributes[ 'class' ] = 'cke_dialog_ui_input_textarea ' + ( elementDefinition[ 'class' ] || '' ); if ( typeof elementDefinition.inputStyle != 'undefined' ) attributes.style = elementDefinition.inputStyle; if ( elementDefinition.dir ) attributes.dir = elementDefinition.dir; var innerHTML = function() { attributes[ 'aria-labelledby' ] = this._.labelId; this._.required && ( attributes[ 'aria-required' ] = this._.required ); var html = [ '<div class="cke_dialog_ui_input_textarea" role="presentation"><textarea id="', domId, '" ' ]; for ( var i in attributes ) html.push( i + '="' + CKEDITOR.tools.htmlEncode( attributes[ i ] ) + '" ' ); html.push( '>', CKEDITOR.tools.htmlEncode( me._[ 'default' ] ), '</textarea></div>' ); return html.join( '' ); }; CKEDITOR.ui.dialog.labeledElement.call( this, dialog, elementDefinition, htmlList, innerHTML ); }
javascript
{ "resource": "" }
q43112
train
function( dialog, elementDefinition, htmlList ) { if ( arguments.length < 3 ) return; var _ = initPrivateObject.call( this, elementDefinition, { 'default': !!elementDefinition[ 'default' ] } ); if ( elementDefinition.validate ) this.validate = elementDefinition.validate; var innerHTML = function() { var myDefinition = CKEDITOR.tools.extend( {}, elementDefinition, { id: elementDefinition.id ? elementDefinition.id + '_checkbox' : CKEDITOR.tools.getNextId() + '_checkbox' }, true ), html = []; var labelId = CKEDITOR.tools.getNextId() + '_label'; var attributes = { 'class': 'cke_dialog_ui_checkbox_input', type: 'checkbox', 'aria-labelledby': labelId }; cleanInnerDefinition( myDefinition ); if ( elementDefinition[ 'default' ] ) attributes.checked = 'checked'; if ( typeof myDefinition.inputStyle != 'undefined' ) myDefinition.style = myDefinition.inputStyle; _.checkbox = new CKEDITOR.ui.dialog.uiElement( dialog, myDefinition, html, 'input', null, attributes ); html.push( ' <label id="', labelId, '" for="', attributes.id, '"' + ( elementDefinition.labelStyle ? ' style="' + elementDefinition.labelStyle + '"' : '' ) + '>', CKEDITOR.tools.htmlEncode( elementDefinition.label ), '</label>' ); return html.join( '' ); }; CKEDITOR.ui.dialog.uiElement.call( this, dialog, elementDefinition, htmlList, 'span', null, null, innerHTML ); }
javascript
{ "resource": "" }
q43113
train
function( dialog, elementDefinition, htmlList ) { if ( arguments.length < 3 ) return; initPrivateObject.call( this, elementDefinition ); if ( !this._[ 'default' ] ) this._[ 'default' ] = this._.initValue = elementDefinition.items[ 0 ][ 1 ]; if ( elementDefinition.validate ) this.validate = elementDefinition.valdiate; var children = [], me = this; var innerHTML = function() { var inputHtmlList = [], html = [], commonName = ( elementDefinition.id ? elementDefinition.id : CKEDITOR.tools.getNextId() ) + '_radio'; for ( var i = 0; i < elementDefinition.items.length; i++ ) { var item = elementDefinition.items[ i ], title = item[ 2 ] !== undefined ? item[ 2 ] : item[ 0 ], value = item[ 1 ] !== undefined ? item[ 1 ] : item[ 0 ], inputId = CKEDITOR.tools.getNextId() + '_radio_input', labelId = inputId + '_label', inputDefinition = CKEDITOR.tools.extend( {}, elementDefinition, { id: inputId, title: null, type: null }, true ), labelDefinition = CKEDITOR.tools.extend( {}, inputDefinition, { title: title }, true ), inputAttributes = { type: 'radio', 'class': 'cke_dialog_ui_radio_input', name: commonName, value: value, 'aria-labelledby': labelId }, inputHtml = []; if ( me._[ 'default' ] == value ) inputAttributes.checked = 'checked'; cleanInnerDefinition( inputDefinition ); cleanInnerDefinition( labelDefinition ); if ( typeof inputDefinition.inputStyle != 'undefined' ) inputDefinition.style = inputDefinition.inputStyle; // Make inputs of radio type focusable (#10866). inputDefinition.keyboardFocusable = true; children.push( new CKEDITOR.ui.dialog.uiElement( dialog, inputDefinition, inputHtml, 'input', null, inputAttributes ) ); inputHtml.push( ' ' ); new CKEDITOR.ui.dialog.uiElement( dialog, labelDefinition, inputHtml, 'label', null, { id: labelId, 'for': inputAttributes.id }, item[ 0 ] ); inputHtmlList.push( inputHtml.join( '' ) ); } new CKEDITOR.ui.dialog.hbox( dialog, children, inputHtmlList, html ); return html.join( '' ); }; // Adding a role="radiogroup" to definition used for wrapper. elementDefinition.role = 'radiogroup'; elementDefinition.includeLabel = true; CKEDITOR.ui.dialog.labeledElement.call( this, dialog, elementDefinition, htmlList, innerHTML ); this._.children = children; }
javascript
{ "resource": "" }
q43114
train
function( dialog, elementDefinition, htmlList ) { if ( !arguments.length ) return; if ( typeof elementDefinition == 'function' ) elementDefinition = elementDefinition( dialog.getParentEditor() ); initPrivateObject.call( this, elementDefinition, { disabled: elementDefinition.disabled || false } ); // Add OnClick event to this input. CKEDITOR.event.implementOn( this ); var me = this; // Register an event handler for processing button clicks. dialog.on( 'load', function( eventInfo ) { var element = this.getElement(); ( function() { element.on( 'click', function( evt ) { me.click(); // #9958 evt.data.preventDefault(); } ); element.on( 'keydown', function( evt ) { if ( evt.data.getKeystroke() in { 32: 1 } ) { me.click(); evt.data.preventDefault(); } } ); } )(); element.unselectable(); }, this ); var outerDefinition = CKEDITOR.tools.extend( {}, elementDefinition ); delete outerDefinition.style; var labelId = CKEDITOR.tools.getNextId() + '_label'; CKEDITOR.ui.dialog.uiElement.call( this, dialog, outerDefinition, htmlList, 'a', null, { style: elementDefinition.style, href: 'javascript:void(0)', title: elementDefinition.label, hidefocus: 'true', 'class': elementDefinition[ 'class' ], role: 'button', 'aria-labelledby': labelId }, '<span id="' + labelId + '" class="cke_dialog_ui_button">' + CKEDITOR.tools.htmlEncode( elementDefinition.label ) + '</span>' ); }
javascript
{ "resource": "" }
q43115
train
function( dialog, elementDefinition, htmlList ) { if ( arguments.length < 3 ) return; var _ = initPrivateObject.call( this, elementDefinition ); if ( elementDefinition.validate ) this.validate = elementDefinition.validate; _.inputId = CKEDITOR.tools.getNextId() + '_select'; var innerHTML = function() { var myDefinition = CKEDITOR.tools.extend( {}, elementDefinition, { id: elementDefinition.id ? elementDefinition.id + '_select' : CKEDITOR.tools.getNextId() + '_select' }, true ), html = [], innerHTML = [], attributes = { 'id': _.inputId, 'class': 'cke_dialog_ui_input_select', 'aria-labelledby': this._.labelId }; html.push( '<div class="cke_dialog_ui_input_', elementDefinition.type, '" role="presentation"' ); if ( elementDefinition.width ) html.push( 'style="width:' + elementDefinition.width + '" ' ); html.push( '>' ); // Add multiple and size attributes from element definition. if ( elementDefinition.size != undefined ) attributes.size = elementDefinition.size; if ( elementDefinition.multiple != undefined ) attributes.multiple = elementDefinition.multiple; cleanInnerDefinition( myDefinition ); for ( var i = 0, item; i < elementDefinition.items.length && ( item = elementDefinition.items[ i ] ); i++ ) { innerHTML.push( '<option value="', CKEDITOR.tools.htmlEncode( item[ 1 ] !== undefined ? item[ 1 ] : item[ 0 ] ).replace( /"/g, '&quot;' ), '" /> ', CKEDITOR.tools.htmlEncode( item[ 0 ] ) ); } if ( typeof myDefinition.inputStyle != 'undefined' ) myDefinition.style = myDefinition.inputStyle; _.select = new CKEDITOR.ui.dialog.uiElement( dialog, myDefinition, html, 'select', null, attributes, innerHTML.join( '' ) ); html.push( '</div>' ); return html.join( '' ); }; CKEDITOR.ui.dialog.labeledElement.call( this, dialog, elementDefinition, htmlList, innerHTML ); }
javascript
{ "resource": "" }
q43116
train
function( dialog, elementDefinition, htmlList ) { if ( arguments.length < 3 ) return; if ( elementDefinition[ 'default' ] === undefined ) elementDefinition[ 'default' ] = ''; var _ = CKEDITOR.tools.extend( initPrivateObject.call( this, elementDefinition ), { definition: elementDefinition, buttons: [] } ); if ( elementDefinition.validate ) this.validate = elementDefinition.validate; /** @ignore */ var innerHTML = function() { _.frameId = CKEDITOR.tools.getNextId() + '_fileInput'; var html = [ '<iframe' + ' frameborder="0"' + ' allowtransparency="0"' + ' class="cke_dialog_ui_input_file"' + ' role="presentation"' + ' id="', _.frameId, '"' + ' title="', elementDefinition.label, '"' + ' src="javascript:void(' ]; // Support for custom document.domain on IE. (#10165) html.push( CKEDITOR.env.ie ? '(function(){' + encodeURIComponent( 'document.open();' + '(' + CKEDITOR.tools.fixDomain + ')();' + 'document.close();' ) + '})()' : '0' ); html.push( ')">' + '</iframe>' ); return html.join( '' ); }; // IE BUG: Parent container does not resize to contain the iframe automatically. dialog.on( 'load', function() { var iframe = CKEDITOR.document.getById( _.frameId ), contentDiv = iframe.getParent(); contentDiv.addClass( 'cke_dialog_ui_input_file' ); } ); CKEDITOR.ui.dialog.labeledElement.call( this, dialog, elementDefinition, htmlList, innerHTML ); }
javascript
{ "resource": "" }
q43117
train
function( dialog, elementDefinition, htmlList ) { if ( arguments.length < 3 ) return; var _ = initPrivateObject.call( this, elementDefinition ), me = this; if ( elementDefinition.validate ) this.validate = elementDefinition.validate; var myDefinition = CKEDITOR.tools.extend( {}, elementDefinition ); var onClick = myDefinition.onClick; myDefinition.className = ( myDefinition.className ? myDefinition.className + ' ' : '' ) + 'cke_dialog_ui_button'; myDefinition.onClick = function( evt ) { var target = elementDefinition[ 'for' ]; // [ pageId, elementId ] if ( !onClick || onClick.call( this, evt ) !== false ) { dialog.getContentElement( target[ 0 ], target[ 1 ] ).submit(); this.disable(); } }; dialog.on( 'load', function() { dialog.getContentElement( elementDefinition[ 'for' ][ 0 ], elementDefinition[ 'for' ][ 1 ] )._.buttons.push( me ); } ); CKEDITOR.ui.dialog.button.call( this, dialog, myDefinition, htmlList ); }
javascript
{ "resource": "" }
q43118
train
function( dialog, childObjList, childHtmlList, htmlList, elementDefinition ) { var legendLabel = elementDefinition.label; /** @ignore */ var innerHTML = function() { var html = []; legendLabel && html.push( '<legend' + ( elementDefinition.labelStyle ? ' style="' + elementDefinition.labelStyle + '"' : '' ) + '>' + legendLabel + '</legend>' ); for ( var i = 0; i < childHtmlList.length; i++ ) html.push( childHtmlList[ i ] ); return html.join( '' ); }; this._ = { children: childObjList }; CKEDITOR.ui.dialog.uiElement.call( this, dialog, elementDefinition, htmlList, 'fieldset', null, null, innerHTML ); }
javascript
{ "resource": "" }
q43119
train
function( label ) { var node = CKEDITOR.document.getById( this._.labelId ); if ( node.getChildCount() < 1 ) ( new CKEDITOR.dom.text( label, CKEDITOR.document ) ).appendTo( node ); else node.getChild( 0 ).$.nodeValue = label; return this; }
javascript
{ "resource": "" }
q43120
train
function() { var node = CKEDITOR.document.getById( this._.labelId ); if ( !node || node.getChildCount() < 1 ) return ''; else return node.getChild( 0 ).getText(); }
javascript
{ "resource": "" }
q43121
train
function() { var me = this.selectParentTab(); // GECKO BUG: setTimeout() is needed to workaround invisible selections. setTimeout( function() { var e = me.getInputElement(); if ( e ) { e.$.focus(); e.$.select(); } }, 0 ); }
javascript
{ "resource": "" }
q43122
train
function( value ) { !value && ( value = '' ); return CKEDITOR.ui.dialog.uiElement.prototype.setValue.apply( this, arguments ); }
javascript
{ "resource": "" }
q43123
train
function( label, value, index ) { var option = new CKEDITOR.dom.element( 'option', this.getDialog().getParentEditor().document ), selectElement = this.getInputElement().$; option.$.text = label; option.$.value = ( value === undefined || value === null ) ? label : value; if ( index === undefined || index === null ) { if ( CKEDITOR.env.ie ) selectElement.add( option.$ ); else selectElement.add( option.$, null ); } else selectElement.add( option.$, index ); return this; }
javascript
{ "resource": "" }
q43124
train
function( value, noChangeEvent ) { var children = this._.children, item; for ( var i = 0; ( i < children.length ) && ( item = children[ i ] ); i++ ) item.getElement().$.checked = ( item.getValue() == value ); !noChangeEvent && this.fire( 'change', { value: value } ); }
javascript
{ "resource": "" }
q43125
train
function() { var children = this._.children; for ( var i = 0; i < children.length; i++ ) { if ( children[ i ].getElement().$.checked ) return children[ i ].getValue(); } return null; }
javascript
{ "resource": "" }
q43126
train
function() { var children = this._.children, i; for ( i = 0; i < children.length; i++ ) { if ( children[ i ].getElement().$.checked ) { children[ i ].getElement().focus(); return; } } children[ 0 ].getElement().focus(); }
javascript
{ "resource": "" }
q43127
train
function( definition ) { var regex = /^on([A-Z]\w+)/, match; var registerDomEvent = function( uiElement, dialog, eventName, func ) { uiElement.on( 'formLoaded', function() { uiElement.getInputElement().on( eventName, func, uiElement ); } ); }; for ( var i in definition ) { if ( !( match = i.match( regex ) ) ) continue; if ( this.eventProcessors[ i ] ) this.eventProcessors[ i ].call( this, this._.dialog, definition[ i ] ); else registerDomEvent( this, this._.dialog, match[ 1 ].toLowerCase(), definition[ i ] ); } return this; }
javascript
{ "resource": "" }
q43128
train
function (callback, context, args) { var arg1, arg2, arg3 arg1 = args[0] arg2 = args[1] arg3 = args[2] switch (args.length) { case 0: callback.call(context); return case 1: callback.call(context, arg1); return case 2: callback.call(arg1, arg2); return case 3: callback.call(context, arg1, arg2, arg3); return default: callback.apply(context, args); return } }
javascript
{ "resource": "" }
q43129
train
function (environment, options) { this.applicationId = options && options.applicationId; this.environment = environment; this.page = page; this.adManager = null; this.path = window.location.pathname; this.events = events; this.adManager = new AdManager(this.applicationId, this.deviceDetails, this.environment); appSettings.overrides = (options && options.overrides) || window.ADLIB_OVERRIDES || null; this.deviceDetails = deviceDetector.getDeviceDetails(); // If the script include is placed in the <head> of the page, // document.body is not ready yet, and we need it to retrieve the token if (document.body) { page.preloadToken(this.environment); } page.addDomReadyListener(this.environment); if (options && options.setupGlobalApi) { //Only when this option is specified, setup the API on the global window this._setUpGlobalAPI(); } }
javascript
{ "resource": "" }
q43130
exp
train
function exp(cmd, confdir) { return function (files, opt) { var defaultOpt = { cwd: process.cwd() }; opt = append(defaultOpt, opt); if (typeof files == 'string') files = [ files ]; require(path.resolve(confdir, cmd + '.js'))(files, opt); }; }
javascript
{ "resource": "" }
q43131
popFootnoteTokens
train
function popFootnoteTokens(tokens) { const from = tokens.findIndex(token => token.type === 'footnote_block_open'); const to = tokens.findIndex(token => token.type === 'footnote_block_close'); if (from === -1 || to === -1) { return []; } return tokens.splice(from, (to - from) + 1); }
javascript
{ "resource": "" }
q43132
footnoteTokensToMeta
train
function footnoteTokensToMeta(tokens, md) { return tokens .map((token, i) => { return token.type === 'footnote_open' ? i : -1; }) .filter(i => i >= 0) .map((i) => { const inlineToken = tokens[i + 2]; assert(inlineToken.type === 'inline'); const anchorToken = tokens[i + 3]; assert(anchorToken.type === 'footnote_anchor'); const content = md.renderer.render([inlineToken], md.options, {}); const id = anchorToken.meta.id + 1; const meta = Object.assign({}, anchorToken.meta, { id }); return Object.assign({}, { content }, meta); }); }
javascript
{ "resource": "" }
q43133
train
function (namespace, names){ if (names){ for (let i = 0, n = names.length; i < n; ++i){ let typeName = names[i]; if (namespace.names.hasOwnProperty(typeName)){ this.names[typeName] = namespace.names[typeName]; } else { throw new ReferenceError('import error: undefined type \'' + typeName + '\''); } } } else { // import * for (let typeName in namespace.names){ if (namespace.names.hasOwnProperty(typeName)){ this.names[typeName] = namespace.names[typeName]; } } } return this; }
javascript
{ "resource": "" }
q43134
train
function(alias, typeName){ let template = this.resolve(typeName); if (!template){ throw new ReferenceError('bad alias \'' + alias + '\': type \'' + typeName + '\' is undefined'); } this.names[alias] = template; }
javascript
{ "resource": "" }
q43135
train
function(typeName, template){ if (!(template instanceof ValueTemplate)){ template = ValueTemplate.parse(template, {namespace:this}); } class UserDefinedTemplate extends ValueTemplate{ constructor(defaultValue, validator){ super(typeName, defaultValue, validator); this.template = template; } validate(value, options){ return this.template.validate(value, options); } } this.names[typeName] = UserDefinedTemplate; return this; }
javascript
{ "resource": "" }
q43136
train
function(lastValue) { //var currentItem if (current === len) { cb && cb(lastValue); return; } var item = items[current++]; setTimeout(function() { fn(item, function(val) { process(val && lastValue); }); }, 20); }
javascript
{ "resource": "" }
q43137
train
function(ns, root){ if (!ns) { return null; } var nsParts = ns.split("."); root = root || this; for (var i = 0, len = nsParts.length; i < len; i++) { if (typeof root[nsParts[i]] === "undefined") { root[nsParts[i]] = {}; } root = root[nsParts[i]]; } return root; }
javascript
{ "resource": "" }
q43138
train
function() { var min, max, args = arguments; //if only one argument is provided we are expecting to have a value between 0 and max if (args.length === 1) { max = args[0]; min = 0; } //two arguments provided mean we are expecting to have a number between min and max if (args.length >= 2) { min = args[0]; max = args[1]; if (min > max) { min = args[1]; max = args[0]; } } return min + Math.floor(Math.random() * (max - min)); }
javascript
{ "resource": "" }
q43139
Server
train
function Server(service, methods) { this.service = service; this.methods = methods; if (typeof service === 'undefined') { throw new Error('Thrift Service is required'); } if (typeof methods !== 'object' || Object.keys(methods).length === 0) { throw new Error('Thrift Methods Handlers are required'); } return thrift.createServer(this.service, this.methods, {transport: thrift.TBufferedTransport, protocol: thrift.TBinaryProtocol}); }
javascript
{ "resource": "" }
q43140
Delegator
train
function Delegator(id, events, capture, bubble, contextDocument) { this.bubble = bubble; this.capture = capture; this.document = contextDocument; this.documentElement = contextDocument.documentElement; this.events = events; this.id = id; this.registry = {}; }
javascript
{ "resource": "" }
q43141
train
function (event) { var trigger = event.target; var probe = function (type) { if ((type !== event.type) || (1 !== trigger.nodeType)) { return false; } var attribute = ['data', this.id, type].join('-'); var key = trigger.getAttribute(attribute); if (key && this.registry.hasOwnProperty(key)) { this.registry[key](event, trigger); return true; } if (-1 !== this.bubble.indexOf(type)) { while (this.documentElement !== trigger) { trigger = trigger.parentNode; if (probe(type)) { break; } } } return false; }.bind(this); this.events.forEach(probe); }
javascript
{ "resource": "" }
q43142
train
function (map) { Object.keys(map).forEach(function (key) { if (!this.registry.hasOwnProperty(key)) { this.registry[key] = map[key]; } }, this); return this; }
javascript
{ "resource": "" }
q43143
LokeConfig
train
function LokeConfig(appName, options) { options = options || {}; // check args if (typeof appName !== 'string' || appName === '') { throw new Error('LokeConfig requires appName to be provided'); } if (Array.isArray(options)) { // Support original argument format: if (options.length === 0) { throw new Error('"paths" contains no items'); } options = {paths: options.slice(1), defaultPath: options[0]}; } var settings, self = this; var argv = minimist(process.argv.slice(2)); var appPath = options.appPath || dirname(require.main.filename); var paths = options.paths; var defaultsPath = options.defaultPath || resolve(appPath, './config/defaults.yml'); var configPath = argv.config; if (!configPath && !paths) { paths = self._getDefaultPaths(appName, appPath); } // first load defaults... // the defaults file locks the object model, so all settings must be defined here. // // anything not defined here won't be able to be set. // this forces everyone to keep the defaults file up to date, and in essence becomes // the documentation for our settings if (!fs.existsSync(defaultsPath)) { throw new Error('Default file missing. Expected path is: ' + defaultsPath); } settings = self._loadYamlFile(defaultsPath) || {}; (paths || []).forEach(function(path, i) { if (fs.existsSync(path)) { settings = mergeInto(settings, self._loadYamlFile(path)); } }); if (configPath) { settings = mergeInto(settings, self._loadYamlFile(configPath)); } Object.defineProperty(self, '_settings', {value: settings}); }
javascript
{ "resource": "" }
q43144
train
function (s) { s = Tools.trim(s); function rep(re, str) { s = s.replace(re, str); } // example: <strong> to [b] rep(/<a.*?href=\"(.*?)\".*?>(.*?)<\/a>/gi, "[url=$1]$2[/url]"); rep(/<font.*?color=\"(.*?)\".*?class=\"codeStyle\".*?>(.*?)<\/font>/gi, "[code][color=$1]$2[/color][/code]"); rep(/<font.*?color=\"(.*?)\".*?class=\"quoteStyle\".*?>(.*?)<\/font>/gi, "[quote][color=$1]$2[/color][/quote]"); rep(/<font.*?class=\"codeStyle\".*?color=\"(.*?)\".*?>(.*?)<\/font>/gi, "[code][color=$1]$2[/color][/code]"); rep(/<font.*?class=\"quoteStyle\".*?color=\"(.*?)\".*?>(.*?)<\/font>/gi, "[quote][color=$1]$2[/color][/quote]"); rep(/<span style=\"color: ?(.*?);\">(.*?)<\/span>/gi, "[color=$1]$2[/color]"); rep(/<font.*?color=\"(.*?)\".*?>(.*?)<\/font>/gi, "[color=$1]$2[/color]"); rep(/<span style=\"font-size:(.*?);\">(.*?)<\/span>/gi, "[size=$1]$2[/size]"); rep(/<font>(.*?)<\/font>/gi, "$1"); rep(/<img.*?src=\"(.*?)\".*?\/>/gi, "[img]$1[/img]"); rep(/<span class=\"codeStyle\">(.*?)<\/span>/gi, "[code]$1[/code]"); rep(/<span class=\"quoteStyle\">(.*?)<\/span>/gi, "[quote]$1[/quote]"); rep(/<strong class=\"codeStyle\">(.*?)<\/strong>/gi, "[code][b]$1[/b][/code]"); rep(/<strong class=\"quoteStyle\">(.*?)<\/strong>/gi, "[quote][b]$1[/b][/quote]"); rep(/<em class=\"codeStyle\">(.*?)<\/em>/gi, "[code][i]$1[/i][/code]"); rep(/<em class=\"quoteStyle\">(.*?)<\/em>/gi, "[quote][i]$1[/i][/quote]"); rep(/<u class=\"codeStyle\">(.*?)<\/u>/gi, "[code][u]$1[/u][/code]"); rep(/<u class=\"quoteStyle\">(.*?)<\/u>/gi, "[quote][u]$1[/u][/quote]"); rep(/<\/(strong|b)>/gi, "[/b]"); rep(/<(strong|b)>/gi, "[b]"); rep(/<\/(em|i)>/gi, "[/i]"); rep(/<(em|i)>/gi, "[i]"); rep(/<\/u>/gi, "[/u]"); rep(/<span style=\"text-decoration: ?underline;\">(.*?)<\/span>/gi, "[u]$1[/u]"); rep(/<u>/gi, "[u]"); rep(/<blockquote[^>]*>/gi, "[quote]"); rep(/<\/blockquote>/gi, "[/quote]"); rep(/<br \/>/gi, "\n"); rep(/<br\/>/gi, "\n"); rep(/<br>/gi, "\n"); rep(/<p>/gi, ""); rep(/<\/p>/gi, "\n"); rep(/&nbsp;|\u00a0/gi, " "); rep(/&quot;/gi, "\""); rep(/&lt;/gi, "<"); rep(/&gt;/gi, ">"); rep(/&amp;/gi, "&"); return s; }
javascript
{ "resource": "" }
q43145
train
function (s) { s = Tools.trim(s); function rep(re, str) { s = s.replace(re, str); } // example: [b] to <strong> rep(/\n/gi, "<br />"); rep(/\[b\]/gi, "<strong>"); rep(/\[\/b\]/gi, "</strong>"); rep(/\[i\]/gi, "<em>"); rep(/\[\/i\]/gi, "</em>"); rep(/\[u\]/gi, "<u>"); rep(/\[\/u\]/gi, "</u>"); rep(/\[url=([^\]]+)\](.*?)\[\/url\]/gi, "<a href=\"$1\">$2</a>"); rep(/\[url\](.*?)\[\/url\]/gi, "<a href=\"$1\">$1</a>"); rep(/\[img\](.*?)\[\/img\]/gi, "<img src=\"$1\" />"); rep(/\[color=(.*?)\](.*?)\[\/color\]/gi, "<font color=\"$1\">$2</font>"); rep(/\[code\](.*?)\[\/code\]/gi, "<span class=\"codeStyle\">$1</span>&nbsp;"); rep(/\[quote.*?\](.*?)\[\/quote\]/gi, "<span class=\"quoteStyle\">$1</span>&nbsp;"); return s; }
javascript
{ "resource": "" }
q43146
addSignature
train
function addSignature(key, secret, uri, body, options) { if (!_.isString(key) || !_.isString(secret)) { throw new errors.AuthenticationRequiredError("key and secret must be provided for signing requests"); } options = options || {}; // remove signature if it exists in URI object uri.removeSearch("signature"); // add api key uri.removeSearch("apikey"); uri.addQuery("apikey", key); // create a valid baseurl // consider that some users might be sitting behind a proxy var signatureBase; var baseurl = options.apiVersion === 3 ? utils.setup().baseurlv3 : utils.setup().baseurl; baseurl = trim(baseurl, "/"); var url = uri.toString(); url = trim(url.substring(0, url.indexOf("?")), "/"); if (url.search(baseurl) !== -1) { baseurl = url; } else { baseurl += "/" + uri.segment().join("/"); } signatureBase = encodeURIComponent(trim(baseurl, "/")); // append a "?" - preparing for parameter string signatureBase += "?"; // create the parameter string var params = uri.search(true); var paramsKeys = utils.sortKeys(params); var parameterString = ""; paramsKeys.forEach(function(paramKey) { if (parameterString !== "") { parameterString += "&"; } parameterString += encodeURIComponent(paramKey) + "=" + encodeURIComponent(params[paramKey]); }); // concatenating the parameter string signatureBase += parameterString; // concatenating the request body, if available if (body) { if (typeof body !== "string") { body = JSON.stringify(body); } signatureBase += encodeURIComponent(body); } // creating a hash var hmac = crypto.createHmac("sha256", secret); hmac.update(signatureBase); var hash = hmac.digest("hex"); // add hash to original uri object uri.addQuery("signature", hash); return uri; }
javascript
{ "resource": "" }
q43147
sign
train
function sign(key, secret, uri, body, options) { // add timestamp uri.addQuery("timestamp", utils.createTimestamp()); // add signature addSignature(key, secret, uri, body, options); return uri; }
javascript
{ "resource": "" }
q43148
makeLink
train
function makeLink(rel, ldo) { var i, key, keys, result; if (typeof ldo === 'string') { return '<' + ldo + '>; rel="' + rel + '"'; } result = '<' + ldo.href + '>; rel="' + rel + '"'; keys = Object.keys(ldo); for (i = 0; i < keys.length; i += 1) { key = keys[i]; if (key !== 'href' && key !== 'rel') { result += '; ' + key + '="' + ldo[key] + '"'; } } return result; }
javascript
{ "resource": "" }
q43149
newFromIdentity
train
function newFromIdentity(identity, region) { var service = identity.serviceByName('object-store', region); var endpoint = service.publicURL; var os = new ObjectStorage(identity.token(), endpoint); return os; }
javascript
{ "resource": "" }
q43150
modifyState
train
function modifyState($n) { var state = self.state; function selectByStateRecursive(name) { if (state.recursive) { return $n.find(name); } else { return $n.children(name) } } var a; var b; if (state.mode == 'code') { a = selectByStateRecursive('pre:visible'); if (a.length > 0) // a.hide(); hideShowCode(a, 'hide'); else { a = selectByStateRecursive('pre'); // a.show(); hideShowCode(a, 'show'); } } if (state.mode == 'childs') { a = selectByStateRecursive('.node:visible'); if (a.length > 0) hideShowNodes(a, 'hide'); // a.hide(); else { a = selectByStateRecursive('.node'); // a.show(); hideShowNodes(a, 'show'); } } if (state.mode == 'code childs') { a = selectByStateRecursive('.node:hidden'); b = selectByStateRecursive('pre:hidden'); if (a.length > 0 || b.length > 0) { hideShowNodes(a, 'show'); hideShowCode(b, 'show'); // a.show(); // b.show(); } else { a = selectByStateRecursive('.node'); b = selectByStateRecursive('pre'); hideShowNodes(a, 'hide'); hideShowCode(b, 'hide'); // a.hide(); // b.hide(); } } }
javascript
{ "resource": "" }
q43151
train
function (baseUrl, cardsDirectory) { var packs = _.filter(FS.readdirSync(cardsDirectory), function (dir) { return _.startsWith(dir, 'hashdo-'); }); console.log('PACKS: Cards will be loaded from %s.', cardsDirectory); var packCounter = 0, cardCounter = 0, hiddenCounter = 0; for (var i = 0; i < packs.length; i++) { var isPackage = false, packDir = Path.join(cardsDirectory, packs[i]); // Check if the directory has a package.json file, otherwise ignore it, it's not a pack. try { FS.statSync(Path.join(packDir, 'package.json')); isPackage = true; } catch (err) {} if (isPackage) { var packageJson = FS.readFileSync(Path.join(packDir, 'package.json')), packageInfo = JSON.parse(packageJson.toString()), packInfo = packageInfo.pack, packCardsDir = Path.join(cardsDirectory, packs[i]), packCards = getPackCardFiles(packCardsDir), packName = packageInfo.name.replace('hashdo-', ''); if (packInfo) { packCounter++; if (!packInfo.hidden) { cardPacks[packName] = { name: packInfo.friendlyName, cards: {} }; for (var j = 0; j < packCards.length; j++) { var card = require(Path.join(packCardsDir, packCards[j])), cardName = packCards[j]; cardCounter++; cardPacks[packName].cards[cardName] = { pack: packName, card: cardName, name: card.name, description: card.description || '', icon: card.icon || _.trimEnd(baseUrl, '/') + '/' + packName + '/' + cardName + '/icon.png', baseUrl: _.trimEnd(baseUrl, '/') + '/' + packName + '/' + cardName, inputs: card.inputs }; } } else { hiddenCounter++; } } } } console.log('PACKS: %d packs and %d card(s) have been loaded (%d hidden).', packCounter, cardCounter, hiddenCounter); }
javascript
{ "resource": "" }
q43152
train
function (filter) { if (cardCount > 0) { return cardCount; } else { cardCount = 0; if (filter) { filter = filter.toLowerCase(); _.each(_.keys(cardPacks), function (packKey) { _.each(_.keys(cardPacks[packKey].cards), function (cardKey) { var card = cardPacks[packKey].cards[cardKey]; if (Fuzzy(filter, card.name.toLowerCase())) { cardCount = cardCount + 1; } }); }); } else { _.each(_.keys(cardPacks), function (packKey) { cardCount = cardCount + _.keys(cardPacks[packKey].cards).length; }); } return cardCount; } }
javascript
{ "resource": "" }
q43153
train
function (pack, card) { if (cardPacks[pack] && cardPacks[pack].cards[card]) { return cardPacks[pack].cards[card]; } }
javascript
{ "resource": "" }
q43154
compile
train
function compile (str, options) { var id; var render; str = str || EMPTY; options = options || {}; id = options.id || str; render = eoraptor[id]; if (render) { return render; } var oTag = options.oTag || OTAG; var cTag = options.cTag || CTAG; var code = build(parse(str, oTag, cTag)); render = function (data) { var result; try { result = new Function('data', codePrefix + code)(data); } catch(err) { console.error('"' +err.message + '" from data and tpl below:'); console.log(data); console.log(str); } return result; }; render.render = render; render.source = 'function (data) {\n' + code + '\n}'; return eoraptor[id] = render; }
javascript
{ "resource": "" }
q43155
isOTag
train
function isOTag (str, oTag, index) { var l = oTag.length, s = str.substr(index, l), sign = str.charAt(index+l); // NOTE 要保证sign有值 如果当前的index已经是字符串尾部 如'foo{{' sign为空 if (oTag === s && sign && SIGN.indexOf(sign) > -1) { return { str: s + sign, index: index, // sign: signType[str.charAt(index+l)], // TODO: delete sign: str.charAt(index+l), // ignore the last oTag charts and the sign char, // l(oTag.length) - 1(oTag's first char) + 1(sign's char) jump: l }; } }
javascript
{ "resource": "" }
q43156
isCTag
train
function isCTag (str, cTag, index) { var l = cTag.length, s = str.substr(index, l); if (cTag === s) { return { str: s, index: index, type: 1, jump: l - 1 }; } }
javascript
{ "resource": "" }
q43157
isOSB
train
function isOSB (str, index) { var quote = str.charAt(index+1); if (quote === DQ || quote === SQ) { return { str: LSB + quote, index: index, quote: quote, jump: 1 }; } }
javascript
{ "resource": "" }
q43158
isCSB
train
function isCSB (str, index, quote) { if (str.charAt(index+1) === RSB) { return { str: quote + RSB, index: index, quote: quote, jump: 1 }; } }
javascript
{ "resource": "" }
q43159
ws
train
function ws(argv, callback) { if (!argv[2]) { console.error("url is required"); console.error("Usage : ws <url>"); process.exit(-1); } var uri = argv[2]; var updatesVia = 'wss://' + uri.split('/')[2] + '/'; var s; var connect = function(){ s = new wss(updatesVia, { origin: 'http://websocket.org' }); s.on('error', function() { callback('socket error'); setTimeout(connect, RECONNECT); }); s.on('open', function open() { var sub = 'sub ' + uri; callback(null, sub); s.send(sub); // periodically ping server setInterval(function() { var message = 'ping'; debug(null, message); s.send(message); }, INTERVAL); }); }; connect(); s.on('message', function message(data, flags) { callback(null, data); }); }
javascript
{ "resource": "" }
q43160
bin
train
function bin(argv) { ws(argv, function(err, res) { if (err) { console.err(err); } else { console.log(res); } }); }
javascript
{ "resource": "" }
q43161
init
train
function init() { /** * Get API key and secret. */ var auth = utils.getAuth(); /** * Set up the SDK. */ sdk.utils.setup({ key: auth.key, secret: auth.secret, }); return { out: out, sdk: sdk, }; }
javascript
{ "resource": "" }
q43162
unipath
train
function unipath(...bases) { return partial; /** * Resolve base with paths. * * @param {...string} paths - Paths to join to base * @returns {string} Resolved path */ function partial(...paths) { const baseList = bases.length ? bases : [ '.' ]; const pathList = paths.length ? paths : [ '.' ]; return path.resolve(path.join(...baseList, ...pathList)); } }
javascript
{ "resource": "" }
q43163
startHeartbeats
train
function startHeartbeats () { _isMaster = true if (_hearbeatInterval) return debug('starting heartbeats') _sendHeartbeat() _hearbeatInterval = setInterval(_sendHeartbeat, HEARTBEAT_INTERVAL) }
javascript
{ "resource": "" }
q43164
findBowerMainFiles
train
function findBowerMainFiles(componentsPath) { var files = []; fs.readdirSync(componentsPath).filter(function (file) { return fs.statSync(componentsPath + '/' + file).isDirectory(); }).forEach(function (packageName) { var bowerJsonPath = componentsPath + '/' + packageName + '/bower.json'; if (fs.existsSync(bowerJsonPath)) { var json = grunt.file.readJSON(bowerJsonPath); files.push(packageName + '/' + json.main); } }); return files; }
javascript
{ "resource": "" }
q43165
extraction
train
function extraction(o) { return _.map(o, function (spec, field) { var fn = _.extract(spec, ['mutators', direction]) || _.identity; return [field, fn]; }); }
javascript
{ "resource": "" }
q43166
cleanup
train
function cleanup(a) { return _.filter(a, function (a) { var field = a[0]; return attr[field]; }); }
javascript
{ "resource": "" }
q43167
getMutations
train
function getMutations(spec, attr) { var fns = compose(extraction, cleanup, stitch)(spec); return _.callmap(fns, attr); }
javascript
{ "resource": "" }
q43168
Connection
train
function Connection(options) { if (!(this instanceof Connection)) { return new Connection(options); } events.EventEmitter.call(this); this.options = merge(Object.create(Connection.DEFAULTS), options); this._log = new kademlia.Logger(this.options.logLevel); this._natClient = nat.createClient(); }
javascript
{ "resource": "" }
q43169
auth
train
function auth(cmd, args, info) { var pass = args[0]; if(pass instanceof Buffer) { pass = pass.toString(); } if(!info.conf.requirepass) { throw AuthNotSet; }else if(pass !== info.conf.requirepass) { throw InvalidPassword; } return true; }
javascript
{ "resource": "" }
q43170
equals
train
function equals(value1, value2, traversedValues) { if (!(value1 instanceof Object)) { return value1 === value2 } for (let wrappedType of WRAPPED_TYPES) { if (value1 instanceof wrappedType) { return (value2 instanceof wrappedType) && (value1.valueOf() === value2.valueOf()) } } if (value1 instanceof RegExp) { return (value2 instanceof RegExp) && (value1.source === value2.source) && (value2.flags === value2.flags) } for (let uninspectableType of UNINSPECTABLE_TYPES) { if (value1 instanceof uninspectableType) { return (value2 instanceof uninspectableType) && (value1 === value2) } } if ((typeof ArrayBuffer === "function") && (value1 instanceof ArrayBuffer)) { return (value2 instanceof ArrayBuffer) && equals(new Int8Array(value1), new Int8Array(value2), traversedValues) } if ((typeof DataView === "function") && (value1 instanceof DataView)) { return (value2 instanceof DataView) && equals( new Int8Array(value1.buffer, value1.byteOffset, value1.byteLength), new Int8Array(value2.buffer, value2.byteOffset, value2.byteLength), traversedValues ) } for (let arrayType of TYPED_ARRAY_TYPES) { if (value1 instanceof arrayType) { return (value2 instanceof arrayType) && arrayEquals(value1, value2, traversedValues) } } if ((typeof ImageData === "function") && (value1 instanceof ImageData)) { return (value2 instanceof ImageData) && (value1.width === value2.width) && (value1.height === value2.height) && equals(value1.data, value2.data, traversedValues) } if (value1 instanceof Array) { return (value2 instanceof Array) && arrayEquals(value1, value2, traversedValues) } if (value1 instanceof Map) { return mapEquals(value1, value2, traversedValues) } if (value1 instanceof Set) { return setEquals(value1, value2, traversedValues) } if (isPlainObjectOrEntity(value1) && isPlainObjectOrEntity(value2)) { return objectEquals(value1, value2, traversedValues) } throw new Error(`Unsupported argument types: ${value1}, ${value2}`) }
javascript
{ "resource": "" }
q43171
objectEquals
train
function objectEquals(object1, object2, traversedValues) { let keys1 = Object.keys(object1) let keys2 = Object.keys(object2) return structureEquals( object1, object2, keys1, keys2, (object, key) => object[key], traversedValues ) }
javascript
{ "resource": "" }
q43172
setEquals
train
function setEquals(set1, set2, traversedValues) { if (set1.size !== set2.size) { return false } return structureEquals( set1, set2, iteratorToArray(set1.values()), iteratorToArray(set2.values()), () => undefined, traversedValues ) }
javascript
{ "resource": "" }
q43173
mapEquals
train
function mapEquals(map1, map2, traversedValues) { if (map1.size !== map2.size) { return false } return structureEquals( map1, map2, iteratorToArray(map1.keys()), iteratorToArray(map2.keys()), (map, key) => map.get(key), traversedValues ) }
javascript
{ "resource": "" }
q43174
arrayEquals
train
function arrayEquals(array1, array2, traversedValues) { if (array1.length !== array2.length) { return false } return structureEquals( array1, array2, iteratorToArray(array1.keys()), iteratorToArray(array2.keys()), (array, key) => array[key], traversedValues ) }
javascript
{ "resource": "" }
q43175
structureEquals
train
function structureEquals(structure1, structure2, keys1, keys2, getter, traversedValues) { if (keys1.length !== keys2.length) { return false } traversedValues.set(structure1, structure2) for (let i = keys1.length; i--;) { let key1 = keys1[i] let key2 = keys2[i] if ((key1 instanceof Object) && traversedValues.has(key1)) { if (traversedValues.get(key1) !== key2) { return false } else { continue } } if (!equals(key1, key2, traversedValues)) { return false } if (key1 instanceof Object) { traversedValues.set(key1, key2) } let value1 = getter(structure1, key1) let value2 = getter(structure2, key2) if ((value1 instanceof Object) && traversedValues.has(value1)) { if (traversedValues.get(value1) !== value2) { return false } else { continue } } if (!equals(value1, value2, traversedValues)) { return false } if (value1 instanceof Object) { traversedValues.set(value1, value2) } } return true }
javascript
{ "resource": "" }
q43176
iteratorToArray
train
function iteratorToArray(iterator) { let elements = [] for (let element of iterator) { elements.push(element) } return elements }
javascript
{ "resource": "" }
q43177
jsonDescription
train
function jsonDescription(format, description) { switch (format) { case 'application/openapi+json': if (typeof description == object) { return description; } else { throw new Error(`application/openapi+json description ${description} is not an object`); } case 'application/openapi+yaml': return yaml.safeLoad(description); default: throw new Error(`Unknown format: ${format} for ${description}`); } }
javascript
{ "resource": "" }
q43178
well
train
function well(promiseOrValue, onFulfilled, onRejected, onProgress) { // Get a trusted promise for the input promiseOrValue, and then // register promise handlers return resolve(promiseOrValue).then(onFulfilled, onRejected, onProgress); }
javascript
{ "resource": "" }
q43179
chain
train
function chain(promiseOrValue, resolver, resolveValue) { var useResolveValue = arguments.length > 2; return well(promiseOrValue, function (val) { val = useResolveValue ? resolveValue : val; resolver.resolve(val); return val; }, function (reason) { resolver.reject(reason); return rejected(reason); }, function (update) { typeof resolver.notify === 'function' && resolver.notify(update); return update; } ); }
javascript
{ "resource": "" }
q43180
processQueue
train
function processQueue(queue, value) { if (!queue || queue.length === 0) return; var handler, i = 0; while (handler = queue[i++]) { handler(value); } }
javascript
{ "resource": "" }
q43181
checkCallbacks
train
function checkCallbacks(start, arrayOfCallbacks) { // TODO: Promises/A+ update type checking and docs var arg, i = arrayOfCallbacks.length; while (i > start) { arg = arrayOfCallbacks[--i]; if (arg != null && typeof arg != 'function') { throw new Error('arg ' + i + ' must be a function'); } } }
javascript
{ "resource": "" }
q43182
git
train
function git(cb) { which('git', function(err, data){ if (err) return cb(err, data); child.exec('git rev-parse HEAD', cb); }); }
javascript
{ "resource": "" }
q43183
combineClassNames
train
function combineClassNames(...classNames) { return classNames.map((value) => { if (!value) { return value; } return Array.isArray(value) ? combineClassNames.apply(void 0, value) : value; }).join(` `).replace(/ +/g, ` `).trim(); }
javascript
{ "resource": "" }
q43184
initAuth
train
function initAuth (req, res, next) { const params = { session: false, state: state.serialize(req), scope: req.authProvider.scope }; // noinspection JSUnresolvedFunction passport.authenticate( req.params.provider, params )(req, res, next); }
javascript
{ "resource": "" }
q43185
train
function(filename) { var filepath = options.cwd + filename; var template = readTemplateFile({ src: [ filepath ] }); return grunt.template.process(template, options); }
javascript
{ "resource": "" }
q43186
train
function(key) { var translation = options.translations[key]; if (!translation) { grunt.fail.warn('No translation found for key:', key); } return translation; }
javascript
{ "resource": "" }
q43187
train
function(options) { var recurse = function(options) { _.each(options, function(value, key) { if (_.isFunction(value)) { options[key] = value(); } else if (_.isObject(value)) { options[key] = recurse(value); } }); return options; }; return recurse(options); }
javascript
{ "resource": "" }
q43188
qG
train
function qG(options) { var defer = q.defer(); var compiledData = []; // Recursive call to paginate function qGCall(pageLink) { var methodCall; // Callback function callback(error, data) { if (error) { defer.reject(new Error(error)); } else { compiledData = compiledData.concat(data); if (github.hasNextPage(data)) { qGCall(data); } else { defer.resolve(compiledData); } } } // If the call is a link to another page, use that. if (pageLink) { method = github.getNextPage(pageLink, callback); } else { githubAuth()[options.obj][options.method](options, callback); } } qGCall(); return defer.promise; }
javascript
{ "resource": "" }
q43189
getObjects
train
function getObjects(user) { var username = (_.isObject(user)) ? user.login : user; var isOrg = (_.isObject(user) && user.type === 'Organization'); var defers = []; // Get repos defers.push(qG({ obj: 'repos', method: 'getFromUser', user: username, sort: 'created', per_page: 100 })); // Get gists defers.push(qG({ obj: 'gists', method: 'getFromUser', user: username, sort: 'created', per_page: 100 })); // Get members (for orgs) if (isOrg) { defers.push(qG({ obj: 'orgs', method: 'getMembers', org: username, per_page: 100 })); } return q.all(defers); }
javascript
{ "resource": "" }
q43190
get
train
function get(usernames, options) { usernames = usernames || ''; usernames = (_.isArray(usernames)) ? usernames : usernames.split(','); options = options || {}; var defers = []; var collection = {}; _.each(usernames, function(u) { var defer = q.defer(); u = u.toLowerCase(); if (u.length === 0) { return; } qG({ obj: 'user', method: 'getFrom', user: u }) .done(function(data) { collection[u] = data[0]; // Get objects for the specific user getObjects(data[0]).done(function(objData) { collection[u].objects = collection[u].objects || {}; collection[u].objects.repos = objData[0]; collection[u].objects.gists = objData[1]; collection[u].objects.members = objData[2]; defer.resolve(collection[u]); }); }); defers.push(defer.promise); }); return q.all(defers).then(function() { return collection; }); }
javascript
{ "resource": "" }
q43191
Poller
train
function Poller(getRequest, options) { options = options || { }; events.EventEmitter.call(this); this._pollerOptions = utils.getPollerOptions([utils.setup().poller, options]); this._get = getRequest; this._params = options.params || { }; this._lastreadId = this._params.lastreadId || null; this._timer = null; this._requestPending = false; this._paused = false; return this; }
javascript
{ "resource": "" }
q43192
train
function (array) { var self = this, deferred = new Deferred(), fulfilled = 0, length, results = [], hasError = false; if (!isArray(array)) { array = slice.call(arguments); } length = array.length; if (length === 0) { deferred.emitSuccess(results); } else { array.forEach(function (promise, index) { self.when(promise, //Success function (value) { results[index] = value; fulfilled += 1; if (fulfilled === length) { if (hasError) { deferred.emitError(results); } else { deferred.emitSuccess(results); } } }, //Error function (error) { results[index] = error; hasError = true; fulfilled += 1; if (fulfilled === length) { deferred.emitError(results); } } ); }); } return deferred.getPromise(); }
javascript
{ "resource": "" }
q43193
train
function (array) { var self = this, deferred = new Deferred(), fulfilled = false, index, length, onSuccess = function (value) { if (!fulfilled) { fulfilled = true; deferred.emitSuccess(value); } }, onError = function (error) { if (!fulfilled) { fulfilled = true; deferred.emitSuccess(error); } }; if (!isArray(array)) { array = slice.call(arguments); } for (index = 0, length = array.length; index < length; index += 1) { this.when(array[index], onSuccess, onError); } return deferred.getPromise(); }
javascript
{ "resource": "" }
q43194
train
function (value) { var nextAction = array.shift(); if (nextAction) { self.when(nextAction(value), next, deferred.reject); } else { deferred.emitSuccess(value); } }
javascript
{ "resource": "" }
q43195
train
function (milliseconds) { var deferred, timer = setTimeout(function () { deferred.emitSuccess(); }, milliseconds), canceller = function () { clearTimeout(timer); }; deferred = new Deferred(canceller); return deferred.getPromise(); }
javascript
{ "resource": "" }
q43196
train
function (resolvedCallback, errorCallback, progressCallback) { var returnDeferred = new Deferred(this._canceller), //new Deferred(this.getPromise().cancel) listener = { resolved : resolvedCallback, error : errorCallback, progress : progressCallback, deferred : returnDeferred }; if (this.finished) { this._notify(listener); } else { this.waiting.push(listener); } return returnDeferred.getPromise(); }
javascript
{ "resource": "" }
q43197
train
function (error, dontThrow) { var self = this; self.isError = true; self._notifyAll(error); if (!dontThrow) { enqueue(function () { if (!self.handled) { throw error; } }); } return self.handled; }
javascript
{ "resource": "" }
q43198
train
function (update) { var waiting = this.waiting, length = waiting.length, index, progress; for (index = 0; index < length; index += 1) { progress = waiting[index].progress; if (progress) { progress(update); } } return this; }
javascript
{ "resource": "" }
q43199
train
function () { if (!this.finished && this._canceller) { var error = this._canceller(); if (!(error instanceof Error)) { error = new Error(error); } return this.emitError(error); } return false; }
javascript
{ "resource": "" }