_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
27
233k
language
stringclasses
1 value
meta_information
dict
q5400
encodeArray_PRIM_BULK_PLAIN
train
function encodeArray_PRIM_BULK_PLAIN( encoder, data, properties ) { // // Bulk Array of Primitives (PRIM_BULK_PLAIN) // // ........ + Signature ID // 01111000 [16-bit] // // Lookup signature var eid = encoder.getSignatureID( properties ), weave = []; encoder.counters.arr_prim_bulk_plain+=1; encoder.log(LOG.ARR, "array.prim.bulk_plain, len="+data.length+ ", signature="+properties.toString()+ ", eid="+eid+" ["); encoder.logIndent(1); // Put header encoder.stream8.write( pack1b( ARR_OP.PRIM_BULK_PLAIN ) ); encoder.stream16.write( pack2b( eid, false ) ); encoder.counters.arr_hdr+=3; // Write bulked properties var weaveArrays
javascript
{ "resource": "" }
q5401
encodeLIREF
train
function encodeLIREF(encoder, op8, op16, local_ids, xrid) { var DEBUG_THIS = false; // Check if the given object is part of the array var id=-1, i=0, l=local_ids.length; for (;i<l;++i) { if (i > 65535) break; if (local_ids[i] === xrid) { id = i; break; } } if (id === -1) { // IREF op8.push( pack1b( PRIM_BULK_KNOWN_OP.IREF | ((xrid >> 16) & 0xF), false ) ); op16.push( pack2b( xrid & 0xFFFF, false ) ); encoder.counters.op_iref+=3; local_ids.push(xrid); if (DEBUG_THIS) console.log("->- IREF(",xrid,",",id,")"); } else if (id < 128) { // LREF_7 op8.push( pack1b( PRIM_BULK_KNOWN_OP.LREF_7 | (id & 0x7F), false ) ); encoder.counters.op_iref+=1; if (DEBUG_THIS) console.log("->- LREF_7(",xrid,",",id,")"); } else
javascript
{ "resource": "" }
q5402
encodeArray_PRIM_SHORT
train
function encodeArray_PRIM_SHORT( encoder, data ) { // // Short Primitive Array (PRIM_SHORT) // // ........ // 01111100 // // Open log group encoder.counters.arr_prim_short+=1; encoder.log(LOG.ARR, "array.prim.short, len="+data.length+ ", peek="+data[0]+" ["); encoder.logIndent(1); // Encode primitives one after the other encoder.stream8.write( pack1b( ARR_OP.PRIM_SHORT ) ); encoder.stream8.write( pack1b(
javascript
{ "resource": "" }
q5403
encodeArray_PRIM_REPEATED
train
function encodeArray_PRIM_REPEATED( encoder, data ) { // // Repeated Primitive Array (PRIM_REPEATED) // // ....... . + Signature ID // 0111100 [LN] [16-bit] // encoder.counters.arr_prim_repeated+=1; encoder.log(LOG.ARR, "array.prim.repeated, len="+data.length+ ", peek="+data[0]); if (data.length < UINT16_MAX) {
javascript
{ "resource": "" }
q5404
encodeArray_PRIM_RAW
train
function encodeArray_PRIM_RAW( encoder, data ) { // // Raw Primitive Array (PRIM_RAW) // // ....... . + Signature ID // 0110101 [LN] [16-bit] // // Write chunk header encoder.counters.arr_prim_raw+=1; encoder.log(LOG.ARR, "array.prim.raw, len="+data.length+ ", peek="+data[0]+" ["); encoder.logIndent(1); if (data.length < UINT16_MAX) { // 16-bit length prefix encoder.stream8.write( pack1b( ARR_OP.PRIM_RAW | NUMTYPE_LN.UINT16 ) ); encoder.stream16.write( pack2b( data.length, false ) ); encoder.counters.arr_hdr+=3; } else { // 32-bit length prefix encoder.stream8.write( pack1b( ARR_OP.PRIM_RAW |
javascript
{ "resource": "" }
q5405
encodeArray_PRIM_CHUNK
train
function encodeArray_PRIM_CHUNK( encoder, data, chunks ) { // // Chunked Primitive Array (PRIM_CHUNK) // // ........ // 01111101 // var chunk, chunkType, chunkSize, chunkSubType, part, num_flag = 0x2; // Check if all chunks are numeric if (!chunks.is_numeric) num_flag = 0; // Write chunk header if (data.length < UINT16_MAX) { // 16-bit length prefix encoder.stream8.write( pack1b( ARR_OP.PRIM_CHUNK | NUMTYPE_LN.UINT16 | num_flag ) ); encoder.stream16.write( pack2b( data.length, false ) ); encoder.counters.arr_hdr+=3; } else { // 32-bit length prefix encoder.stream8.write( pack1b( ARR_OP.PRIM_CHUNK | NUMTYPE_LN.UINT32 | num_flag ) ); encoder.stream32.write( pack4b( data.length, false ) ); encoder.counters.arr_hdr+=5; } // Log
javascript
{ "resource": "" }
q5406
encodeArray_EMPTY
train
function encodeArray_EMPTY( encoder ) { // // Empty Array (EMPTY) // // ........ // 01111110 //
javascript
{ "resource": "" }
q5407
encodeArray_Chunk
train
function encodeArray_Chunk( encoder, data, chunk ) { var n_type, na; // console.log(">>> CFWA Chunk="+_ARR_CHUNK[chunk[2]],", from=" + chunk[0] + ", len=" + chunk[1] + ", arr=" + data.length); // console.log(">>> =",data); // Encode array component according to chunk type switch (chunk[2]) { // Encode as an array of primitives case ARR_CHUNK.PRIMITIVES: if (data.length < 256) { encodeArray_PRIM_SHORT( encoder, data ); } else { encodeArray_PRIM_RAW( encoder, data ); } break; // Encode as a repeated array case ARR_CHUNK.REPEAT: // Prioritize numeric type suggested by chunk n_type = chunk[4]; if (n_type === NUMTYPE.UNKNOWN) n_type = getTypedArrayType( data ); // Check
javascript
{ "resource": "" }
q5408
encodeArray_Numeric
train
function encodeArray_Numeric( encoder, data, n_type ) { var na, keep = true, v, lv, same = true; // Separate small array case if (data.length < 256) { // If the numeric type is unknown, try to find actual type if (n_type === NUMTYPE.NUMERIC) { // Perform fast numeric analysis (skip delta) na = analyzeNumericArray( data, false ); // Check if this is not a numeric array (getTypedArrayType can fail // in Array cases since it's optimised for speed, not accuracy) if (na === null) { keep = false; } else { n_type = na.type; same = na.same; } } else { // Test for same lv = data[0]; for (var i=1, len=data.length; i<len; ++i) { v = data[i]; if (v !== lv) { same = false; break; } lv = v; } } // If for any reason this array is not numeric, don't // try to encode it if (keep) { if (same) { // If all values are the same, prefer repeated instead of short // console.log(">ARR>",data.length,"itms as REPEATED"); encodeArray_NUM_REPEATED( encoder, data, n_type ); } else { // Encode small numeric array // console.log(">ARR>",data.length,"itms as SHORT"); encodeArray_NUM_SHORT( encoder, data, n_type ); } } else { // Pass it to primitive encoder encodeArray_Primitive( encoder, data ); } } else { // Perform full numeric type analysis and encode numeric array na = analyzeNumericArray( data, true ); // Check if this is not a numeric array (getTypedArrayType can fail // in Array cases since it's optimised for speed, not accuracy) if (na !== null) { // Define generic type if (n_type === NUMTYPE.NUMERIC) { n_type = na.type; } // If all values are the same, encode using same numeric encoding if (na.same) { // console.log(">ARR>",data.length,"itms as REPEATED"); encodeArray_NUM_REPEATED( encoder, data, n_type ); return; } // If we have more than <thresshold> items with the same // value, break into chunked array if (na.psame >= encoder.optimize.repeat_break_thresshold) { encodeArray_Primitive( encoder, data ); return; }
javascript
{ "resource": "" }
q5409
encodeArray_Primitive
train
function encodeArray_Primitive( encoder, data ) { // Analyze primitive array and return clusters of values // that can be efficiently merged (such as numbers, repeated values, // primitives etc.) var chunks = analyzePrimitiveArray( encoder, data ); if (chunks.length === 1) { // Just check if (chunks[0][1] !== data.length) { throw new Errors.AssertError('Primitive array analysis reported single chunk but does not match array length!'); }
javascript
{ "resource": "" }
q5410
encodeArray
train
function encodeArray( encoder, data ) { encoder.log(LOG.PRM, "array, len="+data.length+", peek="+data[0]); // Check for empty array if (data.length === 0) { encodeArray_EMPTY( encoder ); return; } // Get typed array typed var tt =
javascript
{ "resource": "" }
q5411
encodeBuffer
train
function encodeBuffer( encoder, buffer_type, mime_type, buffer ) { // Write buffer header according to buffer length if (buffer.length < UINT8_MAX) { encoder.stream8.write( pack1b( PRIM_OP.BUFFER | buffer_type | 0x00 ) ); encoder.stream8.write( pack1b( buffer.length ) ); encoder.counters.dat_hdr+=2; } else if (buffer.length < UINT16_MAX) { encoder.stream8.write( pack1b( PRIM_OP.BUFFER | buffer_type | 0x08 ) ); encoder.stream16.write( pack2b( buffer.length ) ); encoder.counters.dat_hdr+=3; } else if (buffer.length < UINT32_MAX) { encoder.stream8.write( pack1b( PRIM_OP.BUFFER | buffer_type | 0x10 ) ); encoder.stream32.write( pack4b( buffer.length ) ); encoder.counters.dat_hdr+=5; } else { // 4 Gigs? Are you serious? Of course we can fit it in a Float64, but WHY? throw new Errors.RangeError('The buffer you are trying to encode is bigger than the supported size!'); } // Write MIME Type (from string lookup table) if (mime_type !=
javascript
{ "resource": "" }
q5412
encodeEmbeddedFileBuffer
train
function encodeEmbeddedFileBuffer( encoder, buffer_type, filename, mime_type ) { // Get MIME And payload var mime = mime_type || mimeTypeFromFilename( filename ), mime_id = encoder.stringID( mime ), buffer = bufferFromFile( filename ); // Write
javascript
{ "resource": "" }
q5413
encodeEmbeddedBlobBuffer
train
function encodeEmbeddedBlobBuffer( encoder, buffer_type, buffer, mime_type ) { // Get MIME And payload var mime_id = encoder.stringID( mime_type ); // Write buffer header
javascript
{ "resource": "" }
q5414
encodeStringBuffer
train
function encodeStringBuffer( encoder, str, utf8 ) { // If we do not have an explicit utf8 or not decision, pick one now if (utf8 === undefined) { utf8 = false; // Assume false for (var i=0, strLen=str.length; i<strLen; ++i) { if (str.charCodeAt(i) > 255) { utf8 = true; break; } } } // Allocate buffer var buf, bufView, bufType; if (utf8) { buf = new ArrayBuffer(str.length*2); // 2 bytes for each char bufView = new Uint16Array(buf); bufType = PRIM_BUFFER_TYPE.STRING_UTF8; encoder.log(LOG.STR,"string='"+str+"', encoding=utf-8, len="+str.length); } else { buf = new ArrayBuffer(str.length); // 1 byte for
javascript
{ "resource": "" }
q5415
encodeIREF
train
function encodeIREF( encoder, id ) { var hi = (id & 0xF0000) >> 16, lo = (id & 0xFFFF) // Write opcode splitted inti 8-bit and 16-bit encoder.log(LOG.IREF, "iref="+id); encoder.stream8.write( pack1b(
javascript
{ "resource": "" }
q5416
encodeXREF
train
function encodeXREF( encoder, id ) { // Write opcode for 16-bit lookup encoder.log(LOG.XREF, "xref="+id+" [" +
javascript
{ "resource": "" }
q5417
encodeObject
train
function encodeObject( encoder, object ) { // Check ByRef internally var id = encoder.lookupIRef( object ); if (id > -1) { encodeIREF( encoder, id ); return; } // Check ByRef externally id = encoder.lookupXRef( object ); if (id > -1) { encodeXREF( encoder, id); return } // Lookup object type var enc = encoder.profile.encode(object); if (!enc) { throw new Errors.XRefError('An object trying to encode was not declared in the object table!'); } // Populate property table var eid = enc[0], propertyTable = enc[1]( object ); // Check ByVal ref id =
javascript
{ "resource": "" }
q5418
encodePrimitiveDate
train
function encodePrimitiveDate( encoder, object ) { // We have a date primitive encoder.stream8.write( pack1b( PRIM_OP.OBJECT | OBJ_OP.PRIMITIVE | OBJ_PRIM.DATE ) ); // Save date
javascript
{ "resource": "" }
q5419
encodePlainObject
train
function encodePlainObject( encoder, object ) { // Extract plain object signature var o_keys =Object.keys(object); // signature = o_keys.join("+"), var sid = encoder.getSignatureID( o_keys ); // Collect values of all properties var values = []; for (var i=0, len=o_keys.length; i<len; ++i) values.push( object[o_keys[i]] ); encoder.log(LOG.PLO, "plain["+sid+"], signature="+o_keys.toString()+", sid="+sid); // Split entity ID in a 11-bit number var sid_hi = (sid & 0x700) >> 8, sid_lo = sid & 0xFF;
javascript
{ "resource": "" }
q5420
encodePrimitive_NUMBER
train
function encodePrimitive_NUMBER(encoder, data, type) { // Write header encoder.log(LOG.PRM, "primitive.number, type="+_NUMTYPE[numType]+", n="+data); encoder.stream8.write( pack1b( PRIM_OP.NUMBER | numType ) );
javascript
{ "resource": "" }
q5421
train
function(string) { var index = this.stringLookupQuick[string]; // If missing, allocate now if (index === undefined) { index = this.stringLookup.length;
javascript
{ "resource": "" }
q5422
train
function( propertyTable, eid ) { // Check if we have a BST for this type if (this.indexVal[eid] !== undefined) { var id = this.indexVal[eid].search( propertyTable
javascript
{ "resource": "" }
q5423
train
function( object, propertyTable, eid ) { // Create a new BST for this entity for by-value matching if (this.indexVal[eid] === undefined) this.indexVal[eid] = new BinarySearchTree({ compareKeys: objectBstComparison, checkValueEquality: objectBstEquals, unique: true, }); // Keep object references var nid = this.indexRef.length; this.indexVal[eid].insert( propertyTable, nid ); this.indexRef.push( object ); // Keep ID on
javascript
{ "resource": "" }
q5424
train
function( object ) { var keys = Object.keys(object), k, v, lVals = [], lArrays = [], lObjects = []; // Sort to values, arrays and objects var lookupString = ""; for (var i=0; i<keys.length; ++i) { k = keys[i]; v = object[k]; if ((v instanceof Uint8Array) || (v instanceof Int8Array) || (v instanceof Uint16Array) || (v instanceof Int16Array) || (v instanceof Uint32Array) || (v instanceof Int32Array) || (v instanceof Float32Array) || (v instanceof Float64Array)
javascript
{ "resource": "" }
q5425
train
function( object ) { var keys = Object.keys(object), k, v, lookupString, lVals = [], lArrays = [], lObjects = []; // Sort to values, arrays and objects lookupString = ""; for (var i=0; i<keys.length; ++i) { k = keys[i]; v = object[k]; if ((v instanceof Uint8Array) || (v instanceof Int8Array) || (v instanceof Uint16Array) || (v instanceof Int16Array) || (v instanceof Uint32Array) || (v instanceof Int32Array) || (v instanceof Float32Array) || (v instanceof Float64Array) || (v instanceof Array) ) { lArrays.push(k); lookupString += "@"+k; } else if (v.constructor === ({}).constructor) { lObjects.push(k); lookupString += "%"+k; } else { lVals.push(k); lookupString += "$"+k; } } // Lookup or create signature i = this.plainObjectSignatureLookup[lookupString]; if (i === undefined) { // Compile signature var sigbuf = []; sigbuf.push( pack2b( lVals.length )
javascript
{ "resource": "" }
q5426
train
function( db, prefix ) { if (!prefix) prefix=""; // Import into an easy-to-process format var keys = Object.keys(db), k, v; for (var i=0; i<keys.length; ++i) { k = keys[i]; v = db[k]; if (!db.hasOwnProperty(k)) continue;
javascript
{ "resource": "" }
q5427
train
function( filename, mime_type ) { // Calculate relative path var relPath = filename; if (relPath.substr(0,this.baseDir.length) === this.baseDir) relPath = relPath.substr( this.baseDir.lengh ); // Write control operation this.stream8.write( pack1b( CTRL_OP.EMBED ) ); this.counters.op_ctr++; // Write string ID from the
javascript
{ "resource": "" }
q5428
train
function( buffer, name, mime_type ) { // Write control operation this.stream8.write( pack1b( CTRL_OP.EMBED ) ); this.counters.op_ctr++; // Write string ID from the string lookup table this.stream16.write( pack2b( this.stringID(this.bundleName + "/" + name) ) );
javascript
{ "resource": "" }
q5429
train
function(flags) { // Set log flags this.logFlags = flags; // Update flags on streams this.stream64.logWrites = ((this.logFlags & LOG.WRT) != 0); this.stream32.logWrites = ((this.logFlags &
javascript
{ "resource": "" }
q5430
train
function(indent, c) { var iChar = c || ">"; if (indent > 0) { for (var i=0; i<indent; ++i) this.logPrefix+=iChar; } else {
javascript
{ "resource": "" }
q5431
train
function( parent, name ) { /** * State of the bundle item in queue * * 0 - Requested * 1 - Specs loaded * 2 - Imports satisfied * 3 - Loaded */ this.state = STATE_REQUESTED; /** * Reference to the Bundles instance */ this.bundles = parent; /** * The bundle name */ this.name = name; /** * The bundle base directory */ this.bundleURL = null; /** * Suffix to append to bundle files */ this.bundleURLSuffix = "";
javascript
{ "resource": "" }
q5432
App
train
function App(root, options) { options = options || {}; if (!root || typeof root !== 'string') { throw new Error('Application root is not provided or not a string.'); } if (typeof options !== 'object') {
javascript
{ "resource": "" }
q5433
validatePluginName
train
function validatePluginName(plugin, pluginList) { if (!plugin.name) throw new Error(ApiHost.ERR_PLUGIN_MISSING_NAME_PROPERTY); pluginList.forEach(function (collectorPlugin) { if (plugin.name === collectorPlugin.name) {
javascript
{ "resource": "" }
q5434
gpsTimestampToUtcTimestamp
train
function gpsTimestampToUtcTimestamp(gpsTimestamp) { // Get lastIndex for which our gpsTimestamp is greater var lastIndex = void 0; for (lastIndex = 0; lastIndex < gpsLeapSeconds.length; ++lastIndex)
javascript
{ "resource": "" }
q5435
utcTimestampToGpsTimestamp
train
function utcTimestampToGpsTimestamp(utcTimestamp) { // Get lastIndex for which our gpsTimestamp is greater var lastIndex = void 0; for (lastIndex = 0; lastIndex < gpsLeapSeconds.length; ++lastIndex)
javascript
{ "resource": "" }
q5436
getTaskConfiguration
train
function getTaskConfiguration(profile){ var config; profile = profile || 'default'; config = require(__dirname +
javascript
{ "resource": "" }
q5437
build
train
function build(TaskConfig, crx) { return new Promise(function(resolve, reject){ mkdir(path.dirname(TaskConfig.dest), function(err){ if (err) { return reject(err); } resolve(); }); }) .then(function(){ return crx.load(TaskConfig.src); }) .then(function(){ return crx.loadContents(); }) .then(function(archiveBuffer){ if (path.extname(TaskConfig.dest) === '.zip') { grunt.file.write(TaskConfig.dest, archiveBuffer); grunt.log.ok(TaskConfig.dest + ' has been created.'); } return archiveBuffer; })
javascript
{ "resource": "" }
q5438
loadUses
train
function loadUses() { var globs = Array.prototype.slice.call(arguments, 0); var path = require('path'); utils.forEach(globs, function(patt) { var files = glob.sync(patt, {}); utils.forEach(files, function(file) {
javascript
{ "resource": "" }
q5439
setEnabledFeatures
train
function setEnabledFeatures(selectedFeature) { switch (selectedFeature) { case "AnalogInputFirmata": analogInputEnabled = true; break; case "AnalogOutputFirmata": analogOutputEnabled = true;
javascript
{ "resource": "" }
q5440
train
function(config) { var transport; if (config.wifi) { transport = new WiFiTransport({ configuration: config.wifi }); } else if (config.ethernet) { transport = new EthernetTransport({ configuration: config.ethernet }); } else if (config.ble) { transport = new BLETransport({ configuration:
javascript
{ "resource": "" }
q5441
train
function() { var len = this.selectedFeatures.length; clearEnabledFeatures(); for (var i = 0; i < len; i++) { setEnabledFeatures(this.selectedFeatures[i]); var feature = this.allFeatures[this.selectedFeatures[i]]; if (feature.reporting) { this.featuresWithReporting.push(feature); } if (feature.update) {
javascript
{ "resource": "" }
q5442
train
function() { var includes = "#include <ConfigurableFirmata.h>\n\n"; includes += this.transport.createConfigBlock(); for (var i = 0, len = this.selectedFeatures.length; i < len; i++) { var feature = this.allFeatures[this.selectedFeatures[i]]; if (feature.dependencies) { for (var j = 0; j < feature.dependencies.length; j++) { var d = feature.dependencies[j]; // prevent duplicate includes if (d.className && !this.dependencies[d.className]) { includes += "#include <" + d.className + ".h>\n"; this.dependencies[d.className] = true; } } } includes +=
javascript
{ "resource": "" }
q5443
BLETransport
train
function BLETransport(opts) { if (!(this instanceof BLETransport)) { return new BLETransport(opts); } this.configuration = opts.configuration;
javascript
{ "resource": "" }
q5444
parse
train
function parse(str, options) { var doc = options.document || 'xml' , pretty = options.pretty || false , js = str; return '' + 'var ' + doc + ' = factory();\n' + (options.self ? 'var self = locals || {};\n' + js
javascript
{ "resource": "" }
q5445
WiFiTransport
train
function WiFiTransport(opts) { if (!(this instanceof WiFiTransport)) { return new WiFiTransport(opts); } this.configuration = opts.configuration;
javascript
{ "resource": "" }
q5446
serialize
train
function serialize (node, context, fn, eventTarget) { if (!node) return ''; if ('function' === typeof context) { fn = context; context = null; } if (!context) context = null; var rtn; var nodeType = node.nodeType; if (!nodeType && 'number' === typeof node.length) { // assume it's a NodeList or Array of Nodes rtn = exports.serializeNodeList(node, context, fn); } else { if ('function' === typeof fn) { // one-time "serialize" event listener node.addEventListener('serialize', fn, false); } // emit a custom "serialize" event on `node`, in case there // are event listeners for custom serialization of this node var e = new CustomEvent('serialize', { bubbles: true, cancelable: true, detail: { serialize: null, context: context } }); e.serializeTarget = node; var target = eventTarget || node; var cancelled = !target.dispatchEvent(e); // `e.detail.serialize` can be set to a: // String - returned directly // Node - goes through serializer logic instead of `node` // Anything else - get Stringified first, and then returned directly var s = e.detail.serialize; if (s != null) { if ('string' === typeof s) { rtn = s; } else if ('number' === typeof s.nodeType) { // make it go through the serialization logic rtn = serialize(s, context, null, target); } else {
javascript
{ "resource": "" }
q5447
serializeAttribute
train
function serializeAttribute (node, opts) { return node.name + '="' + encode(node.value,
javascript
{ "resource": "" }
q5448
serializeElement
train
function serializeElement (node, context, eventTarget) { var c, i, l; var name = node.nodeName.toLowerCase(); // opening tag var r = '<' + name; // attributes for (i = 0, c = node.attributes, l = c.length; i < l; i++) { r += ' ' + exports.serializeAttribute(c[i]); } r += '>'; // child nodes r +=
javascript
{ "resource": "" }
q5449
serializeText
train
function serializeText (node, opts) { return encode(node.nodeValue, extend({ named: true,
javascript
{ "resource": "" }
q5450
serializeDocument
train
function serializeDocument (node, context, eventTarget) {
javascript
{ "resource": "" }
q5451
serializeDocumentFragment
train
function serializeDocumentFragment (node, context, eventTarget) { return
javascript
{ "resource": "" }
q5452
EthernetTransport
train
function EthernetTransport(opts) { if (!(this instanceof EthernetTransport)) { return new EthernetTransport(opts); } this.configuration = opts.configuration; this.controller = ""; switch (Controllers[this.configuration.controller].driver) { case Controllers.WIZ5100.driver: this.controller = Controllers.WIZ5100; break;
javascript
{ "resource": "" }
q5453
askQuestions
train
async function askQuestions(questions, timeout) { if (typeof questions != 'object') throw new Error('Please give an object with questions') const keys = Object.keys(/** @type {!Object} */ (questions)) const res = await keys.reduce(async (acc, key) => { const accRes = await acc const value = questions[key] /** @type {!_reloquent.Question} */ let question switch (typeof value) { case 'object': question = /** @type {!_reloquent.Question} */ ({ ...value }) break case 'string': question = { text: value } break default: throw new Error('A question must be a string or an object.') } question.text = `${question.text}${question.text.endsWith('?') ? '' : ':'} `
javascript
{ "resource": "" }
q5454
objPath
train
function objPath(obj, path) { if (!path) { return obj; } path = path.split('.'); let i = 0;
javascript
{ "resource": "" }
q5455
reloquent
train
async function reloquent(questions, timeout) { const res
javascript
{ "resource": "" }
q5456
askSingle
train
async function askSingle(question, timeout) { const { question: answer } =
javascript
{ "resource": "" }
q5457
train
function (model, pojo, options) { pojo = pojo || {}; let props = model.serializeProperties || model.properties; props = props.filter(prop => (!model.propertyOptions[prop] || model.propertyOptions[prop].serialize !== false)); props.forEach(key => { let obj; let o = model.propertyOptions[key]; if (o && o.preSerialize) { obj = o.preSerialize(options); } else { obj = model[key]; } if (obj instanceof Array) { let newArr = []; obj.forEach(item => { newArr.push(item instanceof Model ? item.serialize() : item); });
javascript
{ "resource": "" }
q5458
registerEventHandlers
train
function registerEventHandlers(windowBridge, app) { "use strict"; handleOutgoingEvent(windowBridge, app, WebAPIEvents.EVENT_WEBAPI_REQUEST_DESKPRO,
javascript
{ "resource": "" }
q5459
ask
train
function ask(question, options = {}) { const { timeout, password = false, output = process.stdout, input = process.stdin, ...rest } = options const rl = createInterface(/** @type {!readline.ReadLineOptions} */ ({ input, output, ...rest, })) if (password) { /** * Undocumented API. * @type {!NodeJS.WriteStream} * @suppress {checkTypes} */ const o = rl['output'] /** * Undocumented API. * @suppress {checkTypes} */ rl['_writeToOutput'] = (s) => { if (['\r\n', '\n', '\r'].includes(s)) return o.write(s) const v = s.split(question)
javascript
{ "resource": "" }
q5460
hm
train
function hm(n, v, incv, offv, tau, b, offb) { // Apply householder transformation b = b - tau v v' b // LAPACK: DLARF if (tau === 0.0) { return; } // compute v' b var d = b[offb + 0]; for (var i = 1; i < n; ++i) { d += b[offb +
javascript
{ "resource": "" }
q5461
check_STEP_file
train
function check_STEP_file(filename, callback) { "use strict"; // "ISO-10303-21;" // "HEADER;" var stream = fs.createReadStream(filename, {flags:"r"}); var fileData = ""; stream.on('data', function (data) { fileData += data; // The next lines should be improved var lines = fileData.split("\n"); if (lines.length >= 2) { stream.destroy(); if (!pattern_ISO_10303_21.test(lines[0])) { my_callback(new Error("this file is not a STEP FILE : ISO_10303_21 missing")); } else { my_callback(null, lines[0]);
javascript
{ "resource": "" }
q5462
process
train
function process (svg, { prefix }) { // Inject a <style> in the SVG document to allow changing colors svg = svg.replace(/<(path|circle) /gi, (_, tag) => `<${tag} fill="__COLOR__" `) // Since this is a
javascript
{ "resource": "" }
q5463
train
function (login, pass) { try { document.getElementsByName("email")[0].value = login; document.getElementsByName("pass")[0].value = pass;
javascript
{ "resource": "" }
q5464
shortcutRequest
train
function shortcutRequest(req){ req.get = shortcut(req, 'GET') req.post = shortcut(req, 'POST') req.put = shortcut(req, 'PUT') req.patch = shortcut(req, 'PATCH')
javascript
{ "resource": "" }
q5465
lnprior
train
function lnprior(theta) { var m = theta[0], b = theta[1], t = theta[2]; if (0.0 < m && m < 1.0 && 0.0 < b && b < 10.0 && 0.0 <
javascript
{ "resource": "" }
q5466
lnpost
train
function lnpost(theta, x, y) { var lp = lnprior(theta); if (!isFinite(lp)) {
javascript
{ "resource": "" }
q5467
renameSelector
train
function renameSelector(selector, sourcePath, opts, mappings) { return selector.map(function(selector){ return parser(function(sels) { sels.map(function(sel) {
javascript
{ "resource": "" }
q5468
renameNodes
train
function renameNodes(nodes, sourcePath, opts, mappings) { return nodes.map(function(node) { // Process CSS node if (node.type === 'class') { // Process "class" node var orgValue = node.value, newValue = renameClassNode(node.value, sourcePath, opts); // Edit node and store mapping of classname renaming node.value = mappings[orgValue] = newValue; } else if (node.type === 'pseudo' && node.value
javascript
{ "resource": "" }
q5469
renameClassNode
train
function renameClassNode(value, sourcePath, opts) { // Generate hashes var className = value, compositeHash = loaderUtils.getHashDigest( (sourcePath ? sourcePath + className : className), opts.hashType, opts.digestType, opts.maxLength), classHash = loaderUtils.getHashDigest( className, opts.hashType, opts.digestType, opts.maxLength), sourcePathHash = (sourcePath ? loaderUtils.getHashDigest( sourcePath, opts.hashType, opts.digestType, opts.maxLength) : ''),
javascript
{ "resource": "" }
q5470
verifyOptionType
train
function verifyOptionType(sourcePath, name, value) { if (typeof value === 'object') { var msg = 'POSTCSS-HASH-CLASSNAME ERROR: Object value not supported for option "' + name + '"!'; console.error(msg); throw new Error(msg); } else if (!sourcePath && typeof value === 'function') { var msg = 'POSTCSS-HASH-CLASSNAME ERROR: Source file\'s path isn not determined - only explicit values for option "' + name + '" supported! Value passed is a function.'; console.error(msg); throw new Error(msg);
javascript
{ "resource": "" }
q5471
formatFileOutput
train
function formatFileOutput(mappings, type) { var string = JSON.stringify(mappings, null, 2);
javascript
{ "resource": "" }
q5472
createId
train
function createId(coll) { if (_.isEmpty(coll)) { return 1 } else { var id = _.max(coll, function(doc) {
javascript
{ "resource": "" }
q5473
getOverrides
train
function getOverrides (eventType, options) { if (eventType === 'KeyboardEvent' && options) { return { keyCode: options.keyCode || 0,
javascript
{ "resource": "" }
q5474
topsort
train
function topsort(edges, options) { var nodes = {}; options = options || { continueOnCircularDependency: false }; var sorted = []; // hash: id of already visited node => true var visited = {}; // 1. build data structures edges.forEach(function (edge) { var fromEdge = edge[0]; var fromStr = fromEdge.toString(); var fromNode; if (!(fromNode = nodes[fromStr])) { fromNode = nodes[fromStr] = new EdgeNode(fromEdge); } edge.forEach(function (toEdge) { // since from and to are in same array, we'll always see from again, so make sure we skip it.. if (toEdge == fromEdge) { return; } var toEdgeStr = toEdge.toString(); if (!nodes[toEdgeStr]) { nodes[toEdgeStr] = new EdgeNode(toEdge); } fromNode.afters.push(toEdge); }); }); // 2. topological sort var keys = Object.keys(nodes); keys.sort(sortDesc); keys.forEach(function visit(idstr, ancestorsIn) { var node = nodes[idstr]; var id = node.id; // if already exists, do nothing if (visited[idstr]) { return; }
javascript
{ "resource": "" }
q5475
Vultr
train
function Vultr(apiKey) { this.version = 'v1'; this.endpoint = 'https://api.vultr.com/' + this.version + '/'; this.apiKey = (apiKey ? apiKey : config.vultr.apiKey); this.account = new account(this); this.dns = new dns(this);
javascript
{ "resource": "" }
q5476
start
train
function start(object, filename) { var port = process.env.PORT || argv.port var hostname = argv.host === '0.0.0.0' ? 'localhost' : argv.host for (var prop in object) { console.log(chalk.gray(' http://' + hostname + ':' + port + '/') + chalk.cyan(prop)) } console.log( '\nYou can now go to ' + chalk.gray('http://' + hostname + ':' + port + '/\n') ) console.log( 'Enter ' + chalk.cyan('`s`') + ' at any
javascript
{ "resource": "" }
q5477
train
function(metric_type, metric) { var ary = metric.split('.'); if
javascript
{ "resource": "" }
q5478
train
function(time, key, val) { return { db: dbPrefix(key), col: colPrefix('gauges', key),
javascript
{ "resource": "" }
q5479
train
function(dbName, collection, metric, callback) { var colInfo = {capped:true, size:options.size*options.max, max:options.max}; database(dbName, function(err, db) { if (err) { db.close(); return callback(err); }; db.createCollection(collection, colInfo,
javascript
{ "resource": "" }
q5480
train
function(time, metrics) { var metricTypes = ['gauges', 'timer_data', 'timers', 'counters', 'sets']; metricTypes.forEach(function(type, i){ var obj; for (var key in metrics[type]) { obj =
javascript
{ "resource": "" }
q5481
train
function(obj, callback) { if (angular.isArray(obj)) return obj.map(callback) var ret = {}
javascript
{ "resource": "" }
q5482
train
function (model) { if (!this.ngModel) { return; // A kb-item can't be selected without a ng-model on the container element. } if (this.multiple) { if (this.isSelected(model) === false) { this.selected.push(model);
javascript
{ "resource": "" }
q5483
train
function (model) { if (!this.ngModel) { return; } var index = this.selected.indexOf(model); if (index !== -1) { this.selected.splice(index, 1); if (this.multiple) {
javascript
{ "resource": "" }
q5484
train
function (kbItem) { var element = kbItem.element[0]; var items = this._element.querySelectorAll('[kb-item]'); for (var i = 0; i < items.length; i++) { var el = items.item(i); if (el === element) { var siblings = {}; if (i !== 0) { siblings.previous = angular.element(items.item(i - 1)).controller('kbItem');
javascript
{ "resource": "" }
q5485
train
function () { var nodes = this._element.querySelectorAll('[kb-item]'); if (nodes.length) {
javascript
{ "resource": "" }
q5486
distance
train
function distance(direction, currentRect, targetRect) { if (direction === 'left' && targetRect.left < currentRect.left) { return currentRect.left - targetRect.left; } if (direction === 'up' && targetRect.top < currentRect.top) { return currentRect.top - targetRect.top; } if (direction === 'right' && targetRect.left > currentRect.left) {
javascript
{ "resource": "" }
q5487
copyNormalize
train
function copyNormalize() { var stream = gulp.src(src.normalize) .pipe(plugins.rename(function(path) { path.basename = '_' + path.basename,
javascript
{ "resource": "" }
q5488
copySvg4Everybody
train
function copySvg4Everybody(dir) { gulp.src(src.svg4everybody)
javascript
{ "resource": "" }
q5489
copyFont
train
function copyFont(dir) { gulp.src(src.font)
javascript
{ "resource": "" }
q5490
compileSass
train
function compileSass() { var stream = gulp.src(src.scss) .pipe(plugins.sourcemaps.init()) .pipe(plugins.sass().on('error', plugins.sass.logError))
javascript
{ "resource": "" }
q5491
minifyCss
train
function minifyCss() { var stream = gulp.src([compiled.css + '/**/*', '!' + compiled.css + '/styleguide*']) .pipe(plugins.minifyCss())
javascript
{ "resource": "" }
q5492
minifySvg
train
function minifySvg() { var stream = gulp.src([src.svg, '!' + src.icons]) .pipe(plugins.svgmin({ plugins: [ { removeViewBox: false }, { removeUselessStrokeAndFill: false },
javascript
{ "resource": "" }
q5493
makeSvgSprite
train
function makeSvgSprite() { var stream = gulp.src([src.icons]) .pipe(plugins.svgmin({ plugins: [ { removeViewBox: false }, { removeUselessStrokeAndFill: false }, { removeEmptyAttrs: false }, { removeTitle: false }, { removeDesc: true } ],
javascript
{ "resource": "" }
q5494
snsConfirmHandler
train
function snsConfirmHandler() { return (req, res, next) => { // Handle call for SNS confirmation // @see http://docs.aws.amazon.com/sns/latest/dg/SendMessageToHttp.html if (req.headers['x-amz-sns-message-type'] === 'SubscriptionConfirmation') { const subscribeUrl = req.body.SubscribeURL; debug(`Received SubscriptionConfirmation request: ${subscribeUrl}`); return request({ uri: subscribeUrl }, (err, response, body) => { if (err) { return res.status(400).send({error: err.message}); } // Parse the response and extract the subscription ARN const parser = new xml2js.Parser(); return parser.parseString(body, function callback(err, doc) { if (err) { return res.status(400).send({error: err.message}); } let subscriptionArn; try { subscriptionArn = doc.ConfirmSubscriptionResponse.ConfirmSubscriptionResult[0].SubscriptionArn[0];
javascript
{ "resource": "" }
q5495
train
function(url) { //Parse the redirected url return provider.authorization_done(opt, url, window, function() { //Destroy the window
javascript
{ "resource": "" }
q5496
createPadding
train
function createPadding (width) { var result = '' var string = ' ' var n = width do { if (n % 2) { result +=
javascript
{ "resource": "" }
q5497
train
function(obj, objDict) { var parent = objDict[ obj.parentPath ]; if (parent) { if (parent.Substates == undefined)
javascript
{ "resource": "" }
q5498
Connection
train
function Connection(socket) { var self = this; events.EventEmitter.call(this); this._methods = {}; this._socket = socket || new net.Socket(); this._socket.setEncoding('utf8'); this._socket.addListener('connect', function() { var remote = new Remote(self); self.emit('connect', remote); }); this._socket.addListener('data', function(data) { //console.log('RECV: ' + data); self._parser.parse(data); }); this._socket.addListener('end', this.emit.bind(this, 'end')); this._socket.addListener('timeout', this.emit.bind(this, 'timeout')); this._socket.addListener('drain', this.emit.bind(this, 'drain')); this._socket.addListener('error', this.emit.bind(this, 'error')); this._socket.addListener('close', this.emit.bind(this, 'close')); this._parser = new jsonsp.Parser(function(obj) { if (obj.result
javascript
{ "resource": "" }
q5499
send
train
function send (severity, msg) { var len output(severity, msg, msg.length) // this should probably be 1024 if (msg.length > 1024) process.stderr.write(new Error('maximum log length
javascript
{ "resource": "" }