_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q18500
train
function (event, query, handler, context) { return on(this, event, query, handler, context, false); }
javascript
{ "resource": "" }
q18501
train
function (event, handler) { var _h = this._$handlers; if (!event) { this._$handlers = {}; return this; } if (handler) { if (_h[event]) { var newList = []; for (var i = 0, l = _h[event].length; i < l; i++) { if (_h[event][i].h !== handler) { newList.push(_h[event][i]); } } _h[event] = newList; } if (_h[event] && _h[event].length === 0) { delete _h[event]; } } else { delete _h[event]; } return this; }
javascript
{ "resource": "" }
q18502
train
function (type) { var _h = this._$handlers[type]; var eventProcessor = this._$eventProcessor; if (_h) { var args = arguments; var argLen = args.length; if (argLen > 3) { args = arrySlice.call(args, 1); } var len = _h.length; for (var i = 0; i < len;) { var hItem = _h[i]; if (eventProcessor && eventProcessor.filter && hItem.query != null && !eventProcessor.filter(type, hItem.query) ) { i++; continue; } // Optimize advise from backbone switch (argLen) { case 1: hItem.h.call(hItem.ctx); break; case 2: hItem.h.call(hItem.ctx, args[1]); break; case 3: hItem.h.call(hItem.ctx, args[1], args[2]); break; default: // have more than 2 given arguments hItem.h.apply(hItem.ctx, args); break; } if (hItem.one) { _h.splice(i, 1); len--; } else { i++; } } } eventProcessor && eventProcessor.afterTrigger && eventProcessor.afterTrigger(type); return this; }
javascript
{ "resource": "" }
q18503
train
function (event) { event = normalizeEvent(this.dom, event); var element = event.toElement || event.relatedTarget; if (element !== this.dom) { while (element && element.nodeType !== 9) { // 忽略包含在root中的dom引起的mouseOut if (element === this.dom) { return; } element = element.parentNode; } } this.trigger('mouseout', event); }
javascript
{ "resource": "" }
q18504
train
function (x1, y1, x2, y2, x3, y3) { var dashSum = this._dashSum; var offset = this._dashOffset; var lineDash = this._lineDash; var ctx = this._ctx; var x0 = this._xi; var y0 = this._yi; var t; var dx; var dy; var cubicAt = curve.cubicAt; var bezierLen = 0; var idx = this._dashIdx; var nDash = lineDash.length; var x; var y; var tmpLen = 0; if (offset < 0) { // Convert to positive offset offset = dashSum + offset; } offset %= dashSum; // Bezier approx length for (t = 0; t < 1; t += 0.1) { dx = cubicAt(x0, x1, x2, x3, t + 0.1) - cubicAt(x0, x1, x2, x3, t); dy = cubicAt(y0, y1, y2, y3, t + 0.1) - cubicAt(y0, y1, y2, y3, t); bezierLen += mathSqrt(dx * dx + dy * dy); } // Find idx after add offset for (; idx < nDash; idx++) { tmpLen += lineDash[idx]; if (tmpLen > offset) { break; } } t = (tmpLen - offset) / bezierLen; while (t <= 1) { x = cubicAt(x0, x1, x2, x3, t); y = cubicAt(y0, y1, y2, y3, t); // Use line to approximate dashed bezier // Bad result if dash is long idx % 2 ? ctx.moveTo(x, y) : ctx.lineTo(x, y); t += lineDash[idx] / bezierLen; idx = (idx + 1) % nDash; } // Finish the last segment and calculate the new offset (idx % 2 !== 0) && ctx.lineTo(x3, y3); dx = x3 - x; dy = y3 - y; this._dashOffset = -mathSqrt(dx * dx + dy * dy); }
javascript
{ "resource": "" }
q18505
train
function (otherStyle, overwrite) { if (otherStyle) { for (var name in otherStyle) { if (otherStyle.hasOwnProperty(name) && (overwrite === true || ( overwrite === false ? !this.hasOwnProperty(name) : otherStyle[name] != null ) ) ) { this[name] = otherStyle[name]; } } } }
javascript
{ "resource": "" }
q18506
normalizeModuleAndLoadMetadata
train
function normalizeModuleAndLoadMetadata(programPath) { nameAnonymousExports(programPath); const {local, source} = getModuleMetadata(programPath); removeModuleDeclarations(programPath); // Reuse the imported namespace name if there is one. for (const [, metadata] of source) { if (metadata.importsNamespace.size > 0) { // This is kind of gross. If we stop using `loose: true` we should // just make this destructuring assignment. metadata.name = metadata.importsNamespace.values().next().value; } } return { exportName: 'exports', exportNameListName: null, local, source }; }
javascript
{ "resource": "" }
q18507
nameAnonymousExports
train
function nameAnonymousExports(programPath) { // Name anonymous exported locals. programPath.get('body').forEach(child => { if (!child.isExportDefaultDeclaration()) { return; } // export default foo; const declaration = child.get('declaration'); if (declaration.isFunctionDeclaration()) { if (!declaration.node.id) { declaration.node.id = declaration.scope.generateUidIdentifier('default'); } } else if (declaration.isClassDeclaration()) { if (!declaration.node.id) { declaration.node.id = declaration.scope.generateUidIdentifier('default'); } } else { const id = declaration.scope.generateUidIdentifier('default'); const namedDecl = babelTypes.exportNamedDeclaration(null, [ babelTypes.exportSpecifier(babelTypes.identifier(id.name), babelTypes.identifier('default')), ]); namedDecl._blockHoist = child.node._blockHoist; const varDecl = babelTypes.variableDeclaration('var', [ babelTypes.variableDeclarator(id, declaration.node), ]); varDecl._blockHoist = child.node._blockHoist; child.replaceWithMultiple([namedDecl, varDecl]); } }); }
javascript
{ "resource": "" }
q18508
train
function (ctx, rect) { var style = this.style; rect = style.textRect || rect; // Optimize, avoid normalize every time. this.__dirty && textHelper.normalizeTextStyle(style, true); var text = style.text; // Convert to string text != null && (text += ''); if (!textHelper.needDrawText(text, style)) { return; } // FIXME // Do not provide prevEl to `textHelper.renderText` for ctx prop cache, // but use `ctx.save()` and `ctx.restore()`. Because the cache for rect // text propably break the cache for its host elements. ctx.save(); // Transform rect to view space var transform = this.transform; if (!style.transformText) { if (transform) { tmpRect.copy(rect); tmpRect.applyTransform(transform); rect = tmpRect; } } else { this.setTransform(ctx); } // transformText and textRotation can not be used at the same time. textHelper.renderText(this, ctx, text, style, rect, WILL_BE_RESTORED); ctx.restore(); }
javascript
{ "resource": "" }
q18509
train
function (zr) { this.__zr = zr; // 添加动画 var animators = this.animators; if (animators) { for (var i = 0; i < animators.length; i++) { zr.animation.addAnimator(animators[i]); } } if (this.clipPath) { this.clipPath.addSelfToZr(zr); } }
javascript
{ "resource": "" }
q18510
train
function (zr) { this.__zr = null; // 移除动画 var animators = this.animators; if (animators) { for (var i = 0; i < animators.length; i++) { zr.animation.removeAnimator(animators[i]); } } if (this.clipPath) { this.clipPath.removeSelfFromZr(zr); } }
javascript
{ "resource": "" }
q18511
getScrollParent
train
function getScrollParent(element) { // Return body, `getScroll` will take care to get the correct `scrollTop` from it if (!element) { return document.body; } switch (element.nodeName) { case 'HTML': case 'BODY': return element.ownerDocument.body; case '#document': return element.body; } // Firefox want us to check `-x` and `-y` variations as well const { overflow, overflowX, overflowY } = getStyleComputedProperty(element); if (/(auto|scroll|overlay)/.test(overflow + overflowY + overflowX)) { return element; } return getScrollParent(getParentNode(element)); }
javascript
{ "resource": "" }
q18512
getOffsetParent
train
function getOffsetParent(element) { if (!element) { return document.documentElement; } const noOffsetParent = isIE(10) ? document.body : null; // NOTE: 1 DOM access here let offsetParent = element.offsetParent || null; // Skip hidden elements which don't have an offsetParent while (offsetParent === noOffsetParent && element.nextElementSibling) { offsetParent = (element = element.nextElementSibling).offsetParent; } const nodeName = offsetParent && offsetParent.nodeName; if (!nodeName || nodeName === 'BODY' || nodeName === 'HTML') { return element ? element.ownerDocument.documentElement : document.documentElement; } // .offsetParent will return the closest TH, TD or TABLE in case // no offsetParent is present, I hate this job... if (['TH', 'TD', 'TABLE'].indexOf(offsetParent.nodeName) !== -1 && getStyleComputedProperty(offsetParent, 'position') === 'static') { return getOffsetParent(offsetParent); } return offsetParent; }
javascript
{ "resource": "" }
q18513
findCommonOffsetParent
train
function findCommonOffsetParent(element1, element2) { // This check is needed to avoid errors in case one of the elements isn't defined for any reason if (!element1 || !element1.nodeType || !element2 || !element2.nodeType) { return document.documentElement; } // Here we make sure to give as "start" the element that comes first in the DOM const order = element1.compareDocumentPosition(element2) & Node.DOCUMENT_POSITION_FOLLOWING; const start = order ? element1 : element2; const end = order ? element2 : element1; // Get common ancestor container const range = document.createRange(); range.setStart(start, 0); range.setEnd(end, 0); const { commonAncestorContainer } = range; // Both nodes are inside #document if (element1 !== commonAncestorContainer && element2 !== commonAncestorContainer || start.contains(end)) { if (isOffsetContainer(commonAncestorContainer)) { return commonAncestorContainer; } return getOffsetParent(commonAncestorContainer); } // one of the nodes is inside shadowDOM, find which one const element1root = getRoot(element1); if (element1root.host) { return findCommonOffsetParent(element1root.host, element2); } else { return findCommonOffsetParent(element1, getRoot(element2).host); } }
javascript
{ "resource": "" }
q18514
computeAutoPlacement
train
function computeAutoPlacement(placement, refRect, popper, reference, boundariesElement, padding = 0) { if (placement.indexOf('auto') === -1) { return placement; } const boundaries = getBoundaries(popper, reference, padding, boundariesElement); const rects = { top: { width: boundaries.width, height: refRect.top - boundaries.top }, right: { width: boundaries.right - refRect.right, height: boundaries.height }, bottom: { width: boundaries.width, height: boundaries.bottom - refRect.bottom }, left: { width: refRect.left - boundaries.left, height: boundaries.height } }; const sortedAreas = Object.keys(rects).map(key => _extends({ key }, rects[key], { area: getArea(rects[key]) })).sort((a, b) => b.area - a.area); const filteredAreas = sortedAreas.filter(({ width, height }) => width >= popper.clientWidth && height >= popper.clientHeight); const computedPlacement = filteredAreas.length > 0 ? filteredAreas[0].key : sortedAreas[0].key; const variation = placement.split('-')[1]; return computedPlacement + (variation ? `-${variation}` : ''); }
javascript
{ "resource": "" }
q18515
getOppositePlacement
train
function getOppositePlacement(placement) { const hash = { left: 'right', right: 'left', bottom: 'top', top: 'bottom' }; return placement.replace(/left|right|bottom|top/g, matched => hash[matched]); }
javascript
{ "resource": "" }
q18516
getPopperOffsets
train
function getPopperOffsets(popper, referenceOffsets, placement) { placement = placement.split('-')[0]; // Get popper node sizes const popperRect = getOuterSizes(popper); // Add position, width and height to our offsets object const popperOffsets = { width: popperRect.width, height: popperRect.height }; // depending by the popper placement we have to compute its offsets slightly differently const isHoriz = ['right', 'left'].indexOf(placement) !== -1; const mainSide = isHoriz ? 'top' : 'left'; const secondarySide = isHoriz ? 'left' : 'top'; const measurement = isHoriz ? 'height' : 'width'; const secondaryMeasurement = !isHoriz ? 'height' : 'width'; popperOffsets[mainSide] = referenceOffsets[mainSide] + referenceOffsets[measurement] / 2 - popperRect[measurement] / 2; if (placement === secondarySide) { popperOffsets[secondarySide] = referenceOffsets[secondarySide] - popperRect[secondaryMeasurement]; } else { popperOffsets[secondarySide] = referenceOffsets[getOppositePlacement(secondarySide)]; } return popperOffsets; }
javascript
{ "resource": "" }
q18517
isModifierEnabled
train
function isModifierEnabled(modifiers, modifierName) { return modifiers.some(({ name, enabled }) => enabled && name === modifierName); }
javascript
{ "resource": "" }
q18518
getSupportedPropertyName
train
function getSupportedPropertyName(property) { const prefixes = [false, 'ms', 'Webkit', 'Moz', 'O']; const upperProp = property.charAt(0).toUpperCase() + property.slice(1); for (let i = 0; i < prefixes.length; i++) { const prefix = prefixes[i]; const toCheck = prefix ? `${prefix}${upperProp}` : property; if (typeof document.body.style[toCheck] !== 'undefined') { return toCheck; } } return null; }
javascript
{ "resource": "" }
q18519
applyStyleOnLoad
train
function applyStyleOnLoad(reference, popper, options, modifierOptions, state) { // compute reference element offsets const referenceOffsets = getReferenceOffsets(state, popper, reference, options.positionFixed); // compute auto placement, store placement inside the data object, // modifiers will be able to edit `placement` if needed // and refer to originalPlacement to know the original value const placement = computeAutoPlacement(options.placement, referenceOffsets, popper, reference, options.modifiers.flip.boundariesElement, options.modifiers.flip.padding); popper.setAttribute('x-placement', placement); // Apply `position` to popper before anything else because // without the position applied we can't guarantee correct computations setStyles(popper, { position: options.positionFixed ? 'fixed' : 'absolute' }); return options; }
javascript
{ "resource": "" }
q18520
parseOffset
train
function parseOffset(offset, popperOffsets, referenceOffsets, basePlacement) { const offsets = [0, 0]; // Use height if placement is left or right and index is 0 otherwise use width // in this way the first offset will use an axis and the second one // will use the other one const useHeight = ['right', 'left'].indexOf(basePlacement) !== -1; // Split the offset string to obtain a list of values and operands // The regex addresses values with the plus or minus sign in front (+10, -20, etc) const fragments = offset.split(/(\+|\-)/).map(frag => frag.trim()); // Detect if the offset string contains a pair of values or a single one // they could be separated by comma or space const divider = fragments.indexOf(find(fragments, frag => frag.search(/,|\s/) !== -1)); if (fragments[divider] && fragments[divider].indexOf(',') === -1) { console.warn('Offsets separated by white space(s) are deprecated, use a comma (,) instead.'); } // If divider is found, we divide the list of values and operands to divide // them by ofset X and Y. const splitRegex = /\s*,\s*|\s+/; let ops = divider !== -1 ? [fragments.slice(0, divider).concat([fragments[divider].split(splitRegex)[0]]), [fragments[divider].split(splitRegex)[1]].concat(fragments.slice(divider + 1))] : [fragments]; // Convert the values with units to absolute pixels to allow our computations ops = ops.map((op, index) => { // Most of the units rely on the orientation of the popper const measurement = (index === 1 ? !useHeight : useHeight) ? 'height' : 'width'; let mergeWithPrevious = false; return op // This aggregates any `+` or `-` sign that aren't considered operators // e.g.: 10 + +5 => [10, +, +5] .reduce((a, b) => { if (a[a.length - 1] === '' && ['+', '-'].indexOf(b) !== -1) { a[a.length - 1] = b; mergeWithPrevious = true; return a; } else if (mergeWithPrevious) { a[a.length - 1] += b; mergeWithPrevious = false; return a; } else { return a.concat(b); } }, []) // Here we convert the string values into number values (in px) .map(str => toValue(str, measurement, popperOffsets, referenceOffsets)); }); // Loop trough the offsets arrays and execute the operations ops.forEach((op, index) => { op.forEach((frag, index2) => { if (isNumeric(frag)) { offsets[index] += frag * (op[index2 - 1] === '-' ? -1 : 1); } }); }); return offsets; }
javascript
{ "resource": "" }
q18521
addElements
train
function addElements(newElements, ownerDocument) { var elements = html5.elements; if(typeof elements != 'string'){ elements = elements.join(' '); } if(typeof newElements != 'string'){ newElements = newElements.join(' '); } html5.elements = elements +' '+ newElements; shivDocument(ownerDocument); }
javascript
{ "resource": "" }
q18522
getExpandoData
train
function getExpandoData(ownerDocument) { var data = expandoData[ownerDocument[expando]]; if (!data) { data = {}; expanID++; ownerDocument[expando] = expanID; expandoData[expanID] = data; } return data; }
javascript
{ "resource": "" }
q18523
createElement
train
function createElement(nodeName, ownerDocument, data){ if (!ownerDocument) { ownerDocument = document; } if(supportsUnknownElements){ return ownerDocument.createElement(nodeName); } if (!data) { data = getExpandoData(ownerDocument); } var node; if (data.cache[nodeName]) { node = data.cache[nodeName].cloneNode(); } else if (saveClones.test(nodeName)) { node = (data.cache[nodeName] = data.createElem(nodeName)).cloneNode(); } else { node = data.createElem(nodeName); } // Avoid adding some elements to fragments in IE < 9 because // * Attributes like `name` or `type` cannot be set/changed once an element // is inserted into a document/fragment // * Link elements with `src` attributes that are inaccessible, as with // a 403 response, will cause the tab/window to crash // * Script elements appended to fragments will execute when their `src` // or `text` property is set return node.canHaveChildren && !reSkip.test(nodeName) && !node.tagUrn ? data.frag.appendChild(node) : node; }
javascript
{ "resource": "" }
q18524
createDocumentFragment
train
function createDocumentFragment(ownerDocument, data){ if (!ownerDocument) { ownerDocument = document; } if(supportsUnknownElements){ return ownerDocument.createDocumentFragment(); } data = data || getExpandoData(ownerDocument); var clone = data.frag.cloneNode(), i = 0, elems = getElements(), l = elems.length; for(;i<l;i++){ clone.createElement(elems[i]); } return clone; }
javascript
{ "resource": "" }
q18525
createWrapper
train
function createWrapper(element) { var node, nodes = element.attributes, index = nodes.length, wrapper = element.ownerDocument.createElement(shivNamespace + ':' + element.nodeName); // copy element attributes to the wrapper while (index--) { node = nodes[index]; node.specified && wrapper.setAttribute(node.nodeName, node.nodeValue); } // copy element styles to the wrapper wrapper.style.cssText = element.style.cssText; return wrapper; }
javascript
{ "resource": "" }
q18526
train
function(arr, world, refText, refTerms) { this.terms = arr; this.world = world || w; this.refText = refText; this._refTerms = refTerms; this.get = n => { return this.terms[n]; }; //apply getters let keys = Object.keys(getters); for (let i = 0; i < keys.length; i++) { Object.defineProperty(this, keys[i], getters[keys[i]]); } }
javascript
{ "resource": "" }
q18527
train
function(arr) { arr = arr.sort((a, b) => { if (a.index > b.index) { return 1; } if (a.index === b.index) { return 0; } return -1; }); //return ts objects return arr.map((o) => o.ts); }
javascript
{ "resource": "" }
q18528
train
function(str, lex) { if (lex) { w.plugin({ words: lex }); } let doc = buildText(str, w); doc.tagger(); return doc; }
javascript
{ "resource": "" }
q18529
train
function(str, lex) { if (lex) { w2.plugin({ words: lex }); } let doc = buildText(str, w2); doc.tagger(); return doc; }
javascript
{ "resource": "" }
q18530
registerLangHandler
train
function registerLangHandler(handler, fileExtensions) { for (var i = fileExtensions.length; --i >= 0;) { var ext = fileExtensions[i]; if (!langHandlerRegistry.hasOwnProperty(ext)) { langHandlerRegistry[ext] = handler; } else if (win['console']) { console['warn']('cannot override language handler %s', ext); } } }
javascript
{ "resource": "" }
q18531
$prettyPrintOne
train
function $prettyPrintOne(sourceCodeHtml, opt_langExtension, opt_numberLines) { /** @type{number|boolean} */ var nl = opt_numberLines || false; /** @type{string|null} */ var langExtension = opt_langExtension || null; /** @type{!Element} */ var container = document.createElement('div'); // This could cause images to load and onload listeners to fire. // E.g. <img onerror="alert(1337)" src="nosuchimage.png">. // We assume that the inner HTML is from a trusted source. // The pre-tag is required for IE8 which strips newlines from innerHTML // when it is injected into a <pre> tag. // http://stackoverflow.com/questions/451486/pre-tag-loses-line-breaks-when-setting-innerhtml-in-ie // http://stackoverflow.com/questions/195363/inserting-a-newline-into-a-pre-tag-ie-javascript container.innerHTML = '<pre>' + sourceCodeHtml + '</pre>'; container = /** @type{!Element} */(container.firstChild); if (nl) { numberLines(container, nl, true); } /** @type{JobT} */ var job = { langExtension: langExtension, numberLines: nl, sourceNode: container, pre: 1, sourceCode: null, basePos: null, spans: null, decorations: null }; applyDecorator(job); return container.innerHTML; }
javascript
{ "resource": "" }
q18532
loadStylesheetsFallingBack
train
function loadStylesheetsFallingBack(stylesheets) { var n = stylesheets.length; function load(i) { if (i === n) { return; } var link = doc.createElement('link'); link.rel = 'stylesheet'; link.type = 'text/css'; if (i + 1 < n) { // http://pieisgood.org/test/script-link-events/ indicates that many // versions of IE do not support onerror on <link>s, though // http://msdn.microsoft.com/en-us/library/ie/ms535848(v=vs.85).aspx // indicates that recent IEs do support error. link.error = link.onerror = function () { load(i + 1); }; } link.href = stylesheets[i]; head.appendChild(link); } load(0); }
javascript
{ "resource": "" }
q18533
onLangsLoaded
train
function onLangsLoaded() { if (autorun) { contentLoaded( function () { var n = callbacks.length; var callback = n ? function () { for (var i = 0; i < n; ++i) { (function (i) { win.setTimeout( function () { win['exports'][callbacks[i]].apply(win, arguments); }, 0); })(i); } } : void 0; prettyPrint(callback); }); } }
javascript
{ "resource": "" }
q18534
syncTimestamp
train
function syncTimestamp(src, dest, timestamp) { if (timestamp) { var stat = fs.lstatSync(src); var fd = fs.openSync(dest, process.platform === 'win32' ? 'r+' : 'r'); fs.futimesSync(fd, stat.atime, stat.mtime); fs.closeSync(fd); } }
javascript
{ "resource": "" }
q18535
syncMod
train
function syncMod(src, dest, mode) { if (mode !== false) { fs.chmodSync(dest, (mode === true) ? fs.lstatSync(src).mode : mode); } }
javascript
{ "resource": "" }
q18536
breakAfter
train
function breakAfter(lineEndNode) { // If there's nothing to the right, then we can skip ending the line // here, and move root-wards since splitting just before an end-tag // would require us to create a bunch of empty copies. while (!lineEndNode.nextSibling) { lineEndNode = lineEndNode.parentNode; if (!lineEndNode) { return; } } function breakLeftOf(limit, copy) { // Clone shallowly if this node needs to be on both sides of the break. var rightSide = copy ? limit.cloneNode(false) : limit; var parent = limit.parentNode; if (parent) { // We clone the parent chain. // This helps us resurrect important styling elements that cross lines. // E.g. in <i>Foo<br>Bar</i> // should be rewritten to <li><i>Foo</i></li><li><i>Bar</i></li>. var parentClone = breakLeftOf(parent, 1); // Move the clone and everything to the right of the original // onto the cloned parent. var next = limit.nextSibling; parentClone.appendChild(rightSide); for (var sibling = next; sibling; sibling = next) { next = sibling.nextSibling; parentClone.appendChild(sibling); } } return rightSide; } var copiedListItem = breakLeftOf(lineEndNode.nextSibling, 0); // Walk the parent chain until we reach an unattached LI. for (var parent; // Check nodeType since IE invents document fragments. (parent = copiedListItem.parentNode) && parent.nodeType === 1;) { copiedListItem = parent; } // Put it on the list of lines for later processing. listItems.push(copiedListItem); }
javascript
{ "resource": "" }
q18537
createSandbox
train
function createSandbox() { // collect registered language extensions var sandbox = {}; sandbox.extensions = []; // mock prettify.js API sandbox.window = {}; sandbox.window.PR = sandbox.PR = { registerLangHandler: function (handler, exts) { sandbox.extensions = sandbox.extensions.concat(exts); }, createSimpleLexer: function (sPatterns, fPatterns) { return function (job) {}; }, sourceDecorator: function (options) { return function (job) {}; }, prettyPrintOne: function (src, lang, ln) { return src; }, prettyPrint: function (done, root) {}, PR_ATTRIB_NAME: 'atn', PR_ATTRIB_VALUE: 'atv', PR_COMMENT: 'com', PR_DECLARATION: 'dec', PR_KEYWORD: 'kwd', PR_LITERAL: 'lit', PR_NOCODE: 'nocode', PR_PLAIN: 'pln', PR_PUNCTUATION: 'pun', PR_SOURCE: 'src', PR_STRING: 'str', PR_TAG: 'tag', PR_TYPE: 'typ' }; return sandbox; }
javascript
{ "resource": "" }
q18538
runLanguageHandler
train
function runLanguageHandler(src) { // execute source code in an isolated sandbox with a mock PR object var sandbox = createSandbox(); vm.runInNewContext(fs.readFileSync(src), sandbox, { filename: src }); // language name var lang = path.basename(src, path.extname(src)).replace(/^lang-/, ''); // collect and filter extensions var exts = sandbox.extensions.map(function (ext) { // case-insensitive names return ext.toLowerCase(); }).filter(function (ext) { // skip self, and internal names like foo-bar-baz or lang.foo return ext !== lang && !/\W/.test(ext); }); exts = exts.filter(function (ext, pos) { // remove duplicates return exts.indexOf(ext) === pos; }); return exts; }
javascript
{ "resource": "" }
q18539
makeValueChecker
train
function makeValueChecker(ref) { const expected = require(ref); return ({value}) => value === expected || value === expected.default; }
javascript
{ "resource": "" }
q18540
getElementFromObject
train
function getElementFromObject(attachTo) { const op = attachTo.element; if (op instanceof HTMLElement) { return op; } return document.querySelector(op); }
javascript
{ "resource": "" }
q18541
getElementForStep
train
function getElementForStep(step) { const { options: { attachTo } } = step; if (!attachTo) { return null; } const type = typeof attachTo; let element; if (type === 'string') { element = getElementFromString(attachTo); } else if (type === 'object') { element = getElementFromObject(attachTo); } else { /* istanbul ignore next: cannot test undefined attachTo, but it does work! */ element = null; } return element; }
javascript
{ "resource": "" }
q18542
_makeTippyInstance
train
function _makeTippyInstance(attachToOptions) { if (!attachToOptions.element) { return _makeCenteredTippy.call(this); } const tippyOptions = _makeAttachedTippyOptions.call(this, attachToOptions); return tippy(attachToOptions.element, tippyOptions); }
javascript
{ "resource": "" }
q18543
_makeAttachedTippyOptions
train
function _makeAttachedTippyOptions(attachToOptions) { const resultingTippyOptions = { content: this.el, flipOnUpdate: true, placement: attachToOptions.on || 'right' }; Object.assign(resultingTippyOptions, this.options.tippyOptions); if (this.options.title) { const existingTheme = resultingTippyOptions.theme; resultingTippyOptions.theme = existingTheme ? `${existingTheme} shepherd-has-title` : 'shepherd-has-title'; } if (this.options.tippyOptions && this.options.tippyOptions.popperOptions) { Object.assign(defaultPopperOptions, this.options.tippyOptions.popperOptions); } resultingTippyOptions.popperOptions = defaultPopperOptions; return resultingTippyOptions; }
javascript
{ "resource": "" }
q18544
_setupAdvanceOnHandler
train
function _setupAdvanceOnHandler(selector) { return (event) => { if (this.isOpen()) { const targetIsEl = this.el && event.target === this.el; const targetIsSelector = !isUndefined(selector) && event.target.matches(selector); if (targetIsSelector || targetIsEl) { this.tour.next(); } } }; }
javascript
{ "resource": "" }
q18545
positionModalOpening
train
function positionModalOpening(targetElement, openingElement) { if (targetElement.getBoundingClientRect && openingElement instanceof SVGElement) { const { x, y, width, height, left, top } = targetElement.getBoundingClientRect(); // getBoundingClientRect is not consistent. Some browsers use x and y, while others use left and top _setAttributes(openingElement, { x: x || left, y: y || top, width, height }); } }
javascript
{ "resource": "" }
q18546
toggleShepherdModalClass
train
function toggleShepherdModalClass(currentElement) { const shepherdModal = document.querySelector(`${classNames.modalTarget}`); if (shepherdModal) { shepherdModal.classList.remove(classNames.modalTarget); } currentElement.classList.add(classNames.modalTarget); }
javascript
{ "resource": "" }
q18547
_setAttributes
train
function _setAttributes(el, attrs) { Object.keys(attrs).forEach((key) => { el.setAttribute(key, attrs[key]); }); }
javascript
{ "resource": "" }
q18548
arrayReplaceAt
train
function arrayReplaceAt(src, pos, newElements) { return [].concat(src.slice(0, pos), newElements, src.slice(pos + 1)); }
javascript
{ "resource": "" }
q18549
messaging
train
function messaging(request, sender, sendResponse) { let tabId = getId(sender); if (!tabId) return; if (sender.frameId) tabId = `${tabId}-${sender.frameId}`; if (request.type === 'STOP') { if (!Object.keys(window.store.getState().instances.connections).length) { window.store.dispatch({ type: DISCONNECTED }); } return; } if (request.type === 'OPEN_OPTIONS') { chrome.runtime.openOptionsPage(); return; } if (request.type === 'GET_OPTIONS') { window.syncOptions.get(options => { sendResponse({ options }); }); return; } if (request.type === 'GET_REPORT') { getReport(request.payload, tabId, request.instanceId); return; } if (request.type === 'OPEN') { let position = 'devtools-left'; if (['remote', 'panel', 'left', 'right', 'bottom'].indexOf(request.position) !== -1) { position = 'devtools-' + request.position; } openDevToolsWindow(position); return; } if (request.type === 'ERROR') { if (request.payload) { toMonitors(request, tabId); return; } if (!request.message) return; const reducerError = getReducerError(); chrome.notifications.create('app-error', { type: 'basic', title: reducerError ? 'An error occurred in the reducer' : 'An error occurred in the app', message: reducerError || request.message, iconUrl: 'img/logo/48x48.png', isClickable: !!reducerError }); return; } const action = { type: UPDATE_STATE, request, id: tabId }; const instanceId = `${tabId}/${request.instanceId}`; if (request.split) { if (request.split === 'start') { chunks[instanceId] = request; return; } if (request.split === 'chunk') { chunks[instanceId][request.chunk[0]] = (chunks[instanceId][request.chunk[0]] || '') + request.chunk[1]; return; } action.request = chunks[instanceId]; delete chunks[instanceId]; } if (request.instanceId) { action.request.instanceId = instanceId; } window.store.dispatch(action); if (request.type === 'EXPORT') { toMonitors(action, tabId, true); } else { toMonitors(action, tabId); } }
javascript
{ "resource": "" }
q18550
handleMessages
train
function handleMessages(event) { if (!isAllowed()) return; if (!event || event.source !== window || typeof event.data !== 'object') return; const message = event.data; if (message.source !== pageSource) return; if (message.type === 'DISCONNECT') { if (bg) { bg.disconnect(); connected = false; } return; } tryCatch(send, message); }
javascript
{ "resource": "" }
q18551
normalizeUri
train
function normalizeUri(uri) { const anchor = createElement(TagName.A); // This is safe even though the URL might be untrustworthy. // The SafeURL is only used to set the href of an HTMLAnchorElement // that is never added to the DOM. Therefore, the user cannot navigate // to this URL. const safeUrl = uncheckedconversions.safeUrlFromStringKnownToSatisfyTypeContract( Const.from('This URL is never added to the DOM'), uri); setAnchorHref(anchor, safeUrl); return anchor.href; }
javascript
{ "resource": "" }
q18552
getBrowserName
train
function getBrowserName(browserCap) { var name = browserCap.browserName == 'internet explorer' ? 'ie' : browserCap.browserName; var version = browserCap.version || '-latest'; return name + version; }
javascript
{ "resource": "" }
q18553
getJobName
train
function getJobName(browserCap) { var browserName = getBrowserName(browserCap); return process.env.TRAVIS_PULL_REQUEST == 'false' ? 'CO-' + process.env.TRAVIS_BRANCH + '-' + browserName : 'PR-' + process.env.TRAVIS_PULL_REQUEST + '-' + browserName + '-' + process.env.TRAVIS_BRANCH; }
javascript
{ "resource": "" }
q18554
getBrowserCapabilities
train
function getBrowserCapabilities(browsers) { for (var i = 0; i < browsers.length; i++) { var b = browsers[i]; b['tunnel-identifier'] = process.env.TRAVIS_JOB_NUMBER; b['build'] = process.env.TRAVIS_BUILD_NUMBER; b['name'] = getJobName(b); } return browsers; }
javascript
{ "resource": "" }
q18555
prototypeMethodOrNull
train
function prototypeMethodOrNull(className, method) { var ctor = goog.global[className]; return (ctor && ctor.prototype && ctor.prototype[method]) || null; }
javascript
{ "resource": "" }
q18556
genericPropertyGet
train
function genericPropertyGet(fn, object, fallbackPropertyName, fallbackTest) { if (fn) { return fn.apply(object); } var propertyValue = object[fallbackPropertyName]; if (!fallbackTest(propertyValue)) { throw new Error('Clobbering detected'); } return propertyValue; }
javascript
{ "resource": "" }
q18557
genericMethodCall
train
function genericMethodCall(fn, object, fallbackMethodName, args) { if (fn) { return fn.apply(object, args); } // IE8 and IE9 will return 'object' for // CSSStyleDeclaration.(get|set)Attribute, so we can't use typeof. if (userAgentProduct.IE && document.documentMode < 10) { if (!object[fallbackMethodName].call) { throw new Error('IE Clobbering detected'); } } else if (typeof object[fallbackMethodName] != 'function') { throw new Error('Clobbering detected'); } return object[fallbackMethodName].apply(object, args); }
javascript
{ "resource": "" }
q18558
getCssPropertyValue
train
function getCssPropertyValue(cssStyle, propName) { return genericMethodCall( Methods.GET_PROPERTY_VALUE, cssStyle, cssStyle.getPropertyValue ? 'getPropertyValue' : 'getAttribute', [propName]) || ''; }
javascript
{ "resource": "" }
q18559
setCssProperty
train
function setCssProperty(cssStyle, propName, sanitizedValue) { genericMethodCall( Methods.SET_PROPERTY, cssStyle, cssStyle.setProperty ? 'setProperty' : 'setAttribute', [propName, sanitizedValue]); }
javascript
{ "resource": "" }
q18560
train
function(value, opt_parent) { /** * The value stored by the node. * * @type {T} */ this.value = value; /** * The node's parent. Null if the node is the root. * * @type {?Node<T>} */ this.parent = opt_parent ? opt_parent : null; /** * The number of nodes in the subtree rooted at this node. * * @type {number} */ this.count = 1; /** * The node's left child. Null if the node does not have a left child. * * @type {?Node<T>} */ this.left = null; /** * The node's right child. Null if the node does not have a right child. * * @type {?Node<T>} */ this.right = null; /** * Height of this node. * * @type {number} */ this.height = 1; }
javascript
{ "resource": "" }
q18561
finishMessage
train
function finishMessage() { if (parser.tag_ < Parser.PADDING_TAG_) { var message = {}; message[parser.tag_] = parser.messageBuffer_; parser.result_.push(message); } parser.state_ = Parser.State_.INIT; }
javascript
{ "resource": "" }
q18562
train
function(testPath) { var testStartTime = +new Date(); var waitForTest = function(resolve, reject) { // executeScript runs the passed method in the "window" context of // the current test. JSUnit exposes hooks into the test's status through // the "G_testRunner" global object. browser .executeScript(function() { if (window['G_testRunner'] && window['G_testRunner']['isFinished']()) { var status = {}; status['isFinished'] = true; status['isSuccess'] = window['G_testRunner']['isSuccess'](); status['report'] = window['G_testRunner']['getReport'](); return status; } else { return {'isFinished': false}; } }) .then( function(status) { if (status && status.isFinished) { resolve(status); } else { var currTime = +new Date(); if (currTime - testStartTime > TEST_TIMEOUT) { status.isSuccess = false; status.report = testPath + ' timed out after ' + (TEST_TIMEOUT / 1000) + 's!'; // resolve so tests continue running. resolve(status); } else { // Check every 300ms for completion. setTimeout( waitForTest.bind(undefined, resolve, reject), 300); } } }, function(err) { reject(err); }); }; return new Promise(function(resolve, reject) { waitForTest(resolve, reject); }); }
javascript
{ "resource": "" }
q18563
train
function(testPath) { return browser.navigate() .to(TEST_SERVER + '/' + testPath) .then(function() { return waitForTestSuiteCompletion(testPath); }) .then(function(status) { if (!status.isSuccess) { failureReports.push(status.report); } return status; }); }
javascript
{ "resource": "" }
q18564
getSpecificity
train
function getSpecificity(selector) { if (userAgentProduct.IE && !userAgent.isVersionOrHigher(9)) { // IE8 has buggy regex support. return [0, 0, 0, 0]; } var specificity = specificityCache.hasOwnProperty(selector) ? specificityCache[selector] : null; if (specificity) { return specificity; } if (Object.keys(specificityCache).length > (1 << 16)) { // Limit the size of cache to (1 << 16) == 65536. Normally HTML pages don't // have such numbers of selectors. specificityCache = {}; } specificity = calculateSpecificity(selector); specificityCache[selector] = specificity; return specificity; }
javascript
{ "resource": "" }
q18565
replaceWithEmptyText
train
function replaceWithEmptyText(selector, specificity, regex, typeIndex) { return selector.replace(regex, function(match) { specificity[typeIndex] += 1; // Replace this simple selector with whitespace so it won't be counted // in further simple selectors. return Array(match.length + 1).join(' '); }); }
javascript
{ "resource": "" }
q18566
replaceWithPlainText
train
function replaceWithPlainText(selector, regex) { return selector.replace(regex, function(match) { return Array(match.length + 1).join('A'); }); }
javascript
{ "resource": "" }
q18567
calculateSpecificity
train
function calculateSpecificity(selector) { var specificity = [0, 0, 0, 0]; // Cannot use RegExp literals for all regular expressions, IE does not accept // the syntax. // Matches a backslash followed by six hexadecimal digits followed by an // optional single whitespace character. var escapeHexadecimalRegex = new RegExp('\\\\[0-9A-Fa-f]{6}\\s?', 'g'); // Matches a backslash followed by fewer than six hexadecimal digits // followed by a mandatory single whitespace character. var escapeHexadecimalRegex2 = new RegExp('\\\\[0-9A-Fa-f]{1,5}\\s', 'g'); // Matches a backslash followed by any character var escapeSpecialCharacter = /\\./g; selector = replaceWithPlainText(selector, escapeHexadecimalRegex); selector = replaceWithPlainText(selector, escapeHexadecimalRegex2); selector = replaceWithPlainText(selector, escapeSpecialCharacter); // Remove the negation pseudo-class (:not) but leave its argument because // specificity is calculated on its argument. var pseudoClassWithNotRegex = new RegExp(':not\\(([^\\)]*)\\)', 'g'); selector = selector.replace(pseudoClassWithNotRegex, ' $1 '); // Remove anything after a left brace in case a user has pasted in a rule, // not just a selector. var rulesRegex = new RegExp('{[^]*', 'gm'); selector = selector.replace(rulesRegex, ''); // The following regular expressions assume that selectors matching the // preceding regular expressions have been removed. // SPECIFICITY 2: Counts attribute selectors. var attributeRegex = new RegExp('(\\[[^\\]]+\\])', 'g'); selector = replaceWithEmptyText(selector, specificity, attributeRegex, 2); // SPECIFICITY 1: Counts ID selectors. var idRegex = new RegExp('(#[^\\#\\s\\+>~\\.\\[:]+)', 'g'); selector = replaceWithEmptyText(selector, specificity, idRegex, 1); // SPECIFICITY 2: Counts class selectors. var classRegex = new RegExp('(\\.[^\\s\\+>~\\.\\[:]+)', 'g'); selector = replaceWithEmptyText(selector, specificity, classRegex, 2); // SPECIFICITY 3: Counts pseudo-element selectors. var pseudoElementRegex = /(::[^\s\+>~\.\[:]+|:first-line|:first-letter|:before|:after)/gi; selector = replaceWithEmptyText(selector, specificity, pseudoElementRegex, 3); // SPECIFICITY 2: Counts pseudo-class selectors. // A regex for pseudo classes with brackets. For example: // :nth-child() // :nth-last-child() // :nth-of-type() // :nth-last-type() // :lang() var pseudoClassWithBracketsRegex = /(:[\w-]+\([^\)]*\))/gi; selector = replaceWithEmptyText( selector, specificity, pseudoClassWithBracketsRegex, 2); // A regex for other pseudo classes, which don't have brackets. var pseudoClassRegex = /(:[^\s\+>~\.\[:]+)/g; selector = replaceWithEmptyText(selector, specificity, pseudoClassRegex, 2); // Remove universal selector and separator characters. selector = selector.replace(/[\*\s\+>~]/g, ' '); // Remove any stray dots or hashes which aren't attached to words. // These may be present if the user is live-editing this selector. selector = selector.replace(/[#\.]/g, ' '); // SPECIFICITY 3: The only things left should be element selectors. var elementRegex = /([^\s\+>~\.\[:]+)/g; selector = replaceWithEmptyText(selector, specificity, elementRegex, 3); return specificity; }
javascript
{ "resource": "" }
q18568
train
function(prefix, string) { return string.substring(0, prefix.length) == prefix ? string.substring(prefix.length) : ''; }
javascript
{ "resource": "" }
q18569
fetchInOwnScriptThenLoad
train
function fetchInOwnScriptThenLoad() { /** @type {!HTMLDocument} */ var doc = goog.global.document; var key = goog.Dependency.registerCallback_(function() { goog.Dependency.unregisterCallback_(key); load(); }); var script = '<script type="text/javascript">' + goog.protectScriptTag_('goog.Dependency.callback_("' + key + '");') + '</' + 'script>'; doc.write( goog.TRUSTED_TYPES_POLICY_ ? goog.TRUSTED_TYPES_POLICY_.createHTML(script) : script); }
javascript
{ "resource": "" }
q18570
getSafeUri
train
function getSafeUri(uri, propName, uriRewriter) { if (!uriRewriter) { return null; } var safeUri = uriRewriter(uri, propName); if (safeUri && SafeUrl.unwrap(safeUri) != SafeUrl.INNOCUOUS_STRING) { return 'url("' + SafeUrl.unwrap(safeUri).replace(NORM_URL_REGEXP, normalizeUrlChar) + '")'; } return null; }
javascript
{ "resource": "" }
q18571
train
function(opt_maxPoolSize) { /** * The max pool size as configured. * * @private {number} */ this.maxPoolSizeConfigured_ = opt_maxPoolSize || ForwardChannelRequestPool.MAX_POOL_SIZE_; /** * The current size limit of the request pool. This limit is meant to be * read-only after the channel is fully opened. * * If SPDY or HTTP2 is enabled, set it to the max pool size, which is also * configurable. * * @private {number} */ this.maxSize_ = ForwardChannelRequestPool.isSpdyOrHttp2Enabled_() ? this.maxPoolSizeConfigured_ : 1; /** * The container for all the pending request objects. * * @private {Set<ChannelRequest>} */ this.requestPool_ = null; if (this.maxSize_ > 1) { this.requestPool_ = new Set(); } /** * The single request object when the pool size is limited to one. * * @private {ChannelRequest} */ this.request_ = null; /** * Saved pending messages when the pool is cancelled. * * @private {!Array<Wire.QueuedMap>} */ this.pendingMessages_ = []; }
javascript
{ "resource": "" }
q18572
get
train
function get() { if (!moduleManager && getDefault) { moduleManager = getDefault(); } asserts.assert( moduleManager != null, 'The module manager has not yet been set.'); return moduleManager; }
javascript
{ "resource": "" }
q18573
fixProductDates
train
function fixProductDates(products){ let index = 0; products.forEach((product) => { products[index].productAddedDate = new Date(); index++; }); return products; }
javascript
{ "resource": "" }
q18574
mixin
train
function mixin(obj) { for (var key in Emitter.prototype) { obj[key] = Emitter.prototype[key]; } return obj; }
javascript
{ "resource": "" }
q18575
encode2UTF8
train
function encode2UTF8(charCode){ if(charCode <= 0x7f){ return [charCode]; }else if(charCode <= 0x7ff){ return [0xc0|(charCode>>6), 0x80|(charCode & 0x3f)]; }else{ return [0xe0|(charCode>>12), 0x80|((charCode & 0xfc0)>>6), 0x80|(charCode & 0x3f)]; } }
javascript
{ "resource": "" }
q18576
train
function(app, opts) { opts = opts || {}; this.app = app; this.channels = {}; this.prefix = opts.prefix; this.store = opts.store; this.broadcastFilter = opts.broadcastFilter; this.channelRemote = new ChannelRemote(app); }
javascript
{ "resource": "" }
q18577
train
function(name, service) { this.name = name; this.groups = {}; // group map for uids. key: sid, value: [uid] this.records = {}; // member records. key: uid this.__channelService__ = service; this.state = ST_INITED; this.userAmount =0; }
javascript
{ "resource": "" }
q18578
train
function(uid, sid, groups) { if(!sid) { logger.warn('ignore uid %j for sid not specified.', uid); return false; } var group = groups[sid]; if(!group) { group = []; groups[sid] = group; } group.push(uid); return true; }
javascript
{ "resource": "" }
q18579
train
function(sid, frontendId, socket, service) { EventEmitter.call(this); this.id = sid; // r this.frontendId = frontendId; // r this.uid = null; // r this.settings = {}; // private this.__socket__ = socket; this.__sessionService__ = service; this.__state__ = ST_INITED; }
javascript
{ "resource": "" }
q18580
train
function(session) { EventEmitter.call(this); clone(session, this, FRONTEND_SESSION_FIELDS); // deep copy for settings this.settings = dclone(session.settings); this.__session__ = session; }
javascript
{ "resource": "" }
q18581
train
function(socket, opts) { if(!(this instanceof Socket)) { return new Socket(socket, opts); } if(!socket || !opts) { throw new Error('invalid socket or opts'); } if(!opts.headSize || typeof opts.headHandler !== 'function') { throw new Error('invalid opts.headSize or opts.headHandler'); } // stream style interfaces. // TODO: need to port to stream2 after node 0.9 Stream.call(this); this.readable = true; this.writeable = true; this._socket = socket; this.headSize = opts.headSize; this.closeMethod = opts.closeMethod; this.headBuffer = new Buffer(opts.headSize); this.headHandler = opts.headHandler; this.headOffset = 0; this.packageOffset = 0; this.packageSize = 0; this.packageBuffer = null; // bind event form the origin socket this._socket.on('data', ondata.bind(null, this)); this._socket.on('end', onend.bind(null, this)); this._socket.on('error', this.emit.bind(this, 'error')); this._socket.on('close', this.emit.bind(this, 'close')); this.state = ST_HEAD; }
javascript
{ "resource": "" }
q18582
train
function(socket, data, offset) { var hlen = socket.headSize - socket.headOffset; var dlen = data.length - offset; var len = Math.min(hlen, dlen); var dend = offset + len; data.copy(socket.headBuffer, socket.headOffset, offset, dend); socket.headOffset += len; if(socket.headOffset === socket.headSize) { // if head segment finished var size = socket.headHandler(socket.headBuffer); if(size < 0) { throw new Error('invalid body size: ' + size); } // check if header contains a valid type if(checkTypeData(socket.headBuffer[0])) { socket.packageSize = size + socket.headSize; socket.packageBuffer = new Buffer(socket.packageSize); socket.headBuffer.copy(socket.packageBuffer, 0, 0, socket.headSize); socket.packageOffset = socket.headSize; socket.state = ST_BODY; } else { dend = data.length; logger.error('close the connection with invalid head message, the remote ip is %s && port is %s && message is %j', socket._socket.remoteAddress, socket._socket.remotePort, data); socket.close(); } } return dend; }
javascript
{ "resource": "" }
q18583
train
function(socket, data, offset) { var blen = socket.packageSize - socket.packageOffset; var dlen = data.length - offset; var len = Math.min(blen, dlen); var dend = offset + len; data.copy(socket.packageBuffer, socket.packageOffset, offset, dend); socket.packageOffset += len; if(socket.packageOffset === socket.packageSize) { // if all the package finished var buffer = socket.packageBuffer; socket.emit('message', buffer); reset(socket); } return dend; }
javascript
{ "resource": "" }
q18584
train
function(isGlobal, server, msg, session, cb) { var fm; if(isGlobal) { fm = server.globalFilterService; } else { fm = server.filterService; } if(fm) { fm.beforeFilter(msg, session, cb); } else { utils.invokeCallback(cb); } }
javascript
{ "resource": "" }
q18585
train
function(isGlobal, server, err, msg, session, resp, opts, cb) { if(isGlobal) { cb(err, resp, opts); // after filter should not interfere response afterFilter(isGlobal, server, err, msg, session, resp, opts, cb); } else { afterFilter(isGlobal, server, err, msg, session, resp, opts, cb); } }
javascript
{ "resource": "" }
q18586
train
function(cron, crons, server) { if(!containCron(cron.id, crons)) { server.crons.push(cron); } else { logger.warn('cron is duplicated: %j', cron); } }
javascript
{ "resource": "" }
q18587
train
function(id, crons) { for(var i=0, l=crons.length; i<l; i++) { if(id === crons[i].id) { return true; } } return false; }
javascript
{ "resource": "" }
q18588
train
function() { EventEmitter.call(this); this.httpServer = new HttpServer(); var self = this; this.wsServer = new WebSocketServer({server: this.httpServer}); this.wsServer.on('connection', function(socket) { // emit socket to outside self.emit('connection', socket); }); this.state = ST_STARTED; }
javascript
{ "resource": "" }
q18589
train
function(app, args) { app.set(Constants.RESERVED.ENV, args.env || process.env.NODE_ENV || Constants.RESERVED.ENV_DEV, true); }
javascript
{ "resource": "" }
q18590
train
function(app) { if (process.env.POMELO_LOGGER !== 'off') { var env = app.get(Constants.RESERVED.ENV); var originPath = path.join(app.getBase(), Constants.FILEPATH.LOG); var presentPath = path.join(app.getBase(), Constants.FILEPATH.CONFIG_DIR, env, path.basename(Constants.FILEPATH.LOG)); if(fs.existsSync(originPath)) { log.configure(app, originPath); } else if(fs.existsSync(presentPath)) { log.configure(app, presentPath); } else { logger.error('logger file path configuration is error.'); } } }
javascript
{ "resource": "" }
q18591
train
function(app) { var filePath = path.join(app.getBase(), Constants.FILEPATH.SERVER_DIR, app.serverType, Constants.FILEPATH.LIFECYCLE); if(!fs.existsSync(filePath)) { return; } var lifecycle = require(filePath); for(var key in lifecycle) { if(typeof lifecycle[key] === 'function') { app.lifecycleCbs[key] = lifecycle[key]; } else { logger.warn('lifecycle.js in %s is error format.', filePath); } } }
javascript
{ "resource": "" }
q18592
train
function(app) { var paths = []; var role; // master server should not come here if(app.isFrontend()) { role = 'frontend'; } else { role = 'backend'; } var sysPath = pathUtil.getSysRemotePath(role), serverType = app.getServerType(); if(fs.existsSync(sysPath)) { paths.push(pathUtil.remotePathRecord('sys', serverType, sysPath)); } var userPath = pathUtil.getUserRemotePath(app.getBase(), serverType); if(fs.existsSync(userPath)) { paths.push(pathUtil.remotePathRecord('user', serverType, userPath)); } return paths; }
javascript
{ "resource": "" }
q18593
train
function(app, opts) { opts.paths = getRemotePaths(app); opts.context = app; if(!!opts.rpcServer) { return opts.rpcServer.create(opts); } else { return RemoteServer.create(opts); } }
javascript
{ "resource": "" }
q18594
train
function(app, opts) { opts = opts || {}; this.app = app; this.connector = getConnector(app, opts); this.encode = opts.encode; this.decode = opts.decode; this.useCrypto = opts.useCrypto; this.useHostFilter = opts.useHostFilter; this.useAsyncCoder = opts.useAsyncCoder; this.blacklistFun = opts.blacklistFun; this.keys = {}; this.blacklist = []; if (opts.useDict) { app.load(pomelo.dictionary, app.get('dictionaryConfig')); } if (opts.useProtobuf) { app.load(pomelo.protobuf, app.get('protobufConfig')); } // component dependencies this.server = null; this.session = null; this.connection = null; }
javascript
{ "resource": "" }
q18595
train
function(self, socket) { var app = self.app, sid = socket.id; var session = self.session.get(sid); if (session) { return session; } session = self.session.create(sid, app.getServerId(), socket); logger.debug('[%s] getSession session is created with session id: %s', app.getServerId(), sid); // bind events for session socket.on('disconnect', session.closed.bind(session)); socket.on('error', session.closed.bind(session)); session.on('closed', onSessionClose.bind(null, app)); session.on('bind', function(uid) { logger.debug('session on [%s] bind with uid: %s', self.app.serverId, uid); // update connection statistics if necessary if (self.connection) { self.connection.addLoginedUser(uid, { loginTime: Date.now(), uid: uid, address: socket.remoteAddress.ip + ':' + socket.remoteAddress.port }); } self.app.event.emit(events.BIND_SESSION, session); }); session.on('unbind', function(uid) { if (self.connection) { self.connection.removeLoginedUser(uid); } self.app.event.emit(events.UNBIND_SESSION, session); }); return session; }
javascript
{ "resource": "" }
q18596
train
function(route) { if (!route) { return null; } var idx = route.indexOf('.'); if (idx < 0) { return null; } return route.substring(0, idx); }
javascript
{ "resource": "" }
q18597
train
function(app, opts) { this.app = app; this.opts = opts; this.client = genRpcClient(this.app, opts); this.app.event.on(events.ADD_SERVERS, this.addServers.bind(this)); this.app.event.on(events.REMOVE_SERVERS, this.removeServers.bind(this)); this.app.event.on(events.REPLACE_SERVERS, this.replaceServers.bind(this)); }
javascript
{ "resource": "" }
q18598
train
function(app, opts) { opts.context = app; opts.routeContext = app; if(!!opts.rpcClient) { return opts.rpcClient.create(opts); } else { return Client.create(opts); } }
javascript
{ "resource": "" }
q18599
train
function(id, socket) { EventEmitter.call(this); this.id = id; this.socket = socket; this.remoteAddress = { ip: socket.handshake.address.address, port: socket.handshake.address.port }; var self = this; socket.on('disconnect', this.emit.bind(this, 'disconnect')); socket.on('error', this.emit.bind(this, 'error')); socket.on('message', function(msg) { self.emit('message', msg); }); this.state = ST_INITED; // TODO: any other events? }
javascript
{ "resource": "" }