_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q48600
StateLookup
train
function StateLookup(opts) { if (!opts.client) { throw new Error("client property must be supplied"); } this._client = opts.client; this._eventTypes = {}; // store it as a map var self = this; (opts.eventTypes || []).forEach(function(t) { self._eventTypes[t] = true; }); this._dict = { // $room_id: { // syncPromise: Promise, // events: { // $event_type: { // $state_key: { Event } // } // } // } }; }
javascript
{ "resource": "" }
q48601
train
function() { self._client.roomState(roomId).then(function(events) { events.forEach(function(ev) { if (self._eventTypes[ev.type]) { if (!r.events[ev.type]) { r.events[ev.type] = {}; } r.events[ev.type][ev.state_key] = ev; } }); resolve(r); }, function(err) { if (err.httpStatus >= 400 && err.httpStatus < 600) { // 4xx, 5xx reject(err); // don't have permission, don't retry. } // wait a bit then try again Promise.delay(3000).then(function() { if (!self._dict[roomId]) { return; } queryRoomState(); }); }); }
javascript
{ "resource": "" }
q48602
train
function(d, err, result) { if (err) { d.reject(err); } else { d.resolve(result); } }
javascript
{ "resource": "" }
q48603
Request
train
function Request(opts) { opts = opts || {}; this.id = opts.id || generateRequestId(); this.data = opts.data; this.startTs = Date.now(); this.defer = new Promise.defer(); }
javascript
{ "resource": "" }
q48604
Entry
train
function Entry(doc) { doc = doc || {}; this.id = doc.id; this.matrix = doc.matrix_id ? new MatrixRoom(doc.matrix_id, doc.matrix) : undefined; this.remote = doc.remote_id ? new RemoteRoom(doc.remote_id, doc.remote) : undefined; this.data = doc.data; }
javascript
{ "resource": "" }
q48605
serializeEntry
train
function serializeEntry(entry) { return { id: entry.id, remote_id: entry.remote ? entry.remote.getId() : undefined, matrix_id: entry.matrix ? entry.matrix.getId() : undefined, remote: entry.remote ? entry.remote.serialize() : undefined, matrix: entry.matrix ? entry.matrix.serialize() : undefined, data: entry.data } }
javascript
{ "resource": "" }
q48606
MatrixUser
train
function MatrixUser(userId, data, escape=true) { if (!userId) { throw new Error("Missing user_id"); } if (data && Object.prototype.toString.call(data) !== "[object Object]") { throw new Error("data arg must be an Object"); } this.userId = userId; const split = this.userId.split(":"); this.localpart = split[0].substring(1); this.host = split[1]; if (escape) { this.escapeUserId(); } this._data = data || {}; }
javascript
{ "resource": "" }
q48607
AppServiceBot
train
function AppServiceBot(client, registration, memberCache) { this.client = client; this.registration = registration.getOutput(); this.memberCache = memberCache; var self = this; // yank out the exclusive user ID regex strings this.exclusiveUserRegexes = []; if (this.registration.namespaces && this.registration.namespaces.users) { this.registration.namespaces.users.forEach(function(userEntry) { if (!userEntry.exclusive) { return; } self.exclusiveUserRegexes.push(userEntry.regex); }); } }
javascript
{ "resource": "" }
q48608
defaultResolveFn
train
function defaultResolveFn(source, args, context, info) { var fieldName = info.fieldName; // ensure source is a value for which property access is acceptable. if (typeof source === 'object' || typeof source === 'function') { return typeof source[fieldName] === 'function' ? source[fieldName]() : source[fieldName]; } }
javascript
{ "resource": "" }
q48609
resolveWithDirective
train
function resolveWithDirective(resolve, source, directive, context, info) { source = source || ((info || {}).variableValues || {}).input_0 || {}; let directiveConfig = info.schema._directives.filter( d => directive.name.value === d.name, )[0]; let args = {}; for (let arg of directive.arguments) { args[arg.name.value] = arg.value.value; } return directiveConfig.resolve(resolve, source, args, context, info); }
javascript
{ "resource": "" }
q48610
parseSchemaDirectives
train
function parseSchemaDirectives(directives) { let schemaDirectives = []; if ( !directives || !(directives instanceof Object) || Object.keys(directives).length === 0 ) { return []; } for (let directiveName in directives) { let argsList = [], args = ''; Object.keys(directives[directiveName]).map(key => { argsList.push(`${key}:"${directives[directiveName][key]}"`); }); if (argsList.length > 0) { args = `(${argsList.join(',')})`; } schemaDirectives.push(`@${directiveName}${args}`); } return parse(`{ a: String ${schemaDirectives.join(' ')} }`).definitions[0] .selectionSet.selections[0].directives; }
javascript
{ "resource": "" }
q48611
resolveMiddlewareWrapper
train
function resolveMiddlewareWrapper(resolve = defaultResolveFn, directives = {}) { const serverDirectives = parseSchemaDirectives(directives); return (source, args, context, info) => { const directives = serverDirectives.concat( (info.fieldASTs || info.fieldNodes)[0].directives, ); const directive = directives.filter( d => DEFAULT_DIRECTIVES.indexOf(d.name.value) === -1, )[0]; if (!directive) { return resolve(source, args, context, info); } let defer = resolveWithDirective( () => Promise.resolve(resolve(source, args, context, info)), source, directive, context, info, ); defer.catch(e => resolveWithDirective( /* istanbul ignore next */ () => Promise.reject(e), source, directive, context, info, ), ); if (directives.length <= 1) { return defer; } for (let directiveNext of directives.slice(1)) { defer = defer.then(result => resolveWithDirective( () => Promise.resolve(result), source, directiveNext, context, info, ), ); defer.catch(e => resolveWithDirective( () => Promise.reject(e), source, directiveNext, context, info, ), ); } return defer; }; }
javascript
{ "resource": "" }
q48612
train
function(obj) { var accessors = obj.accessors; if (accessors) { createAccessorsFromArray(obj, obj.accessors, d3.keys(accessors)); } }
javascript
{ "resource": "" }
q48613
train
function(opts, data) { var parsed = d4.parsers.nestedGroup() .x(opts.x.$key) .y(opts.y.$key) .nestKey(opts.x.$key) .value(opts.valueKey)(data); return parsed.data; }
javascript
{ "resource": "" }
q48614
train
function(selector) { var soFar = selector, whitespace = '[\\x20\\t\\r\\n\\f]', characterEncoding = '(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+', identifier = characterEncoding.replace('w', 'w#'), attributes = '\\[' + whitespace + '*(' + characterEncoding + ')' + whitespace + '*(?:([*^$|!~]?=)' + whitespace + '*(?:([\'"])((?:\\\\.|[^\\\\])*?)\\3|(' + identifier + ')|)|)' + whitespace + '*\\]', order = ['TAG', 'ID', 'CLASS'], matchers = { 'ID': new RegExp('#(' + characterEncoding + ')'), 'CLASS': new RegExp('\\.(' + characterEncoding + ')'), 'TAG': new RegExp('^(' + characterEncoding.replace('w', 'w*') + ')'), 'ATTR': new RegExp('' + attributes) }, parse = function(exp) { matched = false; tokens[exp] = []; match = true; while (match) { match = matchers[exp].exec(soFar); if (match !== null) { matched = match.shift(); tokens[exp].push(match[0]); soFar = soFar.slice(matched.length); } } }, matched, match, tokens = {}; d4.each(order, parse); d4.each(order, function(exp) { while (soFar) { tokens[exp] = tokens[exp].join(' '); if (!matched) { break; } } }); return tokens; }
javascript
{ "resource": "" }
q48615
train
function(key, items) { var offsets = {}; var stack = d3.layout.stack() .values(function(d) { return d.values; }) .x(function(d) { return d[key]; }) .y(function(d) { return +d[opts.value.key]; }) .out(function(d, y0, y) { d.y = y; if (d.y >= 0) { d.y0 = offsets[d[key] + 'Pos'] = offsets[d[key] + 'Pos'] || 0; offsets[d[key] + 'Pos'] += y; } else { d.y0 = offsets[d[key] + 'Neg'] = offsets[d[key] + 'Neg'] || 0; offsets[d[key] + 'Neg'] -= Math.abs(y); } }); stack(items.reverse()); }
javascript
{ "resource": "" }
q48616
train
function () { var radius = Math.min(Math.sqrt(Math.pow(this.containerRect.width, 2) + Math.pow(this.containerRect.height, 2)), PaperWave.MAX_RADIUS) * 1.1 + 5; var elapsed = 1.1 - 0.2 * (radius / PaperWave.MAX_RADIUS); var currentTime = this.mouseInteractionSeconds / elapsed; var actualRadius = radius * (1 - Math.pow(80, -currentTime)); return Math.abs(actualRadius); }
javascript
{ "resource": "" }
q48617
train
function () { var translateFraction = this.translationFraction; var x = this.startPosition.x; var y = this.startPosition.y; if (this.endPosition.x) { x = this.startPosition.x + translateFraction * (this.endPosition.x - this.startPosition.x); } if (this.endPosition.y) { y = this.startPosition.y + translateFraction * (this.endPosition.y - this.startPosition.y); } return { x: x, y: y }; }
javascript
{ "resource": "" }
q48618
in_half_open_range
train
function in_half_open_range(key, low, high) { //return (low < high && key > low && key <= high) || // (low > high && (key > low || key <= high)) || // (low == high); return (less_than(low, high) && less_than(low, key) && less_than_or_equal(key, high)) || (less_than(high, low) && (less_than(low, key) || less_than_or_equal(key, high))) || (equal_to(low, high)); }
javascript
{ "resource": "" }
q48619
add_exp
train
function add_exp(key, exponent) { var result = key.concat(); // copy array var index = key.length - Math.floor(exponent / 32) - 1; result[index] += 1 << (exponent % 32); var carry = 0; while (index >= 0) { result[index] += carry; carry = 0; if (result[index] > 0xffffffff) { result[index] -= 0x100000000; carry = 1; } --index; } return result; }
javascript
{ "resource": "" }
q48620
chord_send_message
train
function chord_send_message(to, id, message, reply_to) { return last_node_send(to ? to : last_node, {type: MESSAGE, id: id, message: message}, reply_to); }
javascript
{ "resource": "" }
q48621
mkdir
train
function mkdir(dirname, options = {}) { if (fs.existsSync(dirname)) return; assert.equal(typeof dirname, 'string', 'expected dirname to be a string'); let opts = Object.assign({ cwd: process.cwd(), fs }, options); let mode = opts.mode || 0o777 & ~process.umask(); let segs = path.relative(opts.cwd, dirname).split(path.sep); let make = dir => !exists(dir, opts) && fs.mkdirSync(dir, mode); for (let i = 0; i <= segs.length; i++) { try { make((dirname = path.join(opts.cwd, ...segs.slice(0, i)))); } catch (err) { handleError(dirname, opts)(err); } } return dirname; }
javascript
{ "resource": "" }
q48622
cloneDeep
train
function cloneDeep(value) { let obj = {}; switch (typeOf(value)) { case 'object': for (let key of Object.keys(value)) { obj[key] = cloneDeep(value[key]); } return obj; case 'array': return value.map(ele => cloneDeep(ele)); default: { return value; } } }
javascript
{ "resource": "" }
q48623
getMaskComponents
train
function getMaskComponents() { var maskPlaceholderChars = maskPlaceholder.split(''), maskPlaceholderCopy, components; //maskCaretMap can have bad values if the input has the ui-mask attribute implemented as an obversable property, e.g. the demo page if (maskCaretMap && !isNaN(maskCaretMap[0])) { //Instead of trying to manipulate the RegEx based on the placeholder characters //we can simply replace the placeholder characters based on the already built //maskCaretMap to underscores and leave the original working RegEx to get the proper //mask components angular.forEach(maskCaretMap, function(value) { maskPlaceholderChars[value] = '_'; }); } maskPlaceholderCopy = maskPlaceholderChars.join(''); components = maskPlaceholderCopy.replace(/[_]+/g, '_').split('_'); components = components.filter(function(s) { return s !== ''; }); // need a string search offset in cases where the mask contains multiple identical components // E.g., a mask of 99.99.99-999.99 var offset = 0; return components.map(function(c) { var componentPosition = maskPlaceholderCopy.indexOf(c, offset); offset = componentPosition + 1; return { value: c, position: componentPosition }; }); }
javascript
{ "resource": "" }
q48624
removeNode
train
function removeNode(node){ // Remove incoming edges. Object.keys(edges).forEach(function (u){ edges[u].forEach(function (v){ if(v === node){ removeEdge(u, v); } }); }); // Remove outgoing edges (and signal that the node no longer exists). delete edges[node]; return graph; }
javascript
{ "resource": "" }
q48625
nodes
train
function nodes(){ var nodeSet = {}; Object.keys(edges).forEach(function (u){ nodeSet[u] = true; edges[u].forEach(function (v){ nodeSet[v] = true; }); }); return Object.keys(nodeSet); }
javascript
{ "resource": "" }
q48626
setEdgeWeight
train
function setEdgeWeight(u, v, weight){ edgeWeights[encodeEdge(u, v)] = weight; return graph; }
javascript
{ "resource": "" }
q48627
getEdgeWeight
train
function getEdgeWeight(u, v){ var weight = edgeWeights[encodeEdge(u, v)]; return weight === undefined ? 1 : weight; }
javascript
{ "resource": "" }
q48628
addEdge
train
function addEdge(u, v, weight){ addNode(u); addNode(v); adjacent(u).push(v); if (weight !== undefined) { setEdgeWeight(u, v, weight); } return graph; }
javascript
{ "resource": "" }
q48629
removeEdge
train
function removeEdge(u, v){ if(edges[u]){ edges[u] = adjacent(u).filter(function (_v){ return _v !== v; }); } return graph; }
javascript
{ "resource": "" }
q48630
path
train
function path(){ var nodeList = []; var weight = 0; var node = destination; while(p[node]){ nodeList.push(node); weight += getEdgeWeight(p[node], node); node = p[node]; } if (node !== source) { throw new Error("No path found"); } nodeList.push(node); nodeList.reverse(); nodeList.weight = weight; return nodeList; }
javascript
{ "resource": "" }
q48631
serialize
train
function serialize(){ var serialized = { nodes: nodes().map(function (id){ return { id: id }; }), links: [] }; serialized.nodes.forEach(function (node){ var source = node.id; adjacent(source).forEach(function (target){ serialized.links.push({ source: source, target: target, weight: getEdgeWeight(source, target) }); }); }); return serialized; }
javascript
{ "resource": "" }
q48632
deserialize
train
function deserialize(serialized){ serialized.nodes.forEach(function (node){ addNode(node.id); }); serialized.links.forEach(function (link){ addEdge(link.source, link.target, link.weight); }); return graph; }
javascript
{ "resource": "" }
q48633
set
train
function set(changeList, property, value) { changeList.push({ type:'set', path: property, val: value }) }
javascript
{ "resource": "" }
q48634
rm
train
function rm(changeList, property, index, count, a) { var finalIndex = index ? index - count + 1 : 0 changeList.push({ type:'rm', path: property, index: finalIndex, num: count, vals: a.slice(finalIndex, finalIndex+count) }) }
javascript
{ "resource": "" }
q48635
add
train
function add(changeList, property, index, values) { changeList.push({ type:'add', path: property, index: index, vals: values }) }
javascript
{ "resource": "" }
q48636
arrayToMap
train
function arrayToMap(array) { var result = {} array.forEach(function(v) { result[v] = true }) return result }
javascript
{ "resource": "" }
q48637
createCollection
train
function createCollection(proto, objectOnly){ function Collection(a){ if (!this || this.constructor !== Collection) return new Collection(a); this._keys = []; this._values = []; this._itp = []; // iteration pointers this.objectOnly = objectOnly; //parse initial iterable argument passed if (a) init.call(this, a); } //define size for non object-only collections if (!objectOnly) { defineProperty(proto, 'size', { get: sharedSize }); } //set prototype proto.constructor = Collection; Collection.prototype = proto; return Collection; }
javascript
{ "resource": "" }
q48638
traverseSuper
train
function traverseSuper(cls, trait) { var parentNs = parseNameNs(cls, isBuiltInType(cls) ? '' : nsName.prefix); self.mapTypes(parentNs, iterator, trait); }
javascript
{ "resource": "" }
q48639
ModdleElement
train
function ModdleElement(attrs) { props.define(this, '$type', { value: name, enumerable: true }); props.define(this, '$attrs', { value: {} }); props.define(this, '$parent', { writable: true }); forEach(attrs, bind(function(val, key) { this.set(key, val); }, this)); }
javascript
{ "resource": "" }
q48640
spawnIt
train
function spawnIt(args, fn) { var gpg = spawn('gpg', globalArgs.concat(args || []) ); gpg.on('error', fn); return gpg; }
javascript
{ "resource": "" }
q48641
fibonacci
train
function fibonacci( num, scale, offset, smooth ) { if (!smooth) smooth = 0; var b = Math.round( smooth * Math.sqrt( num ) ); var phi = (Math.sqrt( 5 ) + 1) / 2; var pts = []; for (var i = 0; i < num; i++) { var r = (i > num - b) ? 1 : Math.sqrt( i - 0.5 ) / Math.sqrt( num - (b + 1) / 2 ); var theta = 2 * Math.PI * i / (phi * phi); pts.push( new Vector( r * scale * Math.cos( theta ), r * scale * Math.sin( theta ) ).add( offset ) ); } return pts; }
javascript
{ "resource": "" }
q48642
init
train
function init() { shift++; samples = new SamplePoints(); samples.setBounds( new Rectangle( 25, 25 ).size( space.size.x - 25, space.size.y - 25 ), true ); samples.poissonSampler( 6 ); // target 6px radius }
javascript
{ "resource": "" }
q48643
Tri
train
function Tri() { Triangle.apply( this, arguments ); this.target = {vec: null, t: 0}; this.vertices = ["p0","p1","p2"]; this.colorId = 1 + (colorToggle % 3); }
javascript
{ "resource": "" }
q48644
repel
train
function repel( pt, i ) { if ( pt.distance(mouse) < threshold ) { // smaller than threshold distance, push it out var dir = pt.$subtract(mouse).normalize(); pt.set( dir.multiply(threshold).add( mouse ).min( space.size ).max(0, 0) ); } else { // bigger than threshold distance, pull it in var orig = origs[i]; pt.set ( orig.$add( pt.$subtract(orig).multiply(0.98) ) ); } }
javascript
{ "resource": "" }
q48645
train
function(x, y, evt) { // center is at half size center.set(x/2, y/2); var shift = x/10; line1.set(x/2 + shift, 0); line1.p1.set(x/2 - shift, y); line2.set(0, y/2 - shift); line2.p1.set(x, y/2 + shift); rect.size( x/2, y/2 ); rect.setCenter( x/2, y/2 ); }
javascript
{ "resource": "" }
q48646
getMinMax
train
function getMinMax() { var minPt = pts[0]; var maxPt = pts[0]; for (var i=1; i<pts.length; i++) { minPt = minPt.$min( pts[i] ); } for (i=1; i<pts.length; i++) { maxPt = maxPt.$max( pts[i] ); } nextRect.set( minPt).to( maxPt ); }
javascript
{ "resource": "" }
q48647
cornerLine
train
function cornerLine(p, quadrant, size) { switch (quadrant) { case Const.top_left: return new Pair(p).to(p.$add(size, size)); case Const.top_right: return new Pair(p).to(p.$add(-size, size)); case Const.bottom_left: return new Pair(p).to(p.$add(size, -size)); case Const.bottom_right: return new Pair(p).to(p.$add(-size, -size)); case Const.top: return new Pair(p).to(p.$add(0, size)); case Const.bottom: return new Pair(p).to(p.$add(0, -size)); case Const.left: return new Pair(p).to(p.$add(size, 0)); default: return new Pair(p).to(p.$add(-size, 0)); } }
javascript
{ "resource": "" }
q48648
draw
train
function draw() { for (i=0; i<pts.length; i++) { // draw corners var q = mouseP.quadrant(pts[i], 2); var ln = cornerLine(pts[i], q, 12); form.stroke( colors["a"+(q%4+1)], 1.5); form.line( new Pair(ln.p1.x, ln.y).to( ln.x, ln.y) ); form.line( new Pair(ln.x, ln.y).to( ln.x, ln.p1.y) ); // draw point form.fill( colors.c4 ).stroke( false ); form.point( ln.p1, 3, true); } }
javascript
{ "resource": "" }
q48649
init
train
function init( shouldResize ) { if (stopped) return; rects = []; gap = space.size.$subtract( 100, 100 ).divide( steps*2, steps ); if (shouldResize) { var size = space.canvas.parentNode.getBoundingClientRect(); if (size.width && size.height) { space.resize( size.width, size.height ); } } for (var i = 0; i <= (steps * 2); i++) { for (var j = 0; j <= (steps); j++) { var rect = new Pt.Rectangle().to( 10, 10 ); rect.moveTo( 50 - 5.5 + gap.x * i, 50 - 5.5 + gap.y * j ); rect.setCenter(); rects.push( rect ); } } }
javascript
{ "resource": "" }
q48650
interpolatePairs
train
function interpolatePairs( _ps, t1, t2 ) { var pn = []; for (var i=0; i<_ps.length; i++) { var next = (i==_ps.length-1) ? 0 : i+1; pn.push( new Pair( _ps[i].interpolate( t1 ) ).to( _ps[next].interpolate( 1-t2 ) ) ); } return pn; }
javascript
{ "resource": "" }
q48651
setTarget
train
function setTarget(p) { if (!p) p = space.size.$multiply( Math.random(), Math.random() ); timeInc++; target.p++; target.t = 0; target.vec = p; }
javascript
{ "resource": "" }
q48652
gameOfLife
train
function gameOfLife() { for (var i=0; i<grid.columns; i++) { buffer[i] = []; // reset row for (var k=0; k<grid.rows; k++) { var cnt = 0; // counter for ( var m=i-1; m<i+2; m++) { // get the states of surrounding cells var mm = (m<0) ? grid.columns-1 : ( (m>=grid.columns) ? m-grid.columns : m ); for ( var n=k-1; n<k+2; n++) { var nn = (n<0) ? grid.rows-1 : ( (n>=grid.rows) ? n-grid.rows : n ); if (mm===i && nn===k) continue; else if ( !grid.canFit(mm, nn, 1, 1) ) cnt++; } } buffer[i][k] = (grid.canFit(i, k, 1, 1) && cnt==3) || (!grid.canFit(i, k, 1, 1) && cnt>=2 && cnt<=3); } } }
javascript
{ "resource": "" }
q48653
buildReturnTables
train
function buildReturnTables(res, name) { let tables = [] if (Array.isArray(res)) { if (res.length && res[0]) { tables = buildReturnTables(res[0], `${name}[i]`) } } else { const keys = Object.keys(res).map(k => ({ name: k, type: res[k].constructor.name })).sort((a, b) => a.name.localeCompare(b.name)) tables.push({ name, keys }) keys.filter(key => Array.isArray(res[key.name])).forEach((key) => { if (res[key.name].length) { tables = [...tables, ...buildReturnTables( res[key.name][0], `${name}.${key.name}[i]` )] } }) } return tables }
javascript
{ "resource": "" }
q48654
buildMarkdown
train
async function buildMarkdown() { const docs = await documentation.build([filename], { shallow: true }) const functions = docs[0].members.instance.filter(x => x.kind === 'function') for (const fn of functions) { if (typeof calls[fn.name] === 'function') { const res = await calls[fn.name]() const tables = buildReturnTables(res, `${fn.name}()`) fn.description.children.push({ type: 'paragraph', children: [ { type: 'strong', children: [ { type: 'text', value: 'Returns' } ] } ] }) for (const table of tables) { // Add table title fn.description.children.push({ type: 'paragraph', children: [ { type: 'inlineCode', value: table.name } ] }) // Add table fn.description.children.push({ type: 'table', align: ['left', 'left'], children: [{ type: 'tableRow', children: [ { type: 'tableCell', children: [{ type: 'text', value: 'Property' }] }, { type: 'tableCell', children: [{ type: 'text', value: 'Type' }] }, { type: 'tableCell', children: [{ type: 'text', value: 'Note' }] } ] }, ...table.keys.map(key => ({ type: 'tableRow', children: [ { type: 'tableCell', children: [{ type: 'inlineCode', value: key.name }] }, { type: 'tableCell', children: [{ type: 'text', value: key.type }] }, { type: 'tableCell', children: [{ type: 'text', value: notes[key.name] || '' }] } ] }))] }) } } } const markdown = await documentation.formats.md(docs, { markdownToc: true }) fs.writeFileSync(path.join(process.cwd(), 'API.md'), markdown) process.exit() }
javascript
{ "resource": "" }
q48655
request
train
function request(options) { if (!options) { return Promise.reject('Missing options.') } const data = JSON.stringify(options.data) return new Promise((resolve, reject) => { const req = https.request({ host: BASE_URL, port: 443, method: options.method, path: options.path, headers: Object.assign({ 'Accept': '*/*', 'Content-Type': 'application/json', 'User-Agent': USER_AGENT, 'Content-Length': data.length }, options.headers) }, (response) => { const body = [] response.on('data', chunk => body.push(chunk)) response.on('end', () => { let parsedBody = body.join('') try { parsedBody = JSON.parse(parsedBody) } catch (e) { debug('Received non-JSON data from API.', body) } const res = { statusCode: response.statusCode, statusMessage: response.statusMessage, headers: response.headers, body: parsedBody } if (response.statusCode < 200 || response.statusCode > 299) { reject(res) } else { resolve(res) } }) }) if (data) { req.write(data) } req.on('error', e => reject(e)) req.end() }) }
javascript
{ "resource": "" }
q48656
onHidden
train
function onHidden() { bus.sounds.forEach(sound => { if (sound.playing) { sound.pause(); pageHiddenPaused.push(sound); } }); }
javascript
{ "resource": "" }
q48657
normalize
train
function normalize(vec3) { if (vec3.x === 0 && vec3.y === 0 && vec3.z === 0) { return vec3; } const length = Math.sqrt(vec3.x * vec3.x + vec3.y * vec3.y + vec3.z * vec3.z); const invScalar = 1 / length; vec3.x *= invScalar; vec3.y *= invScalar; vec3.z *= invScalar; return vec3; }
javascript
{ "resource": "" }
q48658
isRelativeFilepath
train
function isRelativeFilepath(str) { if (str) { return ( isFilepath(str) && (str.indexOf('./') == 0 || str.indexOf('../') == 0) ); } return false; }
javascript
{ "resource": "" }
q48659
parseProps
train
function parseProps(attributes, prefix) { prefix += '-'; const props = {}; for (const prop in attributes) { // Strip 'inline-' and store if (prop.indexOf(prefix) == 0) { let value = attributes[prop]; if (value === 'false') { value = false; } if (value === 'true') { value = true; } props[prop.slice(prefix.length)] = value; } } return props; }
javascript
{ "resource": "" }
q48660
getSourcepath
train
function getSourcepath(filepath, htmlpath, rootpath) { if (!filepath) { return ['', '']; } if (isRemoteFilepath(filepath)) { const url = new URL(filepath); filepath = `./${url.pathname.slice(1).replace(RE_FORWARD_SLASH, '_')}`; } // Strip query params filepath = filepath.replace(RE_QUERY, ''); // Relative path if (htmlpath && isRelativeFilepath(filepath)) { filepath = path.resolve(path.dirname(htmlpath), filepath); // Strip leading '/' } else if (filepath.indexOf('/') == 0) { filepath = filepath.slice(1); } if (filepath.includes('#')) { filepath = filepath.split('#'); } return Array.isArray(filepath) ? [path.resolve(rootpath, filepath[0]), filepath[1]] : [path.resolve(rootpath, filepath), '']; }
javascript
{ "resource": "" }
q48661
getPadding
train
function getPadding(source, html) { const re = new RegExp(`^([\\t ]+)${escape(source)}`, 'gm'); const match = re.exec(html); return match ? match[1] : ''; }
javascript
{ "resource": "" }
q48662
isIgnored
train
function isIgnored(ignore, tag, type, format) { // Clean svg+xml ==> svg const formatAlt = format && format.indexOf('+') ? format.split('+')[0] : null; if (!Array.isArray(ignore)) { ignore = [ignore]; } return !!( ignore.includes(tag) || ignore.includes(type) || ignore.includes(format) || ignore.includes(formatAlt) ); }
javascript
{ "resource": "" }
q48663
buildLambda
train
function buildLambda(options) { // crawl the module path to make sure the Lambda handler path is // set correctly: <functionDir>/function.fn let handlerPath = (module.parent.parent.parent.filename).split(path.sep).slice(-2).shift(); let fn = { Resources: {} }; // all function parameters available as environment variables fn.Resources[options.name] = { Type: 'AWS::Lambda::Function', Properties: { Code: { S3Bucket: cf.ref('CodeS3Bucket'), S3Key: cf.join([cf.ref('CodeS3Prefix'), cf.ref('GitSha'), '.zip']) }, Role: cf.if('HasDispatchSnsArn', cf.getAtt('LambdaCfnDispatchRole', 'Arn'), cf.getAtt('LambdaCfnRole', 'Arn')), Description: cf.stackName, Environment: { Variables: {} }, Handler: handlerPath + '/function.fn' } }; fn.Resources[options.name].Properties.Timeout = setLambdaTimeout(options.timeout); fn.Resources[options.name].Properties.MemorySize = setLambdaMemorySize(options.memorySize); fn.Resources[options.name].Properties.Runtime = setLambdaRuntine(options.runtime); return fn; }
javascript
{ "resource": "" }
q48664
buildSnsDestination
train
function buildSnsDestination(options) { let sns = { Resources: {}, Parameters: {}, Variables: {}, Policies: [] }; if (options.destinations && options.destinations.sns) { for (let destination in options.destinations.sns) { sns.Parameters[destination + 'Email'] = { Type: 'String', Description: options.destinations.sns[destination].Description }; sns.Policies.push({ PolicyName: destination + 'TopicPermissions', PolicyDocument: { Statement: [ { Effect: 'Allow', Action: 'sns:Publish', Resource: cf.ref(options.name) } ] } }); sns.Resources[destination + 'Topic'] = { Type: 'AWS::SNS::Topic', Properties: { TopicName: cf.join('-', [cf.stackName, destination]), Subscription: [ { Endpoint: cf.ref(destination + 'Email'), Protocol: 'email' } ] } }; sns.Variables[destination + 'Topic'] = cf.ref(destination + 'Topic'); } return sns; } }
javascript
{ "resource": "" }
q48665
buildRole
train
function buildRole(options, roleName='LambdaCfnRole') { let role = { Resources: {} }; role.Resources[roleName] = { Type: 'AWS::IAM::Role', Properties: { AssumeRolePolicyDocument: { Statement: [ { Sid: '', Effect: 'Allow', Principal: { Service: 'lambda.amazonaws.com' }, Action: 'sts:AssumeRole' }, { Sid: '', Effect: 'Allow', Principal: { Service: 'events.amazonaws.com' }, Action: 'sts:AssumeRole' } ] }, Path: '/', Policies: [ { PolicyName: 'basic', PolicyDocument: { Statement: [ { Effect: 'Allow', Action: [ 'logs:*' ], Resource: cf.join(['arn:aws:logs:*:', cf.accountId, ':*']) }, { Effect: 'Allow', Action: [ 'sns:Publish' ], Resource: cf.ref('ServiceAlarmSNSTopic') }, { Effect: 'Allow', Action: [ 'iam:SimulateCustomPolicy' ], Resource: '*' } ] } }, ] } }; if (options.eventSources && options.eventSources.webhook) { role.Resources[roleName].Properties.AssumeRolePolicyDocument.Statement.push({ Sid: '', Effect: 'Allow', Principal: { Service: 'apigateway.amazonaws.com' }, Action: 'sts:AssumeRole' }); } if (options.statements) { statementValidation(options); role.Resources[roleName].Properties.Policies.push({ PolicyName: options.name, PolicyDocument: { Statement: options.statements } }); } return role; }
javascript
{ "resource": "" }
q48666
buildServiceAlarms
train
function buildServiceAlarms(options) { let alarms = { Parameters: {}, Resources: {}, Variables: {} }; let defaultAlarms = [ { AlarmName: 'Errors', MetricName: 'Errors', ComparisonOperator: 'GreaterThanThreshold' }, { AlarmName: 'NoInvocations', MetricName: 'Invocations', ComparisonOperator: 'LessThanThreshold' } ]; defaultAlarms.forEach(function(alarm) { alarms.Resources[options.name + 'Alarm' + alarm.AlarmName] = { Type: 'AWS::CloudWatch::Alarm', Properties: { EvaluationPeriods: `${setLambdaEvaluationPeriods(options.evaluationPeriods)}`, Statistic: 'Sum', Threshold: `${setLambdaThreshold(options.threshold)}`, AlarmDescription: 'https://github.com/mapbox/lambda-cfn/blob/master/alarms.md#' + alarm.AlarmName, Period: `${setLambdaPeriod(options.period)}`, AlarmActions: [cf.ref('ServiceAlarmSNSTopic')], Namespace: 'AWS/Lambda', Dimensions: [ { Name: 'FunctionName', Value: cf.ref(options.name) } ], ComparisonOperator: alarm.ComparisonOperator, MetricName: alarm.MetricName } }; }); alarms.Parameters = { ServiceAlarmEmail:{ Type: 'String', Description: 'Service alarm notifications will send to this email address' } }; alarms.Resources.ServiceAlarmSNSTopic = { Type: 'AWS::SNS::Topic', Properties: { TopicName: cf.join('-', [cf.stackName, 'ServiceAlarm']), Subscription: [ { Endpoint: cf.ref('ServiceAlarmEmail'), Protocol: 'email' } ] } }; alarms.Variables.ServiceAlarmSNSTopic = cf.ref('ServiceAlarmSNSTopic'); return alarms; }
javascript
{ "resource": "" }
q48667
buildCloudwatchEvent
train
function buildCloudwatchEvent(options, functionType) { validateCloudWatchEvent(functionType, options.eventSources); let eventName = options.name + utils.capitalizeFirst(functionType); let event = { Resources: {} }; event.Resources[eventName + 'Permission'] = { Type: 'AWS::Lambda::Permission', Properties: { FunctionName: cf.getAtt(options.name, 'Arn'), Action: 'lambda:InvokeFunction', Principal: 'events.amazonaws.com', SourceArn: cf.getAtt(eventName + 'Rule', 'Arn') } }; event.Resources[eventName + 'Rule'] = { Type: 'AWS::Events::Rule', Properties: { RoleArn: cf.if('HasDispatchSnsArn', cf.getAtt('LambdaCfnDispatchRole', 'Arn'), cf.getAtt('LambdaCfnRole', 'Arn')), State: 'ENABLED', Targets: [ { Arn: cf.getAtt(options.name, 'Arn'), Id: options.name } ] } }; if (functionType === 'cloudwatchEvent') { event.Resources[eventName + 'Rule'].Properties.EventPattern = options.eventSources.cloudwatchEvent.eventPattern; } else { event.Resources[eventName + 'Rule'].Properties.ScheduleExpression = options.eventSources.schedule.expression; } return event; }
javascript
{ "resource": "" }
q48668
compileFunction
train
function compileFunction() { let template = {}; if (arguments) { for (let arg of arguments) { mergeArgumentsTemplate(template, arg, 'Metadata'); mergeArgumentsTemplate(template, arg, 'Parameters'); mergeArgumentsTemplate(template, arg, 'Mappings'); mergeArgumentsTemplate(template, arg, 'Conditions'); mergeArgumentsTemplate(template, arg, 'Resources'); mergeArgumentsTemplate(template, arg, 'Outputs'); mergeArgumentsTemplate(template, arg, 'Variables'); let areValidPolicies = arg.Policies && Array.isArray(arg.Policies) && arg.Policies.length > 0; if (areValidPolicies) { if (!template.Policies) { template.Policies = []; } template.Policies = template.Policies.concat(arg.Policies); } } } return template; }
javascript
{ "resource": "" }
q48669
mergeArgumentsTemplate
train
function mergeArgumentsTemplate(template, arg, propertyName) { if (!template.hasOwnProperty(propertyName)) { template[propertyName] = {}; } if (arg.hasOwnProperty(propertyName)) { if (!arg[propertyName]) { arg[propertyName] = {}; } Object.keys(arg[propertyName]).forEach((key) => { if (template[propertyName].hasOwnProperty(key)) { throw new Error(propertyName + ' name used more than once: ' + key); } template[propertyName][key] = JSON.parse(JSON.stringify(arg[propertyName][key])); }); } }
javascript
{ "resource": "" }
q48670
addDispatchSupport
train
function addDispatchSupport(template, options) { if (!template.Conditions) { template.Conditions = {}; } if (!('HasDispatchSnsArn' in template.Conditions)) { template.Conditions['HasDispatchSnsArn'] = { 'Fn::Not': [ { 'Fn::Equals': [ '', cf.ref('DispatchSnsArn') ] } ] }; } template.Parameters.DispatchSnsArn = { Type: 'String', Description: 'Dispatch SNS ARN (Optional)' }; // Why we need other role for Dispatch? // We can not use conditionals at policy level. We create a new role with all the properties of the // default role plus the conditional and policy to send messages to DispatchSnsArn. let dispatchRole = role.buildRole(options, 'LambdaCfnDispatchRole'); template.Resources['LambdaCfnDispatchRole'] = dispatchRole.Resources['LambdaCfnDispatchRole']; template.Resources['LambdaCfnDispatchRole'].Condition = 'HasDispatchSnsArn'; template.Resources['LambdaCfnDispatchRole'].Properties.Policies[0].PolicyDocument.Statement.push( { Effect: 'Allow', Action: [ 'sns:Publish' ], Resource: cf.ref('DispatchSnsArn') } ); }
javascript
{ "resource": "" }
q48671
EventData
train
function EventData(eventId, type, isJson, data, metadata) { if (!isValidId(eventId)) throw new TypeError("eventId must be a string containing a UUID."); if (typeof type !== 'string' || type === '') throw new TypeError("type must be a non-empty string."); if (isJson && typeof isJson !== 'boolean') throw new TypeError("isJson must be a boolean."); if (data && !Buffer.isBuffer(data)) throw new TypeError("data must be a Buffer."); if (metadata && !Buffer.isBuffer(metadata)) throw new TypeError("metadata must be a Buffer."); this.eventId = eventId; this.type = type; this.isJson = isJson || false; this.data = data || new Buffer(0); this.metadata = metadata || new Buffer(0); Object.freeze(this); }
javascript
{ "resource": "" }
q48672
BufferSegment
train
function BufferSegment(buf, offset, count) { if (!Buffer.isBuffer(buf)) throw new TypeError('buf must be a buffer'); this.buffer = buf; this.offset = offset || 0; this.count = count || buf.length; }
javascript
{ "resource": "" }
q48673
ProjectionsManager
train
function ProjectionsManager(log, httpEndPoint, operationTimeout) { ensure.notNull(log, "log"); ensure.notNull(httpEndPoint, "httpEndPoint"); this._client = new ProjectionsClient(log, operationTimeout); this._httpEndPoint = httpEndPoint; }
javascript
{ "resource": "" }
q48674
pageLoaded
train
function pageLoaded(args) { // Get the event sender var page = args.object; page.bindingContext = new main_view_model_1.HelloWorldModel(page); if (platform_1.isAndroid && platform_1.device.sdkVersion >= '21') { var window_1 = application_1.android.startActivity.getWindow(); window_1.setStatusBarColor(new color_1.Color('#336699').android); } }
javascript
{ "resource": "" }
q48675
train
function(data) { var budget = options.budget, summary = data.data.summary, median = options.repeatView ? data.data.median.repeatView : data.data.median.firstView, pass = true, str = ""; for (var item in budget) { // make sure this is objects own property and not inherited if (budget.hasOwnProperty(item)) { //make sure it exists if (budget[item] !== '' && median.hasOwnProperty(item)) { if (median[item] > budget[item]) { pass = false; str += item + ': ' + median[item] + ' [FAIL]. Budget is ' + budget[item] + '\n'; } else { str += item + ': ' + median[item] + ' [PASS]. Budget is ' + budget[item] + '\n'; } } } } //save the file before failing or passing var output = options.output; if (typeof output !== 'undefined') { grunt.log.ok('Writing file: ' + output); grunt.file.write(output, JSON.stringify(data)); } // //output our header and results if (!pass) { grunt.log.error('\n\n-----------------------------------------------' + '\nTest for ' + options.url + ' \t FAILED' + '\n-----------------------------------------------\n\n'); grunt.log.error(str); grunt.log.error('Summary: ' + summary); done(false); } else { grunt.log.ok('\n\n-----------------------------------------------' + '\nTest for ' + options.url + ' \t PASSED' + '\n-----------------------------------------------\n\n'); grunt.log.ok(str); grunt.log.ok('Summary: ' + summary); done(); } }
javascript
{ "resource": "" }
q48676
train
function(re, s, offset) { var res = s.slice(offset).match(re); if (res) { return offset + res.index; } else { return null; } }
javascript
{ "resource": "" }
q48677
train
function(text) { if (text.indexOf('\t') == -1) { return text; } else { var lastStop = 0; return text.replace(reAllTab, function(match, offset) { var result = ' '.slice((offset - lastStop) % 4); lastStop = offset + 1; return result; }); } }
javascript
{ "resource": "" }
q48678
train
function(re) { var match = re.exec(this.subject.slice(this.pos)); if (match) { this.pos += match.index + match[0].length; return match[0]; } else { return null; } }
javascript
{ "resource": "" }
q48679
train
function(inlines) { var startpos = this.pos; var ticks = this.match(/^`+/); if (!ticks) { return 0; } var afterOpenTicks = this.pos; var foundCode = false; var match; while (!foundCode && (match = this.match(/`+/m))) { if (match == ticks) { inlines.push({ t: 'Code', c: this.subject.slice(afterOpenTicks, this.pos - ticks.length) .replace(/[ \n]+/g,' ') .trim() }); return (this.pos - startpos); } } // If we got here, we didn't match a closing backtick sequence. inlines.push({ t: 'Str', c: ticks }); this.pos = afterOpenTicks; return (this.pos - startpos); }
javascript
{ "resource": "" }
q48680
train
function(inlines) { var m = this.match(reHtmlTag); if (m) { inlines.push({ t: 'Html', c: m }); return m.length; } else { return 0; } }
javascript
{ "resource": "" }
q48681
train
function() { var res = this.match(reLinkDestinationBraces); if (res) { // chop off surrounding <..>: return unescape(res.substr(1, res.length - 2)); } else { res = this.match(reLinkDestination); if (res !== null) { return unescape(res); } else { return null; } } }
javascript
{ "resource": "" }
q48682
train
function() { if (this.peek() != '[') { return 0; } var startpos = this.pos; var nest_level = 0; if (this.label_nest_level > 0) { // If we've already checked to the end of this subject // for a label, even with a different starting [, we // know we won't find one here and we can just return. // This avoids lots of backtracking. // Note: nest level 1 would be: [foo [bar] // nest level 2 would be: [foo [bar [baz] this.label_nest_level--; return 0; } this.pos++; // advance past [ var c; while ((c = this.peek()) && (c != ']' || nest_level > 0)) { switch (c) { case '`': this.parseBackticks([]); break; case '<': this.parseAutolink([]) || this.parseHtmlTag([]) || this.parseString([]); break; case '[': // nested [] nest_level++; this.pos++; break; case ']': // nested [] nest_level--; this.pos++; break; case '\\': this.parseEscaped([]); break; default: this.parseString([]); } } if (c === ']') { this.label_nest_level = 0; this.pos++; // advance past ] return this.pos - startpos; } else { if (!c) { this.label_nest_level = nest_level; } this.pos = startpos; return 0; } }
javascript
{ "resource": "" }
q48683
train
function(inlines) { var startpos = this.pos; var reflabel; var n; var dest; var title; n = this.parseLinkLabel(); if (n === 0) { return 0; } var afterlabel = this.pos; var rawlabel = this.subject.substr(startpos, n); // if we got this far, we've parsed a label. // Try to parse an explicit link: [label](url "title") if (this.peek() == '(') { this.pos++; if (this.spnl() && ((dest = this.parseLinkDestination()) !== null) && this.spnl() && // make sure there's a space before the title: (/^\s/.test(this.subject.charAt(this.pos - 1)) && (title = this.parseLinkTitle() || '') || true) && this.spnl() && this.match(/^\)/)) { inlines.push({ t: 'Link', destination: dest, title: title, label: parseRawLabel(rawlabel) }); return this.pos - startpos; } else { this.pos = startpos; return 0; } } // If we're here, it wasn't an explicit link. Try to parse a reference link. // first, see if there's another label var savepos = this.pos; this.spnl(); var beforelabel = this.pos; n = this.parseLinkLabel(); if (n == 2) { // empty second label reflabel = rawlabel; } else if (n > 0) { reflabel = this.subject.slice(beforelabel, beforelabel + n); } else { this.pos = savepos; reflabel = rawlabel; } // lookup rawlabel in refmap var link = this.refmap[normalizeReference(reflabel)]; if (link) { inlines.push({t: 'Link', destination: link.destination, title: link.title, label: parseRawLabel(rawlabel) }); return this.pos - startpos; } else { this.pos = startpos; return 0; } // Nothing worked, rewind: this.pos = startpos; return 0; }
javascript
{ "resource": "" }
q48684
train
function(inlines) { var m; if ((m = this.match(/^&(?:#x[a-f0-9]{1,8}|#[0-9]{1,8}|[a-z][a-z0-9]{1,31});/i))) { inlines.push({ t: 'Entity', c: m }); return m.length; } else { return 0; } }
javascript
{ "resource": "" }
q48685
train
function(inlines) { var m; if ((m = this.match(reMain))) { inlines.push({ t: 'Str', c: m }); return m.length; } else { return 0; } }
javascript
{ "resource": "" }
q48686
train
function(inlines) { if (this.peek() == '\n') { this.pos++; var last = inlines[inlines.length - 1]; if (last && last.t == 'Str' && last.c.slice(-2) == ' ') { last.c = last.c.replace(/ *$/,''); inlines.push({ t: 'Hardbreak' }); } else { if (last && last.t == 'Str' && last.c.slice(-1) == ' ') { last.c = last.c.slice(0, -1); } inlines.push({ t: 'Softbreak' }); } return 1; } else { return 0; } }
javascript
{ "resource": "" }
q48687
train
function(inlines) { if (this.match(/^!/)) { var n = this.parseLink(inlines); if (n === 0) { inlines.push({ t: 'Str', c: '!' }); return 1; } else if (inlines[inlines.length - 1] && inlines[inlines.length - 1].t == 'Link') { inlines[inlines.length - 1].t = 'Image'; return n+1; } else { throw "Shouldn't happen"; } } else { return 0; } }
javascript
{ "resource": "" }
q48688
train
function(s, refmap) { this.subject = s; this.pos = 0; var rawlabel; var dest; var title; var matchChars; var startpos = this.pos; var match; // label: matchChars = this.parseLinkLabel(); if (matchChars === 0) { return 0; } else { rawlabel = this.subject.substr(0, matchChars); } // colon: if (this.peek() === ':') { this.pos++; } else { this.pos = startpos; return 0; } // link url this.spnl(); dest = this.parseLinkDestination(); if (dest === null || dest.length === 0) { this.pos = startpos; return 0; } var beforetitle = this.pos; this.spnl(); title = this.parseLinkTitle(); if (title === null) { title = ''; // rewind before spaces this.pos = beforetitle; } // make sure we're at line end: if (this.match(/^ *(?:\n|$)/) === null) { this.pos = startpos; return 0; } var normlabel = normalizeReference(rawlabel); if (!refmap[normlabel]) { refmap[normlabel] = { destination: dest, title: title }; } return this.pos - startpos; }
javascript
{ "resource": "" }
q48689
train
function(inlines) { var c = this.peek(); var res; switch(c) { case '\n': res = this.parseNewline(inlines); break; case '\\': res = this.parseEscaped(inlines); break; case '`': res = this.parseBackticks(inlines); break; case '*': case '_': res = this.parseEmphasis(inlines); break; case '[': res = this.parseLink(inlines); break; case '!': res = this.parseImage(inlines); break; case '<': res = this.parseAutolink(inlines) || this.parseHtmlTag(inlines); break; case '&': res = this.parseEntity(inlines); break; default: } return res || this.parseString(inlines); }
javascript
{ "resource": "" }
q48690
train
function(s, refmap) { this.subject = s; this.pos = 0; this.refmap = refmap || {}; var inlines = []; while (this.parseInline(inlines)) ; return inlines; }
javascript
{ "resource": "" }
q48691
InlineParser
train
function InlineParser(){ return { subject: '', label_nest_level: 0, // used by parseLinkLabel method pos: 0, refmap: {}, match: match, peek: peek, spnl: spnl, parseBackticks: parseBackticks, parseEscaped: parseEscaped, parseAutolink: parseAutolink, parseHtmlTag: parseHtmlTag, scanDelims: scanDelims, parseEmphasis: parseEmphasis, parseLinkTitle: parseLinkTitle, parseLinkDestination: parseLinkDestination, parseLinkLabel: parseLinkLabel, parseLink: parseLink, parseEntity: parseEntity, parseString: parseString, parseNewline: parseNewline, parseImage: parseImage, parseReference: parseReference, parseInline: parseInline, parse: parseInlines }; }
javascript
{ "resource": "" }
q48692
train
function(tag, start_line, start_column) { return { t: tag, open: true, last_line_blank: false, start_line: start_line, start_column: start_column, end_line: start_line, children: [], parent: null, // string_content is formed by concatenating strings, in finalize: string_content: "", strings: [], inline_content: [] }; }
javascript
{ "resource": "" }
q48693
train
function(block) { if (block.last_line_blank) { return true; } if ((block.t == 'List' || block.t == 'ListItem') && block.children.length > 0) { return endsWithBlankLine(block.children[block.children.length - 1]); } else { return false; } }
javascript
{ "resource": "" }
q48694
train
function(tag, line_number, offset) { while (!canContain(this.tip.t, tag)) { this.finalize(this.tip, line_number); } var column_number = offset + 1; // offset 0 = column 1 var newBlock = makeBlock(tag, line_number, column_number); this.tip.children.push(newBlock); newBlock.parent = this.tip; this.tip = newBlock; return newBlock; }
javascript
{ "resource": "" }
q48695
train
function(list_data, item_data) { return (list_data.type === item_data.type && list_data.delimiter === item_data.delimiter && list_data.bullet_char === item_data.bullet_char); }
javascript
{ "resource": "" }
q48696
train
function(mythis) { // finalize any blocks not matched while (!already_done && oldtip != last_matched_container) { mythis.finalize(oldtip, line_number); oldtip = oldtip.parent; } var already_done = true; }
javascript
{ "resource": "" }
q48697
train
function(block) { switch(block.t) { case 'Paragraph': case 'SetextHeader': case 'ATXHeader': block.inline_content = this.inlineParser.parse(block.string_content.trim(), this.refmap); block.string_content = ""; break; default: break; } if (block.children) { for (var i = 0; i < block.children.length; i++) { this.processInlines(block.children[i]); } } }
javascript
{ "resource": "" }
q48698
train
function(input) { this.doc = makeBlock('Document', 1, 1); this.tip = this.doc; this.refmap = {}; var lines = input.replace(/\n$/,'').split(/\r\n|\n|\r/); var len = lines.length; for (var i = 0; i < len; i++) { this.incorporateLine(lines[i], i+1); } while (this.tip) { this.finalize(this.tip, len - 1); } this.processInlines(this.doc); return this.doc; }
javascript
{ "resource": "" }
q48699
DocParser
train
function DocParser(){ return { doc: makeBlock('Document', 1, 1), tip: this.doc, refmap: {}, inlineParser: new InlineParser(), breakOutOfLists: breakOutOfLists, addLine: addLine, addChild: addChild, incorporateLine: incorporateLine, finalize: finalize, processInlines: processInlines, parse: parse }; }
javascript
{ "resource": "" }