_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q14300
determineWMSAbstract
train
function determineWMSAbstract(json, version) { var ret = ''; if (version == '1.3.0') { if (json.WMS_Capabilities.Service) { if (json.WMS_Capabilities.Service[0]) { if (json.WMS_Capabilities.Service[0].Abstract) { if (json.WMS_Capabilities.Service[0].Abstract[0]) { ret = json.WMS_Capabilities.Service[0].Abstract[0]; } } } } } else { if (version == '1.1.1' || version == '1.1.0' || version == '1.0.0') { if (json.WMT_MS_Capabilities.Service) { if (json.WMT_MS_Capabilities.Service[0]) { if (json.WMT_MS_Capabilities.Service[0].Abstract) { if (json.WMT_MS_Capabilities.Service[0].Abstract[0]) { ret = json.WMT_MS_Capabilities.Service[0].Abstract[0]; } } } } } } return ret; }
javascript
{ "resource": "" }
q14301
Client
train
function Client(host, port, path, service, transport, protocol) { if (!service.hasOwnProperty('Client')) { throw new Error('Thrift Service must have a Client'); } /** * The host of the thrift server * * @type {string} */ this.host = host; /** * The port of the thrift server * * @type {Number} */ this.port = port; /** * The path for the thrift server * * @type {string} */ this.path = path; /** * Whether or not to autoClose connection * * @type {boolean} */ this.autoClose = true; /** * The thrift service * * @type {Object} */ this.service = service; /** * The thrift transport * * @type {*|TBufferedTransport} */ this.transport = transport || thrift.TBufferedTransport; /** * The thrift protocol * * @type {*|exports.TBinaryProtocol} */ this.protocol = protocol || thrift.TBinaryProtocol; /** * The Thrift Service Client * @type {Client} */ this.client = new service.Client; /** * The Thrift Client Connection * * @type {*} * @private */ this._connection = null; /** * The Thrift Client * * @type {null} * @private */ this._client = null; /** * Whether or not we are connected to thrift * * @type {boolean} */ this.isConnected = false; /** * A Success Pre-parser Callback * @param {*} data * @param {Function} Success Callback * @param {Function} Error Callback * @type {Function|null} */ this.successCallback = null; /** * A Error Pre-parser Callback * @param {*} data * @param {Function} Error Callback * @type {Function|null} */ this.errorCallback = null; }
javascript
{ "resource": "" }
q14302
createChunk
train
function createChunk(type, data) { const length = typeof data != 'undefined' ? data.length : 0; const chunk = Buffer.alloc(4 + 4 + length + 4); chunk.writeUInt32BE(length, 0); chunk.fill(type, 4, 8, 'utf8'); if (typeof data != 'undefined') { chunk.fill(data, 8, chunk.length - 4); } chunk.writeUInt32BE(crc32(chunk.slice(4, -4)), chunk.length - 4); return chunk; }
javascript
{ "resource": "" }
q14303
train
function ( n, buffer, bytes ) { var s = ( n % k ) * slen // how many bytes to read/consume from the input buffer [1 to 4] , rbytes = bytes >>> 0 ? abs( bytes ) % 5 : ibytes , blen = buffer.length - rbytes , bruint = null , sum = 0 , b = 0 ; /* * NOTE: js is not capable to handle integers larger than ~2^53, * when the sum exceeds this limit, we expect to get get biased * results, or in other words, more collisions. It will happens * when we are using large primes as range, or with long buffer * in input. If sum === sum + 1, we could break the for cycle. */ if ( rbytes === 1 ) { // use [] notation when reading input, 1 byte at the time. if ( ibytes === 1 ) { // read input and seed 1 byte at the time for ( ; b <= blen && s <= rlen; ++b, ++s ) sum += buffer[ b ] * result[ s ]; return sum % prange; } for ( ; b <= blen && s <= rlen; ++b, s += ibytes ) sum += buffer[ b ] * result[ ruint ]( s ); return sum % prange; } // build string for read method (16, 24 or 32 bits unsigned integers) bruint = bruint = 'readUInt' + ( rbytes << 3 ) + 'BE'; for ( ; b <= blen && s <= rlen; b += rbytes, s += ibytes ) { sum += buffer[ bruint ]( b ) * result[ ruint ]( s ); sum %= prange; } return sum; }
javascript
{ "resource": "" }
q14304
promiseMiddleware
train
function promiseMiddleware (request, response, middleware) { return new promiseMiddleware.Promise(function (resolve, reject) { middleware(request, response, function next (error) { return error ? reject(error) : resolve() }) }) }
javascript
{ "resource": "" }
q14305
paddLeft
train
function paddLeft(str, length, what) { if (length <= str.length) { return str.substring(0, length); } what = what || ' '; return what.repeat(length - str.length) + str; }
javascript
{ "resource": "" }
q14306
paddRight
train
function paddRight(str, length, what) { if (length <= str.length) { return str.substring(0, length); } what = what || ' '; return str + what.repeat(length - str.length); }
javascript
{ "resource": "" }
q14307
precBase
train
function precBase(base, value, precision) { const val = value.toString(base); const floatingPoint = val.indexOf('.'); if (precision === 0 && floatingPoint > -1) { return val.substring(0, floatingPoint);//Node version > 0.10.* } if (floatingPoint === -1) { return val; } if (val.length - floatingPoint > precision) { return val.substring(0, floatingPoint + precision + 1); } }
javascript
{ "resource": "" }
q14308
ParserContent
train
function ParserContent () { // Parser reference var self = this // Current row var data = [] // Define the parser rules var eol = ['\n','\r\n'] var sep = options.separator || ',' // Handlers are used instead of events atok // Ignore comments .ignore(true) // On rule match, do not do anything, skip the token .addRule('#', eol, 'comment') .ignore() // Turn the ignore property off // Anything else is data // Rule definition: // first argument: always an exact match. To match anything, use '' // next arguments: array of possible matches (first match wins) .addRule('', { firstOf: [ sep ].concat(eol) }, function (token, idx) { // token=the matched data // idx=when using array of patterns, the index of the matched pattern if (token === 'error') { // Build the error message using positioning var err = self.trackError(new Error('Dummy message'), token) self.emit('error', err) return } // Add the data data.push(token) // EOL reached, the parser emits the row if (idx > 0) { self.emit('data', data) data = [] } }) }
javascript
{ "resource": "" }
q14309
_sessionData
train
function _sessionData(variable, value, parameter) { if (this.session === undefined) throw Error('req.sessionData() requires sessions'); var values = this.session.sessionData = this.session.sessionData || {}; if (variable && value) { // Special handling for configuration if (parameter=='setup') { delete values[variable]; } // Special handling for breadcrumb if (variable == 'breadcrumb') { // Do not Add the same Last Url (in case of refresh if (value=='back') { // console.log('%s values[variable].length',srcName,values[variable].length) if (values[variable].length < 2 ) { return values[variable][0] } else { values[variable].pop(); return values[variable].pop(); } } else { if (values[variable] && (values[variable][values[variable].length-1] == value)){ return; } } } // util.format is available in Node.js 0.6+ if (arguments.length > 2 && format && parameter != 'setup' && parameter != 'read') { var args = Array.prototype.slice.call(arguments, 1); value = format.apply(undefined, args); } else if (isArray(value)) { value.forEach(function(val){ (values[variable] = values[variable] || []).push(val); }); return values[variable].length; } return (values[variable] = values[variable] || []).push(value); } else if (variable) { var arr = values[variable]; if ((variable != 'breadcrumb') && (parameter != 'read')){ delete values[variable]; } return arr || []; } else { this.session._sessionData = {}; return values; } }
javascript
{ "resource": "" }
q14310
train
function (server) { // Retrieve the configured handler. if (handler) { handler = require(require('path').resolve() + '/' + handler); } else { console.log('No handler defined for websocket server, not starting websocket.'); return; } // Attach websockets server to http server var WebSocketServer = require('websocket').server; var wsServer = new WebSocketServer({ httpServer: server }); // Handle requests wsServer.on('request', handler); }
javascript
{ "resource": "" }
q14311
transform
train
function transform() { var stack = []; var inside = false; var out = false; var writable = combiner(split(), through2(function(line, encoding, done) { line = line.toString(); if(out) { // Comment with a white space below are ignored if(line.trim() != '') { readable.write(parser(stack.join('\n'), line)) } out = false; stack = []; } else if(!inside) { if(/\s*\/\*\*/.test(line)) { stack = []; inside = true; } } else if(inside) { if(/\*\/\s*$/.test(line)) { inside = false out = true } else { stack.push(line.replace(/^\s*\*{1,2}\s?/,'')); } } done(); }, function(done) { // readable.write(null) readable.emit('end') done(); })) var readable = through2.obj(); return duplexer(writable, readable) }
javascript
{ "resource": "" }
q14312
TaskClauseFormatter
train
function TaskClauseFormatter(o) { var params=[]; if (!o.nodefaultparam) { params.push('p'); } var expects='',locals=[];//$unused=this'; if (o.expects && o.as) fail("SAI compile: cannot have both EXPECTS and AS in a function declaration"); if (o.expects && o.expects.length) { expects=GetExpectsTester(o.expects,'in-line'); } else if (o.as) { for (var i in o.as) { if (i==0) { locals.push(o.as[i][0][1]+'='+params[0]); } else { params.push(o.as[i][0][1]); } } } if (!o.preface) o.preface=''; if (!o.postface) o.postface=''; var finallocals=[]; for (var i in locals) if (!References[locals[i]]) finallocals.push(locals[i]); locals=locals.length?('var '+finallocals.join(',')+';'):''; var code = o.kind+'('+params.join(',')+'){'+o.preface+locals+expects+'{'+o.block+'}'+o.postface+'}'; if (o.execute) code+='()'; return code; }
javascript
{ "resource": "" }
q14313
handleFieldValidated
train
function handleFieldValidated( isValid, msg ) { var input = this.getInputElement(); if ( input ) isValid ? input.removeAttribute( 'aria-invalid' ) : input.setAttribute( 'aria-invalid', true ); if ( !isValid ) { if ( this.select ) this.select(); else this.focus(); } msg && alert( msg ); this.fire( 'validated', { valid: isValid, msg: msg } ); }
javascript
{ "resource": "" }
q14314
train
function( func ) { var contents = me._.contents, stop = false; for ( var i in contents ) { for ( var j in contents[ i ] ) { stop = func.call( this, contents[ i ][ j ] ); if ( stop ) return; } } }
javascript
{ "resource": "" }
q14315
setupFocus
train
function setupFocus() { var focusList = me._.focusList; focusList.sort( function( a, b ) { // Mimics browser tab order logics; if ( a.tabIndex != b.tabIndex ) return b.tabIndex - a.tabIndex; // Sort is not stable in some browsers, // fall-back the comparator to 'focusIndex'; else return a.focusIndex - b.focusIndex; } ); var size = focusList.length; for ( var i = 0; i < size; i++ ) focusList[ i ].focusIndex = i; }
javascript
{ "resource": "" }
q14316
Focusable
train
function Focusable( dialog, element, index ) { this.element = element; this.focusIndex = index; // TODO: support tabIndex for focusables. this.tabIndex = 0; this.isFocusable = function() { return !element.getAttribute( 'disabled' ) && element.isVisible(); }; this.focus = function() { dialog._.currentFocusIndex = this.focusIndex; this.element.focus(); }; // Bind events element.on( 'keydown', function( e ) { if ( e.data.getKeystroke() in { 32: 1, 13: 1 } ) this.fire( 'click' ); } ); element.on( 'focus', function() { this.fire( 'mouseover' ); } ); element.on( 'blur', function() { this.fire( 'mouseout' ); } ); }
javascript
{ "resource": "" }
q14317
resizeWithWindow
train
function resizeWithWindow( dialog ) { var win = CKEDITOR.document.getWindow(); function resizeHandler() { dialog.layout(); } win.on( 'resize', resizeHandler ); dialog.on( 'hide', function() { win.removeListener( 'resize', resizeHandler ); } ); }
javascript
{ "resource": "" }
q14318
train
function() { var element = this._.element.getFirst(); return { width: element.$.offsetWidth || 0, height: element.$.offsetHeight || 0 }; }
javascript
{ "resource": "" }
q14319
train
function() { var el = this.parts.dialog; var dialogSize = this.getSize(); var win = CKEDITOR.document.getWindow(), viewSize = win.getViewPaneSize(); var posX = ( viewSize.width - dialogSize.width ) / 2, posY = ( viewSize.height - dialogSize.height ) / 2; // Switch to absolute position when viewport is smaller than dialog size. if ( !CKEDITOR.env.ie6Compat ) { if ( dialogSize.height + ( posY > 0 ? posY : 0 ) > viewSize.height || dialogSize.width + ( posX > 0 ? posX : 0 ) > viewSize.width ) el.setStyle( 'position', 'absolute' ); else el.setStyle( 'position', 'fixed' ); } this.move( this._.moved ? this._.position.x : posX, this._.moved ? this._.position.y : posY ); }
javascript
{ "resource": "" }
q14320
train
function( fn ) { for ( var i in this._.contents ) { for ( var j in this._.contents[ i ] ) fn.call( this, this._.contents[ i ][ j ] ); } return this; }
javascript
{ "resource": "" }
q14321
train
function() { if ( !this.parts.dialog.isVisible() ) return; this.fire( 'hide', {} ); this._.editor.fire( 'dialogHide', this ); // Reset the tab page. this.selectPage( this._.tabIdList[ 0 ] ); var element = this._.element; element.setStyle( 'display', 'none' ); this.parts.dialog.setStyle( 'visibility', 'hidden' ); // Unregister all access keys associated with this dialog. unregisterAccessKey( this ); // Close any child(top) dialogs first. while ( CKEDITOR.dialog._.currentTop != this ) CKEDITOR.dialog._.currentTop.hide(); // Maintain dialog ordering and remove cover if needed. if ( !this._.parentDialog ) hideCover( this._.editor ); else { var parentElement = this._.parentDialog.getElement().getFirst(); parentElement.setStyle( 'z-index', parseInt( parentElement.$.style.zIndex, 10 ) + Math.floor( this._.editor.config.baseFloatZIndex / 2 ) ); } CKEDITOR.dialog._.currentTop = this._.parentDialog; // Deduct or clear the z-index. if ( !this._.parentDialog ) { CKEDITOR.dialog._.currentZIndex = null; // Remove access key handlers. element.removeListener( 'keydown', accessKeyDownHandler ); element.removeListener( 'keyup', accessKeyUpHandler ); var editor = this._.editor; editor.focus(); // Give a while before unlock, waiting for focus to return to the editable. (#172) setTimeout( function() { editor.focusManager.unlock(); // Fixed iOS focus issue (#12381). // Keep in mind that editor.focus() does not work in this case. if ( CKEDITOR.env.iOS ) { editor.window.focus(); } }, 0 ); } else CKEDITOR.dialog._.currentZIndex -= 10; delete this._.parentDialog; // Reset the initial values of the dialog. this.foreach( function( contentObj ) { contentObj.resetInitValue && contentObj.resetInitValue(); } ); }
javascript
{ "resource": "" }
q14322
train
function( id ) { if ( this._.currentTabId == id ) return; if ( this._.tabs[ id ][ 0 ].hasClass( 'cke_dialog_tab_disabled' ) ) return; // If event was canceled - do nothing. if ( this.fire( 'selectPage', { page: id, currentPage: this._.currentTabId } ) === false ) return; // Hide the non-selected tabs and pages. for ( var i in this._.tabs ) { var tab = this._.tabs[ i ][ 0 ], page = this._.tabs[ i ][ 1 ]; if ( i != id ) { tab.removeClass( 'cke_dialog_tab_selected' ); page.hide(); } page.setAttribute( 'aria-hidden', i != id ); } var selected = this._.tabs[ id ]; selected[ 0 ].addClass( 'cke_dialog_tab_selected' ); // [IE] an invisible input[type='text'] will enlarge it's width // if it's value is long when it shows, so we clear it's value // before it shows and then recover it (#5649) if ( CKEDITOR.env.ie6Compat || CKEDITOR.env.ie7Compat ) { clearOrRecoverTextInputValue( selected[ 1 ] ); selected[ 1 ].show(); setTimeout( function() { clearOrRecoverTextInputValue( selected[ 1 ], 1 ); }, 0 ); } else selected[ 1 ].show(); this._.currentTabId = id; this._.currentTabIndex = CKEDITOR.tools.indexOf( this._.tabIdList, id ); }
javascript
{ "resource": "" }
q14323
train
function( id ) { var tab = this._.tabs[ id ] && this._.tabs[ id ][ 0 ]; if ( !tab || this._.pageCount == 1 || !tab.isVisible() ) return; // Switch to other tab first when we're hiding the active tab. else if ( id == this._.currentTabId ) this.selectPage( getPreviousVisibleTab.call( this ) ); tab.hide(); this._.pageCount--; this.updateStyle(); }
javascript
{ "resource": "" }
q14324
train
function( id ) { var tab = this._.tabs[ id ] && this._.tabs[ id ][ 0 ]; if ( !tab ) return; tab.show(); this._.pageCount++; this.updateStyle(); }
javascript
{ "resource": "" }
q14325
train
function( element, index ) { if ( typeof index == 'undefined' ) { index = this._.focusList.length; this._.focusList.push( new Focusable( this, element, index ) ); } else { this._.focusList.splice( index, 0, new Focusable( this, element, index ) ); for ( var i = index + 1; i < this._.focusList.length; i++ ) this._.focusList[ i ].focusIndex++; } }
javascript
{ "resource": "" }
q14326
train
function( name, dialogDefinition ) { // Avoid path registration from multiple instances override definition. if ( !this._.dialogDefinitions[ name ] || typeof dialogDefinition == 'function' ) this._.dialogDefinitions[ name ] = dialogDefinition; }
javascript
{ "resource": "" }
q14327
train
function( array, id, recurse ) { for ( var i = 0, item; ( item = array[ i ] ); i++ ) { if ( item.id == id ) return item; if ( recurse && item[ recurse ] ) { var retval = getById( item[ recurse ], id, recurse ); if ( retval ) return retval; } } return null; }
javascript
{ "resource": "" }
q14328
train
function( array, newItem, nextSiblingId, recurse, nullIfNotFound ) { if ( nextSiblingId ) { for ( var i = 0, item; ( item = array[ i ] ); i++ ) { if ( item.id == nextSiblingId ) { array.splice( i, 0, newItem ); return newItem; } if ( recurse && item[ recurse ] ) { var retval = addById( item[ recurse ], newItem, nextSiblingId, recurse, true ); if ( retval ) return retval; } } if ( nullIfNotFound ) return null; } array.push( newItem ); return newItem; }
javascript
{ "resource": "" }
q14329
train
function( array, id, recurse ) { for ( var i = 0, item; ( item = array[ i ] ); i++ ) { if ( item.id == id ) return array.splice( i, 1 ); if ( recurse && item[ recurse ] ) { var retval = removeById( item[ recurse ], id, recurse ); if ( retval ) return retval; } } return null; }
javascript
{ "resource": "" }
q14330
train
function( dialog, dialogDefinition ) { // TODO : Check if needed. this.dialog = dialog; // Transform the contents entries in contentObjects. var contents = dialogDefinition.contents; for ( var i = 0, content; ( content = contents[ i ] ); i++ ) contents[ i ] = content && new contentObject( dialog, content ); CKEDITOR.tools.extend( this, dialogDefinition ); }
javascript
{ "resource": "" }
q14331
contentObject
train
function contentObject( dialog, contentDefinition ) { this._ = { dialog: dialog }; CKEDITOR.tools.extend( this, contentDefinition ); }
javascript
{ "resource": "" }
q14332
train
function( dialog, childObjList, childHtmlList, htmlList, elementDefinition ) { if ( arguments.length < 4 ) return; this._ || ( this._ = {} ); var children = this._.children = childObjList, widths = elementDefinition && elementDefinition.widths || null, height = elementDefinition && elementDefinition.height || null, styles = {}, i; /** @ignore */ var innerHTML = function() { var html = [ '<tbody><tr class="cke_dialog_ui_hbox">' ]; for ( i = 0; i < childHtmlList.length; i++ ) { var className = 'cke_dialog_ui_hbox_child', styles = []; if ( i === 0 ) className = 'cke_dialog_ui_hbox_first'; if ( i == childHtmlList.length - 1 ) className = 'cke_dialog_ui_hbox_last'; html.push( '<td class="', className, '" role="presentation" ' ); if ( widths ) { if ( widths[ i ] ) styles.push( 'width:' + cssLength( widths[ i ] ) ); } else styles.push( 'width:' + Math.floor( 100 / childHtmlList.length ) + '%' ); if ( height ) styles.push( 'height:' + cssLength( height ) ); if ( elementDefinition && elementDefinition.padding != undefined ) styles.push( 'padding:' + cssLength( elementDefinition.padding ) ); // In IE Quirks alignment has to be done on table cells. (#7324) if ( CKEDITOR.env.ie && CKEDITOR.env.quirks && children[ i ].align ) styles.push( 'text-align:' + children[ i ].align ); if ( styles.length > 0 ) html.push( 'style="' + styles.join( '; ' ) + '" ' ); html.push( '>', childHtmlList[ i ], '</td>' ); } html.push( '</tr></tbody>' ); return html.join( '' ); }; var attribs = { role: 'presentation' }; elementDefinition && elementDefinition.align && ( attribs.align = elementDefinition.align ); CKEDITOR.ui.dialog.uiElement.call( this, dialog, elementDefinition || { type: 'hbox' }, htmlList, 'table', styles, attribs, innerHTML ); }
javascript
{ "resource": "" }
q14333
train
function( dialog, childObjList, childHtmlList, htmlList, elementDefinition ) { if ( arguments.length < 3 ) return; this._ || ( this._ = {} ); var children = this._.children = childObjList, width = elementDefinition && elementDefinition.width || null, heights = elementDefinition && elementDefinition.heights || null; /** @ignore */ var innerHTML = function() { var html = [ '<table role="presentation" cellspacing="0" border="0" ' ]; html.push( 'style="' ); if ( elementDefinition && elementDefinition.expand ) html.push( 'height:100%;' ); html.push( 'width:' + cssLength( width || '100%' ), ';' ); // (#10123) Temp fix for dialog broken layout in latest webkit. if ( CKEDITOR.env.webkit ) html.push( 'float:none;' ); html.push( '"' ); html.push( 'align="', CKEDITOR.tools.htmlEncode( ( elementDefinition && elementDefinition.align ) || ( dialog.getParentEditor().lang.dir == 'ltr' ? 'left' : 'right' ) ), '" ' ); html.push( '><tbody>' ); for ( var i = 0; i < childHtmlList.length; i++ ) { var styles = []; html.push( '<tr><td role="presentation" ' ); if ( width ) styles.push( 'width:' + cssLength( width || '100%' ) ); if ( heights ) styles.push( 'height:' + cssLength( heights[ i ] ) ); else if ( elementDefinition && elementDefinition.expand ) styles.push( 'height:' + Math.floor( 100 / childHtmlList.length ) + '%' ); if ( elementDefinition && elementDefinition.padding != undefined ) styles.push( 'padding:' + cssLength( elementDefinition.padding ) ); // In IE Quirks alignment has to be done on table cells. (#7324) if ( CKEDITOR.env.ie && CKEDITOR.env.quirks && children[ i ].align ) styles.push( 'text-align:' + children[ i ].align ); if ( styles.length > 0 ) html.push( 'style="', styles.join( '; ' ), '" ' ); html.push( ' class="cke_dialog_ui_vbox_child">', childHtmlList[ i ], '</td></tr>' ); } html.push( '</tbody></table>' ); return html.join( '' ); }; CKEDITOR.ui.dialog.uiElement.call( this, dialog, elementDefinition || { type: 'vbox' }, htmlList, 'div', null, { role: 'presentation' }, innerHTML ); }
javascript
{ "resource": "" }
q14334
train
function( indices ) { // If no arguments, return a clone of the children array. if ( arguments.length < 1 ) return this._.children.concat(); // If indices isn't array, make it one. if ( !indices.splice ) indices = [ indices ]; // Retrieve the child element according to tree position. if ( indices.length < 2 ) return this._.children[ indices[ 0 ] ]; else return ( this._.children[ indices[ 0 ] ] && this._.children[ indices[ 0 ] ].getChild ) ? this._.children[ indices[ 0 ] ].getChild( indices.slice( 1, indices.length ) ) : null; }
javascript
{ "resource": "" }
q14335
train
function( dialogName, callback ) { var dialog = null, dialogDefinitions = CKEDITOR.dialog._.dialogDefinitions[ dialogName ]; if ( CKEDITOR.dialog._.currentTop === null ) showCover( this ); // If the dialogDefinition is already loaded, open it immediately. if ( typeof dialogDefinitions == 'function' ) { var storedDialogs = this._.storedDialogs || ( this._.storedDialogs = {} ); dialog = storedDialogs[ dialogName ] || ( storedDialogs[ dialogName ] = new CKEDITOR.dialog( this, dialogName ) ); callback && callback.call( dialog, dialog ); dialog.show(); } else if ( dialogDefinitions == 'failed' ) { hideCover( this ); throw new Error( '[CKEDITOR.dialog.openDialog] Dialog "' + dialogName + '" failed when loading definition.' ); } else if ( typeof dialogDefinitions == 'string' ) { CKEDITOR.scriptLoader.load( CKEDITOR.getUrl( dialogDefinitions ), function() { var dialogDefinition = CKEDITOR.dialog._.dialogDefinitions[ dialogName ]; // In case of plugin error, mark it as loading failed. if ( typeof dialogDefinition != 'function' ) CKEDITOR.dialog._.dialogDefinitions[ dialogName ] = 'failed'; this.openDialog( dialogName, callback ); }, this, 0, 1 ); } CKEDITOR.skin.loadPart( 'dialog' ); return dialog; }
javascript
{ "resource": "" }
q14336
getWidgetsFromXml
train
async function getWidgetsFromXml(target) { const $ = await parseFile(target) const widgets = [] let widget $('node').each((i, elem) => { const node = $(elem) widget = new Widget() widget.text = node.attr('text') widget.resourceId = node.attr('resource-id') widget.className = node.attr('class') widget.packageName = node.attr('package') widget.contentDesc = node.attr('content-desc') widget.checkable = node.attr('checkable') widget.checked = node.attr('checked') widget.clickable = node.attr('clickable') widget.enabled = node.attr('enabled') widget.focusable = node.attr('focusable') widget.focused = node.attr('focused') widget.scrollable = node.attr('scrollable') widget.longClickable = node.attr('long-clickable') widget.password = node.attr('password') widget.selected = node.attr('selected') widget.bounds = node.attr('bounds') widgets.push(widget) }) return widgets }
javascript
{ "resource": "" }
q14337
threshold
train
function threshold(element) { var rects = element.getBoundingClientRect(); var upperThreshold = (threshold._viewport.height - rects.top) / rects.height; var bottomThreshold = rects.bottom / rects.height; var leftThreshold = (threshold._viewport.width - rects.left) / rects.width; var rightThreshold = rects.right / rects.width; var horizontalTrajectory = rects.width + threshold._viewport.width; var verticalTrajectory = rects.height + threshold._viewport.height; /** * area * * This value represents the area of the component present in the viewport * * It is calculated by using the min value between the distance from the * top, right, bottom and left edges of the element and its height and weight * */ var minXArea = Math.min(leftThreshold, rightThreshold); var xArea = Math.min(1, Math.max(minXArea, 0)); var minYArea = Math.min(upperThreshold, bottomThreshold); var yArea = Math.min(1, Math.max(minYArea, 0)); /** * trajectory * * This value represents the translation of the element from the moment * it enters the viewport until it gets out * * It is calculated by measuring the distance between the top and left edge * of the viewport and the bottom and right edge of the element * */ var xTrajectory = (horizontalTrajectory - rects.right) / horizontalTrajectory; var yTrajectory = (verticalTrajectory - rects.bottom) / verticalTrajectory; return { area: xArea * yArea, trajectory: { x: xTrajectory, y: yTrajectory } }; }
javascript
{ "resource": "" }
q14338
updateViewport
train
function updateViewport() { threshold._viewport.height = window.innerHeight; threshold._viewport.width = window.innerWidth; }
javascript
{ "resource": "" }
q14339
all
train
function all(func) { return function() { var params = getParams(arguments); var length = params.length; for (var i = 0; i < length; i++) { if (!func.call(null, params[i])) { return false; } } return true; }; }
javascript
{ "resource": "" }
q14340
compareVersion
train
function compareVersion(version, range) { var string = (range + ''); var n = +(string.match(/\d+/) || NaN); var op = string.match(/^[<>]=?|/)[0]; return comparator[op] ? comparator[op](version, n) : (version == n || n !== n); }
javascript
{ "resource": "" }
q14341
getParams
train
function getParams(args) { var params = slice.call(args); var length = params.length; if (length === 1 && is.array(params[0])) { // support array params = params[0]; } return params; }
javascript
{ "resource": "" }
q14342
merge
train
function merge (a, b) { for (var k in b) a[k] = a[k] || b[k] }
javascript
{ "resource": "" }
q14343
CrossStyle
train
function CrossStyle(input) { var uInput = UFirst(input); return [ "webkit" + uInput , "moz" + uInput , "ms" + uInput , "o" + uInput , input ] }
javascript
{ "resource": "" }
q14344
IMFClass
train
function IMFClass(opts) { if (!(this instanceof IMFClass)) { return new IMFClass(opts); } opts = opts || {}; this.defaultNamespace = opts.defaultNamespace || ''; this.defaultSeparator = opts.defaultSeparator === undefined ? '.' : opts.defaultSeparator; this.basePath = opts.basePath || 'locales/'; this.fallbackLanguages = opts.fallbackLanguages; this.localeFileResolver = opts.localeFileResolver || function (lang) { return this.basePath + lang + '.json'; }; this.locales = opts.locales || []; this.langs = opts.langs; this.fallbackLocales = opts.fallbackLocales || []; const loadFallbacks = cb => { this.loadLocales(this.fallbackLanguages, function (...fallbackLocales) { this.fallbackLocales.push(...fallbackLocales); if (cb) { return cb(fallbackLocales); } }, true); }; if (opts.languages || opts.callback) { this.loadLocales(opts.languages, () => { const locales = Array.from(arguments); const runCallback = fallbackLocales => { if (opts.callback) { opts.callback.apply(this, [this.getFormatter(opts.namespace), this.getFormatter.bind(this), locales, fallbackLocales]); } }; if (opts.hasOwnProperty('fallbackLanguages')) { loadFallbacks(runCallback); } else { runCallback(); } }); } else if (opts.hasOwnProperty('fallbackLanguages')) { loadFallbacks(); } }
javascript
{ "resource": "" }
q14345
users
train
function users() { var seminarjs = this; var exports = {}; exports.list = []; /** * Add a user * @param {string} name User name * @param {Object} attributes List of attributes to be added to the user */ exports.add = function (name, attributes) { if (exports.find(name)) { return false; } else { exports.list.push(new User(name, attributes)); } }; /** * Finds users * @param {string} name User name * @return {int} Integer >-1 if the user is found, or -1 if not. */ exports.find = function (name) { var total = exports.list.length; for (var i = 0; i < total; i++) { if (exports.list[i].name == name) { return i; } } return -1; }; /** * Removes a user from the list * @param {string} name User name */ exports.remove = function (name) { var index = exports.find(name); exports.list.splice(index, 1); }; /** * Set a property for a user * @param {string} name Username * @param {String} param Parameter name * @param {String} value Parameter value */ exports.set = function (name, param, value) { var index = exports.find(name); exports.list[index][param] = value; }; /** * Get a parameter * @param {string} name User name * @param {String} param Parameter name * @return {String} Parameter value */ exports.get = function (name, param) { var index = exports.find(name); return exports.list[index][param]; }; /** * User constructor * @param {string} name User name * @param {object} attributes User properties */ function User(name, attributes) { var ret = { name: user }; return extend(ret, attributes); } return exports; }
javascript
{ "resource": "" }
q14346
train
function (parts, indent, prefix) { var lines = []; var line = []; var lineLength = !!prefix ? prefix.length - 1: indent.length - 1; parts.forEach(function (part) { if (lineLength + 1 + part.length > textWidth) { lines.push(indent + line.join(' ')); line = []; lineLength = indent.length - 1; } line.push(part); lineLength += part.length + 1; }); if (line) { lines.push(indent + line.join(' ')); } if (prefix) { lines[0] = lines[0].substr(indent.length); } return lines; }
javascript
{ "resource": "" }
q14347
train
function(cfg){ var self = this; var route_opts; patsy.scripture.print('[Patsy]'.yellow + ': Here\'s the proxy my King!\n'); var _getHeaders = function(path, local_headers){ var global_headers = {}; if(typeof cfg.proxy.options.headers !== 'undefined' && typeof cfg.proxy.options.headers === 'object'){ global_headers = xtend({},cfg.proxy.options.headers); } if(typeof local_headers === 'undefined'){ local_headers = {}; } try{ return xtend(global_headers, local_headers); } catch(e){ if(opts.verbose){ utils.fail('Could not extend headers!'); console.log(global_headers, local_headers, e); } else { utils.fail(); } } }; var gotMatch = false, // Find match method _findMatch = function(url, resource){ gotMatch = false; var parsed_resource_pass; if(typeof resource === 'array' || typeof resource === 'object'){ resource.forEach(function(route){ parsed_resource_pass = node_url.parse(route.pass); // First, turn the URL into a regex. // NOTE: Turning user input directly into a Regular Expression is NOT SAFE. var matchPath = new RegExp(route.path.replace(/\//, '\\/')); var matchedPath = matchPath.exec(url); //if(url.match(route.path) && (url !== '/' && route.path.indexOf(url) !== -1)){ if(matchedPath && matchedPath[0] !== '/'){ route_opts = { route : { host: parsed_resource_pass.hostname, port: parsed_resource_pass.port }, from_path : route.path, url : url.replace(route.path, parsed_resource_pass.pathname), headers: _getHeaders(route.path, route.headers || {}) }; //console.log(matchedPath[0],url, route_opts.url, route.path); gotMatch = true; } }); } else if(typeof resource === 'string'){ gotMatch = false; parsed_resource_pass = node_url.parse(resource); if(url.match(resource) && resource.indexOf(url) !== -1){ route_opts = { route : { host: parsed_resource_pass.hostname, port: parsed_resource_pass.port }, url : url, headers: cfg.proxy.options.headers || {} }; gotMatch = true; } } }; try{ // // Create a proxy server with custom application logic // var proxyServer = httpProxy.createServer(function (req, res, proxy) { // // Put your custom server logic here // _findMatch(req.url, cfg.proxy.resources); var _opts = typeof route_opts === 'object' ? route_opts : false; var _route; if(opts.verbose){ util.print('>>'.cyan + ' Setting up route for ' + req.url.cyan + '...'); } if(_opts && gotMatch){ _route = _opts.route; req.url = _opts.url; if(opts.verbose){ utils.ok(); } if(typeof _route !== 'object'){ throw new Error('Required object for proxy is not valid'); } // Set headers // Headers are overwritten like this: // Request headers are overwritten by global headers // Global headers are overwritten by local headers req.headers = xtend(req.headers,_opts.headers || {}); // Set headers with the path we're forwarding from req.headers = xtend(req.headers, { "x-forwarded-path" : _opts.from_path, "x-original-url" : req.url }); if(opts.verbose){ util.print('>>'.cyan + ' Guiding ' + req.url.cyan + ' to ' + _route.host.inverse.magenta + ':' + _route.port.inverse.magenta +'...'); } try{ // Proxy the request proxy.proxyRequest(req, res, _route); } catch( error ){ if(opts.verbose){ utils.fail('Could not proxy given URL when we have match: ' + req.url.cyan); console.log(error, 'Headers',req.headers,'Options',_opts); } else { utils.fail(); } res.writeHead(500, { 'Content-Type': 'text/plain' }); res.write('Could not proxy given URL: ' + req.url +'\n' + 'Given route: ' + JSON.stringify(_route || 'no route found', true, 2) +'\n' + 'Headers:' + JSON.stringify(req.headers, true, 2) +'\n' + 'Given options: ' + JSON.stringify(_opts, true, 2)); res.end(); } if(opts.verbose){ utils.ok(); } } else { // No match found in proxy table for incoming URL, try relay the request to the local webserver instead try{ util.print("WARN".yellow + '\n'); if(opts.verbose){ util.print('>> '.yellow + ' No match found, relaying to: ' + String(cfg.project.environment.host).inverse.magenta +':'+ String(cfg.project.environment.port).inverse.magenta + '...' ); } _route = { host: cfg.project.environment.host, port: cfg.project.environment.port }; // Set headers // Headers are overwritten like this: // Request headers are overwritten by global headers // Global headers are overwritten by local headers req.headers = xtend(req.headers,cfg.proxy.options.headers || {}); // Proxy the request proxy.proxyRequest(req, res, _route); if(opts.verbose){ utils.ok(); } } catch(error){ if(opts.verbose){ utils.fail('Could not proxy given URL with no match found: ' + req.url.cyan); console.log(error, 'Headers',req.headers,'Options',_opts); } else { utils.fail(); } res.writeHead(404, { 'Content-Type': 'text/plain' }); res.write('Could not proxy given URL: ' + req.url +'\n' + 'Headers:' + JSON.stringify(req.headers, true, 2) +'\n' + 'Given options: ' + JSON.stringify(_opts, true, 2)); res.end(); } } // Clean up vars }); proxyServer.listen(cfg.proxy.options.port || 80); proxyServer.proxy.on('proxyError', function (err, req, res) { /*if(typeof req.headers['x-forwarded-path'] !== 'undefined'){ self.mock(res, req); } else {*/ res.writeHead(500, { 'Content-Type': 'text/plain' }); res.write('Something went wrong. And we are reporting a custom error message.') res.write('Could not proxy given URL: ' + req.url +'\n' + 'Headers:' + JSON.stringify(req.headers, true, 2) +'\n'); res.end(); //} }); } catch(e){ util.puts('>> FAIL'.red + ': Could not create proxy server',e); } }
javascript
{ "resource": "" }
q14348
put
train
function put(argv, callback) { if (!argv[2]) { console.error("url is required"); console.error("Usage : put <url> <data>"); process.exit(-1); } if (!argv[3]) { console.error("data is required"); console.error("Usage : put <url> <data>"); process.exit(-1); } util.put(argv[2], argv[3], function(err, val, uri) { if (!err) { console.log('PUT to : ' + argv[2]); } }); }
javascript
{ "resource": "" }
q14349
init
train
function init() { // Locate config if we dont have one {{{ if (_.isUndefined(appConfig)) { appConfigLocations.forEach(function(key) { if (_.has(global, key)) { appConfig = _.get(global, key); return false; } }); if (_.isUndefined(appConfig)) throw new Error('Cannot find email config in', appConfigLocations); } // }}} this.config = { // Reset basics from: appConfig.email.from, to: appConfig.email.to, subject: appConfig.email.subject || '', cc: appConfig.email.cc || [], bcc: appConfig.email.bcc || [], }; // Work out mail transport {{{ if (appConfig.email.enabled) { switch (appConfig.email.method) { case 'mailgun': if ( /^https?:\/\//.test(appConfig.mailgun.domain) || /mailgun/.test(appConfig.mailgun.domain) ) throw new Error("Mailgun domain should not contain 'http(s)://' prefix or mailgun. Should resemble the domain name e.g. 'acme.com'"); transporter = nodemailer.createTransport(nodemailerMailgun({ auth: { api_key: appConfig.mailgun.apiKey, domain: appConfig.mailgun.domain, }, })); break case 'sendmail': transporter = nodemailer.createTransport(nodemailerSendmail()); break; default: next('Unknown mail transport method: ' + appConfig.email.method); } } // }}} return this; }
javascript
{ "resource": "" }
q14350
parseOptions
train
function parseOptions(nopt, optlist){ var params = getParams(optlist); var parsedOptions = nopt(params.known, params.aliases, process.argv, 2); initArrays(optlist, parsedOptions); return parsedOptions; }
javascript
{ "resource": "" }
q14351
resetOptions
train
function resetOptions(grunt, parsedOptions){ for (var i in parsedOptions){ if (parsedOptions.hasOwnProperty(i) && i != 'argv'){ grunt.option(i, parsedOptions[i]); } } }
javascript
{ "resource": "" }
q14352
getParams
train
function getParams(optlist){ var aliases = {}; var known = {}; Object.keys(optlist).forEach(function(key) { var short = optlist[key].short; if (short) { aliases[short] = '--' + key; } known[key] = optlist[key].type; }); return { known: known, aliases: aliases } }
javascript
{ "resource": "" }
q14353
initArrays
train
function initArrays(optlist, parsedOptions){ Object.keys(optlist).forEach(function(key) { if (optlist[key].type === Array && !(key in parsedOptions)) { parsedOptions[key] = []; } }); }
javascript
{ "resource": "" }
q14354
train
function (fn) { /** * Chain function. * * @function * @memberof! funcs * @alias funcs.maxTimesChain * @private * @param {Number} times - The max times the provided function will be invoked * @returns {function} The new wrapper function */ fn.maxTimes = function (times) { return funcs.maxTimes(fn, times); }; /** * Chain function. * * @function * @memberof! funcs * @alias funcs.onceChain * @private * @returns {function} The new wrapper function */ fn.once = function () { return funcs.once(fn); }; /** * Chain function. * * @function * @memberof! funcs * @alias funcs.delayChain * @private * @param {Number} delay - The invocation delay in millies * @returns {function} The new wrapper function */ fn.delay = function (delay) { return funcs.delay(fn, delay); }; /** * Chain function. * * @function * @memberof! funcs * @alias funcs.asyncChain * @private * @returns {function} The new wrapper function */ fn.async = function () { return funcs.async(fn); }; }
javascript
{ "resource": "" }
q14355
nonCharactersBoundary
train
function nonCharactersBoundary( node ) { return !( node.type == CKEDITOR.NODE_ELEMENT && node.isBlockBoundary( CKEDITOR.tools.extend( {}, CKEDITOR.dtd.$empty, CKEDITOR.dtd.$nonEditable ) ) ); }
javascript
{ "resource": "" }
q14356
train
function() { return { textNode: this.textNode, offset: this.offset, character: this.textNode ? this.textNode.getText().charAt( this.offset ) : null, hitMatchBoundary: this._.matchBoundary }; }
javascript
{ "resource": "" }
q14357
syncFieldsBetweenTabs
train
function syncFieldsBetweenTabs( currentPageId ) { var sourceIndex, targetIndex, sourceField, targetField; sourceIndex = currentPageId === 'find' ? 1 : 0; targetIndex = 1 - sourceIndex; var i, l = fieldsMapping.length; for ( i = 0; i < l; i++ ) { sourceField = this.getContentElement( pages[ sourceIndex ], fieldsMapping[ i ][ sourceIndex ] ); targetField = this.getContentElement( pages[ targetIndex ], fieldsMapping[ i ][ targetIndex ] ); targetField.setValue( sourceField.getValue() ); } }
javascript
{ "resource": "" }
q14358
train
function( range, matchWord ) { var self = this; var walker = new CKEDITOR.dom.walker( range ); walker.guard = matchWord ? nonCharactersBoundary : function( node ) { !nonCharactersBoundary( node ) && ( self._.matchBoundary = true ); }; walker[ 'evaluator' ] = findEvaluator; walker.breakOnFalse = 1; if ( range.startContainer.type == CKEDITOR.NODE_TEXT ) { this.textNode = range.startContainer; this.offset = range.startOffset - 1; } this._ = { matchWord: matchWord, walker: walker, matchBoundary: false }; }
javascript
{ "resource": "" }
q14359
train
function( characterWalker, rangeLength ) { this._ = { walker: characterWalker, cursors: [], rangeLength: rangeLength, highlightRange: null, isMatched: 0 }; }
javascript
{ "resource": "" }
q14360
train
function( domRange ) { var cursor, walker = new characterWalker( domRange ); this._.cursors = []; do { cursor = walker.next(); if ( cursor.character ) this._.cursors.push( cursor ); } while ( cursor.character ); this._.rangeLength = this._.cursors.length; }
javascript
{ "resource": "" }
q14361
train
function() { // Do not apply if nothing is found. if ( this._.cursors.length < 1 ) return; // Remove the previous highlight if there's one. if ( this._.highlightRange ) this.removeHighlight(); // Apply the highlight. var range = this.toDomRange(), bookmark = range.createBookmark(); highlightStyle.applyToRange( range, editor ); range.moveToBookmark( bookmark ); this._.highlightRange = range; // Scroll the editor to the highlighted area. var element = range.startContainer; if ( element.type != CKEDITOR.NODE_ELEMENT ) element = element.getParent(); element.scrollIntoView(); // Update the character cursors. this.updateFromDomRange( range ); }
javascript
{ "resource": "" }
q14362
train
function() { if ( !this._.highlightRange ) return; var bookmark = this._.highlightRange.createBookmark(); highlightStyle.removeFromRange( this._.highlightRange, editor ); this._.highlightRange.moveToBookmark( bookmark ); this.updateFromDomRange( this._.highlightRange ); this._.highlightRange = null; }
javascript
{ "resource": "" }
q14363
getRangeAfterCursor
train
function getRangeAfterCursor( cursor, inclusive ) { var range = editor.createRange(); range.setStart( cursor.textNode, ( inclusive ? cursor.offset : cursor.offset + 1 ) ); range.setEndAt( editor.editable(), CKEDITOR.POSITION_BEFORE_END ); return range; }
javascript
{ "resource": "" }
q14364
getRangeBeforeCursor
train
function getRangeBeforeCursor( cursor ) { var range = editor.createRange(); range.setStartAt( editor.editable(), CKEDITOR.POSITION_AFTER_START ); range.setEnd( cursor.textNode, cursor.offset ); return range; }
javascript
{ "resource": "" }
q14365
train
function( pattern, ignoreCase ) { var overlap = [ -1 ]; if ( ignoreCase ) pattern = pattern.toLowerCase(); for ( var i = 0; i < pattern.length; i++ ) { overlap.push( overlap[ i ] + 1 ); while ( overlap[ i + 1 ] > 0 && pattern.charAt( i ) != pattern.charAt( overlap[ i + 1 ] - 1 ) ) overlap[ i + 1 ] = overlap[ overlap[ i + 1 ] - 1 ] + 1; } this._ = { overlap: overlap, state: 0, ignoreCase: !!ignoreCase, pattern: pattern }; }
javascript
{ "resource": "" }
q14366
train
function(query, scope) { return Array.prototype.slice.call((scope || document).querySelectorAll(query)); }
javascript
{ "resource": "" }
q14367
ES6ImportsRenamer
train
function ES6ImportsRenamer(config, callback) { config = config || {}; this._basePath = config.basePath; this._renameDependencies = config.renameDependencies; this._renameFn = config.renameFn; this._callback = callback; this._addedMap = {}; this._initStack(config.sources || []); this._renameNextAst(); }
javascript
{ "resource": "" }
q14368
createRequireFunc
train
function createRequireFunc(customResolver) { return function (requestedPath) { var resolvedPath = null; try { resolvedPath = resolve.sync(requestedPath, {basedir: FIRBASE_DIR}); } catch (e) {} return customResolver(requestedPath, resolvedPath); }; }
javascript
{ "resource": "" }
q14369
runNextRequest
train
function runNextRequest(){ var self = this; var req = parser.read() if (req){ var res = new Response(req); res.assignSocket(socket) //No matter how the response object gets closed this //will trigger the next one if there is one. res.once('close', function(){ //Check if there is work. if(self.work){ runNextRequest.call(self) } else { //Let the system know that you have stopped working self.working = false; } }); this.emit('request', req, res); } }
javascript
{ "resource": "" }
q14370
rand16Num
train
function rand16Num(len) { let result = []; for (let i = 0; i < len; i++) { result.push('0123456789abcdef'.charAt( Math.floor(Math.random() * 16)) ); } return result.join(''); }
javascript
{ "resource": "" }
q14371
ClassBuilder
train
function ClassBuilder(InstanceBuilder, Parent, Constructor, props) { // Last input argument is an object of properties for a new class props = arguments[arguments.length - 1]; // Second last input argument is a constructor function Constructor = arguments[arguments.length - 2]; // Set default Parent class if it is not provided if (arguments.length === 3) { Parent = Object; } // Validate input arguments // -------------------------------------------------- if (arguments.length < 3 || typeof InstanceBuilder !== 'function' || Object.prototype.toString.call(Parent) !== '[object Function]' || (Constructor !== null && typeof Constructor !== 'function') || Object.prototype.toString.call(props) !== '[object Object]') { throw new Error('Incorrect input arguments. It should be: ClassBuilder(Function, [Function], Function | null, Object)'); } // -------------------------------------------------- // Extract class name if defined // -------------------------------------------------- var className = ''; if (typeof props.__name === 'string' && props.__name) { className = props.__name; } delete props.__name; // -------------------------------------------------- // Prepare an array of what is going to be encapsulated into a new class // -------------------------------------------------- var encapsulations = []; // Collect objects properties and methods if (props.Encapsulate) { if (Object.prototype.toString.call(props.Encapsulate) === '[object Array]') { encapsulations = encapsulations.concat(props.Encapsulate); } else { encapsulations.push(props.Encapsulate); } // Remove "Encapsulate" property, because it is not need to be encapsulated delete props.Encapsulate; } // Put parent's defaults into an encapsulation stack if (Parent.prototype.__defaults) { encapsulations.unshift(Parent.prototype.__defaults); } // Put properties and methods for a new class into the encapsulation stack encapsulations.push(props); // Validate what is going to be encapsulated if (encapsulations.some(function(item) { var type = Object.prototype.toString.call(item); return type !== '[object Function]' && type !== '[object Object]'; })) { throw new Error('Some of the items for encapsulation is incorrect. An item can be: Object, Function, Class'); } // -------------------------------------------------- // Clone class constructor function to prevent a sharing of instance builder function // -------------------------------------------------- var Class; var declaration = className ? 'var ' + className + '; Class = ' + className + ' = ' : 'Class = '; eval(declaration + InstanceBuilder.toString()); // -------------------------------------------------- // Inheritance chain // -------------------------------------------------- // Derive a new class from a Parent class Class.prototype = Object.create(Parent.prototype); // Revert back the reference to the instance builder function Class.prototype.constructor = Class; // Store the reference to the constructor function if (Constructor) { Class.prototype.__constructor = Constructor; } // Create a storage for default properties Class.prototype.__defaults = {}; // Store a reference to a parent's prototype object for internal usage Class.__parent = Parent.prototype; // -------------------------------------------------- // Encapsulate properties and methods // -------------------------------------------------- for (var n = 0, N = encapsulations.length; n < N; n++) { ClassBuilder.encapsulate(encapsulations[n], Class); } // -------------------------------------------------- return Class; }
javascript
{ "resource": "" }
q14372
train
function() { var block = this.emptyBlock(0); while ('eos' != this.peek().type) { if ('newline' == this.peek().type) { this.advance(); } else if ('text-html' == this.peek().type) { block.nodes = block.nodes.concat(this.parseTextHtml()); } else { var expr = this.parseExpr(); if (expr) block.nodes.push(expr); } } return block; }
javascript
{ "resource": "" }
q14373
train
function() { var tok = this.expect('filter'); var block, attrs = []; if (this.peek().type === 'start-attributes') { attrs = this.attrs(); } if (this.peek().type === 'text') { var textToken = this.advance(); block = this.initBlock(textToken.line, [ { type: 'Text', val: textToken.val, line: textToken.line, filename: this.filename } ]); } else if (this.peek().type === 'filter') { block = this.initBlock(tok.line, [this.parseFilter()]); } else { block = this.parseTextBlock() || this.emptyBlock(tok.line); } return { type: 'Filter', name: tok.val, block: block, attrs: attrs, line: tok.line, filename: this.filename }; }
javascript
{ "resource": "" }
q14374
train
function() { var tok = this.expect('block'); var node = 'indent' == this.peek().type ? this.block() : this.emptyBlock(tok.line); node.type = 'NamedBlock'; node.name = tok.val.trim(); node.mode = tok.mode; node.line = tok.line; return node; }
javascript
{ "resource": "" }
q14375
Stringme
train
function Stringme(val, opt) { if (val === undefined) { val = '"undefined"'; } else if (val === null) { val = '"null"'; } else { var replace = opt && opt.replace ? opt.replace : null; var space = opt && opt.space ? opt.space : null; val = JSON.stringify(val, replace, space); } if (opt && opt.quotes === false && !/(^{|\[).*?([}\]])$/gm.test(val)) val = val.slice(1, val.length - 1); return val; }
javascript
{ "resource": "" }
q14376
ucFirst
train
function ucFirst( str ) { str += ''; var f = str.charAt( 0 ).toUpperCase(); return f + str.substr( 1 ); }
javascript
{ "resource": "" }
q14377
browseServer
train
function browseServer( evt ) { var dialog = this.getDialog(); var editor = dialog.getParentEditor(); editor._.filebrowserSe = this; var width = editor.config[ 'filebrowser' + ucFirst( dialog.getName() ) + 'WindowWidth' ] || editor.config.filebrowserWindowWidth || '80%'; var height = editor.config[ 'filebrowser' + ucFirst( dialog.getName() ) + 'WindowHeight' ] || editor.config.filebrowserWindowHeight || '70%'; var params = this.filebrowser.params || {}; params.CKEditor = editor.name; params.CKEditorFuncNum = editor._.filebrowserFn; if ( !params.langCode ) params.langCode = editor.langCode; var url = addQueryString( this.filebrowser.url, params ); // TODO: V4: Remove backward compatibility (#8163). editor.popup( url, width, height, editor.config.filebrowserWindowFeatures || editor.config.fileBrowserWindowFeatures ); }
javascript
{ "resource": "" }
q14378
uploadFile
train
function uploadFile( evt ) { var dialog = this.getDialog(); var editor = dialog.getParentEditor(); editor._.filebrowserSe = this; // If user didn't select the file, stop the upload. if ( !dialog.getContentElement( this[ 'for' ][ 0 ], this[ 'for' ][ 1 ] ).getInputElement().$.value ) return false; if ( !dialog.getContentElement( this[ 'for' ][ 0 ], this[ 'for' ][ 1 ] ).getAction() ) return false; return true; }
javascript
{ "resource": "" }
q14379
setupFileElement
train
function setupFileElement( editor, fileInput, filebrowser ) { var params = filebrowser.params || {}; params.CKEditor = editor.name; params.CKEditorFuncNum = editor._.filebrowserFn; if ( !params.langCode ) params.langCode = editor.langCode; fileInput.action = addQueryString( filebrowser.url, params ); fileInput.filebrowser = filebrowser; }
javascript
{ "resource": "" }
q14380
attachFileBrowser
train
function attachFileBrowser( editor, dialogName, definition, elements ) { if ( !elements || !elements.length ) return; var element, fileInput; for ( var i = elements.length; i--; ) { element = elements[ i ]; if ( element.type == 'hbox' || element.type == 'vbox' || element.type == 'fieldset' ) attachFileBrowser( editor, dialogName, definition, element.children ); if ( !element.filebrowser ) continue; if ( typeof element.filebrowser == 'string' ) { var fb = { action: ( element.type == 'fileButton' ) ? 'QuickUpload' : 'Browse', target: element.filebrowser }; element.filebrowser = fb; } if ( element.filebrowser.action == 'Browse' ) { var url = element.filebrowser.url; if ( url === undefined ) { url = editor.config[ 'filebrowser' + ucFirst( dialogName ) + 'BrowseUrl' ]; if ( url === undefined ) url = editor.config.filebrowserBrowseUrl; } if ( url ) { element.onClick = browseServer; element.filebrowser.url = url; element.hidden = false; } } else if ( element.filebrowser.action == 'QuickUpload' && element[ 'for' ] ) { url = element.filebrowser.url; if ( url === undefined ) { url = editor.config[ 'filebrowser' + ucFirst( dialogName ) + 'UploadUrl' ]; if ( url === undefined ) url = editor.config.filebrowserUploadUrl; } if ( url ) { var onClick = element.onClick; element.onClick = function( evt ) { // "element" here means the definition object, so we need to find the correct // button to scope the event call var sender = evt.sender; if ( onClick && onClick.call( sender, evt ) === false ) return false; return uploadFile.call( sender, evt ); }; element.filebrowser.url = url; element.hidden = false; setupFileElement( editor, definition.getContents( element[ 'for' ][ 0 ] ).get( element[ 'for' ][ 1 ] ), element.filebrowser ); } } } }
javascript
{ "resource": "" }
q14381
isConfigured
train
function isConfigured( definition, tabId, elementId ) { if ( elementId.indexOf( ";" ) !== -1 ) { var ids = elementId.split( ";" ); for ( var i = 0; i < ids.length; i++ ) { if ( isConfigured( definition, tabId, ids[ i ] ) ) return true; } return false; } var elementFileBrowser = definition.getContents( tabId ).get( elementId ).filebrowser; return ( elementFileBrowser && elementFileBrowser.url ); }
javascript
{ "resource": "" }
q14382
findDirRec
train
function findDirRec(dir, callback) { var result = path.resolve(dir, dirmod); fs.stat(result, function stat(err, stat) { if (err || !stat.isDirectory()) { if (lastResult == result) { callback(new Error('No configuration directory found.')); return; } lastResult = result; findDirRec(path.resolve(dir, '..'), callback); } else { callback(null, result); } }); }
javascript
{ "resource": "" }
q14383
train
function(obj) { _.forEach(obj, function(val, key) { if (_.isString(val)) { if (Mixins.isObjectId(val)) { obj[key] = Mixins.newObjectId(val); } else if (Mixins.isValidISO8601String(val)) { obj[key] = new Date(val); } } else if (_.isDate(val)) { obj[key] = val; } else if (_.isObject(val)) { if (val['$oid']) { obj[key] = val['$oid']; } else { obj[key] = this.cast(val); } } }.bind(this)); return obj; }
javascript
{ "resource": "" }
q14384
train
function(obj) { _.forEach(obj, function(val, key) { if (val && _.isFunction(val.toHexString)) { obj[key] = val.toHexString(); } else if (_.isDate(val)) { obj[key] = val; } else if (_.isObject(val)) { if (val['$oid']) { obj[key] = val['$oid']; } else { obj[key] = this.uncast(val); } } }.bind(this)); return obj; }
javascript
{ "resource": "" }
q14385
train
function (requestURL, filename, fileType) { if (gc.coreFunctions.getReqestExtension(filename) == '.ipa'){ // The template of an entry as well as the indicator variable for a file or dir. // This is used for IPA files that need to be installed on iOS devices so .manifest is appended to search for the appropriate manifest. var listingEntry = '<tr><td>{itemType}</td><td><a href="itms-services://?action=download-manifest&url={hrefLink}.plist">{itemName}</a></td></tr>\n'; // Populate the template now using the placeholders as text to be replaced. listingEntry = listingEntry.replace('{itemType}', "iOS"); listingEntry = listingEntry.replace('{hrefLink}', gc.coreFunctions.joinPaths(requestURL, filename)); listingEntry = listingEntry.replace('{itemName}', filename); } else { // The template of an entry as well as the indicator variable for a file or dir. var listingEntry = '<tr><td>{itemType}</td><td><a href="{hrefLink}">{itemName}</a></td></tr>\n'; // Populate the template now using the placeholders as text to be replaced. listingEntry = listingEntry.replace('{itemType}', fileType); listingEntry = listingEntry.replace('{hrefLink}', gc.coreFunctions.joinPaths(requestURL, filename)); listingEntry = listingEntry.replace('{itemName}', filename); } // Return the entry. return listingEntry; }
javascript
{ "resource": "" }
q14386
Class
train
function Class(superCtor, props){ let cls = function (...args) { if (!(this instanceof cls)) { throw new Error('Class constructors cannot be invoked without \'new\''); } //extend prototype data to instance //avoid instance change data to pullte prototype cls.extend(cls.__props__, this); if(isFunction(this.init)){ this.__initReturn = this.init(...args); } }; cls.__props__ = {}; cls.extend = function(props, target){ target = target || cls.prototype; let name, value; for(name in props){ value = props[name]; if (isArray(value)) { cls.__props__[name] = target[name] = extend([], value); }else if(isObject(value)){ cls.__props__[name] = target[name] = extend({}, value); }else{ target[name] = value; } } return cls; }; cls.inherits = function(superCtor){ cls.super_ = superCtor; //if superCtor.prototype is not enumerable if(Object.keys(superCtor.prototype).length === 0){ cls.prototype = Object.create(superCtor.prototype, { constructor: { value: cls, enumerable: false, writable: true, configurable: true } }); }else{ extend(cls.prototype, superCtor.prototype); } return cls; }; if (!isFunction(superCtor)) { props = superCtor; }else if (isFunction(superCtor)) { cls.inherits(superCtor); } if (props) { cls.extend(props); } /** * invoke super class method * @param {String} name [] * @param {Mixed} data [] * @return {Mixed} [] */ cls.prototype.super = function(name, data){ if (!this[name]) { this.super_c = null; return; } let super_ = this.super_c ? this.super_c.super_ : this.constructor.super_; if (!super_ || !isFunction(super_.prototype[name])) { this.super_c = null; return; } while(this[name] === super_.prototype[name] && super_.super_){ super_ = super_.super_; } this.super_c = super_; if (!this.super_t) { this.super_t = 1; } if (!isArray(data) && !isArguments(data)) { data = arguments.length === 1 ? [] : [data]; } let t = ++this.super_t, ret, method = super_.prototype[name]; ret = method.apply(this, data); if (t === this.super_t) { this.super_c = null; this.super_t = 0; } return ret; }; return cls; }
javascript
{ "resource": "" }
q14387
TypedArray
train
function TypedArray (config) { const array = this; // validate min items if (config.hasOwnProperty('minItems') && (!util.isInteger(config.minItems) || config.minItems < 0)) { throw Error('Invalid configuration value for property: minItems. Must be an integer that is greater than or equal to zero. Received: ' + config.minItems); } const minItems = config.hasOwnProperty('minItems') ? config.minItems : 0; // validate max items if (config.hasOwnProperty('maxItems') && (!util.isInteger(config.maxItems) || config.maxItems < minItems)) { throw Error('Invalid configuration value for property: maxItems. Must be an integer that is greater than or equal to the minItems. Received: ' + config.maxItems); } // validate schema if (config.hasOwnProperty('schema')) config.schema = FullyTyped(config.schema); // define properties Object.defineProperties(array, { maxItems: { /** * @property * @name TypedArray#maxItems * @type {number} */ value: Math.round(config.maxItems), writable: false }, minItems: { /** * @property * @name TypedArray#minItems * @type {number} */ value: Math.round(config.minItems), writable: false }, schema: { /** * @property * @name TypedArray#schema * @type {object} */ value: config.schema, writable: false }, uniqueItems: { /** * @property * @name TypedArray#uniqueItems * @type {boolean} */ value: !!config.uniqueItems, writable: false } }); return array; }
javascript
{ "resource": "" }
q14388
registerOptionsObserver
train
function registerOptionsObserver(instance) { if (!instance._mounted || !instance._options) { return } instance._observer.observe(instance._options, { childList: true, attributes: true, characterData: true, subtree: true, attributeFilter: ['disabled', 'label', 'selected', 'title', 'multiple'], }) }
javascript
{ "resource": "" }
q14389
addEventListeners
train
function addEventListeners(instance) { if (!instance._mounted || !instance._options) { return } instance._options.addEventListener('change', instance._onSelectionChange) instance._root.addEventListener('mouseover', instance._onItemHovered) instance._root.addEventListener('mousedown', instance._onItemSelectionStart) instance._root.addEventListener('mouseup', instance._onItemClicked) addEventListener('mouseup', instance._onSelectionEnd) }
javascript
{ "resource": "" }
q14390
removeEventListeners
train
function removeEventListeners(instance) { if (instance._options) { instance._options.removeEventListener('change', instance._onSelectionChange) } instance._root.removeEventListener('mouseover', instance._onItemHovered) instance._root.removeEventListener('mousedown', instance._onItemSelectionStart) instance._root.removeEventListener('mouseup', instance._onItemClicked) removeEventListener('mouseup', instance._onSelectionEnd) }
javascript
{ "resource": "" }
q14391
onItemHovered
train
function onItemHovered(instance, itemUi) { if (instance._options.disabled || !isEnabledOptionUi(itemUi)) { return } if (instance._options.multiple) { if (instance._dragSelectionStartOption) { updateMultiSelection(instance, itemUi) } return } instance._root.setAttribute('data-szn-options--highlighting', '') const previouslyHighlighted = instance._root.querySelector('[data-szn-options--highlighted]') if (previouslyHighlighted) { previouslyHighlighted.removeAttribute('data-szn-options--highlighted') } itemUi.setAttribute('data-szn-options--highlighted', '') }
javascript
{ "resource": "" }
q14392
onItemClicked
train
function onItemClicked(instance, itemUi) { if (instance._dragSelectionStartOption) { // multi-select instance._dragSelectionStartOption = null return } if (instance._options.disabled || !isEnabledOptionUi(itemUi)) { return } instance._root.removeAttribute('data-szn-options--highlighting') instance._options.selectedIndex = itemUi._option.index instance._options.dispatchEvent(new CustomEvent('change', {bubbles: true, cancelable: true})) }
javascript
{ "resource": "" }
q14393
onItemSelectionStart
train
function onItemSelectionStart(instance, itemUi, event) { if (instance._options.disabled || !instance._options.multiple || !isEnabledOptionUi(itemUi)) { return } const options = instance._options.options if (event.shiftKey && instance._previousSelectionStartIndex > -1) { instance._dragSelectionStartOption = options.item(instance._previousSelectionStartIndex) } else { if (event.ctrlKey) { instance._additionalSelectedIndexes = [] for (let i = 0, length = options.length; i < length; i++) { if (options.item(i).selected) { instance._additionalSelectedIndexes.push(i) } } instance._invertSelection = itemUi._option.selected } else { instance._invertSelection = false } instance._dragSelectionStartOption = itemUi._option } instance._previousSelectionStartIndex = instance._dragSelectionStartOption.index updateMultiSelection(instance, itemUi) }
javascript
{ "resource": "" }
q14394
scrollToSelection
train
function scrollToSelection(instance, selectionStartIndex, selectionEndIndex) { const lastSelectionIndexes = instance._lastSelectionIndexes if ( selectionStartIndex !== -1 && (selectionStartIndex !== lastSelectionIndexes.start || selectionEndIndex !== lastSelectionIndexes.end) ) { const changedIndex = selectionStartIndex !== lastSelectionIndexes.start ? selectionStartIndex : selectionEndIndex scrollToOption(instance, changedIndex) } lastSelectionIndexes.start = selectionStartIndex lastSelectionIndexes.end = selectionEndIndex }
javascript
{ "resource": "" }
q14395
scrollToOption
train
function scrollToOption(instance, optionIndex) { const ui = instance._root if (ui.clientHeight >= ui.scrollHeight) { return } const uiBounds = ui.getBoundingClientRect() const options = instance._root.querySelectorAll('[data-szn-options--option]') const optionBounds = options[optionIndex].getBoundingClientRect() if (optionBounds.top >= uiBounds.top && optionBounds.bottom <= uiBounds.bottom) { return } const delta = optionBounds.top < uiBounds.top ? optionBounds.top - uiBounds.top : optionBounds.bottom - uiBounds.bottom ui.scrollTop += delta }
javascript
{ "resource": "" }
q14396
updateMultiSelection
train
function updateMultiSelection(instance, lastHoveredItem) { const startIndex = instance._dragSelectionStartOption.index const lastIndex = lastHoveredItem._option.index const minIndex = Math.min(startIndex, lastIndex) const maxIndex = Math.max(startIndex, lastIndex) const options = instance._options.options const additionalIndexes = instance._additionalSelectedIndexes for (let i = 0, length = options.length; i < length; i++) { const option = options.item(i) if (isOptionEnabled(option)) { let isOptionSelected = additionalIndexes.indexOf(i) > -1 if (i >= minIndex && i <= maxIndex) { isOptionSelected = !instance._invertSelection } option.selected = isOptionSelected } } instance._options.dispatchEvent(new CustomEvent('change', {bubbles: true, cancelable: true})) }
javascript
{ "resource": "" }
q14397
updateUi
train
function updateUi(instance) { if (!instance._options) { return } if (instance._options.disabled) { instance._root.setAttribute('disabled', '') } else { instance._root.removeAttribute('disabled') } if (instance._options.multiple) { instance._root.setAttribute('data-szn-options--multiple', '') } else { instance._root.removeAttribute('data-szn-options--multiple') } updateGroupUi(instance._root, instance._options) if (instance._mounted) { const options = instance._options.options let lastSelectedIndex = -1 for (let i = options.length - 1; i >= 0; i--) { if (options.item(i).selected) { lastSelectedIndex = i break } } scrollToSelection(instance, instance._options.selectedIndex, lastSelectedIndex) } }
javascript
{ "resource": "" }
q14398
updateGroupUi
train
function updateGroupUi(uiContainer, optionsGroup) { removeRemovedItems(uiContainer, optionsGroup) updateExistingItems(uiContainer) addMissingItems(uiContainer, optionsGroup) }
javascript
{ "resource": "" }
q14399
removeRemovedItems
train
function removeRemovedItems(uiContainer, optionsGroup) { const options = Array.prototype.slice.call(optionsGroup.children) let currentItemUi = uiContainer.firstElementChild while (currentItemUi) { if (options.indexOf(currentItemUi._option) > -1) { currentItemUi = currentItemUi.nextElementSibling continue } const itemToRemove = currentItemUi currentItemUi = currentItemUi.nextElementSibling uiContainer.removeChild(itemToRemove) } }
javascript
{ "resource": "" }