_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q21600
processIssueHtml
train
function processIssueHtml(element) { let outerHTML = null; let innerHTML = null; if (!element.outerHTML) { return outerHTML; } outerHTML = element.outerHTML; if (element.innerHTML.length > 31) { innerHTML = `${element.innerHTML.substr(0, 31)}...`; outerHTML = outerHTML.replace(element.innerHTML, innerHTML); } if (outerHTML.length > 251) { outerHTML = `${outerHTML.substr(0, 250)}...`; } return outerHTML; }
javascript
{ "resource": "" }
q21601
getCssSelectorForElement
train
function getCssSelectorForElement(element, selectorParts = []) { if (isElementNode(element)) { const identifier = buildElementIdentifier(element); selectorParts.unshift(identifier); if (!element.id && element.parentNode) { return getCssSelectorForElement(element.parentNode, selectorParts); } } return selectorParts.join(' > '); }
javascript
{ "resource": "" }
q21602
buildElementIdentifier
train
function buildElementIdentifier(element) { if (element.id) { return `#${element.id}`; } let identifier = element.tagName.toLowerCase(); if (!element.parentNode) { return identifier; } const siblings = getSiblings(element); const childIndex = siblings.indexOf(element); if (!isOnlySiblingOfType(element, siblings) && childIndex !== -1) { identifier += `:nth-child(${childIndex + 1})`; } return identifier; }
javascript
{ "resource": "" }
q21603
isOnlySiblingOfType
train
function isOnlySiblingOfType(element, siblings) { const siblingsOfType = siblings.filter(sibling => { return (sibling.tagName === element.tagName); }); return (siblingsOfType.length <= 1); }
javascript
{ "resource": "" }
q21604
isIssueNotIgnored
train
function isIssueNotIgnored(issue) { if (options.ignore.indexOf(issue.code.toLowerCase()) !== -1) { return false; } if (options.ignore.indexOf(issue.type) !== -1) { return false; } return true; }
javascript
{ "resource": "" }
q21605
isElementOutsideHiddenArea
train
function isElementOutsideHiddenArea(issue) { const hiddenElements = [...window.document.querySelectorAll(options.hideElements)]; return !hiddenElements.some(hiddenElement => { return hiddenElement.contains(issue.element); }); }
javascript
{ "resource": "" }
q21606
generate
train
function generate() { store.generate(req); originalId = req.sessionID; originalHash = hash(req.session); wrapmethods(req.session); }
javascript
{ "resource": "" }
q21607
inflate
train
function inflate (req, sess) { store.createSession(req, sess) originalId = req.sessionID originalHash = hash(sess) if (!resaveSession) { savedHash = originalHash } wrapmethods(req.session) }
javascript
{ "resource": "" }
q21608
shouldSave
train
function shouldSave(req) { // cannot set cookie without a session ID if (typeof req.sessionID !== 'string') { debug('session ignored because of bogus req.sessionID %o', req.sessionID); return false; } return !saveUninitializedSession && cookieId !== req.sessionID ? isModified(req.session) : !isSaved(req.session) }
javascript
{ "resource": "" }
q21609
shouldTouch
train
function shouldTouch(req) { // cannot set cookie without a session ID if (typeof req.sessionID !== 'string') { debug('session ignored because of bogus req.sessionID %o', req.sessionID); return false; } return cookieId === req.sessionID && !shouldSave(req); }
javascript
{ "resource": "" }
q21610
shouldSetCookie
train
function shouldSetCookie(req) { // cannot set cookie without a session ID if (typeof req.sessionID !== 'string') { return false; } return cookieId !== req.sessionID ? saveUninitializedSession || isModified(req.session) : rollingSessions || req.session.cookie.expires != null && isModified(req.session); }
javascript
{ "resource": "" }
q21611
hash
train
function hash(sess) { // serialize var str = JSON.stringify(sess, function (key, val) { // ignore sess.cookie property if (this === sess && key === 'cookie') { return } return val }) // hash return crypto .createHash('sha1') .update(str, 'utf8') .digest('hex') }
javascript
{ "resource": "" }
q21612
issecure
train
function issecure(req, trustProxy) { // socket is https server if (req.connection && req.connection.encrypted) { return true; } // do not trust proxy if (trustProxy === false) { return false; } // no explicit trust; try req.secure from express if (trustProxy !== true) { return req.secure === true } // read the proto from x-forwarded-proto header var header = req.headers['x-forwarded-proto'] || ''; var index = header.indexOf(','); var proto = index !== -1 ? header.substr(0, index).toLowerCase().trim() : header.toLowerCase().trim() return proto === 'https'; }
javascript
{ "resource": "" }
q21613
unsigncookie
train
function unsigncookie(val, secrets) { for (var i = 0; i < secrets.length; i++) { var result = signature.unsign(val, secrets[i]); if (result !== false) { return result; } } return false; }
javascript
{ "resource": "" }
q21614
Session
train
function Session(req, data) { Object.defineProperty(this, 'req', { value: req }); Object.defineProperty(this, 'id', { value: req.sessionID }); if (typeof data === 'object' && data !== null) { // merge data into this, ignoring prototype properties for (var prop in data) { if (!(prop in this)) { this[prop] = data[prop] } } } }
javascript
{ "resource": "" }
q21615
fix_and_export
train
function fix_and_export(class_name) { var Src = window.bigdecimal[class_name]; var Fixed = Src; if(Src.__init__) { Fixed = function wrap_constructor() { var args = Array.prototype.slice.call(arguments); return Src.__init__(args); }; Fixed.prototype = Src.prototype; for (var a in Src) if(Src.hasOwnProperty(a)) { if((typeof Src[a] != 'function') || !a.match(/_va$/)) Fixed[a] = Src[a]; else { var pub_name = a.replace(/_va$/, ''); Fixed[pub_name] = function wrap_classmeth () { var args = Array.prototype.slice.call(arguments); return wrap_classmeth.inner_method(args); }; Fixed[pub_name].inner_method = Src[a]; } } } var proto = Fixed.prototype; for (var a in proto) { if(proto.hasOwnProperty(a) && (typeof proto[a] == 'function') && a.match(/_va$/)) { var pub_name = a.replace(/_va$/, ''); proto[pub_name] = function wrap_meth() { var args = Array.prototype.slice.call(arguments); return wrap_meth.inner_method.apply(this, [args]); }; proto[pub_name].inner_method = proto[a]; delete proto[a]; } } exports[class_name] = Fixed; }
javascript
{ "resource": "" }
q21616
multiply
train
function multiply(x, k, base) { var m, temp, xlo, xhi, carry = 0, i = x.length, klo = k % SQRT_BASE, khi = k / SQRT_BASE | 0; for (x = x.slice(); i--;) { xlo = x[i] % SQRT_BASE; xhi = x[i] / SQRT_BASE | 0; m = khi * xlo + xhi * klo; temp = klo * xlo + ((m % SQRT_BASE) * SQRT_BASE) + carry; carry = (temp / base | 0) + (m / SQRT_BASE | 0) + khi * xhi; x[i] = temp % base; } if (carry) x = [carry].concat(x); return x; }
javascript
{ "resource": "" }
q21617
isOdd
train
function isOdd(n) { var k = n.c.length - 1; return bitFloor(n.e / LOG_BASE) == k && n.c[k] % 2 != 0; }
javascript
{ "resource": "" }
q21618
Deflate
train
function Deflate(options) { if (!(this instanceof Deflate)) return new Deflate(options); this.options = utils.assign({ level: Z_DEFAULT_COMPRESSION, method: Z_DEFLATED, chunkSize: 16384, windowBits: 15, memLevel: 8, strategy: Z_DEFAULT_STRATEGY, to: '' }, options || {}); var opt = this.options; if (opt.raw && (opt.windowBits > 0)) { opt.windowBits = -opt.windowBits; } else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) { opt.windowBits += 16; } this.err = 0; // error code, if happens (0 = Z_OK) this.msg = ''; // error message this.ended = false; // used to avoid multiple onEnd() calls this.chunks = []; // chunks of compressed data this.strm = new ZStream(); this.strm.avail_out = 0; var status = zlib_deflate.deflateInit2( this.strm, opt.level, opt.method, opt.windowBits, opt.memLevel, opt.strategy ); if (status !== Z_OK) { throw new Error(msg[status]); } if (opt.header) { zlib_deflate.deflateSetHeader(this.strm, opt.header); } if (opt.dictionary) { var dict; // Convert data if needed if (typeof opt.dictionary === 'string') { // If we need to compress text, change encoding to utf8. dict = strings.string2buf(opt.dictionary); } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') { dict = new Uint8Array(opt.dictionary); } else { dict = opt.dictionary; } status = zlib_deflate.deflateSetDictionary(this.strm, dict); if (status !== Z_OK) { throw new Error(msg[status]); } this._dict_set = true; } }
javascript
{ "resource": "" }
q21619
Inflate
train
function Inflate(options) { if (!(this instanceof Inflate)) return new Inflate(options); this.options = utils.assign({ chunkSize: 16384, windowBits: 0, to: '' }, options || {}); var opt = this.options; // Force window size for `raw` data, if not set directly, // because we have no header for autodetect. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) { opt.windowBits = -opt.windowBits; if (opt.windowBits === 0) { opt.windowBits = -15; } } // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate if ((opt.windowBits >= 0) && (opt.windowBits < 16) && !(options && options.windowBits)) { opt.windowBits += 32; } // Gzip header has no info about windows size, we can do autodetect only // for deflate. So, if window size not set, force it to max when gzip possible if ((opt.windowBits > 15) && (opt.windowBits < 48)) { // bit 3 (16) -> gzipped data // bit 4 (32) -> autodetect gzip/deflate if ((opt.windowBits & 15) === 0) { opt.windowBits |= 15; } } this.err = 0; // error code, if happens (0 = Z_OK) this.msg = ''; // error message this.ended = false; // used to avoid multiple onEnd() calls this.chunks = []; // chunks of compressed data this.strm = new ZStream(); this.strm.avail_out = 0; var status = zlib_inflate.inflateInit2( this.strm, opt.windowBits ); if (status !== c.Z_OK) { throw new Error(msg[status]); } this.header = new GZheader(); zlib_inflate.inflateGetHeader(this.strm, this.header); // Setup dictionary if (opt.dictionary) { // Convert data if needed if (typeof opt.dictionary === 'string') { opt.dictionary = strings.string2buf(opt.dictionary); } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') { opt.dictionary = new Uint8Array(opt.dictionary); } if (opt.raw) { //In raw mode we need to set the dictionary early status = zlib_inflate.inflateSetDictionary(this.strm, opt.dictionary); if (status !== c.Z_OK) { throw new Error(msg[status]); } } } }
javascript
{ "resource": "" }
q21620
filterDepWithoutEntryPoints
train
function filterDepWithoutEntryPoints(dep) { // Return true if we want to add a dependency to externals try { // If the root of the dependency has an index.js, return true if (fs.existsSync(path.join(__dirname, `node_modules/${dep}/index.js`))) { return false; } const pgkString = fs .readFileSync(path.join(__dirname, `node_modules/${dep}/package.json`)) .toString(); const pkg = JSON.parse(pgkString); const fields = ['main', 'module', 'jsnext:main', 'browser']; return !fields.some(field => field in pkg); } catch (e) { console.log(e); return true; } }
javascript
{ "resource": "" }
q21621
createDebug
train
function createDebug(namespace) { let prevTime; function debug(...args) { // Disabled? if (!debug.enabled) { return; } const self = debug; // Set `diff` timestamp const curr = Number(new Date()); const ms = curr - (prevTime || curr); self.diff = ms; self.prev = prevTime; self.curr = curr; prevTime = curr; args[0] = createDebug.coerce(args[0]); if (typeof args[0] !== 'string') { // Anything else let's inspect with %O args.unshift('%O'); } // Apply any `formatters` transformations let index = 0; args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { // If we encounter an escaped % then don't increase the array index if (match === '%%') { return match; } index++; const formatter = createDebug.formatters[format]; if (typeof formatter === 'function') { const val = args[index]; match = formatter.call(self, val); // Now we need to remove `args[index]` since it's inlined in the `format` args.splice(index, 1); index--; } return match; }); // Apply env-specific formatting (colors, etc.) createDebug.formatArgs.call(self, args); const logFn = self.log || createDebug.log; logFn.apply(self, args); } debug.namespace = namespace; debug.enabled = createDebug.enabled(namespace); debug.useColors = createDebug.useColors(); debug.color = selectColor(namespace); debug.destroy = destroy; debug.extend = extend; // Debug.formatArgs = formatArgs; // debug.rawLog = rawLog; // env-specific initialization logic for debug instances if (typeof createDebug.init === 'function') { createDebug.init(debug); } createDebug.instances.push(debug); return debug; }
javascript
{ "resource": "" }
q21622
disable
train
function disable() { const namespaces = [ ...createDebug.names.map(toNamespace), ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace) ].join(','); createDebug.enable(''); return namespaces; }
javascript
{ "resource": "" }
q21623
enabled
train
function enabled(name) { if (name[name.length - 1] === '*') { return true; } let i; let len; for (i = 0, len = createDebug.skips.length; i < len; i++) { if (createDebug.skips[i].test(name)) { return false; } } for (i = 0, len = createDebug.names.length; i < len; i++) { if (createDebug.names[i].test(name)) { return true; } } return false; }
javascript
{ "resource": "" }
q21624
load
train
function load() { let r; try { r = exports.storage.getItem('debug'); } catch (error) { // Swallow // XXX (@Qix-) should we be logging these? } // If debug isn't set in LS, and we're in Electron, try to load $DEBUG if (!r && typeof process !== 'undefined' && 'env' in process) { r = process.env.DEBUG; } return r; }
javascript
{ "resource": "" }
q21625
useColors
train
function useColors() { return 'colors' in exports.inspectOpts ? Boolean(exports.inspectOpts.colors) : tty.isatty(process.stderr.fd); }
javascript
{ "resource": "" }
q21626
formatArgs
train
function formatArgs(args) { const {namespace: name, useColors} = this; if (useColors) { const c = this.color; const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); const prefix = ` ${colorCode};1m${name} \u001B[0m`; args[0] = prefix + args[0].split('\n').join('\n' + prefix); args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m'); } else { args[0] = getDate() + name + ' ' + args[0]; } }
javascript
{ "resource": "" }
q21627
init
train
function init(debug) { debug.inspectOpts = {}; const keys = Object.keys(exports.inspectOpts); for (let i = 0; i < keys.length; i++) { debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; } }
javascript
{ "resource": "" }
q21628
train
function(Jupyter, kernel) { if (kernel.comm_manager && kernel.widget_manager === undefined) { // Clear any old widget manager if (Jupyter.WidgetManager) { Jupyter.WidgetManager._managers[0].clear_state(); } // Create a new widget manager instance. Use the global // Jupyter.notebook handle. var manager = new mngr.WidgetManager(kernel.comm_manager, Jupyter.notebook); // For backwards compatibility and interactive use. Jupyter.WidgetManager = mngr.WidgetManager; // Store a handle to the manager so we know not to // another for this kernel. This also is a convenience // for the user. kernel.widget_manager = manager; } }
javascript
{ "resource": "" }
q21629
render
train
function render(output, data, node) { // data is a model id var manager = Jupyter.notebook && Jupyter.notebook.kernel && Jupyter.notebook.kernel.widget_manager; if (!manager) { node.textContent = "Error rendering Jupyter widget: missing widget manager"; return; } // Missing model id means the view was removed. Hide this element. if (data.model_id === '') { node.style.display = 'none'; return; } var model = manager.get_model(data.model_id); if (model) { model.then(function(model) { return manager.display_model(void 0, model, {output: output}); }).then(function(view) { var id = view.cid; output._jupyterWidgetViews = output._jupyterWidgetViews || []; output._jupyterWidgetViews.push(id); views[id] = view; PhosphorWidget.Widget.attach(view.pWidget, node); // Make the node completely disappear if the view is removed. view.once('remove', () => { // Since we have a mutable reference to the data, delete the // model id to indicate the view is removed. data.model_id = ''; node.style.display = 'none'; }) }); } else { node.textContent = 'A Jupyter widget could not be displayed because the widget state could not be found. This could happen if the kernel storing the widget is no longer available, or if the widget state was not saved in the notebook. You may be able to create the widget by running the appropriate cells.'; } }
javascript
{ "resource": "" }
q21630
train
function(json, md, element) { var toinsert = this.create_output_subarea(md, CLASS_NAME, MIME_TYPE); this.keyboard_manager.register_events(toinsert); render(this, json, toinsert[0]); element.append(toinsert); return toinsert; }
javascript
{ "resource": "" }
q21631
createWidget
train
function createWidget(widgetType, value, description) { // Create the widget model. return manager.new_model({ model_module: '@jupyter-widgets/controls', model_name: widgetType + 'Model', model_id: 'widget-1' // Create a view for the model. }).then(function(model) { console.log(widgetType + ' model created'); model.set({ description: description || '', value: value, }); return manager.create_view(model); }, console.error.bind(console)) .then(function(view) { console.log(widgetType + ' view created'); manager.display_view(null, view); return view; }, console.error.bind(console)); }
javascript
{ "resource": "" }
q21632
getImports
train
function getImports(sourceFile) { var imports = []; handleNode(sourceFile); function handleNode(node) { switch (node.kind) { case ts.SyntaxKind.ImportDeclaration: imports.push(node.moduleSpecifier.text); break; case ts.SyntaxKind.ImportEqualsDeclaration: imports.push(node.moduleReference.expression.text); break; } ts.forEachChild(node, handleNode); } return imports; }
javascript
{ "resource": "" }
q21633
validate
train
function validate(dname) { var filenames = glob.sync(dname + '/src/*.ts*'); filenames = filenames.concat(glob.sync(dname + '/src/**/*.ts*')); if (filenames.length == 0) { return []; } var imports = []; try { var pkg = require(path.resolve(dname) + '/package.json'); } catch (e) { return []; } var ignore = IGNORE[pkg['name']] || []; var deps = pkg['dependencies']; // Extract all of the imports from the TypeScript files. filenames.forEach(fileName => { var sourceFile = ts.createSourceFile(fileName, readFileSync(fileName).toString(), ts.ScriptTarget.ES6, /*setParentNodes */ true); imports = imports.concat(getImports(sourceFile)); //console.log(fileName, getImports(sourceFile)); }); var names = Array.from(new Set(imports)).sort(); names = names.map(function(name) { var parts = name.split('/'); if (name.indexOf('@') === 0) { return parts[0] + '/' + parts[1]; } return parts[0]; }) var problems = []; names.forEach(function(name) { if (name === '..' || name === '.' || ignore.indexOf(name) !== -1) { return; } if (!deps[name]) { problems.push('Missing package: ' + name); } }); Object.keys(deps).forEach(function(name) { if (versions[name]) { var desired = '^' + versions[name]; if (deps[name] !== desired) { problems.push('Bad core version: ' + name + ' should be ' + desired); } } if (ignore.indexOf(name) !== -1) { return; } if (names.indexOf(name) === -1) { problems.push('Unused package: ' + name); } }); return problems; }
javascript
{ "resource": "" }
q21634
handlePackage
train
function handlePackage(packagePath) { // Read in the package.json. var packagePath = path.join(packagePath, 'package.json'); try { var package = require(packagePath); } catch (e) { console.log('Skipping package ' + packagePath); return; } // Update dependencies as appropriate. if (package.dependencies && target in package['dependencies']) { package['dependencies'][target] = specifier; } else if (package.devDependencies && target in package['devDependencies']) { package['devDependencies'][target] = specifier; } // Write the file back to disk. fs.writeFileSync(packagePath, JSON.stringify(package, null, 2) + '\n'); }
javascript
{ "resource": "" }
q21635
train
function( name, constructor ) { if( typeof constructor !== 'function' ) { throw new Error( 'Please register a constructor function' ); } if( this._components[ name ] !== undefined ) { throw new Error( 'Component ' + name + ' is already registered' ); } this._components[ name ] = constructor; }
javascript
{ "resource": "" }
q21636
train
function() { var config = $.extend( true, {}, this.config ); config.content = []; var next = function( configNode, item ) { var key, i; for( key in item.config ) { if( key !== 'content' ) { configNode[ key ] = item.config[ key ]; } } if( item.contentItems.length ) { configNode.content = []; for( i = 0; i < item.contentItems.length; i++ ) { configNode.content[ i ] = {}; next( configNode.content[ i ], item.contentItems[ i ] ); } } }; next( config, this.root ); return config; }
javascript
{ "resource": "" }
q21637
train
function( name ) { if( this._components[ name ] === undefined ) { throw new lm.errors.ConfigurationError( 'Unknown component ' + name ); } return this._components[ name ]; }
javascript
{ "resource": "" }
q21638
train
function() { if( document.readyState === 'loading' || document.body === null ) { $(document).ready( lm.utils.fnBind( this.init, this )); return; } this._setContainer(); this.dropTargetIndicator = new lm.controls.DropTargetIndicator( this.container ); this.transitionIndicator = new lm.controls.TransitionIndicator(); this.updateSize(); this._create( this.config ); this._bindEvents(); this.isInitialised = true; this.emit( 'initialised' ); }
javascript
{ "resource": "" }
q21639
train
function( config, parent ) { var typeErrorMsg, contentItem; if( typeof config.type !== 'string' ) { throw new lm.errors.ConfigurationError( 'Missing parameter \'type\'', config ); } if( !this._typeToItem[ config.type ] ) { typeErrorMsg = 'Unknown type \'' + config.type + '\'. ' + 'Valid types are ' + lm.utils.objectKeys( this._typeToItem ).join( ',' ); throw new lm.errors.ConfigurationError( typeErrorMsg ); } /** * We add an additional stack around every component that's not within a stack anyways */ if( config.type === 'component' && !( parent instanceof lm.items.Stack ) && !!parent ) { config = { type: 'stack', isClosable: config.isClosable, width: config.width, height: config.height, content: [ config ] }; } contentItem = new this._typeToItem[ config.type ]( this, config, parent ); return contentItem; }
javascript
{ "resource": "" }
q21640
train
function( contentItem, index ) { var tab = new lm.controls.Tab( this, contentItem ); if( this.tabs.length === 0 ) { this.tabs.push( tab ); this.tabsContainer.append( tab.element ); return; } if( index === undefined ) { index = this.tabs.length; } if( index > 0 ) { this.tabs[ index - 1 ].element.after( tab.element ); } else { this.tabs[ 0 ].element.before( tab.element ); } this.tabs.splice( index, 0, tab ); }
javascript
{ "resource": "" }
q21641
train
function( contentItem ) { for( var i = 0; i < this.tabs.length; i++ ) { if( this.tabs[ i ].contentItem === contentItem ) { this.tabs[ i ]._$destroy(); this.tabs.splice( i, 1 ); return; } } throw new Error( 'contentItem is not controlled by this header' ); }
javascript
{ "resource": "" }
q21642
train
function() { var availableWidth = this.element.outerWidth() - this.controlsContainer.outerWidth(), totalTabWidth = 0, tabElement, i, marginLeft, gap; for( i = 0; i < this.tabs.length; i++ ) { tabElement = this.tabs[ i ].element; /* * In order to show every tab's close icon, decrement the z-index from left to right */ tabElement.css( 'z-index', this.tabs.length - i ); totalTabWidth += tabElement.outerWidth() + parseInt( tabElement.css( 'margin-right' ), 10 ); } gap = ( totalTabWidth - availableWidth ) / ( this.tabs.length - 1 ) for( i = 0; i < this.tabs.length; i++ ) { /* * The active tab keeps it's original width */ if( !this.tabs[ i ].isActive && gap > 0 ) { marginLeft = '-' + Math.floor( gap )+ 'px'; } else { marginLeft = ''; } this.tabs[ i ].element.css( 'margin-left', marginLeft ); } if( this.element.outerWidth() < this.tabs[ 0 ].element.outerWidth() ) { this.element.css( 'overflow', 'hidden' ); } else { this.element.css( 'overflow', 'visible' ); } }
javascript
{ "resource": "" }
q21643
train
function( functionName, functionArguments, bottomUp, skipSelf ) { var i; if( bottomUp !== true && skipSelf !== true ) { this[ functionName ].apply( this, functionArguments || [] ); } for( i = 0; i < this.contentItems.length; i++ ) { this.contentItems[ i ].callDownwards( functionName, functionArguments, bottomUp ); } if( bottomUp === true && skipSelf !== true ) { this[ functionName ].apply( this, functionArguments || [] ); } }
javascript
{ "resource": "" }
q21644
train
function( element ) { element = element || this.element; var offset = element.offset(), width = element.width(), height = element.height(); return { x1: offset.left, y1: offset.top, x2: offset.left + width, y2: offset.top + height, surface: width * height, contentItem: this }; }
javascript
{ "resource": "" }
q21645
train
function( name, event ) { if( event instanceof lm.utils.BubblingEvent && event.isPropagationStopped === false && this.isInitialised === true ) { /** * In some cases (e.g. if an element is created from a DragSource) it * doesn't have a parent and is not below root. If that's the case * propagate the bubbling event from the top level of the substree directly * to the layoutManager */ if( this.isRoot === false && this.parent ) { this.parent.emit.apply( this.parent, Array.prototype.slice.call( arguments, 0 ) ); } else { this._scheduleEventPropagationToLayoutManager( name, event ); } } }
javascript
{ "resource": "" }
q21646
train
function( name, event ) { if( lm.utils.indexOf( name, this._throttledEvents ) === -1 ) { this.layoutManager.emit( name, event.origin ); } else { if( this._pendingEventPropagations[ name ] !== true ) { this._pendingEventPropagations[ name ] = true; lm.utils.animFrame( lm.utils.fnBind( this._propagateEventToLayoutManager, this, [ name, event ] ) ); } } }
javascript
{ "resource": "" }
q21647
train
function( oldChild, newChild ) { var size = oldChild.config[ this._dimension ]; lm.items.AbstractContentItem.prototype.replaceChild.call( this, oldChild, newChild ); newChild.config[ this._dimension ] = size; this.callDownwards( 'setSize' ); this.emitBubblingEvent( 'stateChanged' ); }
javascript
{ "resource": "" }
q21648
train
function() { if( this.isInitialised === true ) return; var i; lm.items.AbstractContentItem.prototype._$init.call( this ); for( i = 0; i < this.contentItems.length - 1; i++ ) { this.contentItems[ i ].element.after( this._createSplitter( i ).element ); } }
javascript
{ "resource": "" }
q21649
train
function( splitter ) { var index = lm.utils.indexOf( splitter, this._splitter ); return { before: this.contentItems[ index ], after: this.contentItems[ index + 1 ] }; }
javascript
{ "resource": "" }
q21650
train
function( splitter, offsetX, offsetY ) { var offset = this._isColumn ? offsetY : offsetX; if( offset > this._splitterMinPosition && offset < this._splitterMaxPosition ) { this._splitterPosition = offset; splitter.element.css( this._isColumn ? 'top' : 'left', offset ); } }
javascript
{ "resource": "" }
q21651
train
function( splitter ) { var items = this._getItemsForSplitter( splitter ), sizeBefore = items.before.element[ this._dimension ](), sizeAfter = items.after.element[ this._dimension ](), splitterPositionInRange = ( this._splitterPosition + sizeBefore ) / ( sizeBefore + sizeAfter ), totalRelativeSize = items.before.config[ this._dimension ] + items.after.config[ this._dimension ]; items.before.config[ this._dimension ] = splitterPositionInRange * totalRelativeSize; items.after.config[ this._dimension ] = ( 1 - splitterPositionInRange ) * totalRelativeSize; splitter.element.css({ 'top': 0, 'left': 0 }); lm.utils.animFrame( lm.utils.fnBind( this.callDownwards, this, [ 'setSize' ] ) ); }
javascript
{ "resource": "" }
q21652
train
function( root ) { var config, next, i; if( this.isInitialised === false ) { throw new Error( 'Can\'t create config, layout not yet initialised' ); } if( root && !( root instanceof lm.items.AbstractContentItem ) ) { throw new Error( 'Root must be a ContentItem' ); } /* * settings & labels */ config = { settings: lm.utils.copy( {}, this.config.settings ), dimensions: lm.utils.copy( {}, this.config.dimensions ), labels: lm.utils.copy( {}, this.config.labels ) }; /* * Content */ config.content = []; next = function( configNode, item ) { var key, i; for( key in item.config ) { if( key !== 'content' ) { configNode[ key ] = item.config[ key ]; } } if( item.contentItems.length ) { configNode.content = []; for( i = 0; i < item.contentItems.length; i++ ) { configNode.content[ i ] = {}; next( configNode.content[ i ], item.contentItems[ i ] ); } } }; if( root ) { next( config, { contentItems: [ root ] } ); } else { next( config, this.root ); } /* * Retrieve config for subwindows */ this._$reconcilePopoutWindows(); config.openPopouts = []; for( i = 0; i < this.openPopouts.length; i++ ) { config.openPopouts.push( this.openPopouts[ i ].toConfig() ); } /* * Add maximised item */ config.maximisedItemId = this._maximisedItem ? '__glMaximised' : null; return config; }
javascript
{ "resource": "" }
q21653
train
function() { /** * Create the popout windows straight away. If popouts are blocked * an error is thrown on the same 'thread' rather than a timeout and can * be caught. This also prevents any further initilisation from taking place. */ if( this._subWindowsCreated === false ) { this._createSubWindows(); this._subWindowsCreated = true; } /** * If the document isn't ready yet, wait for it. */ if( document.readyState === 'loading' || document.body === null ) { $( document ).ready( lm.utils.fnBind( this.init, this ) ); return; } /** * If this is a subwindow, wait a few milliseconds for the original * page's js calls to be executed, then replace the bodies content * with GoldenLayout */ if( this.isSubWindow === true && this._creationTimeoutPassed === false ) { setTimeout( lm.utils.fnBind( this.init, this ), 7 ); this._creationTimeoutPassed = true; return; } if( this.isSubWindow === true ) { this._adjustToWindowMode(); } this._setContainer(); this.dropTargetIndicator = new lm.controls.DropTargetIndicator( this.container ); this.transitionIndicator = new lm.controls.TransitionIndicator(); this.updateSize(); this._create( this.config ); this._bindEvents(); this.isInitialised = true; this._adjustColumnsResponsive(); this.emit( 'initialised' ); }
javascript
{ "resource": "" }
q21654
train
function( config, parent ) { var typeErrorMsg, contentItem; if( typeof config.type !== 'string' ) { throw new lm.errors.ConfigurationError( 'Missing parameter \'type\'', config ); } if( config.type === 'react-component' ) { config.type = 'component'; config.componentName = 'lm-react-component'; } if( !this._typeToItem[ config.type ] ) { typeErrorMsg = 'Unknown type \'' + config.type + '\'. ' + 'Valid types are ' + lm.utils.objectKeys( this._typeToItem ).join( ',' ); throw new lm.errors.ConfigurationError( typeErrorMsg ); } /** * We add an additional stack around every component that's not within a stack anyways. */ if( // If this is a component config.type === 'component' && // and it's not already within a stack !( parent instanceof lm.items.Stack ) && // and we have a parent !!parent && // and it's not the topmost item in a new window !( this.isSubWindow === true && parent instanceof lm.items.Root ) ) { config = { type: 'stack', width: config.width, height: config.height, content: [ config ] }; } contentItem = new this._typeToItem[ config.type ]( this, config, parent ); return contentItem; }
javascript
{ "resource": "" }
q21655
train
function( configOrContentItem, dimensions, parentId, indexInParent ) { var config = configOrContentItem, isItem = configOrContentItem instanceof lm.items.AbstractContentItem, self = this, windowLeft, windowTop, offset, parent, child, browserPopout; parentId = parentId || null; if( isItem ) { config = this.toConfig( configOrContentItem ).content; parentId = lm.utils.getUniqueId(); /** * If the item is the only component within a stack or for some * other reason the only child of its parent the parent will be destroyed * when the child is removed. * * In order to support this we move up the tree until we find something * that will remain after the item is being popped out */ parent = configOrContentItem.parent; child = configOrContentItem; while( parent.contentItems.length === 1 && !parent.isRoot ) { parent = parent.parent; child = child.parent; } parent.addId( parentId ); if( isNaN( indexInParent ) ) { indexInParent = lm.utils.indexOf( child, parent.contentItems ); } } else { if( !( config instanceof Array ) ) { config = [ config ]; } } if( !dimensions && isItem ) { windowLeft = window.screenX || window.screenLeft; windowTop = window.screenY || window.screenTop; offset = configOrContentItem.element.offset(); dimensions = { left: windowLeft + offset.left, top: windowTop + offset.top, width: configOrContentItem.element.width(), height: configOrContentItem.element.height() }; } if( !dimensions && !isItem ) { dimensions = { left: window.screenX || window.screenLeft + 20, top: window.screenY || window.screenTop + 20, width: 500, height: 309 }; } if( isItem ) { configOrContentItem.remove(); } browserPopout = new lm.controls.BrowserPopout( config, dimensions, parentId, indexInParent, this ); browserPopout.on( 'initialised', function() { self.emit( 'windowOpened', browserPopout ); } ); browserPopout.on( 'closed', function() { self._$reconcilePopoutWindows(); } ); this.openPopouts.push( browserPopout ); return browserPopout; }
javascript
{ "resource": "" }
q21656
train
function( contentItemOrConfig, parent ) { if( !contentItemOrConfig ) { throw new Error( 'No content item defined' ); } if( lm.utils.isFunction( contentItemOrConfig ) ) { contentItemOrConfig = contentItemOrConfig(); } if( contentItemOrConfig instanceof lm.items.AbstractContentItem ) { return contentItemOrConfig; } if( $.isPlainObject( contentItemOrConfig ) && contentItemOrConfig.type ) { var newContentItem = this.createContentItem( contentItemOrConfig, parent ); newContentItem.callDownwards( '_$init' ); return newContentItem; } else { throw new Error( 'Invalid contentItem' ); } }
javascript
{ "resource": "" }
q21657
train
function() { var popInButton = $( '<div class="lm_popin" title="' + this.config.labels.popin + '">' + '<div class="lm_icon"></div>' + '<div class="lm_bg"></div>' + '</div>' ); popInButton.on( 'click', lm.utils.fnBind( function() { this.emit( 'popIn' ); }, this ) ); document.title = lm.utils.stripTags( this.config.content[ 0 ].title ); $( 'head' ).append( $( 'body link, body style, template, .gl_keep' ) ); this.container = $( 'body' ) .html( '' ) .css( 'visibility', 'visible' ) .append( popInButton ); /* * This seems a bit pointless, but actually causes a reflow/re-evaluation getting around * slickgrid's "Cannot find stylesheet." bug in chrome */ var x = document.body.offsetHeight; // jshint ignore:line /* * Expose this instance on the window object * to allow the opening window to interact with * it */ window.__glInstance = this; }
javascript
{ "resource": "" }
q21658
train
function() { if( this.config.settings.closePopoutsOnUnload === true ) { for( var i = 0; i < this.openPopouts.length; i++ ) { this.openPopouts[ i ].close(); } } }
javascript
{ "resource": "" }
q21659
train
function() { // If there is no min width set, or not content items, do nothing. if( !this._useResponsiveLayout() || this._updatingColumnsResponsive || !this.config.dimensions || !this.config.dimensions.minItemWidth || this.root.contentItems.length === 0 || !this.root.contentItems[ 0 ].isRow ) { this._firstLoad = false; return; } this._firstLoad = false; // If there is only one column, do nothing. var columnCount = this.root.contentItems[ 0 ].contentItems.length; if( columnCount <= 1 ) { return; } // If they all still fit, do nothing. var minItemWidth = this.config.dimensions.minItemWidth; var totalMinWidth = columnCount * minItemWidth; if( totalMinWidth <= this.width ) { return; } // Prevent updates while it is already happening. this._updatingColumnsResponsive = true; // Figure out how many columns to stack, and put them all in the first stack container. var finalColumnCount = Math.max( Math.floor( this.width / minItemWidth ), 1 ); var stackColumnCount = columnCount - finalColumnCount; var rootContentItem = this.root.contentItems[ 0 ]; var firstStackContainer = this._findAllStackContainers()[ 0 ]; for( var i = 0; i < stackColumnCount; i++ ) { // Stack from right. var column = rootContentItem.contentItems[ rootContentItem.contentItems.length - 1 ]; this._addChildContentItemsToContainer( firstStackContainer, column ); } this._updatingColumnsResponsive = false; }
javascript
{ "resource": "" }
q21660
train
function( container, node ) { if( node.type === 'stack' ) { node.contentItems.forEach( function( item ) { container.addChild( item ); node.removeChild( item, true ); } ); } else { node.contentItems.forEach( lm.utils.fnBind( function( item ) { this._addChildContentItemsToContainer( container, item ); }, this ) ); } }
javascript
{ "resource": "" }
q21661
train
function( stackContainers, node ) { node.contentItems.forEach( lm.utils.fnBind( function( item ) { if( item.type == 'stack' ) { stackContainers.push( item ); } else if( !item.isComponent ) { this._findAllStackContainersRecursive( stackContainers, item ); } }, this ) ); }
javascript
{ "resource": "" }
q21662
train
function() { var contentItem, isClosable, len, i; isClosable = this.header._isClosable(); for( i = 0, len = this.contentItems.length; i < len; i++ ) { if( !isClosable ) { break; } isClosable = this.contentItems[ i ].config.isClosable; } this.header._$setClosable( isClosable ); }
javascript
{ "resource": "" }
q21663
train
function( x, y ) { var segment, area; for( segment in this._contentAreaDimensions ) { area = this._contentAreaDimensions[ segment ].hoverArea; if( area.x1 < x && area.x2 > x && area.y1 < y && area.y2 > y ) { if( segment === 'header' ) { this._dropSegment = 'header'; this._highlightHeaderDropZone( this._sided ? y : x ); } else { this._resetHeaderDropZone(); this._highlightBodyDropZone( segment ); } return; } } }
javascript
{ "resource": "" }
q21664
train
function( e ) { e && e.preventDefault(); if( this.isMaximised === true ) { this.layoutManager._$minimiseItem( this ); } else { this.layoutManager._$maximiseItem( this ); } this.isMaximised = !this.isMaximised; this.emitBubblingEvent( 'stateChanged' ); }
javascript
{ "resource": "" }
q21665
train
function( id ) { if( !this.config.id ) { return false; } else if( typeof this.config.id === 'string' ) { return this.config.id === id; } else if( this.config.id instanceof Array ) { return lm.utils.indexOf( id, this.config.id ) !== -1; } }
javascript
{ "resource": "" }
q21666
train
function( id ) { if( !this.hasId( id ) ) { throw new Error( 'Id not found' ); } if( typeof this.config.id === 'string' ) { delete this.config.id; } else if( this.config.id instanceof Array ) { var index = lm.utils.indexOf( id, this.config.id ); this.config.id.splice( index, 1 ); } }
javascript
{ "resource": "" }
q21667
train
function() { var childConfig, parentItem, index = this._indexInParent; if( this._parentId ) { /* * The $.extend call seems a bit pointless, but it's crucial to * copy the config returned by this.getGlInstance().toConfig() * onto a new object. Internet Explorer keeps the references * to objects on the child window, resulting in the following error * once the child window is closed: * * The callee (server [not server application]) is not available and disappeared */ childConfig = $.extend( true, {}, this.getGlInstance().toConfig() ).content[ 0 ]; parentItem = this._layoutManager.root.getItemsById( this._parentId )[ 0 ]; /* * Fallback if parentItem is not available. Either add it to the topmost * item or make it the topmost item if the layout is empty */ if( !parentItem ) { if( this._layoutManager.root.contentItems.length > 0 ) { parentItem = this._layoutManager.root.contentItems[ 0 ]; } else { parentItem = this._layoutManager.root; } index = 0; } } parentItem.addChild( childConfig, this._indexInParent ); this.close(); }
javascript
{ "resource": "" }
q21668
train
function() { var checkReadyInterval, url = this._createUrl(), /** * Bogus title to prevent re-usage of existing window with the * same title. The actual title will be set by the new window's * GoldenLayout instance if it detects that it is in subWindowMode */ title = Math.floor( Math.random() * 1000000 ).toString( 36 ), /** * The options as used in the window.open string */ options = this._serializeWindowOptions( { width: this._dimensions.width, height: this._dimensions.height, innerWidth: this._dimensions.width, innerHeight: this._dimensions.height, menubar: 'no', toolbar: 'no', location: 'no', personalbar: 'no', resizable: 'yes', scrollbars: 'no', status: 'no' } ); this._popoutWindow = window.open( url, title, options ); if( !this._popoutWindow ) { if( this._layoutManager.config.settings.blockedPopoutsThrowError === true ) { var error = new Error( 'Popout blocked' ); error.type = 'popoutBlocked'; throw error; } else { return; } } $( this._popoutWindow ) .on( 'load', lm.utils.fnBind( this._positionWindow, this ) ) .on( 'unload beforeunload', lm.utils.fnBind( this._onClose, this ) ); /** * Polling the childwindow to find out if GoldenLayout has been initialised * doesn't seem optimal, but the alternatives - adding a callback to the parent * window or raising an event on the window object - both would introduce knowledge * about the parent to the child window which we'd rather avoid */ checkReadyInterval = setInterval( lm.utils.fnBind( function() { if( this._popoutWindow.__glInstance && this._popoutWindow.__glInstance.isInitialised ) { this._onInitialised(); clearInterval( checkReadyInterval ); } }, this ), 10 ); }
javascript
{ "resource": "" }
q21669
train
function() { var config = { content: this._config }, storageKey = 'gl-window-config-' + lm.utils.getUniqueId(), urlParts; config = ( new lm.utils.ConfigMinifier() ).minifyConfig( config ); try { localStorage.setItem( storageKey, JSON.stringify( config ) ); } catch( e ) { throw new Error( 'Error while writing to localStorage ' + e.toString() ); } urlParts = document.location.href.split( '?' ); // URL doesn't contain GET-parameters if( urlParts.length === 1 ) { return urlParts[ 0 ] + '?gl-window=' + storageKey; // URL contains GET-parameters } else { return document.location.href + '&gl-window=' + storageKey; } }
javascript
{ "resource": "" }
q21670
train
function( form ) { var inputGroups = form.find( '.inputGroup' ), isValid = true, inputGroup, i; for( i = 0; i < inputGroups.length; i++ ) { inputGroup = $( inputGroups[ i ] ); if( $.trim( inputGroup.find( 'input' ).val() ).length === 0 ) { inputGroup.addClass( 'error' ); isValid = false; } else { inputGroup.removeClass( 'error' ); } } return isValid; }
javascript
{ "resource": "" }
q21671
train
function( offsetX, offsetY, event ) { event = event.originalEvent && event.originalEvent.touches ? event.originalEvent.touches[ 0 ] : event; var x = event.pageX, y = event.pageY, isWithinContainer = x > this._minX && x < this._maxX && y > this._minY && y < this._maxY; if( !isWithinContainer && this._layoutManager.config.settings.constrainDragToContainer === true ) { return; } this._setDropPosition( x, y ); }
javascript
{ "resource": "" }
q21672
train
function( x, y ) { this.element.css( { left: x, top: y } ); this._area = this._layoutManager._$getArea( x, y ); if( this._area !== null ) { this._lastValidArea = this._area; this._area.contentItem._$highlightDropZone( x, y, this._area ); } }
javascript
{ "resource": "" }
q21673
train
function() { var dimensions = this._layoutManager.config.dimensions, width = dimensions.dragProxyWidth, height = dimensions.dragProxyHeight; this.element.width( width ); this.element.height( height ); width -= ( this._sided ? dimensions.headerHeight : 0 ); height -= ( !this._sided ? dimensions.headerHeight : 0 ); this.childElementContainer.width( width ); this.childElementContainer.height( height ); this._contentItem.element.width( width ); this._contentItem.element.height( height ); this._contentItem.callDownwards( '_$show' ); this._contentItem.callDownwards( 'setSize' ); }
javascript
{ "resource": "" }
q21674
train
function( position ) { var previous = this.parent._header.show; if( this.parent._docker && this.parent._docker.docked ) throw new Error( 'Can\'t change header position in docked stack' ); if( previous && !this.parent._side ) previous = 'top'; if( position !== undefined && this.parent._header.show != position ) { this.parent._header.show = position; this.parent.config.header ? this.parent.config.header.show = position : this.parent.config.header = { show:position }; this.parent._setupHeaderPosition(); } return previous; }
javascript
{ "resource": "" }
q21675
train
function( isClosable ) { this._canDestroy = isClosable || this.tabs.length > 1; if( this.closeButton && this._isClosable() ) { this.closeButton.element[ isClosable ? "show" : "hide" ](); return true; } return false; }
javascript
{ "resource": "" }
q21676
train
function( isDockable ) { if ( this.dockButton && this.parent._header && this.parent._header.dock ) { this.dockButton.element.toggle( !!isDockable ); return true; } return false; }
javascript
{ "resource": "" }
q21677
train
function() { ReactDOM.unmountComponentAtNode( this._container.getElement()[ 0 ] ); this._container.off( 'open', this._render, this ); this._container.off( 'destroy', this._destroy, this ); }
javascript
{ "resource": "" }
q21678
train
function( nextProps, nextState ) { this._container.setState( nextState ); this._originalComponentWillUpdate.call( this._reactComponent, nextProps, nextState ); }
javascript
{ "resource": "" }
q21679
train
function() { var componentName = this._container._config.component; var reactClass; if( !componentName ) { throw new Error( 'No react component name. type: react-component needs a field `component`' ); } reactClass = this._container.layoutManager.getComponent( componentName ); if( !reactClass ) { throw new Error( 'React component "' + componentName + '" not found. ' + 'Please register all components with GoldenLayout using `registerComponent(name, component)`' ); } return reactClass; }
javascript
{ "resource": "" }
q21680
train
function() { var defaultProps = { glEventHub: this._container.layoutManager.eventHub, glContainer: this._container, ref: this._gotReactComponent.bind( this ) }; var props = $.extend( defaultProps, this._container._config.props ); return React.createElement( this._reactClass, props ); }
javascript
{ "resource": "" }
q21681
train
function( contentItem, index, _$suspendResize ) { var newItemSize, itemSize, i, splitterElement; contentItem = this.layoutManager._$normalizeContentItem( contentItem, this ); if( index === undefined ) { index = this.contentItems.length; } if( this.contentItems.length > 0 ) { splitterElement = this._createSplitter( Math.max( 0, index - 1 ) ).element; if( index > 0 ) { this.contentItems[ index - 1 ].element.after( splitterElement ); splitterElement.after( contentItem.element ); if ( this._isDocked( index - 1 ) ) { this._splitter[ index - 1 ].element.hide(); this._splitter[ index ].element.show(); } } else { this.contentItems[ 0 ].element.before( splitterElement ); splitterElement.before( contentItem.element ); } } else { this.childElementContainer.append( contentItem.element ); } lm.items.AbstractContentItem.prototype.addChild.call( this, contentItem, index ); newItemSize = ( 1 / this.contentItems.length ) * 100; if( _$suspendResize === true ) { this.emitBubblingEvent( 'stateChanged' ); return; } for( i = 0; i < this.contentItems.length; i++ ) { if( this.contentItems[ i ] === contentItem ) { contentItem.config[ this._dimension ] = newItemSize; } else { itemSize = this.contentItems[ i ].config[ this._dimension ] *= ( 100 - newItemSize ) / 100; this.contentItems[ i ].config[ this._dimension ] = itemSize; } } this.callDownwards( 'setSize' ); this.emitBubblingEvent( 'stateChanged' ); this._validateDocking(); }
javascript
{ "resource": "" }
q21682
train
function() { if( this.isInitialised === true ) return; var i; lm.items.AbstractContentItem.prototype._$init.call( this ); for( i = 0; i < this.contentItems.length - 1; i++ ) { this.contentItems[ i ].element.after( this._createSplitter( i ).element ); } for( i = 0; i < this.contentItems.length; i++ ) { if( this.contentItems[ i ]._header && this.contentItems[ i ]._header.docked ) this.dock( this.contentItems[ i ], true, true ); } }
javascript
{ "resource": "" }
q21683
train
function() { var i, totalSplitterSize = (this.contentItems.length - 1) * this._splitterSize, headerSize = this.layoutManager.config.dimensions.headerHeight, totalWidth = this.element.width(), totalHeight = this.element.height(), totalAssigned = 0, additionalPixel, itemSize, itemSizes = []; if( this._isColumn ) { totalHeight -= totalSplitterSize; } else { totalWidth -= totalSplitterSize; } for( i = 0; i < this.contentItems.length; i++ ) { if( this._isDocked( i ) ) if( this._isColumn ) { totalHeight -= headerSize - this._splitterSize; } else { totalWidth -= headerSize - this._splitterSize; } } for( i = 0; i < this.contentItems.length; i++ ) { if( this._isColumn ) { itemSize = Math.floor( totalHeight * ( this.contentItems[ i ].config.height / 100 ) ); } else { itemSize = Math.floor( totalWidth * (this.contentItems[ i ].config.width / 100) ); } if( this._isDocked( i ) ) itemSize = headerSize; totalAssigned += itemSize; itemSizes.push( itemSize ); } additionalPixel = Math.floor( (this._isColumn ? totalHeight : totalWidth) - totalAssigned ); return { itemSizes: itemSizes, additionalPixel: additionalPixel, totalWidth: totalWidth, totalHeight: totalHeight }; }
javascript
{ "resource": "" }
q21684
train
function() { var minItemWidth = this.layoutManager.config.dimensions ? (this.layoutManager.config.dimensions.minItemWidth || 0) : 0, sizeData = null, entriesOverMin = [], totalOverMin = 0, totalUnderMin = 0, remainingWidth = 0, itemSize = 0, contentItem = null, reducePercent, reducedWidth, allEntries = [], entry; if( this._isColumn || !minItemWidth || this.contentItems.length <= 1 ) { return; } sizeData = this._calculateAbsoluteSizes(); /** * Figure out how much we are under the min item size total and how much room we have to use. */ for( var i = 0; i < this.contentItems.length; i++ ) { contentItem = this.contentItems[ i ]; itemSize = sizeData.itemSizes[ i ]; if( itemSize < minItemWidth ) { totalUnderMin += minItemWidth - itemSize; entry = { width: minItemWidth }; } else { totalOverMin += itemSize - minItemWidth; entry = { width: itemSize }; entriesOverMin.push( entry ); } allEntries.push( entry ); } /** * If there is nothing under min, or there is not enough over to make up the difference, do nothing. */ if( totalUnderMin === 0 || totalUnderMin > totalOverMin ) { return; } /** * Evenly reduce all columns that are over the min item width to make up the difference. */ reducePercent = totalUnderMin / totalOverMin; remainingWidth = totalUnderMin; for( i = 0; i < entriesOverMin.length; i++ ) { entry = entriesOverMin[ i ]; reducedWidth = Math.round( ( entry.width - minItemWidth ) * reducePercent ); remainingWidth -= reducedWidth; entry.width -= reducedWidth; } /** * Take anything remaining from the last item. */ if( remainingWidth !== 0 ) { allEntries[ allEntries.length - 1 ].width -= remainingWidth; } /** * Set every items size relative to 100 relative to its size to total */ for( i = 0; i < this.contentItems.length; i++ ) { this.contentItems[ i ].config.width = (allEntries[ i ].width / sizeData.totalWidth) * 100; } }
javascript
{ "resource": "" }
q21685
train
function( index ) { var splitter; splitter = new lm.controls.Splitter( this._isColumn, this._splitterSize, this._splitterGrabSize ); splitter.on( 'drag', lm.utils.fnBind( this._onSplitterDrag, this, [ splitter ] ), this ); splitter.on( 'dragStop', lm.utils.fnBind( this._onSplitterDragStop, this, [ splitter ] ), this ); splitter.on( 'dragStart', lm.utils.fnBind( this._onSplitterDragStart, this, [ splitter ] ), this ); this._splitter.splice( index, 0, splitter ); return splitter; }
javascript
{ "resource": "" }
q21686
train
function ( index ) { if ( typeof index == 'undefined' ) { var count = 0; for (var i = 0; i < this.contentItems.length; ++i) if ( this._isDocked( i ) ) count++; return count; } if ( index < this.contentItems.length ) return this.contentItems[ index ]._docker && this.contentItems[ index ]._docker.docked; }
javascript
{ "resource": "" }
q21687
train
function ( that ) { that = that || this; var can = that.contentItems.length - that._isDocked() > 1; for (var i = 0; i < that.contentItems.length; ++i ) if ( that.contentItems[ i ] instanceof lm.items.Stack ) { that.contentItems[ i ].header._setDockable( that._isDocked( i ) || can ); that.contentItems[ i ].header._$setClosable( can ); } }
javascript
{ "resource": "" }
q21688
train
function( arr ) { var minWidth = 0, minHeight = 0; for( var i = 0; i < arr.length; ++i ) { minWidth = Math.max( arr[ i ].minWidth || 0, minWidth ); minHeight = Math.max( arr[ i ].minHeight || 0, minHeight ); } return { horizontal: minWidth, vertical: minHeight }; }
javascript
{ "resource": "" }
q21689
train
function() { this.element.off( 'mousedown touchstart', this._onTabClickFn ); this.closeElement.off( 'click touchstart', this._onCloseClickFn ); if( this._dragListener ) { this.contentItem.off( 'destroy', this._dragListener.destroy, this._dragListener ); this._dragListener.off( 'dragStart', this._onDragStart ); this._dragListener = null; } this.element.remove(); }
javascript
{ "resource": "" }
q21690
train
function( x, y ) { if( !this.header._canDestroy ) return null; if( this.contentItem.parent.isMaximised === true ) { this.contentItem.parent.toggleMaximise(); } new lm.controls.DragProxy( x, y, this._dragListener, this._layoutManager, this.contentItem, this.header.parent ); }
javascript
{ "resource": "" }
q21691
train
function( event ) { // left mouse button or tap if( event.button === 0 || event.type === 'touchstart' ) { this.header.parent.setActiveContentItem( this.contentItem ); // middle mouse button } else if( event.button === 1 && this.contentItem.config.isClosable ) { this._onCloseClick( event ); } }
javascript
{ "resource": "" }
q21692
updateStepAboveIO
train
function updateStepAboveIO() { io.stepAbove = stepEl.map((el, i) => { const marginTop = -offsetMargin + stepOffsetHeight[i]; const marginBottom = offsetMargin - viewH; const rootMargin = `${marginTop}px 0px ${marginBottom}px 0px`; const options = { rootMargin }; // console.log(options); const obs = new IntersectionObserver(intersectStepAbove, options); obs.observe(el); return obs; }); }
javascript
{ "resource": "" }
q21693
updateStepProgressIO
train
function updateStepProgressIO() { io.stepProgress = stepEl.map((el, i) => { const marginTop = stepOffsetHeight[i] - offsetMargin; const marginBottom = -viewH + offsetMargin; const rootMargin = `${marginTop}px 0px ${marginBottom}px 0px`; const threshold = createThreshold(stepOffsetHeight[i]); const options = { rootMargin, threshold }; // console.log(options); const obs = new IntersectionObserver(intersectStepProgress, options); obs.observe(el); return obs; }); }
javascript
{ "resource": "" }
q21694
train
function(model) { this.localStorage().setItem(this.name+"-"+model.id, JSON.stringify(model)); if (!_.include(this.records, model.id.toString())) this.records.push(model.id.toString()); this.save(); return this.find(model); }
javascript
{ "resource": "" }
q21695
train
function() { return _(this.records).chain() .map(function(id){ return this.jsonData(this.localStorage().getItem(this.name+"-"+id)); }, this) .compact() .value(); }
javascript
{ "resource": "" }
q21696
train
function(model) { if (model.isNew()) return false this.localStorage().removeItem(this.name+"-"+model.id); this.records = _.reject(this.records, function(id){ return id === model.id.toString(); }); this.save(); return model; }
javascript
{ "resource": "" }
q21697
train
function (name, data, o) { // be sure sub folders exist var parent = parentFolder(name), dataType = JSZip.utils.getTypeOf(data); if (parent) { folderAdd.call(this, parent); } o = prepareFileAttrs(o); if (o.dir || data === null || typeof data === "undefined") { o.base64 = false; o.binary = false; data = null; } else if (dataType === "string") { if (o.binary && !o.base64) { // optimizedBinaryString == true means that the file has already been filtered with a 0xFF mask if (o.optimizedBinaryString !== true) { // this is a string, not in a base64 format. // Be sure that this is a correct "binary string" data = JSZip.utils.string2binary(data); } } } else { // arraybuffer, uint8array, ... o.base64 = false; o.binary = true; if (!dataType && !(data instanceof JSZip.CompressedObject)) { throw new Error("The data of '" + name + "' is in an unsupported format !"); } // special case : it's way easier to work with Uint8Array than with ArrayBuffer if (dataType === "arraybuffer") { data = JSZip.utils.transformTo("uint8array", data); } } return this.files[name] = new ZipObject(name, data, o); }
javascript
{ "resource": "" }
q21698
train
function (file, compression) { var result = new JSZip.CompressedObject(), content; // the data has not been decompressed, we might reuse things ! if (file._data instanceof JSZip.CompressedObject) { result.uncompressedSize = file._data.uncompressedSize; result.crc32 = file._data.crc32; if (result.uncompressedSize === 0 || file.options.dir) { compression = JSZip.compressions['STORE']; result.compressedContent = ""; result.crc32 = 0; } else if (file._data.compressionMethod === compression.magic) { result.compressedContent = file._data.getCompressedContent(); } else { content = file._data.getContent() // need to decompress / recompress result.compressedContent = compression.compress(JSZip.utils.transformTo(compression.compressInputType, content)); } } else { // have uncompressed data content = getBinaryData(file); if (!content || content.length === 0 || file.options.dir) { compression = JSZip.compressions['STORE']; content = ""; } result.uncompressedSize = content.length; result.crc32 = this.crc32(content); result.compressedContent = compression.compress(JSZip.utils.transformTo(compression.compressInputType, content)); } result.compressedSize = result.compressedContent.length; result.compressionMethod = compression.magic; return result; }
javascript
{ "resource": "" }
q21699
train
function(name, file, compressedObject, offset) { var data = compressedObject.compressedContent, utfEncodedFileName = this.utf8encode(file.name), useUTF8 = utfEncodedFileName !== file.name, o = file.options, dosTime, dosDate; // date // @see http://www.delorie.com/djgpp/doc/rbinter/it/52/13.html // @see http://www.delorie.com/djgpp/doc/rbinter/it/65/16.html // @see http://www.delorie.com/djgpp/doc/rbinter/it/66/16.html dosTime = o.date.getHours(); dosTime = dosTime << 6; dosTime = dosTime | o.date.getMinutes(); dosTime = dosTime << 5; dosTime = dosTime | o.date.getSeconds() / 2; dosDate = o.date.getFullYear() - 1980; dosDate = dosDate << 4; dosDate = dosDate | (o.date.getMonth() + 1); dosDate = dosDate << 5; dosDate = dosDate | o.date.getDate(); var header = ""; // version needed to extract header += "\x0A\x00"; // general purpose bit flag // set bit 11 if utf8 header += useUTF8 ? "\x00\x08" : "\x00\x00"; // compression method header += compressedObject.compressionMethod; // last mod file time header += decToHex(dosTime, 2); // last mod file date header += decToHex(dosDate, 2); // crc-32 header += decToHex(compressedObject.crc32, 4); // compressed size header += decToHex(compressedObject.compressedSize, 4); // uncompressed size header += decToHex(compressedObject.uncompressedSize, 4); // file name length header += decToHex(utfEncodedFileName.length, 2); // extra field length header += "\x00\x00"; var fileRecord = JSZip.signature.LOCAL_FILE_HEADER + header + utfEncodedFileName; var dirRecord = JSZip.signature.CENTRAL_FILE_HEADER + // version made by (00: DOS) "\x14\x00" + // file header (common to file and central directory) header + // file comment length "\x00\x00" + // disk number start "\x00\x00" + // internal file attributes TODO "\x00\x00" + // external file attributes (file.options.dir===true?"\x10\x00\x00\x00":"\x00\x00\x00\x00")+ // relative offset of local header decToHex(offset, 4) + // file name utfEncodedFileName; return { fileRecord : fileRecord, dirRecord : dirRecord, compressedObject : compressedObject }; }
javascript
{ "resource": "" }