_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q62400
selectBestInvalidOverloadIndex
test
function selectBestInvalidOverloadIndex(candidates, argumentCount) { var maxParamsSignatureIndex = -1; var maxParams = -1; for (var i = 0; i < candidates.length; i++) { var candidate = candidates[i]; if (candidate.hasRestParameter || candidate.parameters.length >= argumentCount) { return i; } if (candidate.parameters.length > maxParams) { maxParams = candidate.parameters.length; maxParamsSignatureIndex = i; } } return maxParamsSignatureIndex; }
javascript
{ "resource": "" }
q62401
getTokenAtPositionWorker
test
function getTokenAtPositionWorker(sourceFile, position, allowPositionInLeadingTrivia, includeItemAtEndPosition) { var current = sourceFile; outer: while (true) { if (isToken(current)) { // exit early return current; } // find the child that contains 'position' for (var i = 0, n = current.getChildCount(sourceFile); i < n; i++) { var child = current.getChildAt(i); var start = allowPositionInLeadingTrivia ? child.getFullStart() : child.getStart(sourceFile); if (start <= position) { var end = child.getEnd(); if (position < end || (position === end && child.kind === 1 /* EndOfFileToken */)) { current = child; continue outer; } else if (includeItemAtEndPosition && end === position) { var previousToken = findPrecedingToken(position, sourceFile, child); if (previousToken && includeItemAtEndPosition(previousToken)) { return previousToken; } } } } return current; } }
javascript
{ "resource": "" }
q62402
findTokenOnLeftOfPosition
test
function findTokenOnLeftOfPosition(file, position) { // Ideally, getTokenAtPosition should return a token. However, it is currently // broken, so we do a check to make sure the result was indeed a token. var tokenAtPosition = getTokenAtPosition(file, position); if (isToken(tokenAtPosition) && position > tokenAtPosition.getStart(file) && position < tokenAtPosition.getEnd()) { return tokenAtPosition; } return findPrecedingToken(position, file); }
javascript
{ "resource": "" }
q62403
getJsDocTagAtPosition
test
function getJsDocTagAtPosition(sourceFile, position) { var node = ts.getTokenAtPosition(sourceFile, position); if (isToken(node)) { switch (node.kind) { case 102 /* VarKeyword */: case 108 /* LetKeyword */: case 74 /* ConstKeyword */: // if the current token is var, let or const, skip the VariableDeclarationList node = node.parent === undefined ? undefined : node.parent.parent; break; default: node = node.parent; break; } } if (node) { var jsDocComment = node.jsDocComment; if (jsDocComment) { for (var _i = 0, _a = jsDocComment.tags; _i < _a.length; _i++) { var tag = _a[_i]; if (tag.pos <= position && position <= tag.end) { return tag; } } } } return undefined; }
javascript
{ "resource": "" }
q62404
stripQuotes
test
function stripQuotes(name) { var length = name.length; if (length >= 2 && name.charCodeAt(0) === name.charCodeAt(length - 1) && (name.charCodeAt(0) === 34 /* doubleQuote */ || name.charCodeAt(0) === 39 /* singleQuote */)) { return name.substring(1, length - 1); } ; return name; }
javascript
{ "resource": "" }
q62405
fixTokenKind
test
function fixTokenKind(tokenInfo, container) { if (ts.isToken(container) && tokenInfo.token.kind !== container.kind) { tokenInfo.token.kind = container.kind; } return tokenInfo; }
javascript
{ "resource": "" }
q62406
isListElement
test
function isListElement(parent, node) { switch (parent.kind) { case 214 /* ClassDeclaration */: case 215 /* InterfaceDeclaration */: return ts.rangeContainsRange(parent.members, node); case 218 /* ModuleDeclaration */: var body = parent.body; return body && body.kind === 192 /* Block */ && ts.rangeContainsRange(body.statements, node); case 248 /* SourceFile */: case 192 /* Block */: case 219 /* ModuleBlock */: return ts.rangeContainsRange(parent.statements, node); case 244 /* CatchClause */: return ts.rangeContainsRange(parent.block.statements, node); } return false; }
javascript
{ "resource": "" }
q62407
findEnclosingNode
test
function findEnclosingNode(range, sourceFile) { return find(sourceFile); function find(n) { var candidate = ts.forEachChild(n, function (c) { return ts.startEndContainsRange(c.getStart(sourceFile), c.end, range) && c; }); if (candidate) { var result = find(candidate); if (result) { return result; } } return n; } }
javascript
{ "resource": "" }
q62408
prepareRangeContainsErrorFunction
test
function prepareRangeContainsErrorFunction(errors, originalRange) { if (!errors.length) { return rangeHasNoErrors; } // pick only errors that fall in range var sorted = errors .filter(function (d) { return ts.rangeOverlapsWithStartEnd(originalRange, d.start, d.start + d.length); }) .sort(function (e1, e2) { return e1.start - e2.start; }); if (!sorted.length) { return rangeHasNoErrors; } var index = 0; return function (r) { // in current implementation sequence of arguments [r1, r2...] is monotonically increasing. // 'index' tracks the index of the most recent error that was checked. while (true) { if (index >= sorted.length) { // all errors in the range were already checked -> no error in specified range return false; } var error = sorted[index]; if (r.end <= error.start) { // specified range ends before the error refered by 'index' - no error in range return false; } if (ts.startEndOverlapsWithStartEnd(r.pos, r.end, error.start, error.start + error.length)) { // specified range overlaps with error range return true; } index++; } }; function rangeHasNoErrors(r) { return false; } }
javascript
{ "resource": "" }
q62409
isInsideComment
test
function isInsideComment(sourceFile, token, position) { // The position has to be: 1. in the leading trivia (before token.getStart()), and 2. within a comment return position <= token.getStart(sourceFile) && (isInsideCommentRange(ts.getTrailingCommentRanges(sourceFile.text, token.getFullStart())) || isInsideCommentRange(ts.getLeadingCommentRanges(sourceFile.text, token.getFullStart()))); function isInsideCommentRange(comments) { return ts.forEach(comments, function (comment) { // either we are 1. completely inside the comment, or 2. at the end of the comment if (comment.pos < position && position < comment.end) { return true; } else if (position === comment.end) { var text = sourceFile.text; var width = comment.end - comment.pos; // is single line comment or just /* if (width <= 2 || text.charCodeAt(comment.pos + 1) === 47 /* slash */) { return true; } else { // is unterminated multi-line comment return !(text.charCodeAt(comment.end - 1) === 47 /* slash */ && text.charCodeAt(comment.end - 2) === 42 /* asterisk */); } } return false; }); } }
javascript
{ "resource": "" }
q62410
getSemanticDiagnostics
test
function getSemanticDiagnostics(fileName) { synchronizeHostData(); var targetSourceFile = getValidSourceFile(fileName); // For JavaScript files, we don't want to report the normal typescript semantic errors. // Instead, we just report errors for using TypeScript-only constructs from within a // JavaScript file. if (ts.isJavaScript(fileName)) { return getJavaScriptSemanticDiagnostics(targetSourceFile); } // Only perform the action per file regardless of '-out' flag as LanguageServiceHost is expected to call this function per file. // Therefore only get diagnostics for given file. var semanticDiagnostics = program.getSemanticDiagnostics(targetSourceFile, cancellationToken); if (!program.getCompilerOptions().declaration) { return semanticDiagnostics; } // If '-d' is enabled, check for emitter error. One example of emitter error is export class implements non-export interface var declarationDiagnostics = program.getDeclarationDiagnostics(targetSourceFile, cancellationToken); return ts.concatenate(semanticDiagnostics, declarationDiagnostics); }
javascript
{ "resource": "" }
q62411
getCompletionEntryDisplayName
test
function getCompletionEntryDisplayName(name, target, performCharacterChecks) { if (!name) { return undefined; } name = ts.stripQuotes(name); if (!name) { return undefined; } // If the user entered name for the symbol was quoted, removing the quotes is not enough, as the name could be an // invalid identifier name. We need to check if whatever was inside the quotes is actually a valid identifier name. // e.g "b a" is valid quoted name but when we strip off the quotes, it is invalid. // We, thus, need to check if whatever was inside the quotes is actually a valid identifier name. if (performCharacterChecks) { if (!ts.isIdentifierStart(name.charCodeAt(0), target)) { return undefined; } for (var i = 1, n = name.length; i < n; i++) { if (!ts.isIdentifierPart(name.charCodeAt(i), target)) { return undefined; } } } return name; }
javascript
{ "resource": "" }
q62412
getScopeNode
test
function getScopeNode(initialToken, position, sourceFile) { var scope = initialToken; while (scope && !ts.positionBelongsToNode(scope, position, sourceFile)) { scope = scope.parent; } return scope; }
javascript
{ "resource": "" }
q62413
tryGetObjectLikeCompletionSymbols
test
function tryGetObjectLikeCompletionSymbols(objectLikeContainer) { // We're looking up possible property names from contextual/inferred/declared type. isMemberCompletion = true; var typeForObject; var existingMembers; if (objectLikeContainer.kind === 165 /* ObjectLiteralExpression */) { // We are completing on contextual types, but may also include properties // other than those within the declared type. isNewIdentifierLocation = true; typeForObject = typeChecker.getContextualType(objectLikeContainer); existingMembers = objectLikeContainer.properties; } else if (objectLikeContainer.kind === 161 /* ObjectBindingPattern */) { // We are *only* completing on properties from the type being destructured. isNewIdentifierLocation = false; var rootDeclaration = ts.getRootDeclaration(objectLikeContainer.parent); if (ts.isVariableLike(rootDeclaration)) { // We don't want to complete using the type acquired by the shape // of the binding pattern; we are only interested in types acquired // through type declaration or inference. if (rootDeclaration.initializer || rootDeclaration.type) { typeForObject = typeChecker.getTypeAtLocation(objectLikeContainer); existingMembers = objectLikeContainer.elements; } } else { ts.Debug.fail("Root declaration is not variable-like."); } } else { ts.Debug.fail("Expected object literal or binding pattern, got " + objectLikeContainer.kind); } if (!typeForObject) { return false; } var typeMembers = typeChecker.getPropertiesOfType(typeForObject); if (typeMembers && typeMembers.length > 0) { // Add filtered items to the completion list symbols = filterObjectMembersList(typeMembers, existingMembers); } return true; }
javascript
{ "resource": "" }
q62414
tryGetImportOrExportClauseCompletionSymbols
test
function tryGetImportOrExportClauseCompletionSymbols(namedImportsOrExports) { var declarationKind = namedImportsOrExports.kind === 225 /* NamedImports */ ? 222 /* ImportDeclaration */ : 228 /* ExportDeclaration */; var importOrExportDeclaration = ts.getAncestor(namedImportsOrExports, declarationKind); var moduleSpecifier = importOrExportDeclaration.moduleSpecifier; if (!moduleSpecifier) { return false; } isMemberCompletion = true; isNewIdentifierLocation = false; var exports; var moduleSpecifierSymbol = typeChecker.getSymbolAtLocation(importOrExportDeclaration.moduleSpecifier); if (moduleSpecifierSymbol) { exports = typeChecker.getExportsOfModule(moduleSpecifierSymbol); } symbols = exports ? filterNamedImportOrExportCompletionItems(exports, namedImportsOrExports.elements) : emptyArray; return true; }
javascript
{ "resource": "" }
q62415
tryGetObjectLikeCompletionContainer
test
function tryGetObjectLikeCompletionContainer(contextToken) { if (contextToken) { switch (contextToken.kind) { case 15 /* OpenBraceToken */: // let x = { | case 24 /* CommaToken */: var parent_10 = contextToken.parent; if (parent_10 && (parent_10.kind === 165 /* ObjectLiteralExpression */ || parent_10.kind === 161 /* ObjectBindingPattern */)) { return parent_10; } break; } } return undefined; }
javascript
{ "resource": "" }
q62416
filterJsxAttributes
test
function filterJsxAttributes(symbols, attributes) { var seenNames = {}; for (var _i = 0; _i < attributes.length; _i++) { var attr = attributes[_i]; // If this is the current item we are editing right now, do not filter it out if (attr.getStart() <= position && position <= attr.getEnd()) { continue; } if (attr.kind === 238 /* JsxAttribute */) { seenNames[attr.name.text] = true; } } return ts.filter(symbols, function (a) { return !ts.lookUp(seenNames, a.name); }); }
javascript
{ "resource": "" }
q62417
isWriteAccess
test
function isWriteAccess(node) { if (node.kind === 69 /* Identifier */ && ts.isDeclarationName(node)) { return true; } var parent = node.parent; if (parent) { if (parent.kind === 180 /* PostfixUnaryExpression */ || parent.kind === 179 /* PrefixUnaryExpression */) { return true; } else if (parent.kind === 181 /* BinaryExpression */ && parent.left === node) { var operator = parent.operatorToken.kind; return 56 /* FirstAssignment */ <= operator && operator <= 68 /* LastAssignment */; } } return false; }
javascript
{ "resource": "" }
q62418
getSignatureHelpItems
test
function getSignatureHelpItems(fileName, position) { synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); return ts.SignatureHelp.getSignatureHelpItems(program, sourceFile, position, cancellationToken); }
javascript
{ "resource": "" }
q62419
hasValueSideModule
test
function hasValueSideModule(symbol) { return ts.forEach(symbol.declarations, function (declaration) { return declaration.kind === 218 /* ModuleDeclaration */ && ts.getModuleInstanceState(declaration) === 1 /* Instantiated */; }); }
javascript
{ "resource": "" }
q62420
classifyTokenType
test
function classifyTokenType(tokenKind, token) { if (ts.isKeyword(tokenKind)) { return 3 /* keyword */; } // Special case < and > If they appear in a generic context they are punctuation, // not operators. if (tokenKind === 25 /* LessThanToken */ || tokenKind === 27 /* GreaterThanToken */) { // If the node owning the token has a type argument list or type parameter list, then // we can effectively assume that a '<' and '>' belong to those lists. if (token && ts.getTypeArgumentOrTypeParameterList(token.parent)) { return 10 /* punctuation */; } } if (ts.isPunctuation(tokenKind)) { if (token) { if (tokenKind === 56 /* EqualsToken */) { // the '=' in a variable declaration is special cased here. if (token.parent.kind === 211 /* VariableDeclaration */ || token.parent.kind === 141 /* PropertyDeclaration */ || token.parent.kind === 138 /* Parameter */) { return 5 /* operator */; } } if (token.parent.kind === 181 /* BinaryExpression */ || token.parent.kind === 179 /* PrefixUnaryExpression */ || token.parent.kind === 180 /* PostfixUnaryExpression */ || token.parent.kind === 182 /* ConditionalExpression */) { return 5 /* operator */; } } return 10 /* punctuation */; } else if (tokenKind === 8 /* NumericLiteral */) { return 4 /* numericLiteral */; } else if (tokenKind === 9 /* StringLiteral */) { return 6 /* stringLiteral */; } else if (tokenKind === 10 /* RegularExpressionLiteral */) { // TODO: we should get another classification type for these literals. return 6 /* stringLiteral */; } else if (ts.isTemplateLiteralKind(tokenKind)) { // TODO (drosen): we should *also* get another classification type for these literals. return 6 /* stringLiteral */; } else if (tokenKind === 69 /* Identifier */) { if (token) { switch (token.parent.kind) { case 214 /* ClassDeclaration */: if (token.parent.name === token) { return 11 /* className */; } return; case 137 /* TypeParameter */: if (token.parent.name === token) { return 15 /* typeParameterName */; } return; case 215 /* InterfaceDeclaration */: if (token.parent.name === token) { return 13 /* interfaceName */; } return; case 217 /* EnumDeclaration */: if (token.parent.name === token) { return 12 /* enumName */; } return; case 218 /* ModuleDeclaration */: if (token.parent.name === token) { return 14 /* moduleName */; } return; case 138 /* Parameter */: if (token.parent.name === token) { return 17 /* parameterName */; } return; } } return 2 /* identifier */; } }
javascript
{ "resource": "" }
q62421
getParametersFromRightHandSideOfAssignment
test
function getParametersFromRightHandSideOfAssignment(rightHandSide) { while (rightHandSide.kind === 172 /* ParenthesizedExpression */) { rightHandSide = rightHandSide.expression; } switch (rightHandSide.kind) { case 173 /* FunctionExpression */: case 174 /* ArrowFunction */: return rightHandSide.parameters; case 186 /* ClassExpression */: for (var _i = 0, _a = rightHandSide.members; _i < _a.length; _i++) { var member = _a[_i]; if (member.kind === 144 /* Constructor */) { return member.parameters; } } break; } return emptyArray; }
javascript
{ "resource": "" }
q62422
score
test
function score(backend, errorBasis) { if (typeof errorBasis !== "number" && !errorBasis) errorBasis = Date.now(); const timeSinceError = (errorBasis - backend.lastError); const statuses = backend.statuses; const timeWeight = (backend.lastError === 0 && 0) || ((timeSinceError < 1000) && 1) || ((timeSinceError < 3000) && 0.8) || ((timeSinceError < 5000) && 0.3) || ((timeSinceError < 10000) && 0.1) || 0; if (statuses.length == 0) return 0; let requests = 0; let errors = 0; for (let i = 0; i < statuses.length; i++) { const status = statuses[i]; if (status && !isNaN(status)) { requests += 1; if (status >= 500 && status < 600) { errors += 1; } } } const score = (1 - (timeWeight * (errors / requests))); backend.healthScore = score; backend.scoredRequestCount = backend.requestCount; return score; }
javascript
{ "resource": "" }
q62423
origin
test
async function origin(req, init) { const url = new URL(req.url) const status = parseInt(url.searchParams.get('status') || '200') if (status === 200) { return new Response(`hello from ${req.url} on ${new Date()}`) } else { return new Response(`an error! Number ${status}`, { status: status }) } }
javascript
{ "resource": "" }
q62424
test
function(element, transform, touch) { // // use translate both as basis for the new transform: // var t = $drag.TRANSLATE_BOTH(element, transform, touch); // // Add rotation: // var Dx = touch.distanceX; var t0 = touch.startTransform; var sign = Dx < 0 ? -1 : 1; var angle = sign * Math.min((Math.abs(Dx) / 700) * 30, 30); t.rotateZ = angle + (Math.round(t0.rotateZ)); return t; }
javascript
{ "resource": "" }
q62425
test
function(t) { var absAngle = abs(t.angle); absAngle = absAngle >= 90 ? absAngle - 90 : absAngle; var validDistance = t.total - t.distance <= TURNAROUND_MAX; var validAngle = absAngle <= ANGLE_THRESHOLD || absAngle >= 90 - ANGLE_THRESHOLD; var validVelocity = t.averageVelocity >= VELOCITY_THRESHOLD; return validDistance && validAngle && validVelocity; }
javascript
{ "resource": "" }
q62426
test
function(element, eventHandlers, options) { options = angular.extend({}, defaultOptions, options || {}); return $touch.bind(element, eventHandlers, options); }
javascript
{ "resource": "" }
q62427
test
function(type, c, t0, tl) { // Compute values for new TouchInfo based on coordinates and previus touches. // - c is coords of new touch // - t0 is first touch: useful to compute duration and distance (how far pointer // got from first touch) // - tl is last touch: useful to compute velocity and length (total length of the movement) t0 = t0 || {}; tl = tl || {}; // timestamps var ts = now(); var ts0 = t0.timestamp || ts; var tsl = tl.timestamp || ts0; // coords var x = c.x; var y = c.y; var x0 = t0.x || x; var y0 = t0.y || y; var xl = tl.x || x0; var yl = tl.y || y0; // total movement var totalXl = tl.totalX || 0; var totalYl = tl.totalY || 0; var totalX = totalXl + abs(x - xl); var totalY = totalYl + abs(y - yl); var total = len(totalX, totalY); // duration var duration = timediff(ts, ts0); var durationl = timediff(ts, tsl); // distance var dxl = x - xl; var dyl = y - yl; var dl = len(dxl, dyl); var dx = x - x0; var dy = y - y0; var d = len(dx, dy); // velocity (px per second) var v = durationl > 0 ? abs(dl / (durationl / 1000)) : 0; var tv = duration > 0 ? abs(total / (duration / 1000)) : 0; // main direction: 'LEFT', 'RIGHT', 'TOP', 'BOTTOM' var dir = abs(dx) > abs(dy) ? (dx < 0 ? 'LEFT' : 'RIGHT') : (dy < 0 ? 'TOP' : 'BOTTOM'); // angle (angle between distance vector and x axis) // angle will be: // 0 for x > 0 and y = 0 // 90 for y < 0 and x = 0 // 180 for x < 0 and y = 0 // -90 for y > 0 and x = 0 // // -90° // | // | // | // 180° --------|-------- 0° // | // | // | // 90° // var angle = dx !== 0 || dy !== 0 ? atan2(dy, dx) * (180 / Math.PI) : null; angle = angle === -180 ? 180 : angle; return { type: type, timestamp: ts, duration: duration, startX: x0, startY: y0, prevX: xl, prevY: yl, x: c.x, y: c.y, step: dl, // distance from prev stepX: dxl, stepY: dyl, velocity: v, averageVelocity: tv, distance: d, // distance from start distanceX: dx, distanceY: dy, total: total, // total length of momement, // considering turnaround totalX: totalX, totalY: totalY, direction: dir, angle: angle }; }
javascript
{ "resource": "" }
q62428
test
function(event) { // don't handle multi-touch if (event.touches && event.touches.length > 1) { return; } tl = t0 = buildTouchInfo('touchstart', getCoordinates(event)); $movementTarget.on(moveEvents, onTouchMove); $movementTarget.on(endEvents, onTouchEnd); if (cancelEvents) { $movementTarget.on(cancelEvents, onTouchCancel); } if (startEventHandler) { startEventHandler(t0, event); } }
javascript
{ "resource": "" }
q62429
test
function(e) { e = e.length ? e[0] : e; var tr = window .getComputedStyle(e, null) .getPropertyValue(transformProperty); return tr; }
javascript
{ "resource": "" }
q62430
test
function(elem, value) { elem = elem.length ? elem[0] : elem; elem.style[styleProperty] = value; }
javascript
{ "resource": "" }
q62431
test
function(e, t) { var str = (typeof t === 'string') ? t : this.toCss(t); setElementTransformProperty(e, str); }
javascript
{ "resource": "" }
q62432
test
function (_path) { if (/^((pre|post)?loader)s?/ig.test(_path)) { return _path.replace(/^((pre|post)?loader)s?/ig, 'module.$1s') } if (/^(plugin)s?/g.test(_path)) { return _path.replace(/^(plugin)s?/g, '$1s') } return _path }
javascript
{ "resource": "" }
q62433
getPayload
test
function getPayload(token) { const payloadBase64 = token .split(".")[1] .replace("-", "+") .replace("_", "/"); const payloadDecoded = base64.decode(payloadBase64); const payloadObject = JSON.parse(payloadDecoded); if (AV.isNumber(payloadObject.exp)) { payloadObject.exp = new Date(payloadObject.exp * 1000); } return payloadObject; }
javascript
{ "resource": "" }
q62434
setChapterActive
test
function setChapterActive($chapter, hash) { // No chapter and no hash means first chapter if (!$chapter && !hash) { $chapter = $chapters.first(); } // If hash is provided, set as active chapter if (!!hash) { // Multiple chapters for this file if ($chapters.length > 1) { $chapter = $chapters.filter(function() { var titleId = getChapterHash($(this)); return titleId == hash; }).first(); } // Only one chapter, no need to search else { $chapter = $chapters.first(); } } // Don't update current chapter if ($chapter.is($activeChapter)) { return; } // Update current active chapter $activeChapter = $chapter; // Add class to selected chapter $chapters.removeClass('active'); $chapter.addClass('active'); // Update history state if needed hash = getChapterHash($chapter); var oldUri = window.location.pathname + window.location.hash, uri = window.location.pathname + hash; if (uri != oldUri) { history.replaceState({ path: uri }, null, uri); } }
javascript
{ "resource": "" }
q62435
getChapterHash
test
function getChapterHash($chapter) { var $link = $chapter.children('a'), hash = $link.attr('href').split('#')[1]; if (hash) hash = '#'+hash; return (!!hash)? hash : ''; }
javascript
{ "resource": "" }
q62436
handleScrolling
test
function handleScrolling() { // Get current page scroll var $scroller = getScroller(), scrollTop = $scroller.scrollTop(), scrollHeight = $scroller.prop('scrollHeight'), clientHeight = $scroller.prop('clientHeight'), nbChapters = $chapters.length, $chapter = null; // Find each title position in reverse order $($chapters.get().reverse()).each(function(index) { var titleId = getChapterHash($(this)), titleTop; if (!!titleId && !$chapter) { titleTop = getElementTopPosition(titleId); // Set current chapter as active if scroller passed it if (scrollTop >= titleTop) { $chapter = $(this); } } // If no active chapter when reaching first chapter, set it as active if (index == (nbChapters - 1) && !$chapter) { $chapter = $(this); } }); // ScrollTop is at 0, set first chapter anyway if (!$chapter && !scrollTop) { $chapter = $chapters.first(); } // Set last chapter as active if scrolled to bottom of page if (!!scrollTop && (scrollHeight - scrollTop == clientHeight)) { $chapter = $chapters.last(); } setChapterActive($chapter); }
javascript
{ "resource": "" }
q62437
insertAt
test
function insertAt(parent, selector, index, element) { var lastIndex = parent.children(selector).length; if (index < 0) { index = Math.max(0, lastIndex + 1 + index); } parent.append(element); if (index < lastIndex) { parent.children(selector).eq(index).before(parent.children(selector).last()); } }
javascript
{ "resource": "" }
q62438
createDropdownMenu
test
function createDropdownMenu(dropdown) { var $menu = $('<div>', { 'class': 'dropdown-menu', 'html': '<div class="dropdown-caret"><span class="caret-outer"></span><span class="caret-inner"></span></div>' }); if (typeof dropdown == 'string') { $menu.append(dropdown); } else { var groups = dropdown.map(function(group) { if ($.isArray(group)) return group; else return [group]; }); // Create buttons groups groups.forEach(function(group) { var $group = $('<div>', { 'class': 'buttons' }); var sizeClass = 'size-'+group.length; // Append buttons group.forEach(function(btn) { btn = $.extend({ text: '', className: '', onClick: defaultOnClick }, btn || {}); var $btn = $('<button>', { 'class': 'button '+sizeClass+' '+btn.className, 'text': btn.text }); $btn.click(btn.onClick); $group.append($btn); }); $menu.append($group); }); } return $menu; }
javascript
{ "resource": "" }
q62439
createButton
test
function createButton(opts) { opts = $.extend({ // Aria label for the button label: '', // Icon to show icon: '', // Inner text text: '', // Right or left position position: 'left', // Other class name to add to the button className: '', // Triggered when user click on the button onClick: defaultOnClick, // Button is a dropdown dropdown: null, // Position in the toolbar index: null, // Button id for removal id: generateId() }, opts || {}); buttons.push(opts); updateButton(opts); return opts.id; }
javascript
{ "resource": "" }
q62440
removeButton
test
function removeButton(id) { buttons = $.grep(buttons, function(button) { return button.id != id; }); updateAllButtons(); }
javascript
{ "resource": "" }
q62441
removeButtons
test
function removeButtons(ids) { buttons = $.grep(buttons, function(button) { return ids.indexOf(button.id) == -1; }); updateAllButtons(); }
javascript
{ "resource": "" }
q62442
toggleSidebar
test
function toggleSidebar(_state, animation) { if (gitbook.state != null && isOpen() == _state) return; if (animation == null) animation = true; gitbook.state.$book.toggleClass('without-animation', !animation); gitbook.state.$book.toggleClass('with-summary', _state); gitbook.storage.set('sidebar', isOpen()); }
javascript
{ "resource": "" }
q62443
filterSummary
test
function filterSummary(paths) { var $summary = $('.book-summary'); $summary.find('li').each(function() { var path = $(this).data('path'); var st = paths == null || paths.indexOf(path) !== -1; $(this).toggle(st); if (st) $(this).parents('li').show(); }); }
javascript
{ "resource": "" }
q62444
init
test
function init() { $(document).on('click', '.toggle-dropdown', toggleDropdown); $(document).on('click', '.dropdown-menu', function(e){ e.stopPropagation(); }); $(document).on('click', closeDropdown); }
javascript
{ "resource": "" }
q62445
init
test
function init() { // Next bindShortcut(['right'], function(e) { navigation.goNext(); }); // Prev bindShortcut(['left'], function(e) { navigation.goPrev(); }); // Toggle Summary bindShortcut(['s'], function(e) { sidebar.toggle(); }); }
javascript
{ "resource": "" }
q62446
addDirective
test
function addDirective (type) { return function (name, directive) { if (typeof name === 'function') { directive = name } if (typeof directive !== 'function') { throw new TypeError('Directive must be a function') } name = typeof name === 'string' ? name : directive.name if (!name) { throw new TypeError('Directive function must have a name') } directive.$name = name Toxy[type][name] = directive return Toxy } }
javascript
{ "resource": "" }
q62447
Directive
test
function Directive (directive) { Rule.call(this) this.enabled = true this.directive = directive this.name = directive.$name || directive.name }
javascript
{ "resource": "" }
q62448
Toxy
test
function Toxy (opts) { if (!(this instanceof Toxy)) return new Toxy(opts) opts = Object.assign({}, Toxy.defaults, opts) Proxy.call(this, opts) this.routes = [] this._rules = midware() this._inPoisons = midware() this._outPoisons = midware() setupMiddleware(this) }
javascript
{ "resource": "" }
q62449
getModifiedConfigModuleIndex
test
function getModifiedConfigModuleIndex(fileStr, snakedEnv, classedEnv) { // TODO [sthzg] we might want to rewrite the AST-mods in this function using a walker. const moduleFileAst = acorn.parse(fileStr, { module: true }); // if required env was already created, just return the original string if (jp.paths(moduleFileAst, `$..[?(@.value=="./${classedEnv}" && @.type=="Literal")]`).length > 0) { return fileStr; } // insert require call for the new env const envImportAst = acorn.parse(`const ${snakedEnv} = require('./${classedEnv}');`); const insertAt = jp.paths(moduleFileAst, '$..[?(@.name=="require")]').pop()[2] + 1; moduleFileAst.body.splice(insertAt, 0, envImportAst); // add new env to module.exports const exportsAt = jp.paths(moduleFileAst, '$..[?(@.name=="exports")]').pop()[2]; moduleFileAst.body[exportsAt].expression.right.properties.push(createExportNode(snakedEnv)); return escodegen.generate(moduleFileAst, { format: { indent: { style: ' ' } } }); }
javascript
{ "resource": "" }
q62450
test
function(path) { const data = fs.readFileSync(path, 'utf8'); const ast = esprima.parse(data); // List of css dialects we want to add postCSS for // On regular css, we can add the loader to the end // of the chain. If we have a preprocessor, we will add // it before the initial loader const cssDialects = [ '\\.cssmodule\\.css$', '^.((?!cssmodule).)*\\.css$' ]; const preprocessorDialects = [ '\\.cssmodule\\.(sass|scss)$', '^.((?!cssmodule).)*\\.(sass|scss)$', '\\.cssmodule\\.less$', '^.((?!cssmodule).)*\\.less$', '\\.cssmodule\\.styl$', '^.((?!cssmodule).)*\\.styl$' ]; // Prepare postCSS statement for inclusion const postcssFunction = 'var postcss = { postcss: function() { return []; } }'; const postcssAst = esprima.parse(postcssFunction); const postcss = postcssAst.body[0].declarations[0].init.properties[0]; // The postcss loader item to add const postcssLoaderObject = 'var postcss = [{ loader: \'postcss-loader\'}]'; const postcssLoaderAst = esprima.parse(postcssLoaderObject); const postcssLoader = postcssLoaderAst.body[0].declarations[0].init.elements[0]; // Add postcss to the loaders array walk.walkAddParent(ast, (node) => { // Add the postcss key to the global configuration if( node.type === 'MethodDefinition' && node.key.name === 'defaultSettings' ) { const returnStatement = node.value.body.body[1]; returnStatement.argument.properties.push(postcss); } // Parse all property nodes that use a regex. // This should only be available under module.(pre)loaders if( node.type === 'Property' && node.key.type === 'Identifier' && node.key.name === 'test' && typeof node.value.regex !== 'undefined' ) { // Regular css usage if(cssDialects.indexOf(node.value.regex.pattern) !== -1) { const loaderData = node.parent.properties[1]; loaderData.value.elements.push(postcssLoader); } if(preprocessorDialects.indexOf(node.value.regex.pattern) !== -1) { const loaderData = node.parent.properties[1]; const lastElm = loaderData.value.elements.pop(); loaderData.value.elements.push(postcssLoader); loaderData.value.elements.push(lastElm); } } }); // Prepare the final code and write it back const finalCode = escodegen.generate(ast, { format: { indent: { adjustMultilineComment: true, style: ' ' } }, comment: true }); fs.writeFileSync(path, finalCode, 'utf8'); }
javascript
{ "resource": "" }
q62451
Metadata
test
function Metadata (options, controlConnection) { if (!options) { throw new errors.ArgumentError('Options are not defined'); } Object.defineProperty(this, 'options', { value: options, enumerable: false, writable: false}); Object.defineProperty(this, 'controlConnection', { value: controlConnection, enumerable: false, writable: false}); this.keyspaces = {}; this.initialized = false; this._schemaParser = schemaParserFactory.getByVersion(options, controlConnection, this.getUdt.bind(this)); const self = this; this._preparedQueries = new PreparedQueries(options.maxPrepared, function () { self.log.apply(self, arguments); }); }
javascript
{ "resource": "" }
q62452
checkUdtTypes
test
function checkUdtTypes(type) { if (type.code === types.dataTypes.udt) { const udtName = type.info.split('.'); type.info = { keyspace: udtName[0], name: udtName[1] }; if (!type.info.name) { if (!keyspace) { throw new TypeError('No keyspace specified for udt: ' + udtName.join('.')); } //use the provided keyspace type.info.name = type.info.keyspace; type.info.keyspace = keyspace; } udts.push(type); return; } if (!type.info) { return; } if (type.code === types.dataTypes.list || type.code === types.dataTypes.set) { return checkUdtTypes(type.info); } if (type.code === types.dataTypes.map) { checkUdtTypes(type.info[0]); checkUdtTypes(type.info[1]); } }
javascript
{ "resource": "" }
q62453
PreparedQueries
test
function PreparedQueries(maxPrepared, logger) { this.length = 0; this._maxPrepared = maxPrepared; this._mapByKey = {}; this._mapById = {}; this._logger = logger; }
javascript
{ "resource": "" }
q62454
DriverError
test
function DriverError (message) { Error.call(this, message); Error.captureStackTrace(this, this.constructor); this.name = this.constructor.name; this.info = 'Cassandra Driver Error'; // Explicitly set the message property as the Error.call() doesn't set the property on v8 this.message = message; }
javascript
{ "resource": "" }
q62455
NoHostAvailableError
test
function NoHostAvailableError(innerErrors, message) { DriverError.call(this, message); this.innerErrors = innerErrors; this.info = 'Represents an error when a query cannot be performed because no host is available or could be reached by the driver.'; if (!message) { this.message = 'All host(s) tried for query failed.'; if (innerErrors) { const hostList = Object.keys(innerErrors); if (hostList.length > 0) { const host = hostList[0]; this.message += util.format(' First host tried, %s: %s. See innerErrors.', host, innerErrors[host]); } } } }
javascript
{ "resource": "" }
q62456
BusyConnectionError
test
function BusyConnectionError(address, maxRequestsPerConnection, connectionLength) { const message = util.format('All connections to host %s are busy, %d requests are in-flight on %s', address, maxRequestsPerConnection, connectionLength === 1 ? 'a single connection': 'each connection'); DriverError.call(this, message, this.constructor); this.info = 'Represents a client-side error indicating that all connections to a certain host have reached ' + 'the maximum amount of in-flight requests supported (pooling.maxRequestsPerConnection)'; }
javascript
{ "resource": "" }
q62457
extend
test
function extend(baseOptions, userOptions) { if (arguments.length === 1) { userOptions = arguments[0]; baseOptions = {}; } const options = utils.deepExtend(baseOptions, defaultOptions(), userOptions); if (!util.isArray(options.contactPoints) || options.contactPoints.length === 0) { throw new TypeError('Contacts points are not defined.'); } for (let i = 0; i < options.contactPoints.length; i++) { const hostName = options.contactPoints[i]; if (!hostName) { throw new TypeError(util.format('Contact point %s (%s) is not a valid host name, ' + 'the following values are valid contact points: ipAddress, hostName or ipAddress:port', i, hostName)); } } if (!options.logEmitter) { options.logEmitter = function () {}; } if (!options.queryOptions) { throw new TypeError('queryOptions not defined in options'); } if (options.requestTracker !== null && !(options.requestTracker instanceof tracker.RequestTracker)) { throw new TypeError('requestTracker must be an instance of RequestTracker'); } if (!(options.metrics instanceof metrics.ClientMetrics)) { throw new TypeError('metrics must be an instance of ClientMetrics'); } validatePoliciesOptions(options.policies); validateProtocolOptions(options.protocolOptions); validateSocketOptions(options.socketOptions); options.encoding = options.encoding || {}; validateEncodingOptions(options.encoding); if (options.profiles && !util.isArray(options.profiles)) { throw new TypeError('profiles must be an Array of ExecutionProfile instances'); } return options; }
javascript
{ "resource": "" }
q62458
validatePoliciesOptions
test
function validatePoliciesOptions(policiesOptions) { if (!policiesOptions) { throw new TypeError('policies not defined in options'); } if (!(policiesOptions.loadBalancing instanceof policies.loadBalancing.LoadBalancingPolicy)) { throw new TypeError('Load balancing policy must be an instance of LoadBalancingPolicy'); } if (!(policiesOptions.reconnection instanceof policies.reconnection.ReconnectionPolicy)) { throw new TypeError('Reconnection policy must be an instance of ReconnectionPolicy'); } if (!(policiesOptions.retry instanceof policies.retry.RetryPolicy)) { throw new TypeError('Retry policy must be an instance of RetryPolicy'); } if (!(policiesOptions.addressResolution instanceof policies.addressResolution.AddressTranslator)) { throw new TypeError('Address resolution policy must be an instance of AddressTranslator'); } if (policiesOptions.timestampGeneration !== null && !(policiesOptions.timestampGeneration instanceof policies.timestampGeneration.TimestampGenerator)) { throw new TypeError('Timestamp generation policy must be an instance of TimestampGenerator'); } }
javascript
{ "resource": "" }
q62459
validateProtocolOptions
test
function validateProtocolOptions(protocolOptions) { if (!protocolOptions) { throw new TypeError('protocolOptions not defined in options'); } const version = protocolOptions.maxVersion; if (version && (typeof version !== 'number' || !types.protocolVersion.isSupported(version))) { throw new TypeError(util.format('protocolOptions.maxVersion provided (%s) is invalid', version)); } }
javascript
{ "resource": "" }
q62460
validateSocketOptions
test
function validateSocketOptions(socketOptions) { if (!socketOptions) { throw new TypeError('socketOptions not defined in options'); } if (typeof socketOptions.readTimeout !== 'number') { throw new TypeError('socketOptions.readTimeout must be a Number'); } if (typeof socketOptions.coalescingThreshold !== 'number' || socketOptions.coalescingThreshold <= 0) { throw new TypeError('socketOptions.coalescingThreshold must be a positive Number'); } }
javascript
{ "resource": "" }
q62461
validateEncodingOptions
test
function validateEncodingOptions(encodingOptions) { if (encodingOptions.map) { const mapConstructor = encodingOptions.map; if (typeof mapConstructor !== 'function' || typeof mapConstructor.prototype.forEach !== 'function' || typeof mapConstructor.prototype.set !== 'function') { throw new TypeError('Map constructor not valid'); } } if (encodingOptions.set) { const setConstructor = encodingOptions.set; if (typeof setConstructor !== 'function' || typeof setConstructor.prototype.forEach !== 'function' || typeof setConstructor.prototype.add !== 'function') { throw new TypeError('Set constructor not valid'); } } if ((encodingOptions.useBigIntAsLong || encodingOptions.useBigIntAsVarint) && typeof BigInt === 'undefined') { throw new TypeError('BigInt is not supported by the JavaScript engine'); } }
javascript
{ "resource": "" }
q62462
setProtocolDependentDefaults
test
function setProtocolDependentDefaults(options, version) { let coreConnectionsPerHost = coreConnectionsPerHostV3; let maxRequestsPerConnection = maxRequestsPerConnectionV3; if (!types.protocolVersion.uses2BytesStreamIds(version)) { coreConnectionsPerHost = coreConnectionsPerHostV2; maxRequestsPerConnection = maxRequestsPerConnectionV2; } options.pooling = utils.deepExtend({}, { coreConnectionsPerHost, maxRequestsPerConnection }, options.pooling); }
javascript
{ "resource": "" }
q62463
test
function(name) { name = name.toLowerCase(); if (name.indexOf('<') > 0) { const listMatches = /^(list|set)<(.+)>$/.exec(name); if (listMatches) { return { code: this[listMatches[1]], info: this.getByName(listMatches[2])}; } const mapMatches = /^(map)< *(.+) *, *(.+)>$/.exec(name); if (mapMatches) { return { code: this[mapMatches[1]], info: [this.getByName(mapMatches[2]), this.getByName(mapMatches[3])]}; } const udtMatches = /^(udt)<(.+)>$/.exec(name); if (udtMatches) { //udt name as raw string return { code: this[udtMatches[1]], info: udtMatches[2]}; } const tupleMatches = /^(tuple)<(.+)>$/.exec(name); if (tupleMatches) { //tuple info as an array of types return { code: this[tupleMatches[1]], info: tupleMatches[2].split(',').map(function (x) { return this.getByName(x.trim()); }, this)}; } } const typeInfo = { code: this[name], info: null}; if (typeof typeInfo.code !== 'number') { throw new TypeError('Data type with name ' + name + ' not valid'); } return typeInfo; }
javascript
{ "resource": "" }
q62464
getDataTypeNameByCode
test
function getDataTypeNameByCode(item) { if (!item || typeof item.code !== 'number') { throw new errors.ArgumentError('Invalid signature type definition'); } const typeName = _dataTypesByCode[item.code]; if (!typeName) { throw new errors.ArgumentError(util.format('Type with code %d not found', item.code)); } if (!item.info) { return typeName; } if (util.isArray(item.info)) { return (typeName + '<' + item.info.map(function (t) { return getDataTypeNameByCode(t); }).join(', ') + '>'); } if (typeof item.info.code === 'number') { return typeName + '<' + getDataTypeNameByCode(item.info) + '>'; } return typeName; }
javascript
{ "resource": "" }
q62465
FrameHeader
test
function FrameHeader(version, flags, streamId, opcode, bodyLength) { this.version = version; this.flags = flags; this.streamId = streamId; this.opcode = opcode; this.bodyLength = bodyLength; }
javascript
{ "resource": "" }
q62466
generateTimestamp
test
function generateTimestamp(date, microseconds) { if (!date) { date = new Date(); } let longMicro = Long.ZERO; if (typeof microseconds === 'number' && microseconds >= 0 && microseconds < 1000) { longMicro = Long.fromInt(microseconds); } else { if (_timestampTicks > 999) { _timestampTicks = 0; } longMicro = Long.fromInt(_timestampTicks); _timestampTicks++; } return Long .fromNumber(date.getTime()) .multiply(_longOneThousand) .add(longMicro); }
javascript
{ "resource": "" }
q62467
MutableLong
test
function MutableLong(b00, b16, b32, b48) { // Use an array of uint16 this._arr = [ b00 & 0xffff, b16 & 0xffff, b32 & 0xffff, b48 & 0xffff ]; }
javascript
{ "resource": "" }
q62468
Aggregate
test
function Aggregate() { /** * Name of the aggregate. * @type {String} */ this.name = null; /** * Name of the keyspace where the aggregate is declared. */ this.keyspaceName = null; /** * Signature of the aggregate. * @type {Array.<String>} */ this.signature = null; /** * List of the CQL aggregate argument types. * @type {Array.<{code, info}>} */ this.argumentTypes = null; /** * State Function. * @type {String} */ this.stateFunction = null; /** * State Type. * @type {{code, info}} */ this.stateType = null; /** * Final Function. * @type {String} */ this.finalFunction = null; this.initConditionRaw = null; /** * Initial state value of this aggregate. * @type {String} */ this.initCondition = null; /** * Type of the return value. * @type {{code: number, info: (Object|Array|null)}} */ this.returnType = null; }
javascript
{ "resource": "" }
q62469
Host
test
function Host(address, protocolVersion, options, metadata) { events.EventEmitter.call(this); /** * Gets ip address and port number of the node separated by `:`. * @type {String} */ this.address = address; this.setDownAt = 0; /** * Gets the timestamp of the moment when the Host was marked as UP. * @type {Number|null} * @ignore * @internal */ this.isUpSince = null; Object.defineProperty(this, 'options', { value: options, enumerable: false, writable: false}); /** * The host pool. * @internal * @ignore * @type {HostConnectionPool} */ Object.defineProperty(this, 'pool', { value: new HostConnectionPool(this, protocolVersion), enumerable: false}); const self = this; this.pool.on('open', this._onNewConnectionOpen.bind(this)); this.pool.on('remove', function onConnectionRemovedFromPool() { self._checkPoolState(); }); /** * Gets string containing the Cassandra version. * @type {String} */ this.cassandraVersion = null; /** * Gets data center name of the node. * @type {String} */ this.datacenter = null; /** * Gets rack name of the node. * @type {String} */ this.rack = null; /** * Gets the tokens assigned to the node. * @type {Array} */ this.tokens = null; /** * Gets the id of the host. * <p>This identifier is used by the server for internal communication / gossip.</p> * @type {Uuid} */ this.hostId = null; // the distance as last set using the load balancing policy this._distance = types.distance.ignored; this._healthResponseCounter = 0; // Make some of the private instance variables not enumerable to prevent from showing when inspecting Object.defineProperty(this, '_metadata', { value: metadata, enumerable: false }); Object.defineProperty(this, '_healthResponseCountTimer', { value: null, enumerable: false, writable: true }); this.reconnectionSchedule = this.options.policies.reconnection.newSchedule(); this.reconnectionDelay = 0; }
javascript
{ "resource": "" }
q62470
ConstantSpeculativeExecutionPolicy
test
function ConstantSpeculativeExecutionPolicy(delay, maxSpeculativeExecutions) { if (!(delay >= 0)) { throw new errors.ArgumentError('delay must be a positive number or zero'); } if (!(maxSpeculativeExecutions > 0)) { throw new errors.ArgumentError('maxSpeculativeExecutions must be a positive number'); } this._delay = delay; this._maxSpeculativeExecutions = maxSpeculativeExecutions; }
javascript
{ "resource": "" }
q62471
MaterializedView
test
function MaterializedView(name) { DataCollection.call(this, name); /** * Name of the table. * @type {String} */ this.tableName = null; /** * View where clause. * @type {String} */ this.whereClause = null; /** * Determines if all the table columns where are included in the view. * @type {boolean} */ this.includeAllColumns = false; }
javascript
{ "resource": "" }
q62472
DataCollection
test
function DataCollection(name) { events.EventEmitter.call(this); this.setMaxListeners(0); //private Object.defineProperty(this, 'loading', { value: false, enumerable: false, writable: true }); Object.defineProperty(this, 'loaded', { value: false, enumerable: false, writable: true }); /** * Name of the object * @type {String} */ this.name = name; /** * False-positive probability for SSTable Bloom filters. * @type {number} */ this.bloomFilterFalsePositiveChance = 0; /** * Level of caching: all, keys_only, rows_only, none * @type {String} */ this.caching = null; /** * A human readable comment describing the table. * @type {String} */ this.comment = null; /** * Specifies the time to wait before garbage collecting tombstones (deletion markers) * @type {number} */ this.gcGraceSeconds = 0; /** * Compaction strategy class used for the table. * @type {String} */ this.compactionClass = null; /** * Associative-array containing the compaction options keys and values. * @type {Object} */ this.compactionOptions = null; /** * Associative-array containing the compression options. * @type {Object} */ this.compression = null; /** * Specifies the probability of read repairs being invoked over all replicas in the current data center. * @type {number} */ this.localReadRepairChance = 0; /** * Specifies the probability with which read repairs should be invoked on non-quorum reads. The value must be * between 0 and 1. * @type {number} */ this.readRepairChance = 0; /** * An associative Array containing extra metadata for the table. * <p> * For Apache Cassandra versions prior to 3.0.0, this method always returns <code>null</code>. * </p> * @type {Object} */ this.extensions = null; /** * When compression is enabled, this option defines the probability * with which checksums for compressed blocks are checked during reads. * The default value for this options is 1.0 (always check). * <p> * For Apache Cassandra versions prior to 3.0.0, this method always returns <code>null</code>. * </p> * @type {Number|null} */ this.crcCheckChance = null; /** * Whether the populate I/O cache on flush is set on this table. * @type {Boolean} */ this.populateCacheOnFlush = false; /** * Returns the default TTL for this table. * @type {Number} */ this.defaultTtl = 0; /** * * Returns the speculative retry option for this table. * @type {String} */ this.speculativeRetry = 'NONE'; /** * Returns the minimum index interval option for this table. * <p> * Note: this option is available in Apache Cassandra 2.1 and above, and will return <code>null</code> for * earlier versions. * </p> * @type {Number|null} */ this.minIndexInterval = 128; /** * Returns the maximum index interval option for this table. * <p> * Note: this option is available in Apache Cassandra 2.1 and above, and will return <code>null</code> for * earlier versions. * </p> * @type {Number|null} */ this.maxIndexInterval = 2048; /** * Array describing the table columns. * @type {Array} */ this.columns = null; /** * An associative Array of columns by name. * @type {Object} */ this.columnsByName = null; /** * Array describing the columns that are part of the partition key. * @type {Array} */ this.partitionKeys = []; /** * Array describing the columns that form the clustering key. * @type {Array} */ this.clusteringKeys = []; /** * Array describing the clustering order of the columns in the same order as the clusteringKeys. * @type {Array} */ this.clusteringOrder = []; }
javascript
{ "resource": "" }
q62473
example
test
async function example() { await client.connect(); await client.execute(`CREATE KEYSPACE IF NOT EXISTS examples WITH replication = {'class': 'SimpleStrategy', 'replication_factor': '1' }`); await client.execute(`USE examples`); await client.execute(`CREATE TABLE IF NOT EXISTS tbl_sample_kv (id uuid, value text, PRIMARY KEY (id))`); // The maximum amount of async executions that are going to be launched in parallel // at any given time const concurrencyLevel = 32; const promises = new Array(concurrencyLevel); const info = { totalLength: 10000, counter: 0 }; // Launch in parallel n async operations (n being the concurrency level) for (let i = 0; i < concurrencyLevel; i++) { promises[i] = executeOneAtATime(info); } try { // The n promises are going to be resolved when all the executions are completed. await Promise.all(promises); console.log(`Finished executing ${info.totalLength} queries with a concurrency level of ${concurrencyLevel}.`); } finally { client.shutdown(); } }
javascript
{ "resource": "" }
q62474
TableMetadata
test
function TableMetadata(name) { DataCollection.call(this, name); /** * Applies only to counter tables. * When set to true, replicates writes to all affected replicas regardless of the consistency level specified by * the client for a write request. For counter tables, this should always be set to true. * @type {Boolean} */ this.replicateOnWrite = true; /** * Returns the memtable flush period (in milliseconds) option for this table. * @type {Number} */ this.memtableFlushPeriod = 0; /** * Returns the index interval option for this table. * <p> * Note: this option is only available in Apache Cassandra 2.0. It is deprecated in Apache Cassandra 2.1 and * above, and will therefore return <code>null</code> for 2.1 nodes. * </p> * @type {Number|null} */ this.indexInterval = null; /** * Determines whether the table uses the COMPACT STORAGE option. * @type {Boolean} */ this.isCompact = false; /** * * @type {Array.<Index>} */ this.indexes = null; /** * Determines whether the Change Data Capture (CDC) flag is set for the table. * @type {Boolean|null} */ this.cdc = null; /** * Determines whether the table is a virtual table or not. * @type {Boolean} */ this.virtual = false; }
javascript
{ "resource": "" }
q62475
SchemaParserV1
test
function SchemaParserV1(options, cc) { SchemaParser.call(this, options, cc); this.selectTable = _selectTableV1; this.selectColumns = _selectColumnsV1; this.selectUdt = _selectUdtV1; this.selectAggregates = _selectAggregatesV1; this.selectFunctions = _selectFunctionsV1; }
javascript
{ "resource": "" }
q62476
SchemaParserV2
test
function SchemaParserV2(options, cc, udtResolver) { SchemaParser.call(this, options, cc); this.udtResolver = udtResolver; this.selectTable = _selectTableV2; this.selectColumns = _selectColumnsV2; this.selectUdt = _selectUdtV2; this.selectAggregates = _selectAggregatesV2; this.selectFunctions = _selectFunctionsV2; this.selectIndexes = _selectIndexesV2; }
javascript
{ "resource": "" }
q62477
SchemaParserV3
test
function SchemaParserV3(options, cc, udtResolver) { SchemaParserV2.call(this, options, cc, udtResolver); this.supportsVirtual = true; }
javascript
{ "resource": "" }
q62478
getByVersion
test
function getByVersion(options, cc, udtResolver, version, currentInstance) { let parserConstructor = SchemaParserV1; if (version && version[0] === 3) { parserConstructor = SchemaParserV2; } else if (version && version[0] >= 4) { parserConstructor = SchemaParserV3; } if (!currentInstance || !(currentInstance instanceof parserConstructor)){ return new parserConstructor(options, cc, udtResolver); } return currentInstance; }
javascript
{ "resource": "" }
q62479
encodeRoutingKey
test
function encodeRoutingKey(fromUser) { const encoder = self._getEncoder(); try { if (fromUser) { encoder.setRoutingKeyFromUser(params, execOptions); } else { encoder.setRoutingKeyFromMeta(meta, params, execOptions); } } catch (err) { return callback(err); } callback(); }
javascript
{ "resource": "" }
q62480
getJsFiles
test
function getJsFiles(dir, fileArray) { const files = fs.readdirSync(dir); fileArray = fileArray || []; files.forEach(function(file) { if (file === 'node_modules') { return; } if (fs.statSync(dir + file).isDirectory()) { getJsFiles(dir + file + '/', fileArray); return; } if (file.substring(file.length-3, file.length) !== '.js') { return; } fileArray.push(dir+file); }); return fileArray; }
javascript
{ "resource": "" }
q62481
SchemaFunction
test
function SchemaFunction() { /** * Name of the cql function. * @type {String} */ this.name = null; /** * Name of the keyspace where the cql function is declared. */ this.keyspaceName = null; /** * Signature of the function. * @type {Array.<String>} */ this.signature = null; /** * List of the function argument names. * @type {Array.<String>} */ this.argumentNames = null; /** * List of the function argument types. * @type {Array.<{code, info}>} */ this.argumentTypes = null; /** * Body of the function. * @type {String} */ this.body = null; /** * Determines if the function is called when the input is null. * @type {Boolean} */ this.calledOnNullInput = null; /** * Name of the programming language, for example: java, javascript, ... * @type {String} */ this.language = null; /** * Type of the return value. * @type {{code: number, info: (Object|Array|null)}} */ this.returnType = null; }
javascript
{ "resource": "" }
q62482
copyBuffer
test
function copyBuffer(buf) { const targetBuffer = allocBufferUnsafe(buf.length); buf.copy(targetBuffer); return targetBuffer; }
javascript
{ "resource": "" }
q62483
fixStack
test
function fixStack(stackTrace, error) { if (stackTrace) { error.stack += '\n (event loop)\n' + stackTrace.substr(stackTrace.indexOf("\n") + 1); } return error; }
javascript
{ "resource": "" }
q62484
log
test
function log(type, info, furtherInfo) { if (!this.logEmitter) { if (!this.options || !this.options.logEmitter) { throw new Error('Log emitter not defined'); } this.logEmitter = this.options.logEmitter; } this.logEmitter('log', type, this.constructor.name, info, furtherInfo || ''); }
javascript
{ "resource": "" }
q62485
toLowerCaseProperties
test
function toLowerCaseProperties(obj) { const keys = Object.keys(obj); const result = {}; for (let i = 0; i < keys.length; i++) { const k = keys[i]; result[k.toLowerCase()] = obj[k]; } return result; }
javascript
{ "resource": "" }
q62486
deepExtend
test
function deepExtend(target) { const sources = Array.prototype.slice.call(arguments, 1); sources.forEach(function (source) { for (const prop in source) { if (!source.hasOwnProperty(prop)) { continue; } const targetProp = target[prop]; const targetType = (typeof targetProp); //target prop is // a native single type // or not existent // or is not an anonymous object (not class instance) if (!targetProp || targetType === 'number' || targetType === 'string' || util.isArray(targetProp) || util.isDate(targetProp) || targetProp.constructor.name !== 'Object') { target[prop] = source[prop]; } else { //inner extend target[prop] = deepExtend({}, targetProp, source[prop]); } } }); return target; }
javascript
{ "resource": "" }
q62487
arrayIterator
test
function arrayIterator (arr) { let index = 0; return { next : function () { if (index >= arr.length) { return {done: true}; } return {value: arr[index++], done: false }; }}; }
javascript
{ "resource": "" }
q62488
iteratorToArray
test
function iteratorToArray(iterator) { const values = []; let item = iterator.next(); while (!item.done) { values.push(item.value); item = iterator.next(); } return values; }
javascript
{ "resource": "" }
q62489
binarySearch
test
function binarySearch(arr, key, compareFunc) { let low = 0; let high = arr.length-1; while (low <= high) { const mid = (low + high) >>> 1; const midVal = arr[mid]; const cmp = compareFunc(midVal, key); if (cmp < 0) { low = mid + 1; } else if (cmp > 0) { high = mid - 1; } else { //The key was found in the Array return mid; } } // key not found return ~low; }
javascript
{ "resource": "" }
q62490
insertSorted
test
function insertSorted(arr, item, compareFunc) { if (arr.length === 0) { return arr.push(item); } let position = binarySearch(arr, item, compareFunc); if (position < 0) { position = ~position; } arr.splice(position, 0, item); }
javascript
{ "resource": "" }
q62491
validateFn
test
function validateFn(fn, name) { if (typeof fn !== 'function') { throw new errors.ArgumentError(util.format('%s is not a function', name || 'callback')); } return fn; }
javascript
{ "resource": "" }
q62492
stringRepeat
test
function stringRepeat(val, times) { if (!times || times < 0) { return null; } if (times === 1) { return val; } return new Array(times + 1).join(val); }
javascript
{ "resource": "" }
q62493
promiseWrapper
test
function promiseWrapper(options, originalCallback, handler) { if (typeof originalCallback === 'function') { // Callback-based invocation handler.call(this, originalCallback); return undefined; } const factory = options.promiseFactory || defaultPromiseFactory; const self = this; return factory(function handlerWrapper(callback) { handler.call(self, callback); }); }
javascript
{ "resource": "" }
q62494
WhiteListPolicy
test
function WhiteListPolicy (childPolicy, whiteList) { if (!childPolicy) { throw new Error("You must specify a child load balancing policy"); } if (!util.isArray(whiteList)) { throw new Error("You must provide the white list of host addresses"); } this.childPolicy = childPolicy; const map = {}; whiteList.forEach(function (address) { map[address] = true; }); this.whiteList = map; }
javascript
{ "resource": "" }
q62495
EventDebouncer
test
function EventDebouncer(delay, logger) { this._delay = delay; this._logger = logger; this._queue = null; this._timeout = null; }
javascript
{ "resource": "" }
q62496
FrameReader
test
function FrameReader(header, body, offset) { this.header = header; this.opcode = header.opcode; this.offset = offset || 0; this.buf = body; }
javascript
{ "resource": "" }
q62497
Connection
test
function Connection(endpoint, protocolVersion, options) { events.EventEmitter.call(this); this.setMaxListeners(0); if (!options) { throw new Error('options is not defined'); } /** * Gets the ip and port of the server endpoint. * @type {String} */ this.endpoint = endpoint; /** * Gets the friendly name of the host, used to identify the connection in log messages. * With direct connect, this is the address and port. * @type {String} */ this.endpointFriendlyName = endpoint; if (!this.endpoint || this.endpoint.indexOf(':') < 0) { throw new Error('EndPoint must contain the ip address and port separated by : symbol'); } const portSeparatorIndex = this.endpoint.lastIndexOf(':'); this.address = this.endpoint.substr(0, portSeparatorIndex); this.port = this.endpoint.substr(portSeparatorIndex + 1); Object.defineProperty(this, "options", { value: options, enumerable: false, writable: false}); if (protocolVersion === null) { // Set initial protocol version protocolVersion = types.protocolVersion.maxSupported; if (options.protocolOptions.maxVersion) { // User provided the protocol version protocolVersion = options.protocolOptions.maxVersion; } // Allow to check version using this connection instance this._checkingVersion = true; } this.protocolVersion = protocolVersion; /** @type {Object.<String, OperationState>} */ this._operations = {}; this._pendingWrites = []; this._preparing = {}; /** * The timeout state for the idle request (heartbeat) */ this._idleTimeout = null; this.timedOutOperations = 0; this._streamIds = new StreamIdStack(this.protocolVersion); this._metrics = options.metrics; this.encoder = new Encoder(protocolVersion, options); this.keyspace = null; this.emitDrain = false; /** * Determines if the socket is open and startup succeeded, whether the connection can be used to send requests / * receive events */ this.connected = false; /** * Determines if the socket can be considered as open */ this.isSocketOpen = false; }
javascript
{ "resource": "" }
q62498
getClockId
test
function getClockId(clockId) { let buffer = clockId; if (typeof clockId === 'string') { buffer = utils.allocBufferFromString(clockId, 'ascii'); } if (!(buffer instanceof Buffer)) { //Generate buffer = getRandomBytes(2); } else if (buffer.length !== 2) { throw new Error('Clock identifier must have 2 bytes'); } return buffer; }
javascript
{ "resource": "" }
q62499
getNodeId
test
function getNodeId(nodeId) { let buffer = nodeId; if (typeof nodeId === 'string') { buffer = utils.allocBufferFromString(nodeId, 'ascii'); } if (!(buffer instanceof Buffer)) { //Generate buffer = getRandomBytes(6); } else if (buffer.length !== 6) { throw new Error('Node identifier must have 6 bytes'); } return buffer; }
javascript
{ "resource": "" }