_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q46800
Autodoc
train
function Autodoc(options) { options = Lazy(options || {}) .defaults(Autodoc.options) .toObject(); this.codeParser = wrapParser(options.codeParser); this.commentParser = wrapParser(options.commentParser); this.markdownParser = wrapParser(options.markdownParser, Autodoc.processInternalLinks); this.highlighter = options.highlighter; this.language = options.language || 'javascript'; this.compiler = options.compiler[this.language]; this.namespaces = options.namespaces || []; this.tags = options.tags || []; this.grep = options.grep; this.javascripts = options.javascripts || []; this.exampleHandlers = exampleHandlers(options.exampleHandlers); this.template = options.template; this.templateEngine = options.templateEngine; this.templatePartials = options.templatePartials; this.extraOptions = options.extraOptions || {}; this.errors = []; if (this.highlighter) { this.highlighter.loadMode(this.language); } }
javascript
{ "resource": "" }
q46801
splitCamelCase
train
function splitCamelCase(string) { var matcher = /[^A-Z]([A-Z])|([A-Z])[^A-Z]/g, tokens = [], position = 0, index, match; string || (string = ''); while (match = matcher.exec(string)) { index = typeof match[1] === 'string' ? match.index + 1 : match.index; if (position === index) { continue; } tokens.push(string.substring(position, index).toLowerCase()); position = index; } if (position < string.length) { tokens.push(string.substring(position).toLowerCase()); } return tokens; }
javascript
{ "resource": "" }
q46802
divide
train
function divide(string, divider) { var seam = string.indexOf(divider); if (seam === -1) { return [string]; } return [string.substring(0, seam), string.substring(seam + divider.length)]; }
javascript
{ "resource": "" }
q46803
unindent
train
function unindent(string, skipFirstLine) { var lines = string.split('\n'), skipFirst = typeof skipFirstLine !== 'undefined' ? skipFirstLine : true, start = skipFirst ? 1 : 0; var indentation, smallestIndentation = Infinity; for (var i = start, len = lines.length; i < len; ++i) { if (isBlank(lines[i])) { continue; } indentation = getIndentation(lines[i]); if (indentation < smallestIndentation) { smallestIndentation = indentation; } } var result = [lines[0]] .concat( lines .slice(1) .map(function(line) { return decreaseIndent(line, smallestIndentation); }) ) .join('\n'); return result; }
javascript
{ "resource": "" }
q46804
firstLine
train
function firstLine(string) { var lineBreak = string.indexOf('\n'); if (lineBreak === -1) { return string; } return string.substring(0, lineBreak) + ' (...)'; }
javascript
{ "resource": "" }
q46805
exampleHandlers
train
function exampleHandlers(customHandlers) { return (customHandlers || []).concat([ { pattern: /^(\w[\w\.\(\)\[\]'"]*)\s*===?\s*(.*)$/, template: 'equality', data: function(match) { return { left: match[1], right: match[2] }; } }, { pattern: /^(\w[\w\.\(\)\[\]'"]*)\s*!==?\s*(.*)$/, template: 'inequality', data: function(match) { return { left: match[1], right: match[2] }; } }, { pattern: /^instanceof (.*)$/, template: 'instanceof', data: function(match) { return { type: match[1] }; } }, { pattern: /^NaN$/, template: 'nan' }, { pattern: /^throws$/, template: 'throws' }, { pattern: /^calls\s+(\w+)\s+(\d+)(?:\s+times?)?$/, template: 'calls', data: function(match) { return { callback: match[1], count: getCount(match[2]) }; } }, { pattern: /^calls\s+(\w+)\s+(\d+)\s+times? asynchronously$/, template: 'calls_async', data: function(match) { return { callback: match[1], count: getCount(match[2]) }; } }, { pattern: /^=~\s+\/(.*)\/$/, template: 'string_proximity', data: function(match) { return { pattern: match[1] }; } }, { pattern: /^=~\s+\[(.*),?\s*\.\.\.\s*\]$/, template: 'array_inclusion', data: function(match) { return { elements: match[1] }; } }, { pattern: /^one of (.*)$/, template: 'array_membership', data: function(match) { return { values: match[1] }; } }, { pattern: /^=~\s+\[(.*)\]$/, template: 'array_proximity', data: function(match) { return { elements: match[1] }; } }, { pattern: /^\[(.*),?\s*\.\.\.\s*\]$/, template: 'array_head', data: function(match) { return { head: match[1] }; } }, { pattern: /^\[\s*\.\.\.,?\s*(.*)\]$/, template: 'array_tail', data: function(match) { return { tail: match[1] }; } }, { pattern: /\{([\s\S]*),?[\s\n]*\.\.\.[\s\n]*\}/, template: 'object_proximity', data: function(match) { return { properties: match[1] }; } } ]); }
javascript
{ "resource": "" }
q46806
train
function(string, delimiter) { var start = 0, parts = [], index = string.indexOf(delimiter); if (delimiter === '') { while (index < string.length) { parts.push(string.charAt(index++)); } return parts; } while (index !== -1 & index < string.length) { parts.push(string.substring(start, index)); start = index + delimiter.length; index = string.indexOf(delimiter, start); } if (start < string.length) { parts.push(string.substring(start)); } return parts; }
javascript
{ "resource": "" }
q46807
train
function(string) { var chars = new Array(string.length); var charCode; for (var i = 0, len = chars.length; i < len; ++i) { charCode = string.charCodeAt(i); if (charCode > 96 && charCode < 123) { charCode -= 32; } chars[i] = String.fromCharCode(charCode); } return chars.join(''); }
javascript
{ "resource": "" }
q46808
printEvens
train
function printEvens(N) { try { var i = -1; beginning: do { if (++i < N) { if (i % 2 !== 0) { continue beginning; } printNumber(i); } break; } while (true); } catch (e) { debugger; } }
javascript
{ "resource": "" }
q46809
validateVar
train
function validateVar({ spec = {}, name, rawValue }) { if (typeof spec._parse !== 'function') { throw new EnvError(`Invalid spec for "${name}"`) } const value = spec._parse(rawValue) if (spec.choices) { if (!Array.isArray(spec.choices)) { throw new TypeError(`"choices" must be an array (in spec for "${name}")`) } else if (!spec.choices.includes(value)) { throw new EnvError(`Value "${value}" not in choices [${spec.choices}]`) } } if (value == null) throw new EnvError(`Invalid value for env var "${name}"`) return value }
javascript
{ "resource": "" }
q46810
formatSpecDescription
train
function formatSpecDescription(spec) { const egText = spec.example ? ` (eg. "${spec.example}")` : '' const docsText = spec.docs ? `. See ${spec.docs}` : '' return `${spec.desc}${egText}${docsText}` || '' }
javascript
{ "resource": "" }
q46811
extendWithDotEnv
train
function extendWithDotEnv(inputEnv, dotEnvPath = '.env') { let dotEnvBuffer = null try { dotEnvBuffer = fs.readFileSync(dotEnvPath) } catch (err) { if (err.code === 'ENOENT') return inputEnv throw err } const parsed = dotenv.parse(dotEnvBuffer) return extend(parsed, inputEnv) }
javascript
{ "resource": "" }
q46812
useSingleQuote
train
function useSingleQuote(node, options) { return ( !node.isDoubleQuote || (options.singleQuote && !node.raw.match(/\\n|\\t|\\r|\\t|\\v|\\e|\\f/) && !node.value.match( /["'$\n]|\\[0-7]{1,3}|\\x[0-9A-Fa-f]{1,2}|\\u{[0-9A-Fa-f]+}/ )) ); }
javascript
{ "resource": "" }
q46813
doSearch
train
function doSearch(docClient, tableName, scanParams, limit, startKey, progress, readOperation = 'scan') { limit = limit !== undefined ? limit : null startKey = startKey !== undefined ? startKey : null let params = { TableName: tableName, } if (scanParams !== undefined && scanParams) { params = Object.assign(params, scanParams) } if (limit !== null) { params.Limit = limit } if (startKey !== null) { params.ExclusiveStartKey = startKey } const readMethod = { scan: (...args) => docClient.scan(...args).promise(), query: (...args) => docClient.query(...args).promise(), }[readOperation] let items = [] const getNextBite = (params, nextKey = null) => { if (nextKey) { params.ExclusiveStartKey = nextKey } return readMethod(params) .then(data => { if (data && data.Items && data.Items.length > 0) { items = items.concat(data.Items) } let lastStartKey = null if (data) { lastStartKey = data.LastEvaluatedKey } if (progress) { const stop = progress(data.Items, lastStartKey) if (stop) { return items } } if (!lastStartKey) { return items } return getNextBite(params, lastStartKey) }) } return getNextBite(params) }
javascript
{ "resource": "" }
q46814
loadDynamoConfig
train
function loadDynamoConfig(env, AWS) { const dynamoConfig = { endpoint: 'http://localhost:8000', sslEnabled: false, region: 'us-east-1', accessKeyId: 'key', secretAccessKey: env.AWS_SECRET_ACCESS_KEY || 'secret' } loadDynamoEndpoint(env, dynamoConfig) if (AWS.config) { if (AWS.config.region !== undefined) { dynamoConfig.region = AWS.config.region } if (AWS.config.credentials) { if (AWS.config.credentials.accessKeyId !== undefined) { dynamoConfig.accessKeyId = AWS.config.credentials.accessKeyId } } } if (env.AWS_REGION) { dynamoConfig.region = env.AWS_REGION } if (env.AWS_ACCESS_KEY_ID) { dynamoConfig.accessKeyId = env.AWS_ACCESS_KEY_ID } return dynamoConfig }
javascript
{ "resource": "" }
q46815
metrics
train
function metrics(context) { //x-height context.fillStyle = 'blue' context.fillRect(0, -layout.height + layout.baseline, 15, -layout.xHeight) //ascender context.fillStyle = 'pink' context.fillRect(27, -layout.height, 36, layout.ascender) //cap height context.fillStyle = 'yellow' context.fillRect(110, -layout.height + layout.baseline , 18, -layout.capHeight) //baseline context.fillStyle = 'orange' context.fillRect(140, -layout.height, 36, layout.baseline) //descender context.fillStyle = 'green' context.fillRect(0, 0, 30, layout.descender) //line height context.fillStyle = 'red' context.fillRect(0, -layout.height + layout.baseline, 52, layout.lineHeight) //bounds context.strokeRect(0, 0, layout.width, -layout.height) }
javascript
{ "resource": "" }
q46816
createNav
train
function createNav(sources) { const defaultCategory = 'Uncategorized'; const sourcesByCategories = sources. // get category names reduce((categories, source) => categories. concat(source.attrs.category || defaultCategory), []). // remove duplicates filter((value, i, self) => self.indexOf(value) === i). // create category object and fill it with related sources reduce((categories, categoryName) => { categories.push({ name: categoryName, items: createCategoryItemsFromSources(sources, categoryName) }); return categories; }, []); sourcesByCategories.sort(categoriesSorter); sourcesByCategories. forEach(category => category.items.sort(categoryItemsSorter)); return sourcesByCategories; }
javascript
{ "resource": "" }
q46817
focusFirst
train
function focusFirst() { const controls = node.queryAll('input,select,button,textarea,*[contentEditable=true]'). filter(inputNode => getStyles(inputNode).display !== 'none'); if (controls.length) { controls[0].focus(); } }
javascript
{ "resource": "" }
q46818
dock
train
function dock() { onBeforeDock(); panel.classList.add(DOCKED_CSS_CLASS_NAME); if (dockedPanelClass) { panel.classList.add(dockedPanelClass); } isDocked = true; }
javascript
{ "resource": "" }
q46819
checkPanelPosition
train
function checkPanelPosition() { const currentPanelRect = panel.getBoundingClientRect(); if (currentPanelRect.top + currentPanelRect.height > getScrollContainerHeight() && !isDocked) { dock(); } else if ( isDocked && currentPanelRect.top + currentPanelRect.height + getScrollContainerScrollTop() >= getInitialUndockedPosition() + TOGGLE_GAP ) { undock(); } }
javascript
{ "resource": "" }
q46820
startOldBrowsersDetector
train
function startOldBrowsersDetector(onOldBrowserDetected) { previousWindowErrorHandler = window.onerror; window.onerror = function oldBrowsersMessageShower(errorMsg, url, lineNumber) { if (onOldBrowserDetected) { onOldBrowserDetected(); } if (previousWindowErrorHandler) { return previousWindowErrorHandler(errorMsg, url, lineNumber); } return false; }; }
javascript
{ "resource": "" }
q46821
focusOnElement
train
function focusOnElement(element) { if (!element) { return; } if (element.hasAttribute(RING_SELECT) || element.tagName.toLowerCase() === RING_SELECT) { focusOnElement(element.querySelector(RING_SELECT_SELECTOR)); return; } if (element.matches(FOCUSABLE_ELEMENTS) && element.focus) { element.focus(); return; } const focusableChild = element.querySelector(FOCUSABLE_ELEMENTS); if (focusableChild && focusableChild.focus) { focusableChild.focus(); } }
javascript
{ "resource": "" }
q46822
scrollSpeed
train
function scrollSpeed(date) { const monthStart = moment(date).startOf('month'); const monthEnd = moment(date).endOf('month'); return (monthEnd - monthStart) / monthHeight(monthStart); }
javascript
{ "resource": "" }
q46823
getModifierClassNames
train
function getModifierClassNames(props) { return modifierKeys.reduce((result, key) => { if (props[key]) { return result.concat(styles[`${key}-${props[key]}`]); } return result; }, []); }
javascript
{ "resource": "" }
q46824
watch
train
function watch (glob, watchOpt) { if (!started) { deferredWatch = emitter.watch.bind(null, glob, watchOpt) } else { // destroy previous if (fileWatcher) fileWatcher.close() glob = glob && glob.length > 0 ? glob : defaultWatchGlob glob = Array.isArray(glob) ? glob : [ glob ] watchOpt = xtend({ poll: opts.poll }, watchOpt) fileWatcher = createFileWatch(glob, watchOpt) fileWatcher.on('watch', emitter.emit.bind(emitter, 'watch')) } return emitter }
javascript
{ "resource": "" }
q46825
live
train
function live (liveOpts) { if (!started) { deferredLive = emitter.live.bind(null, liveOpts) } else { // destroy previous if (reloader) reloader.close() // pass some options for the server middleware server.setLiveOptions(xtend(liveOpts)) // create a web socket server for live reload reloader = createReloadServer(server, opts) } return emitter }
javascript
{ "resource": "" }
q46826
parseError
train
function parseError (err) { var filePath, lineNum, splitLines var result = {} // For root files that syntax-error doesn't pick up: var parseFilePrefix = 'Parsing file ' if (err.indexOf(parseFilePrefix) === 0) { var pathWithErr = err.substring(parseFilePrefix.length) filePath = getFilePath(pathWithErr) if (!filePath) return result result.path = filePath var messageAndLine = pathWithErr.substring(filePath.length) lineNum = /\((\d+):(\d+)\)/.exec(messageAndLine) if (!lineNum) return result result.message = messageAndLine.substring(1, lineNum.index).trim() result.line = parseInt(lineNum[1], 10) result.column = parseInt(lineNum[2], 10) result.format = true return result } // if module not found var cannotFindModule = /^Cannot find module '(.+)' from '(.+)'(?:$| while parsing file: (.*)$)/.exec(err.trim()) if (cannotFindModule) { result.missingModule = cannotFindModule[1] result.path = cannotFindModule[3] || cannotFindModule[2] result.message = "Cannot find module '" + result.missingModule + "'" result.format = true return result } // syntax-error returns the path and line number, also a \n at start err = err.trim() filePath = getFilePath(err) if (!filePath) return result result.path = filePath var restOfMessage = err.substring(filePath.length) var parsedSyntaxError = /^:(\d+)/.exec(restOfMessage) if (parsedSyntaxError) { // this is a syntax-error lineNum = parseInt(parsedSyntaxError[1], 10) if (isFinite(lineNum)) result.line = lineNum splitLines = restOfMessage.split('\n') var code = splitLines.slice(1, splitLines.length - 1).join('\n') result.code = code result.message = splitLines[splitLines.length - 1] result.format = true return result } // remove colon restOfMessage = restOfMessage.substring(1).trim() var whileParsing = 'while parsing file: ' var whileParsingIdx = restOfMessage.indexOf(whileParsing) if (whileParsingIdx >= 0) { var beforeWhile = restOfMessage.substring(0, whileParsingIdx) lineNum = /\((\d+):(\d+)\)/.exec(beforeWhile.split('\n')[0]) var messageStr = beforeWhile if (lineNum) { var line = parseInt(lineNum[1], 10) var col = parseInt(lineNum[2], 10) if (isFinite(line)) result.line = line if (isFinite(col)) result.column = col messageStr = messageStr.substring(0, lineNum.index) } result.message = messageStr.trim() splitLines = restOfMessage.split('\n') result.code = splitLines.slice(2).join('\n') result.format = true } return result }
javascript
{ "resource": "" }
q46827
getFilePath
train
function getFilePath (str) { var hasRoot = /^[a-z]:/i.exec(str) var colonLeftIndex = 0 if (hasRoot) { colonLeftIndex = hasRoot[0].length } var pathEnd = str.split('\n')[0].indexOf(':', colonLeftIndex) if (pathEnd === -1) { // invalid string, return non-formattable result return null } return str.substring(0, pathEnd) }
javascript
{ "resource": "" }
q46828
update
train
function update (e) { // tab indent if (e.keyCode === 9) { e.preventDefault(); var selection = window.getSelection(); var range = selection.getRangeAt(0); var text = document.createTextNode('\t'); range.deleteContents(); range.insertNode(text); range.setStartAfter(text); selection.removeAllRanges(); selection.addRange(range); return; } var namespace = '.scope'; var raw = editor.textContent; var pragma = /\/\* @scope (.*?) \*\//g.exec(raw); if (pragma != null) { namespace = pragma[1].trim(); } var processed = stylis(namespace, raw); // apply formatting processed = processed.replace(/(;|\})/g, format.newlines); processed = processed.replace(/(.*?)\{/g, format.selector); processed = processed.replace(/:(.*);/g, format.value); processed = processed.replace(/^.*;$/gm, format.tabs); processed = processed.replace(/\}\n\n\}/g, '}\n}'); processed = processed.replace(/(.*@.*\{)([^\0]+\})(\n\})/g, format.block); processed = processed.replace(/['"`].*?['"`]/g, format.string); output.innerHTML = processed; }
javascript
{ "resource": "" }
q46829
options
train
function options(defaults, opts) { for (var p in opts) { if (opts[p] && opts[p].constructor && opts[p].constructor === Object) { defaults[p] = defaults[p] || {}; options(defaults[p], opts[p]); } else { defaults[p] = opts[p]; } } return defaults; }
javascript
{ "resource": "" }
q46830
line
train
function line (line, left, right, intersection){ var width = 0 , line = left + repeat(line, totalWidth - 2) + right; colWidths.forEach(function (w, i){ if (i == colWidths.length - 1) return; width += w + 1; line = line.substr(0, width) + intersection + line.substr(width + 1); }); return applyStyles(options.style.border, line); }
javascript
{ "resource": "" }
q46831
lineTop
train
function lineTop (){ var l = line(chars.top , chars['top-left'] || chars.top , chars['top-right'] || chars.top , chars['top-mid']); if (l) ret += l + "\n"; }
javascript
{ "resource": "" }
q46832
string
train
function string (str, index){ var str = String(typeof str == 'object' && str.text ? str.text : str) , length = utils.strlen(str) , width = colWidths[index] - (style['padding-left'] || 0) - (style['padding-right'] || 0) , align = options.colAligns[index] || 'left'; return repeat(' ', style['padding-left'] || 0) + (length == width ? str : (length < width ? pad(str, ( width + (str.length - length) ), ' ', align == 'left' ? 'right' : (align == 'middle' ? 'both' : 'left')) : (truncater ? truncate(str, width, truncater) : str)) ) + repeat(' ', style['padding-right'] || 0); }
javascript
{ "resource": "" }
q46833
charset
train
function charset (type) { if (!type || typeof type !== 'string') { return false } // TODO: use media-typer var match = EXTRACT_TYPE_REGEXP.exec(type) var mime = match && db[match[1].toLowerCase()] if (mime && mime.charset) { return mime.charset } // default text/* to utf-8 if (match && TEXT_TYPE_REGEXP.test(match[1])) { return 'UTF-8' } return false }
javascript
{ "resource": "" }
q46834
contentType
train
function contentType (str) { // TODO: should this even be in this module? if (!str || typeof str !== 'string') { return false } var mime = str.indexOf('/') === -1 ? exports.lookup(str) : str if (!mime) { return false } // TODO: use content-type or other module if (mime.indexOf('charset') === -1) { var charset = exports.charset(mime) if (charset) mime += '; charset=' + charset.toLowerCase() } return mime }
javascript
{ "resource": "" }
q46835
extension
train
function extension (type) { if (!type || typeof type !== 'string') { return false } // TODO: use media-typer var match = EXTRACT_TYPE_REGEXP.exec(type) // get extensions var exts = match && exports.extensions[match[1].toLowerCase()] if (!exts || !exts.length) { return false } return exts[0] }
javascript
{ "resource": "" }
q46836
populateMaps
train
function populateMaps (extensions, types) { // source preference (least -> most) var preference = ['nginx', 'apache', undefined, 'iana'] Object.keys(db).forEach(function forEachMimeType (type) { var mime = db[type] var exts = mime.extensions if (!exts || !exts.length) { return } // mime -> extensions extensions[type] = exts // extension -> mime for (var i = 0; i < exts.length; i++) { var extension = exts[i] if (types[extension]) { var from = preference.indexOf(db[types[extension]].source) var to = preference.indexOf(mime.source) if (types[extension] !== 'application/octet-stream' && (from > to || (from === to && types[extension].substr(0, 12) === 'application/'))) { // skip the remapping continue } } // set the extension -> mime types[extension] = type } }) }
javascript
{ "resource": "" }
q46837
getGitFolderPath
train
function getGitFolderPath(currentPath) { var git = path.resolve(currentPath, '.git') if (!exists(git) || !fs.lstatSync(git).isDirectory()) { console.log('pre-commit:'); console.log('pre-commit: Not found .git folder in', git); var newPath = path.resolve(currentPath, '..'); // Stop if we on top folder if (currentPath === newPath) { return null; } return getGitFolderPath(newPath); } console.log('pre-commit:'); console.log('pre-commit: Found .git folder in', git); return git; }
javascript
{ "resource": "" }
q46838
Hook
train
function Hook(fn, options) { if (!this) return new Hook(fn, options); options = options || {}; this.options = options; // Used for testing only. Ignore this. Don't touch. this.config = {}; // pre-commit configuration from the `package.json`. this.json = {}; // Actual content of the `package.json`. this.npm = ''; // The location of the `npm` binary. this.git = ''; // The location of the `git` binary. this.root = ''; // The root location of the .git folder. this.status = ''; // Contents of the `git status`. this.exit = fn; // Exit function. this.initialize(); }
javascript
{ "resource": "" }
q46839
loadView
train
function loadView(view) { $errorMessage.empty(); var ctrl = loadCtrl(view); if (!ctrl) return; // Check if View Requires Authentication if (ctrl.requireADLogin && !authContext.getCachedUser()) { authContext.config.redirectUri = window.location.href; authContext.login(); return; } // Load View HTML $.ajax({ type: "GET", url: "views/" + view + '.html', dataType: "html", }).done(function (html) { // Show HTML Skeleton (Without Data) var $html = $(html); $html.find(".data-container").empty(); $panel.html($html.html()); ctrl.postProcess(html); }).fail(function () { $errorMessage.html('Error loading page.'); }).always(function () { }); }
javascript
{ "resource": "" }
q46840
getSourceList
train
function getSourceList(playlist) { return (playlist || []).map((_, i) => getTrackSources(playlist, i)[0].src); }
javascript
{ "resource": "" }
q46841
getGoToTrackState
train
function getGoToTrackState({ prevState, index, track, shouldPlay = true, shouldForceLoad = false }) { const isNewTrack = prevState.activeTrackIndex !== index; const shouldLoadAsNew = Boolean(isNewTrack || shouldForceLoad); const currentTime = track.startingTime || 0; return { duration: getInitialDuration(track), activeTrackIndex: index, trackLoading: shouldLoadAsNew, mediaCannotPlay: prevState.mediaCannotPlay && !shouldLoadAsNew, currentTime: convertToNumberWithinIntervalBounds(currentTime, 0), loop: shouldLoadAsNew ? false : prevState.loop, shouldRequestPlayOnNextUpdate: Boolean(shouldPlay), awaitingPlayAfterTrackLoad: Boolean(shouldPlay), awaitingForceLoad: Boolean(shouldForceLoad), maxKnownTime: shouldLoadAsNew ? 0 : prevState.maxKnownTime }; }
javascript
{ "resource": "" }
q46842
pxToEmOrRem
train
function pxToEmOrRem(breakpoints, ratio = 16, unit) { const newBreakpoints = {}; for (let key in breakpoints) { const point = breakpoints[key]; if (String(point).includes('px')) { newBreakpoints[key] = +(parseInt(point) / ratio) + unit; continue; } newBreakpoints[key] = point; } return newBreakpoints; }
javascript
{ "resource": "" }
q46843
Manager
train
function Manager (uri, opts, fn) { if (!uri) { throw Error('No connection URI provided.') } if (!(this instanceof Manager)) { return new Manager(uri, opts, fn) } if (typeof opts === 'function') { fn = opts opts = {} } opts = opts || {} this._collectionOptions = objectAssign({}, DEFAULT_OPTIONS, opts.collectionOptions || {}) delete opts.collectionOptions if (Array.isArray(uri)) { if (!opts.database) { for (var i = 0, l = uri.length; i < l; i++) { if (!opts.database) { opts.database = uri[i].replace(/([^\/])+\/?/, '') // eslint-disable-line } uri[i] = uri[i].replace(/\/.*/, '') } } uri = uri.join(',') + '/' + opts.database monkDebug('repl set connection "%j" to database "%s"', uri, opts.database) } if (typeof uri === 'string') { if (!/^mongodb:\/\//.test(uri)) { uri = 'mongodb://' + uri } } this._state = STATE.OPENING this._queue = [] this.on('open', function (db) { monkDebug('connection opened') monkDebug('emptying queries queue (%s to go)', this._queue.length) this._queue.forEach(function (cb) { cb(db) }) }.bind(this)) this._connectionURI = uri this._connectionOptions = opts this.open(uri, opts, fn && function (err) { fn(err, this) }.bind(this)) this.helper = { id: ObjectId } this.collections = {} this.open = this.open.bind(this) this.close = this.close.bind(this) this.executeWhenOpened = this.executeWhenOpened.bind(this) this.collection = this.col = this.get = this.get.bind(this) this.oid = this.id this.setDefaultCollectionOptions = this.setDefaultCollectionOptions.bind(this) this.addMiddleware = this.addMiddleware.bind(this) }
javascript
{ "resource": "" }
q46844
tapename
train
function tapename(req, body) { var hash = opts.hash || messageHash.sync; return hash(req, Buffer.concat(body)) + '.js'; }
javascript
{ "resource": "" }
q46845
write
train
function write(filename, data) { return Promise.fromCallback(function (done) { debug('write', filename); fs.writeFile(filename, data, done); }); }
javascript
{ "resource": "" }
q46846
createNewTask
train
function createNewTask(task) { console.log("Creating task..."); //set up the new list item const listItem = document.createElement("li"); const checkBox = document.createElement("input"); const label = document.createElement("label"); //pull the inputed text into label label.innerText = task; //add properties checkBox.type = "checkbox"; //add items to the li listItem.appendChild(checkBox); listItem.appendChild(label); //everything put together return listItem; }
javascript
{ "resource": "" }
q46847
addTask
train
function addTask() { const task = newTask.value.trim(); console.log("Adding task: " + task); // ***** // *** we need to add a task to the fluence cluster after we pressed the `Add task` button // ***** addTaskToFluence(task); updateTaskList(task) }
javascript
{ "resource": "" }
q46848
deleteTask
train
function deleteTask() { console.log("Deleting task..."); const listItem = this.parentNode; const ul = listItem.parentNode; const task = listItem.getElementsByTagName('label')[0].innerText; // ***** // *** delete a task from the cluster when we press `Delete` button on the completed task // ***** deleteFromFluence(task); ul.removeChild(listItem); }
javascript
{ "resource": "" }
q46849
onLocalModuleBinding
train
function onLocalModuleBinding(ident, ast, acc) { traverse(ast, { CallExpression({ node: callExpression }) { // left must be a member expression if (t.isMemberExpression(callExpression.callee) === false) { return; } const memberExpression = callExpression.callee; /** * Search for `makeX().then(...)` */ if ( t.isCallExpression(memberExpression.object) && memberExpression.object.callee.name === ident.name && memberExpression.property.name === "then" ) { const [thenFnBody] = callExpression.arguments; if (typeof thenFnBody === "undefined") { return; } onInstanceThenFn(thenFnBody, acc); } } }); }
javascript
{ "resource": "" }
q46850
onInstanceThenFn
train
function onInstanceThenFn(fn, acc) { if (t.isArrowFunctionExpression(fn) === false) { throw new Error("Unsupported function type: " + fn.type); } let [localIdent] = fn.params; /** * `then(({exports}) => ...)` * * We need to resolve the identifier (binding) from the ObjectPattern. * * TODO(sven): handle renaming the binding here */ if (t.isObjectPattern(localIdent) === true) { // ModuleInstance has the exports prop by spec localIdent = t.identifier("exports"); } traverse(fn.body, { noScope: true, MemberExpression(path) { const { object, property } = path.node; /** * Search for `localIdent.exports` */ if ( identEq(object, localIdent) === true && t.isIdentifier(property, { name: "exports" }) ) { /** * We are looking for the right branch of the parent MemberExpression: * `(localIdent.exports).x` * ^ */ const { property } = path.parentPath.node; // Found an usage of an export acc.push(property.name); path.stop(); } else if (identEq(object, localIdent) === true) { /** * `exports` might be a local binding (from destructuring) */ // Found an usage of an export acc.push(property.name); path.stop(); } } }); }
javascript
{ "resource": "" }
q46851
configureMonaco
train
function configureMonaco() { monaco.languages.register({ id: "wast" }); monaco.languages.setMonarchTokensProvider("wast", { tokenizer: { root: [ [REGEXP_KEYWORD, "keyword"], [REGEXP_KEYWORD_ASSERTS, "keyword"], [REGEXP_NUMBER, "number"], [/\$([a-zA-Z0-9_`\+\-\*\/\\\^~=<>!\?@#$%&|:\.]+)/, "variable"], [REGEXP_STRING, "string"], [/;;.*$/, "comment"] ] } }); monaco.editor.defineTheme("wastTheme", { base: "vs-dark", inherit: true, rules: [ { token: "string", foreground: "4caf50" }, { token: "number", foreground: "808080" } ] }); }
javascript
{ "resource": "" }
q46852
encodeBufferCommon
train
function encodeBufferCommon(buffer, signed) { let signBit; let bitCount; if (signed) { signBit = bits.getSign(buffer); bitCount = signedBitCount(buffer); } else { signBit = 0; bitCount = unsignedBitCount(buffer); } const byteCount = Math.ceil(bitCount / 7); const result = bufs.alloc(byteCount); for (let i = 0; i < byteCount; i++) { const payload = bits.extract(buffer, i * 7, 7, signBit); result[i] = payload | 0x80; } // Mask off the top bit of the last byte, to indicate the end of the // encoding. result[byteCount - 1] &= 0x7f; return result; }
javascript
{ "resource": "" }
q46853
encodedLength
train
function encodedLength(encodedBuffer, index) { let result = 0; while (encodedBuffer[index + result] >= 0x80) { result++; } result++; // to account for the last byte if (index + result > encodedBuffer.length) { // FIXME(sven): seems to cause false positives // throw new Error("integer representation too long"); } return result; }
javascript
{ "resource": "" }
q46854
decodeBufferCommon
train
function decodeBufferCommon(encodedBuffer, index, signed) { index = index === undefined ? 0 : index; let length = encodedLength(encodedBuffer, index); const bitLength = length * 7; let byteLength = Math.ceil(bitLength / 8); let result = bufs.alloc(byteLength); let outIndex = 0; while (length > 0) { bits.inject(result, outIndex, 7, encodedBuffer[index]); outIndex += 7; index++; length--; } let signBit; let signByte; if (signed) { // Sign-extend the last byte. let lastByte = result[byteLength - 1]; const endBit = outIndex % 8; if (endBit !== 0) { const shift = 32 - endBit; // 32 because JS bit ops work on 32-bit ints. lastByte = result[byteLength - 1] = ((lastByte << shift) >> shift) & 0xff; } signBit = lastByte >> 7; signByte = signBit * 0xff; } else { signBit = 0; signByte = 0; } // Slice off any superfluous bytes, that is, ones that add no meaningful // bits (because the value would be the same if they were removed). while ( byteLength > 1 && result[byteLength - 1] === signByte && (!signed || result[byteLength - 2] >> 7 === signBit) ) { byteLength--; } result = bufs.resize(result, byteLength); return { value: result, nextIndex: index }; }
javascript
{ "resource": "" }
q46855
vhost
train
function vhost (hostname, handle) { if (!hostname) { throw new TypeError('argument hostname is required') } if (!handle) { throw new TypeError('argument handle is required') } if (typeof handle !== 'function') { throw new TypeError('argument handle must be a function') } // create regular expression for hostname var regexp = hostregexp(hostname) return function vhost (req, res, next) { var vhostdata = vhostof(req, regexp) if (!vhostdata) { return next() } // populate req.vhost = vhostdata // handle handle(req, res, next) } }
javascript
{ "resource": "" }
q46856
hostnameof
train
function hostnameof (req) { var host = req.headers.host if (!host) { return } var offset = host[0] === '[' ? host.indexOf(']') + 1 : 0 var index = host.indexOf(':', offset) return index !== -1 ? host.substring(0, index) : host }
javascript
{ "resource": "" }
q46857
hostregexp
train
function hostregexp (val) { var source = !isregexp(val) ? String(val).replace(ESCAPE_REGEXP, ESCAPE_REPLACE).replace(ASTERISK_REGEXP, ASTERISK_REPLACE) : val.source // force leading anchor matching if (source[0] !== '^') { source = '^' + source } // force trailing anchor matching if (!END_ANCHORED_REGEXP.test(source)) { source += '$' } return new RegExp(source, 'i') }
javascript
{ "resource": "" }
q46858
vhostof
train
function vhostof (req, regexp) { var host = req.headers.host var hostname = hostnameof(req) if (!hostname) { return } var match = regexp.exec(hostname) if (!match) { return } var obj = Object.create(null) obj.host = host obj.hostname = hostname obj.length = match.length - 1 for (var i = 1; i < match.length; i++) { obj[i - 1] = match[i] } return obj }
javascript
{ "resource": "" }
q46859
analyzeField
train
function analyzeField (field) { var obj = {} var namedType = field.type obj.name = field.name obj.isDeprecated = field.isDeprecated obj.deprecationReason = field.deprecationReason obj.defaultValue = field.defaultValue if (namedType.kind === 'NON_NULL') { obj.isRequired = true namedType = namedType.ofType } else { obj.isRequired = false } if (namedType.kind === 'LIST') { obj.isList = true namedType = namedType.ofType } else { obj.isList = field.type.kind === 'LIST' } if (namedType.kind === 'NON_NULL') { obj.isNestedRequired = true namedType = namedType.ofType } else { obj.isNestedRequired = false } obj.type = namedType.name obj.isUnionType = namedType.kind === 'UNION' obj.isObjectType = namedType.kind === 'OBJECT' obj.isEnumType = namedType.kind === 'ENUM' obj.isInterfaceType = namedType.kind === 'INTERFACE' obj.isInputType = namedType.kind === 'INPUT_OBJECT' return obj }
javascript
{ "resource": "" }
q46860
processType
train
function processType (item, entities, types) { var type = _.find(types, { name: item }) var additionalTypes = [] // get the type names of the union or interface's possible types, given its type name var addPossibleTypes = typeName => { var union = _.find(types, { name: typeName }) var possibleTypes = _.map(union.possibleTypes, 'name') // we must also process the union/interface type, as well as its possible types additionalTypes = _.union(additionalTypes, possibleTypes, [typeName]) } var fields = _.map(type.fields, field => { var obj = analyzeField.call(this, field) if ( (obj.isUnionType && !this.theme.unions.hide) || (obj.isInterfaceType && !this.theme.interfaces.hide) ) { addPossibleTypes(obj.type) } // process args if (!this.theme.field.noargs) { if (field.args && field.args.length) { obj.args = _.map(field.args, analyzeField.bind(this)) } } return obj }) entities[type.name] = { name: type.name, fields: fields, isObjectType: true, isInterfaceType: type.kind === 'INTERFACE', isUnionType: type.kind === 'UNION', possibleTypes: _.map(type.possibleTypes, 'name') } var linkeditems = _.chain(fields) .filter('isObjectType') .map('type') .union(additionalTypes) .uniq() .value() return linkeditems }
javascript
{ "resource": "" }
q46861
walkBFS
train
function walkBFS (obj, iter) { var q = _.map(_.keys(obj), k => { return { key: k, path: '["' + k + '"]' } }) var current var currentNode var retval var push = (v, k) => { q.push({ key: k, path: current.path + '["' + k + '"]' }) } while (q.length) { current = q.shift() currentNode = _.get(obj, current.path) retval = iter(currentNode, current.key, current.path) if (retval) { return retval } if (_.isPlainObject(currentNode) || _.isArray(currentNode)) { _.each(currentNode, push) } } }
javascript
{ "resource": "" }
q46862
isEnabled
train
function isEnabled (obj) { var enabled = false if (obj.isEnumType) { enabled = !this.theme.enums.hide } else if (obj.isInputType) { enabled = !this.theme.inputs.hide } else if (obj.isInterfaceType) { enabled = !this.theme.interfaces.hide } else if (obj.isUnionType) { enabled = !this.theme.unions.hide } else { enabled = true } return enabled }
javascript
{ "resource": "" }
q46863
getColor
train
function getColor (obj) { var color = this.theme.types.color if (obj.isEnumType && !this.theme.enums.hide) { color = this.theme.enums.color } else if (obj.isInputType && !this.theme.inputs.hide) { color = this.theme.inputs.color } else if (obj.isInterfaceType && !this.theme.interfaces.hide) { color = this.theme.interfaces.color } else if (obj.isUnionType && !this.theme.unions.hide) { color = this.theme.unions.color } return color }
javascript
{ "resource": "" }
q46864
createTable
train
function createTable (context) { var result = '"' + context.typeName + '" ' result += '[label=<<TABLE COLOR="' + context.color + '" BORDER="0" CELLBORDER="1" CELLSPACING="0">' result += '<TR><TD PORT="__title"' + (this.theme.header.invert ? ' BGCOLOR="' + context.color + '"' : '') + '><FONT COLOR="' + (this.theme.header.invert ? 'WHITE' : context.color) + '">' + (_.isEmpty(context.stereotype) || context.stereotype === 'null' ? '' : '&laquo;' + context.stereotype + '&raquo;<BR/>') + '<B>' + context.typeName + '</B></FONT></TD></TR>' if (context.rows.length) { if (this.theme.field.hideSeperators) { result += '<TR><TD><TABLE COLOR="' + context.color + '" BORDER="0" CELLBORDER="0" CELLSPACING="0">' } result += context.rows.map(row => { return ( '<TR><TD ALIGN="' + this.theme.field.align + '" PORT="' + row.port + '"><FONT COLOR="' + context.color + '">' + row.text + '</FONT></TD></TR>' ) }) if (this.theme.field.hideSeperators) { result += '</TABLE></TD></TR>' } } result += '</TABLE>>];' return result }
javascript
{ "resource": "" }
q46865
graph
train
function graph (processedTypes, typeTheme) { var result = '' if (typeTheme.group) { result += 'subgraph cluster_' + groupId++ + ' {' if (typeTheme.color) { result += 'color=' + typeTheme.color + ';' } if (typeTheme.groupLabel) { result += 'label="' + typeTheme.groupLabel + '";' } } result += _.map(processedTypes, v => { // sort if desired if (this.theme.field.sort) { v.fields = _.sortBy(v.fields, 'name') } var rows = _.map(v.fields, v => { return { text: createField.call(this, v), port: v.name + 'port' } }) return createTable.call(this, { typeName: getTypeDisplayName(v.name), color: typeTheme.color, stereotype: typeTheme.stereotype, rows: rows }) }).join('\n') if (typeTheme.group) { result += '}' } result += '\n\n' return result }
javascript
{ "resource": "" }
q46866
fatal
train
function fatal (e, text) { console.error('ERROR processing input. Use --verbose flag to see output.') console.error(e.message) if (cli.flags.verbose) { console.error(text) } process.exit(1) }
javascript
{ "resource": "" }
q46867
introspect
train
function introspect (text) { return new Promise(function (resolve, reject) { try { var astDocument = parse(text) var schema = buildASTSchema(astDocument) graphql(schema, graphqlviz.query) .then(function (data) { resolve(data) }) .catch(function (e) { reject('Fatal error, exiting.') fatal(e, text) }) } catch (e) { reject('Fatal error, exiting.') fatal(e, text) } }) }
javascript
{ "resource": "" }
q46868
train
function (done) { if (called) return; called = true; // wait for req events to fire process.nextTick(function() { if (waitend && req.readable) { // dump rest of request req.resume(); req.once('end', done); return; } done(); }); }
javascript
{ "resource": "" }
q46869
Metrics
train
function Metrics(requests) { this.requests = requests; // The total amount of requests send this.connections = 0; // Connections established this.disconnects = 0; // Closed connections this.failures = 0; // Connections that received an error this.errors = Object.create(null); // Collection of different errors this.timing = Object.create(null); // Different timings this.latency = new Stats(); // Latencies of the echo'd messages this.handshaking = new Stats(); // Handshake duration this.read = 0; // Bytes read this.send = 0; // Bytes send // Start tracking this.start(); }
javascript
{ "resource": "" }
q46870
write
train
function write(socket, task, id, fn) { session[binary ? 'binary' : 'utf8'](task.size, function message(err, data) { var start = socket.last = Date.now(); socket.send(data, { binary: binary, mask: masked }, function sending(err) { if (err) { process.send({ type: 'error', message: err.message, concurrent: --concurrent, id: id }); socket.close(); delete connections[id]; } if (fn) fn(err); }); }); }
javascript
{ "resource": "" }
q46871
toBuffer
train
function toBuffer (typed) { var ab = typed.buffer; var buffer = new Buffer(ab.byteLength); var view = new Uint8Array(ab); for (var i = 0; i < buffer.length; ++i) { buffer[i] = view[i]; } return buffer; }
javascript
{ "resource": "" }
q46872
ByteBuffer
train
function ByteBuffer(arg) { var initial_size; if (arg == null) { initial_size = 1024 * 1024; } else if (typeof arg === "number") { initial_size = arg; } else if (arg instanceof Uint8Array) { this.buffer = arg; this.position = 0; // Overwrite return; } else { // typeof arg -> String throw typeof arg + " is invalid parameter type for ByteBuffer constructor"; } // arg is null or number this.buffer = new Uint8Array(initial_size); this.position = 0; }
javascript
{ "resource": "" }
q46873
train
function (callback) { async.map([ "tid.dat.gz", "tid_pos.dat.gz", "tid_map.dat.gz" ], function (filename, _callback) { loadArrayBuffer(path.join(dic_path, filename), function (err, buffer) { if(err) { return _callback(err); } _callback(null, buffer); }); }, function (err, buffers) { if(err) { return callback(err); } var token_info_buffer = new Uint8Array(buffers[0]); var pos_buffer = new Uint8Array(buffers[1]); var target_map_buffer = new Uint8Array(buffers[2]); dic.loadTokenInfoDictionaries(token_info_buffer, pos_buffer, target_map_buffer); callback(null); }); }
javascript
{ "resource": "" }
q46874
train
function (callback) { loadArrayBuffer(path.join(dic_path, "cc.dat.gz"), function (err, buffer) { if(err) { return callback(err); } var cc_buffer = new Int16Array(buffer); dic.loadConnectionCosts(cc_buffer); callback(null); }); }
javascript
{ "resource": "" }
q46875
DynamicDictionaries
train
function DynamicDictionaries(trie, token_info_dictionary, connection_costs, unknown_dictionary) { if (trie != null) { this.trie = trie; } else { this.trie = doublearray.builder(0).build([ {k: "", v: 1} ]); } if (token_info_dictionary != null) { this.token_info_dictionary = token_info_dictionary; } else { this.token_info_dictionary = new TokenInfoDictionary(); } if (connection_costs != null) { this.connection_costs = connection_costs; } else { // backward_size * backward_size this.connection_costs = new ConnectionCosts(0, 0); } if (unknown_dictionary != null) { this.unknown_dictionary = unknown_dictionary; } else { this.unknown_dictionary = new UnknownDictionary(); } }
javascript
{ "resource": "" }
q46876
ViterbiNode
train
function ViterbiNode(node_name, node_cost, start_pos, length, type, left_id, right_id, surface_form) { this.name = node_name; this.cost = node_cost; this.start_pos = start_pos; this.length = length; this.left_id = left_id; this.right_id = right_id; this.prev = null; this.surface_form = surface_form; if (type === "BOS") { this.shortest_cost = 0; } else { this.shortest_cost = Number.MAX_VALUE; } this.type = type; }
javascript
{ "resource": "" }
q46877
MultiId
train
function MultiId(node) { this.nodes = Object.create(null); this.nodes[node._nid] = node; this.length = 1; this.firstNode = undefined; }
javascript
{ "resource": "" }
q46878
isA
train
function isA(elt, set) { if (typeof set === 'string') { // convenience case for testing a particular HTML element return elt.namespaceURI === NAMESPACE.HTML && elt.localName === set; } var tagnames = set[elt.namespaceURI]; return tagnames && tagnames[elt.localName]; }
javascript
{ "resource": "" }
q46879
equal
train
function equal(newelt, oldelt, oldattrs) { if (newelt.localName !== oldelt.localName) return false; if (newelt._numattrs !== oldattrs.length) return false; for(var i = 0, n = oldattrs.length; i < n; i++) { var oldname = oldattrs[i][0]; var oldval = oldattrs[i][1]; if (!newelt.hasAttribute(oldname)) return false; if (newelt.getAttribute(oldname) !== oldval) return false; } return true; }
javascript
{ "resource": "" }
q46880
train
function() { var frag = doc.createDocumentFragment(); var root = doc.firstChild; while(root.hasChildNodes()) { frag.appendChild(root.firstChild); } return frag; }
javascript
{ "resource": "" }
q46881
handleSimpleAttribute
train
function handleSimpleAttribute() { SIMPLEATTR.lastIndex = nextchar-1; var matched = SIMPLEATTR.exec(chars); if (!matched) throw new Error("should never happen"); var name = matched[1]; if (!name) return false; var value = matched[2]; var len = value.length; switch(value[0]) { case '"': case "'": value = value.substring(1, len-1); nextchar += (matched[0].length-1); tokenizer = after_attribute_value_quoted_state; break; default: tokenizer = before_attribute_name_state; nextchar += (matched[0].length-1); value = value.substring(0, len-1); break; } // Make sure there isn't already an attribute with this name // If there is, ignore this one. for(var i = 0; i < attributes.length; i++) { if (attributes[i][0] === name) return true; } attributes.push([name, value]); return true; }
javascript
{ "resource": "" }
q46882
getMatchingChars
train
function getMatchingChars(pattern) { pattern.lastIndex = nextchar - 1; var match = pattern.exec(chars); if (match && match.index === nextchar - 1) { match = match[0]; nextchar += match.length - 1; /* Careful! Make sure we haven't matched the EOF character! */ if (input_complete && nextchar === numchars) { // Oops, backup one. match = match.slice(0, -1); nextchar--; } return match; } else { throw new Error("should never happen"); } }
javascript
{ "resource": "" }
q46883
emitCharsWhile
train
function emitCharsWhile(pattern) { pattern.lastIndex = nextchar-1; var match = pattern.exec(chars)[0]; if (!match) return false; emitCharString(match); nextchar += match.length - 1; return true; }
javascript
{ "resource": "" }
q46884
emitCharString
train
function emitCharString(s) { if (textrun.length > 0) flushText(); if (ignore_linefeed) { ignore_linefeed = false; if (s[0] === "\n") s = s.substring(1); if (s.length === 0) return; } insertToken(TEXT, s); }
javascript
{ "resource": "" }
q46885
insertElement
train
function insertElement(eltFunc) { var elt; if (foster_parent_mode && isA(stack.top, tablesectionrowSet)) { elt = fosterParent(eltFunc); } else if (stack.top instanceof impl.HTMLTemplateElement) { // "If the adjusted insertion location is inside a template element, // let it instead be inside the template element's template contents" elt = eltFunc(stack.top.content.ownerDocument); stack.top.content._appendChild(elt); } else { elt = eltFunc(stack.top.ownerDocument); stack.top._appendChild(elt); } stack.push(elt); return elt; }
javascript
{ "resource": "" }
q46886
after_attribute_name_state
train
function after_attribute_name_state(c) { switch(c) { case 0x0009: // CHARACTER TABULATION (tab) case 0x000A: // LINE FEED (LF) case 0x000C: // FORM FEED (FF) case 0x0020: // SPACE /* Ignore the character. */ break; case 0x002F: // SOLIDUS // Keep in sync with before_attribute_name_state. addAttribute(attrnamebuf); tokenizer = self_closing_start_tag_state; break; case 0x003D: // EQUALS SIGN tokenizer = before_attribute_value_state; break; case 0x003E: // GREATER-THAN SIGN // Keep in sync with before_attribute_name_state. tokenizer = data_state; addAttribute(attrnamebuf); emitTag(); break; case -1: // EOF // Keep in sync with before_attribute_name_state. addAttribute(attrnamebuf); emitEOF(); break; default: addAttribute(attrnamebuf); beginAttrName(); reconsume(c, attribute_name_state); break; } }
javascript
{ "resource": "" }
q46887
before_html_mode
train
function before_html_mode(t,value,arg3,arg4) { var elt; switch(t) { case 1: // TEXT value = value.replace(LEADINGWS, ""); // Ignore spaces if (value.length === 0) return; // Are we done? break; // Handle anything non-space text below case 5: // DOCTYPE /* ignore the token */ return; case 4: // COMMENT doc._appendChild(doc.createComment(value)); return; case 2: // TAG if (value === "html") { elt = createHTMLElt(doc, value, arg3); stack.push(elt); doc.appendChild(elt); // XXX: handle application cache here parser = before_head_mode; return; } break; case 3: // ENDTAG switch(value) { case "html": case "head": case "body": case "br": break; // fall through on these default: return; // ignore most end tags } } // Anything that didn't get handled above is handled like this: elt = createHTMLElt(doc, "html", null); stack.push(elt); doc.appendChild(elt); // XXX: handle application cache here parser = before_head_mode; parser(t,value,arg3,arg4); }
javascript
{ "resource": "" }
q46888
before_head_mode
train
function before_head_mode(t,value,arg3,arg4) { switch(t) { case 1: // TEXT value = value.replace(LEADINGWS, ""); // Ignore spaces if (value.length === 0) return; // Are we done? break; // Handle anything non-space text below case 5: // DOCTYPE /* ignore the token */ return; case 4: // COMMENT insertComment(value); return; case 2: // TAG switch(value) { case "html": in_body_mode(t,value,arg3,arg4); return; case "head": var elt = insertHTMLElement(value, arg3); head_element_pointer = elt; parser = in_head_mode; return; } break; case 3: // ENDTAG switch(value) { case "html": case "head": case "body": case "br": break; default: return; // ignore most end tags } } // If not handled explicitly above before_head_mode(TAG, "head", null); // create a head tag parser(t, value, arg3, arg4); // then try again with this token }
javascript
{ "resource": "" }
q46889
in_head_noscript_mode
train
function in_head_noscript_mode(t, value, arg3, arg4) { switch(t) { case 5: // DOCTYPE return; case 4: // COMMENT in_head_mode(t, value); return; case 1: // TEXT var ws = value.match(LEADINGWS); if (ws) { in_head_mode(t, ws[0]); value = value.substring(ws[0].length); } if (value.length === 0) return; // no more text break; // Handle non-whitespace below case 2: // TAG switch(value) { case "html": in_body_mode(t, value, arg3, arg4); return; case "basefont": case "bgsound": case "link": case "meta": case "noframes": case "style": in_head_mode(t, value, arg3); return; case "head": case "noscript": return; } break; case 3: // ENDTAG switch(value) { case "noscript": stack.pop(); parser = in_head_mode; return; case "br": break; // goes to the outer default default: return; // ignore other end tags } break; } // If not handled above in_head_noscript_mode(ENDTAG, "noscript", null); parser(t, value, arg3, arg4); }
javascript
{ "resource": "" }
q46890
train
function(event) { return (this._armed !== null && event.type === 'mouseup' && event.isTrusted && event.button === 0 && event.timeStamp - this._armed.t < 1000 && Math.abs(event.clientX - this._armed.x) < 10 && Math.abs(event.clientY - this._armed.Y) < 10); }
javascript
{ "resource": "" }
q46891
train
function(filter){ var buffer = "", c = this.read(); while(c !== null && filter(c)){ buffer += c; c = this.read(); } return buffer; }
javascript
{ "resource": "" }
q46892
train
function(matcher){ var source = this._input.substring(this._cursor), value = null; //if it's a string, just do a straight match if (typeof matcher === "string"){ if (source.indexOf(matcher) === 0){ value = this.readCount(matcher.length); } } else if (matcher instanceof RegExp){ if (matcher.test(source)){ value = this.readCount(RegExp.lastMatch.length); } } return value; }
javascript
{ "resource": "" }
q46893
TokenStreamBase
train
function TokenStreamBase(input, tokenData){ /** * The string reader for easy access to the text. * @type StringReader * @property _reader * @private */ this._reader = input ? new StringReader(input.toString()) : null; /** * Token object for the last consumed token. * @type Token * @property _token * @private */ this._token = null; /** * The array of token information. * @type Array * @property _tokenData * @private */ this._tokenData = tokenData; /** * Lookahead token buffer. * @type Array * @property _lt * @private */ this._lt = []; /** * Lookahead token buffer index. * @type int * @property _ltIndex * @private */ this._ltIndex = 0; this._ltIndexCache = []; }
javascript
{ "resource": "" }
q46894
Attr
train
function Attr(elt, lname, prefix, namespace, value) { // localName and namespace are constant for any attr object. // But value may change. And so can prefix, and so, therefore can name. this.localName = lname; this.prefix = (prefix===null || prefix==='') ? null : ('' + prefix); this.namespaceURI = (namespace===null || namespace==='') ? null : ('' + namespace); this.data = value; // Set ownerElement last to ensure it is hooked up to onchange handler this._setOwnerElement(elt); }
javascript
{ "resource": "" }
q46895
train
function(version) { var result; /** local */ var ensure = function(key) { return function(r) { if (r && !r[key]) { throw new Error('result missing ' + key); } return r; }; }; return plugins.first(function(plugin) { return Promise.resolve() .then(function() { return plugin.match(version); }) .then(ensure('command')) .then(ensure('version')) .then(function(r) { return (result = r); }); }) .then(function(plugin) { return result && _.extend({ plugin: plugin }, result); }); }
javascript
{ "resource": "" }
q46896
train
function(error) { return util.format(' %s: %s', chalk.magenta(error.plugin.name), error.message); }
javascript
{ "resource": "" }
q46897
train
function() { return Promise.resolve() .then(function() { return npm.loadAsync(); }) .then(function(npm) { npm.config.set('spin', false); npm.config.set('global', true); npm.config.set('depth', 0); return Promise.promisify(npm.commands.list)([], true); }) .then(function(data) { return data; }); }
javascript
{ "resource": "" }
q46898
addTodo
train
function addTodo(text) { var todo = { _id: new Date().toISOString(), title: text, completed: false }; db.put(todo, function callback (err, result) { if (!err) { console.log('Successfully posted a todo!'); } }); }
javascript
{ "resource": "" }
q46899
showTodos
train
function showTodos() { db.allDocs({ include_docs: true, descending: true }, function(err, doc) { redrawTodosUI(doc.rows); }); }
javascript
{ "resource": "" }