_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
27
233k
language
stringclasses
1 value
meta_information
dict
q5300
train
function(inputs, callback) { // Remove any empty inputs var filteredInputs = RunUtil.filterEmptyInputs(inputs || []); runner.run(method.slug, script, { input: filteredInputs
javascript
{ "resource": "" }
q5301
train
function(flags, checkFlags, value) { [].concat(checkFlags || []).forEach((function(flag, i) { if (i == value) { this.ensureFlag(flags, flag); } else
javascript
{ "resource": "" }
q5302
Client
train
function Client(appId, options) { this.appId = appId; this.stubbed = false; this.userAgent = defaultUserAgent; this._validator = new Validator(); // NOTE: We need to add a listener to the "error" event so the users aren't // forced to set up a listener themselves. If no listener for "error" // exists, emitting the event results in an uncaught
javascript
{ "resource": "" }
q5303
addToContainer
train
function addToContainer(container, key, val) { if (container instanceof Array) { container.push(val);
javascript
{ "resource": "" }
q5304
train
function(dir) { var methods = []; var findConfigFiles = function(dir) { fs.readdirSync(dir).forEach(function(file) { file = path.join(dir, file); var stat = fs.statSync(file); if(stat && stat.isDirectory()) { findConfigFiles(file); } else
javascript
{ "resource": "" }
q5305
runCmd
train
function runCmd(cmd) { return new Promise((resolve, reject) => { exec(cmd, {}, function(err, stdout) { if(err) {
javascript
{ "resource": "" }
q5306
train
function(value) { var d = FxoUtils.parseDateTimeField(value);
javascript
{ "resource": "" }
q5307
train
function(value, options) { var format = options.dateOnly ? '{yyyy}-{MM}-{dd}' :
javascript
{ "resource": "" }
q5308
source
train
function source(value, indent, limit, offset, visited) { var result; var names; var nestingIndex; var isCompact = !isUndefined(limit); indent = indent || " "; offset = (offset || ""); result = ""; visited = visited || []; if (isUndefined(value)) { result += "undefined"; } else if (isNull(value)) { result += "null"; } else if (isString(value)) { result += "\"" + value + "\""; } else if (isFunction(value)) { value = String(value).split("\n"); if (isCompact && value.length > 2) { value = value.splice(0, 2); value.push("...}"); } result += value.join("\n" + offset); } else if (isArray(value)) { if ((nestingIndex = (visited.indexOf(value) + 1))) { result = "#" + nestingIndex + "#"; } else { visited.push(value); if (isCompact) value = value.slice(0, limit); result += "[\n"; result += value.map(function(value) { return offset + indent + source(value, indent, limit, offset + indent, visited); }).join(",\n"); result += isCompact && value.length > limit ? ",\n" + offset + "...]" : "\n" + offset + "]"; } } else if (isObject(value)) { if ((nestingIndex = (visited.indexOf(value) + 1))) { result = "#" + nestingIndex + "#" } else { visited.push(value) names = Object.keys(value); result += "{ // " + value + "\n"; result += (isCompact ? names.slice(0, limit) : names).map(function(name) { var _limit = isCompact ? limit - 1 : limit; var descriptor = Object.getOwnPropertyDescriptor(value, name); var result = offset + indent + "// "; var accessor; if (0 <= name.indexOf(" ")) name = "\"" + name + "\""; if (descriptor.writable) result += "writable "; if (descriptor.configurable) result += "configurable "; if (descriptor.enumerable) result += "enumerable "; result += "\n"; if ("value" in descriptor) { result += offset + indent + name + ": "; result += source(descriptor.value, indent, _limit, indent + offset,
javascript
{ "resource": "" }
q5309
ApiError
train
function ApiError(response, client) { this.name = "heap.ApiError"; this.response = response; this.client = client;
javascript
{ "resource": "" }
q5310
init
train
function init(options, callback, proxies, logLevel) { if (! callback) { log.error("The end callback is not defined"); } // Default options globalOptions = createDefaultOptions(); // Merge default options values & overridden values provided by the arg options if (options) { _.extend(globalOptions, options); } // if using rateLimits we want to use only one connection with delay between requests if (globalOptions.rateLimits !== 0) { globalOptions.maxConnections = 1; } // create the crawl store store.createStore(globalOptions.storeModuleName, globalOptions.storeParams ? globalOptions.storeParams : null); // If the options object contains an new implementation of the updateDepth method if
javascript
{ "resource": "" }
q5311
queue
train
function queue(options) { if (! endCallback) { console.log("The end callback is not defined, impossible to run correctly"); return; } // Error if no options if (! options){ crawl({errorCode : "NO_OPTIONS"}, {method:"GET", url : "unknown", proxy : "", error : true}, function(error){ if (requestQueue.idle()) { endCallback(); } }); return; } // if Array => recall this method for each element if (_.isArray(options)) { options.forEach(function(opt){ queue(opt); }); return; } // if String, we expect to receive an url
javascript
{ "resource": "" }
q5312
addDefaultOptions
train
function addDefaultOptions(options, defaultOptions) { _.defaults(options, defaultOptions);
javascript
{ "resource": "" }
q5313
buildNewOptions
train
function buildNewOptions (options, newUrl) { // Old method /* var o = createDefaultOptions(newUrl); // Copy only options attributes that are in the options used for the previous request // Could be more simple ? ;-) o = _.extend(o, _.pick(options, _.without(_.keys(o), "url"))); */ var o = _.clone(options); o.url =
javascript
{ "resource": "" }
q5314
createDefaultOptions
train
function createDefaultOptions(url) { var options = { referer : DEFAULT_REFERER, skipDuplicates : DEFAULT_SKIP_DUPLICATES, maxConnections : DEFAULT_NUMBER_OF_CONNECTIONS, rateLimits : DEFAULT_RATE_LIMITS, externalDomains : DEFAULT_CRAWL_EXTERNAL_DOMAINS, externalHosts : DEFAULT_CRAWL_EXTERNAL_HOSTS, firstExternalLinkOnly : DEFAULT_FIRST_EXTERNAL_LINK_ONLY, scripts : DEFAULT_CRAWL_SCRIPTS, links : DEFAULT_CRAWL_LINKS, linkTypes : DEFAULT_LINKS_TYPES, images : DEFAULT_CRAWL_IMAGES, protocols : DEFAULT_PROTOCOLS_TO_CRAWL, timeout : DEFAULT_TIME_OUT, retries : DEFAULT_RETRIES, retryTimeout : DEFAULT_RETRY_TIMEOUT, depthLimit
javascript
{ "resource": "" }
q5315
analyzeHTML
train
function analyzeHTML(result, $, callback) { // if $ is note defined, this is not a HTML page with an http status 200 if (! $) { return callback(); } log.debug({"url" : result.url, "step" : "analyzeHTML", "message" : "Start check HTML code"}); async.parallel([
javascript
{ "resource": "" }
q5316
crawlHrefs
train
function crawlHrefs(result, $, endCallback) { log.debug({"url" : result.url, "step" : "analyzeHTML", "message" : "CrawlHrefs"}); async.each($('a'), function(a,
javascript
{ "resource": "" }
q5317
crawlHref
train
function crawlHref($,result, a, callback) { var link = $(a).attr('href'); var parentUrl = result.url; if (link) { var anchor = $(a).text() ? $(a).text() : ""; var noFollow = $(a).attr("rel"); var isDoFollow = ! (noFollow && noFollow === "nofollow"); var linkUri = URI.linkToURI(parentUrl, link);
javascript
{ "resource": "" }
q5318
crawLink
train
function crawLink($,result,linkTag, callback) { var link = $(linkTag).attr('href'); var parentUrl = result.url; if (link) { var rel = $(linkTag).attr('rel'); if (result.linkTypes.indexOf(rel) > 0) { var linkUri = URI.linkToURI(parentUrl, link); pm.crawlLink(parentUrl,
javascript
{ "resource": "" }
q5319
crawlScripts
train
function crawlScripts(result, $, endCallback) { if (! result.scripts) { return endCallback(); } log.debug({"url" : result.url, "step" : "analyzeHTML", "message" : "CrawlScripts"});
javascript
{ "resource": "" }
q5320
crawlScript
train
function crawlScript($,result, script, callback) { var link = $(script).attr('src'); var parentUrl = result.url; if (link) { var linkUri = URI.linkToURI(parentUrl, link); pm.crawlLink(parentUrl, linkUri, null, null, function(){
javascript
{ "resource": "" }
q5321
crawlImages
train
function crawlImages(result, $, endCallback) { if (! result.images) { return endCallback(); } log.debug({"url" : result.url, "step" : "analyzeHTML", "message" : "CrawlImages"});
javascript
{ "resource": "" }
q5322
crawlImage
train
function crawlImage ($,result, img, callback) { var parentUrl = result.url; var link = $(img).attr('src'); var alt = $(img).attr('alt'); if (link) { var linkUri = URI.linkToURI(parentUrl, link); pm.crawlImage(parentUrl, linkUri, alt, function(){
javascript
{ "resource": "" }
q5323
updateDepth
train
function updateDepth(parentUrl, linkUri, callback) { var depths = {parentUrl : parentUrl, linkUri : linkUri, parentDepth : 0, linkDepth : 0}; var execFns = async.seq(getDepths , calcultateDepths , saveDepths); execFns(depths, function (error, result) {
javascript
{ "resource": "" }
q5324
getDepths
train
function getDepths(depths, callback) { async.parallel([ async.apply(store.getStore().getDepth.bind(store.getStore()), depths.parentUrl), async.apply(store.getStore().getDepth.bind(store.getStore()), depths.linkUri)
javascript
{ "resource": "" }
q5325
calcultateDepths
train
function calcultateDepths(depths, callback) { if (depths.parentDepth) { // if a depth of the links doesn't exist : assign the parehtDepth +1 // if not, this link has been already found in the past => don't update its depth if (! depths.linkDepth) { depths.linkDepth
javascript
{ "resource": "" }
q5326
saveDepths
train
function saveDepths(depths, callback) { async.parallel([ async.apply(store.getStore().setDepth.bind(store.getStore()), depths.parentUrl, depths.parentDepth ), async.apply(store.getStore().setDepth.bind(store.getStore()),
javascript
{ "resource": "" }
q5327
extend
train
function extend(d, element) { var map = Object.keys(element.prototype).reduce(function (descriptors, key) {
javascript
{ "resource": "" }
q5328
init
train
function init (options, crawlCallback, recrawlCallback, endCallback, proxies) { requestQueue = require(options.queueModuleName);
javascript
{ "resource": "" }
q5329
queue
train
function queue(options, callback) { // if skipDuplicates, don't crawl twice the same url if (options.skipDuplicates) { store.getStore().checkInCrawlHistory(options.url, function(error, isInCrawlHistory) { if (isInCrawlHistory) { log.debug({"url" : options.url, "step" : "queue-resquester.queue", "message" : "Don't crawl this url - Option skipDuplicates=true & the url has already been crawled" }); callback(); } else { //numOfUrl++ //console.log("Queue length : " + requestQueue.length() + " - Running : " + requestQueue.running() + " - Total Add :" + numOfUrl + " - Total End : " + endUrl + " url : " + options.url ); log.debug({"url" : options.url, "step" : "queue-resquester.queue", "message" : "Add in the request queue"}); requestQueue.push(options); callback(); } });
javascript
{ "resource": "" }
q5330
execHttp
train
function execHttp(options, callback) { if (proxyList) { options.proxy = proxyList.getProxy().getUrl(); } log.debug({"url" : options.url, "step" : "queue-requester.execHttp", "message" : "Execute the request"}); request.get(options, function(error, result) { log.debug({"url" : options.url, "step" : "queue-requester.execHttp", "message" : "Execute the request done"}); // TODO : review this solution/try to understand the origin of this problem // some sites provide inconsistent response for some urls (status 40* instead of 200). // In such case, it should be nice to retry (if the option retry400 == true) if (result.statusCode && result.statusCode >= 400 && result.statusCode <= 499 && result.retry400) {
javascript
{ "resource": "" }
q5331
retrySameUrl
train
function retrySameUrl(error, options, callback) { if (options.currentRetries <= options.retries) { log.warn({"url" : options.url, "step" : "queue-requester.recrawlUrl", "message" : "Recrawl - retries : " + options.currentRetries}); options.crawlWithDelay = true; //TODO : async this code // Reinject the same request in the queue // 1. Remove it from the crawl history in order
javascript
{ "resource": "" }
q5332
Tokenizer
train
function Tokenizer(str) { this.str = (str || '').toString(); this.operatorCurrent = ''; this.operatorExpecting = '';
javascript
{ "resource": "" }
q5333
Plugin
train
function Plugin() { this.name = "Audit-Plugin"; this.resources = new Map(); this.duplicateContents = new Map(); this.inLinks = new Map(); this.outLinks = new Map(); this.externalLinks = new
javascript
{ "resource": "" }
q5334
train
function(map, key, value) { var list = []; if (map.has(key)) { list = map.get(key); if (!list) {
javascript
{ "resource": "" }
q5335
AssertionError
train
function AssertionError(options) { var assertionError = Object.create(AssertionError.prototype); if (utils.isString(options)) options = { message: options }; if ("actual" in options) assertionError.actual = options.actual; if ("expected" in options) assertionError.expected = options.expected; if
javascript
{ "resource": "" }
q5336
equal
train
function equal(actual, expected, message) { if (actual == expected) { this.pass(message); }
javascript
{ "resource": "" }
q5337
notEqual
train
function notEqual(actual, expected, message) { if (actual != expected) { this.pass(message); } else { this.fail({ actual: actual, expected:
javascript
{ "resource": "" }
q5338
notStrictEqual
train
function notStrictEqual(actual, expected, message) { if (actual !== expected) { this.pass(message); } else { this.fail({ actual: actual,
javascript
{ "resource": "" }
q5339
train
function(obj) { var cloned = {}; for(var key in obj) { if(obj.hasOwnProperty(key)) {
javascript
{ "resource": "" }
q5340
train
function(prevHandler, connection, parsed, data, callback) { if (hasCondstoreOption(parsed.attributes && parsed.attributes[1], parsed.attributes, 1)) { connection.sessionCondstore = true; } else if ('sessionCondstore' in connection) {
javascript
{ "resource": "" }
q5341
train
function () { var map, bounds, coords; if (this.isDestroying || this.isDestroyed) { return; } map = this.get('googleObject'); if (this._state !== 'inDOM' || !map) { this._scheduleAutoFitBounds(coords); return; } coords = this.get('fitBoundsArray'); if (!coords) { return; } if (Ember.isArray(coords)) {
javascript
{ "resource": "" }
q5342
head
train
function head(url, uploadOptions, redirectCount, callback) { var options = getRequestOptions('HEAD', url, uploadOptions.downloadHeaders, uploadOptions.downloadAgent); var downloadProtocol = getProtocol(url); var req = downloadProtocol.request(options, function(res) { try { if ((res.statusCode == 301) || (res.statusCode == 302)) { if (redirectCount >= uploadOptions.maxRedirects) { return callback('Redirect count reached. Aborting upload.'); } var location = res.headers.location; if (location) { redirectCount++; var redirectUrl = parseUri(location); return head(redirectUrl, uploadOptions, redirectCount, callback); } } if ((res.statusCode < 200) || (res.statusCode >= 300)) { return callback('Invalid response from remote file server. statusCode: ' + res.statusCode); } var contentLength = parseInt(res.headers['content-length'], 10); if (isNaN(contentLength)) { //this shouldn't happen, but it does return callback('Remote web server returned an invalid content length'); } if (!validateFileSize(uploadOptions.maxFileSize, contentLength)) { return callback('File is too large. maxFileSize: ' + uploadOptions.maxFileSize + ', content-length: ' + contentLength); } //can we bail out early? if (uploadOptions.downloadFileName) { return callback(null, url, contentLength, uploadOptions.downloadFileName); } //no download specified, attempt to parse one out var file, ext, mimeExt;
javascript
{ "resource": "" }
q5343
train
function (priorities) { if (!angular.isArray(priorities)) { return false; } for (var i = 0; i < priorities.length; i += 1) { if (service.config.placementPriority.indexOf(priorities[i]) === -1) {
javascript
{ "resource": "" }
q5344
train
function (filter) { var obj = {} var val = this.__input this.each(function (property, key) { obj[key] = property.flatten ? property.flatten(filter) : property }, wrapFilter(filter)) if (val !== void 0) { if (val instanceof Base) { val = { reference: val.path } } obj.val = val } // refactoring non standard keys var flattened = flatten(obj)
javascript
{ "resource": "" }
q5345
custom
train
function custom (properties, property, key, event) { if (property === null) { properties[key] = null } else if (property.val) { property.val = parseProperty(property.val) var prototype = property.val.prototype if (prototype && prototype instanceof Base) { if (property.override) { properties._overrides = properties._overrides || {} properties._overrides[key] = property.override properties[key] = Properties .createPropertyConstructor(property.val, property.override, true) properties[key].override = property.override
javascript
{ "resource": "" }
q5346
LargeObject
train
function LargeObject(query, oid, fd) { this._query = query;
javascript
{ "resource": "" }
q5347
htmlStringify
train
function htmlStringify(obj, fromRecur) { var tag = (fromRecur) ? 'span' : 'div'; var nextLevel = (fromRecur || 0) + 1; // strings if (typeof obj == 'string') { return '<' + tag + ' style="color: #0e4889; cursor: default;">"' + obj + '"</' + tag + '>'; } // booleans, null and undefined else if (typeof obj == 'boolean' || obj === null || obj === undefined) { return '<' + tag + '><em style="color: #06624b; cursor: default;">' + obj + '</em></' + tag + '>'; } // numbers else if (typeof obj == 'number') { return '<' + tag + ' style="color: #ca000a; cursor: default;">' + obj + '</' + tag + '>'; } // dates else if (Object.prototype.toString.call(obj) == '[object Date]') { return '<' + tag + ' style="color: #009f7b; cursor: default;">' + obj + '</' + tag + '>'; } // arrays else if (Array.isArray(obj)) { var rtn = '<' + tag + ' style="color: #666; cursor: default;">Array: ['; if (!obj.length) { return rtn + ']</' + tag + '>'; } rtn += '</' + tag + '><div style="padding-left: 20px;">'; for (var i = 0; i < obj.length; i++) { rtn += '<span></span>' + htmlStringify(obj[i], nextLevel); // give the DOM structure has as many elements as an object, for collapse behaviour if (i < obj.length - 1) { rtn += ', <br>'; } } return rtn + '</div><' + tag + ' style="color: #666">]</' + tag + '>'; } // objects else if (obj && typeof obj == 'object') { var
javascript
{ "resource": "" }
q5348
train
function (options) { events.EventEmitter.call(this); var defaultOptions = { tree: {} };
javascript
{ "resource": "" }
q5349
train
function(params) { if (!params) { return { error: 'params cannot be null.' }; } // query is mandatory if (!params.hasOwnProperty('query')) { return { error: 'query param required.' }; } if (!validator.isString(params.query)) { return { error: 'query must be a string.' }; } if (!validator.isValidType(params)) {
javascript
{ "resource": "" }
q5350
train
function(params) { var baseUrl = 'http://www.omdbapi.com/'; var query = '?'; // mandatory query += 's='.concat(encodeURIComponent(params.query)); if (params.year) { query += '&y='.concat(params.year); } if (params.type) {
javascript
{ "resource": "" }
q5351
Notification
train
function Notification(name, object, info) {
javascript
{ "resource": "" }
q5352
getName
train
function getName(name, width, separator) { // handle empty separator as no separator if (typeof separator === 'undefined') { separator = ''; } if
javascript
{ "resource": "" }
q5353
BlobResource
train
function BlobResource(uri, context) { var instance = Resource.call(this, uri, context); /** * The resource data. * * @type
javascript
{ "resource": "" }
q5354
extractAndUpdateResources
train
function extractAndUpdateResources(data, links, rootResource, resource) { var resources = []; var selfHref = ((data._links || {}).self || {}).href; if (!selfHref) { throw new Error('Self link href expected but not found'); } // Extract links angular.extend(links, data._links); delete data._links; // Extract and update embedded resources Object.keys(data._embedded || {}).forEach(function (rel) { var embeds = data._embedded[rel]; // Add link to embedded resource if missing if (!(rel in links)) { links[rel] = forArray(embeds, function (embedded) { return {href: embedded._links.self.href}; });
javascript
{ "resource": "" }
q5355
forArray
train
function forArray(arg, func, context) { if (angular.isUndefined(arg)) return undefined; if (Array.isArray(arg)) { return arg.map(function (elem) {
javascript
{ "resource": "" }
q5356
defineProperties
train
function defineProperties(obj, props) { props = angular.copy(props); angular.forEach(props, function
javascript
{ "resource": "" }
q5357
subscribe
train
function subscribe (obs, path, index, length, type, val, id, fire, origin, event, nocontext) { if (index === length) { // TODO added this to subscribe to key => this is probably not the best way to catch this if (obs.on) { obs.on('remove', function () { // null subscribe(origin, path, 0, length, type, val, id, false, origin, event) }, id, true, event, nocontext) obs.on(type, val, id, true, event, nocontext) } if (fire) { // **TODO** SUPER DIRTY // need to have some godamn arguments if (event === void 0) { var trigger = true event = new Event('data') // wrong } if (typeof val === 'function') { val.call(obs, obs.__input, event) } else { // weird gaurd if (val && val[0]) { val[0].call(obs, type === 'data' ? obs.__input : void 0, event, val[1]) } } if (trigger) { event.trigger() } } return obs } else { let key = path[index] let property = obs[key] let result if (property && property.__input !== null) { result =
javascript
{ "resource": "" }
q5358
train
function(pattern, callback) { glob(pattern, opts, function(err, globbedFiles) { if (isArray(globbedFiles) && globbedFiles.length && !err) { callback(null, globbedFiles); } else { console.error('The glob
javascript
{ "resource": "" }
q5359
train
function() { var bomBuffer = this.read(bytesPerBom); if (bomBuffer == null || bomBuffer.length !== bytesPerBom) { status = 'error'; processor.emit('processing.error', { file: filePath, message: 'Skipping
javascript
{ "resource": "" }
q5360
resolveContext
train
function resolveContext (emitter, context, storageKey) { // TODO: clean up - try to use internal context resolve more on no // use the one from on (resolve) // figure out why we cant use resolveContextSet since thats what it is if (context) { // this is lame stuff! should be in observable in some way... let base = emitter.parent.parent let type = emitter.key let setObj = { on:
javascript
{ "resource": "" }
q5361
gPrga
train
function gPrga(key, s) { var keystream = []; var k = 0; var j = 0; var len = key.length; for (var i = 0; i <
javascript
{ "resource": "" }
q5362
body
train
function body(inp, ksa, prga, container, length) { var i = 0, j1 = 0, j2 = 0; var out = container; var s1 = ksa.slice(); var s2 = prga.slice(); for (var y = 0; y < length; ++y) { i = (i + 1) % 256; j1 = (j1 + s1[i]) % 256; s1[j1] = [ s1[i], s1[i] = s1[j1] ][0]; out[y] = inp[y] ^ s2[(s1[i] + s1[j1])
javascript
{ "resource": "" }
q5363
decodeBlobURL
train
function decodeBlobURL( bundle, length ) { var mimeType = bundle.readStringLT(), blob = new Blob([ bundle.readTypedArray(NUMTYPE.UINT8, length ) ], { type: mimeType }); return
javascript
{ "resource": "" }
q5364
decodeBuffer
train
function decodeBuffer( bundle, len, buf_type ) { var length=0, ans=""; switch (len) { case 0: length = bundle.u8[bundle.i8++]; break; case 1: length = bundle.u16[bundle.i16++]; break; case 2: length = bundle.u32[bundle.i32++]; break; case 3: length = bundle.f64[bundle.i64++]; break; } // Process buffer according to type if (buf_type === 0) { // STRING_LATIN ans = String.fromCharCode.apply(null, bundle.readTypedArray( NUMTYPE.UINT8 , length ) ); return DEBUG ? __debugMeta( ans, 'string.latin', {} ) : ans; } else if (buf_type === 1) { // STRING_UTF8 ans = String.fromCharCode.apply(null, bundle.readTypedArray( NUMTYPE.UINT16 , length ) ); return DEBUG ? __debugMeta( ans, 'string.utf8', {} ) : ans; } else if (buf_type === 2) { // IMAGE var img = document.createElement('img');
javascript
{ "resource": "" }
q5365
decodeObject
train
function decodeObject( bundle, database, op ) { if ( !(op & 0x20) || ((op & 0x30) === 0x20) ) { // Predefined objects var eid = op; if (op & 0x20) eid = bundle.u8[bundle.i8++] | ((op & 0x0F) << 8); // Fetch object class var FACTORY = bundle.profile.decode(eid); if (FACTORY === undefined) { throw new Errors.AssertError('Could not found known object entity #'+eid+'!'); } // Call entity factory var instance = FACTORY.create(); // Keep on irefs bundle.iref_table.push( instance ); // Fetch property table // console.assert(eid != 50); var prop_table = decodePrimitive( bundle, database ); // Run initializer FACTORY.init( instance, prop_table, 1, 0 ); // Append debug metadata DEBUG && __debugMeta( instance, 'object.known', { 'eid': eid } );
javascript
{ "resource": "" }
q5366
decodePivotArrayFloat
train
function decodePivotArrayFloat( bundle, database, len, num_type ) { var ans = new NUMTYPE_CLASS[ NUMTYPE_DELTA_FLOAT.FROM[ num_type ] ]( len ), // pivot = bundle.readTypedNum( NUMTYPE_DELTA_FLOAT.FROM[ num_type ] ), scale = bundle.readFloat64(), values = bundle.readTypedArray( NUMTYPE_DELTA_FLOAT.TO[ num_type ] , len ); // console.log(">> DELTA_FLOAT len=",len,"type=",num_type,"scale=",scale,"pivot=",pivot);
javascript
{ "resource": "" }
q5367
decodeDeltaArrayInt
train
function decodeDeltaArrayInt( bundle, database, len, num_type ) { var fromType = NUMTYPE_DELTA_INT.FROM[ num_type ], ans = new NUMTYPE_CLASS[ fromType ]( len ), v=0; // readTypedNum(fromType) switch (fromType) { case 0: v = bundle.u8[bundle.i8++]; break; case 1: v = bundle.s8[bundle.i8++]; break; case 2: v = bundle.u16[bundle.i16++]; break; case 3: v = bundle.s16[bundle.i16++]; break; case 4: v = bundle.u32[bundle.i32++]; break; case 5: v = bundle.s32[bundle.i32++]; break; case 6: v = bundle.f32[bundle.i32++]; break; case 7:
javascript
{ "resource": "" }
q5368
decodePlainBulkArray
train
function decodePlainBulkArray( bundle, database ) { // Get signature ID var sid = bundle.u16[bundle.i16++], properties = bundle.signature_table[sid], factory = bundle.factory_plain_bulk[sid]; // Check for invalid objects if (factory === undefined) throw new Errors.AssertError('Could not found simple object signature with id #'+sid+'!'); // Read property arrays var values
javascript
{ "resource": "" }
q5369
decodePrimitive
train
function decodePrimitive( bundle, database ) { var op = bundle.u8[bundle.i8++]; if ((op & 0x80) === 0x00) { // Array return decodeArray(bundle, database, (op & 0x7F) ); } else if ((op & 0xC0) === 0x80) { // Object return decodeObject(bundle, database, (op & 0x3F) ); } else if ((op & 0xE0) === 0xC0) { // Buffer return decodeBuffer(bundle, (op & 0x18) >> 3, (op & 0x07) ); } else if ((op & 0xF0) === 0xE0) { // I-Ref var id = bundle.u16[bundle.i16++]; id = ((op & 0x0F) << 16) | id; if (id >= bundle.iref_table.length) throw new Errors.IRefError('Invalid IREF #'+id+'!'); return DEBUG ? __debugMeta( bundle.iref_table[id], 'object.iref', { 'id': id } ) : bundle.iref_table[id]; } else if ((op & 0xF8) === 0xF0) { // Number switch (op & 0x07) { case 0: return bundle.u8[bundle.i8++]; case 1: return bundle.s8[bundle.i8++]; case 2: return bundle.u16[bundle.i16++]; case 3: return bundle.s16[bundle.i16++]; case 4: return bundle.u32[bundle.i32++]; case 5: return bundle.s32[bundle.i32++]; case 6: return bundle.f32[bundle.i32++]; case
javascript
{ "resource": "" }
q5370
parseBundle
train
function parseBundle( bundle, database ) { while (!bundle.eof()) { var op = bundle.u8[bundle.i8++]; switch (op) { case 0xF8: // Export var export_name = bundle.prefix + bundle.readStringLT(); database[ export_name ] = decodePrimitive( bundle, database );
javascript
{ "resource": "" }
q5371
train
function( url, callback ) { // Node quick, not present on browser builds if (IS_NODE) { // Helper function var readChunk = function ( filename ) { // Read into buffer var file = fs.readFileSync(filename), u8 = new Uint8Array(file); // Return buffer return u8.buffer; } // Read by chunks if (url.substr(-5) === ".jbbp") { // Add by buffer var base = url.substr(0,url.length-5); this.addByBuffer( [ readChunk(base + '.jbbp'), readChunk(base + '_b16.jbbp'), readChunk(base + '_b32.jbbp'), readChunk(base + '_b64.jbbp'), ], callback ); } else { // Add by buffer this.addByBuffer( readChunk(url), callback ); } // Don't continue
javascript
{ "resource": "" }
q5372
train
function( buffer, callback ) { // Prepare pending bundle var pendingBundle = { 'callback': callback, 'status': PBUND_LOADED, 'buffer': buffer, 'url': undefined, };
javascript
{ "resource": "" }
q5373
train
function( callback ) { var self = this; if (!callback) callback = function(){}; // If there are no queued requests, fire callback as-is if (this.queuedRequests.length === 0) { callback( null, this.database ); return; } // First make sure that there are no bundles pending loading var pendingLoading = false; for (var i=0; i<this.queuedRequests.length; ++i) { if (this.queuedRequests[i].status === PBUND_REQUESTED) { pendingLoading = true; break; } } //////////////////////////////////////////////////////// // Iteration 1 - PBUND_REQUESTED -> PBUND_LOADED // ---------------------------------------------------- // Download all bundles in pending state. //////////////////////////////////////////////////////// if (pendingLoading) { // Prepare the callbacks for when this is finished var state = { 'counter': 0 } var continue_callback = (function() { // When reached 0, continue loading if (--this.counter === 0) self.__process( callback ); }).bind(state); // Place all requests in parallel var triggeredError = false; for (var i=0; i<this.queuedRequests.length; ++i) { var req = this.queuedRequests[i], part = this.progressManager.part(); if (req.status === PBUND_REQUESTED) { // Download bundle from URL(s) state.counter++;
javascript
{ "resource": "" }
q5374
compileFile
train
function compileFile( sourceBundle, bundleFile, config, callback ) { var fname = sourceBundle + "/bundle.json"; fs.readFile(fname, 'utf8', function (err,data) { if (err) { console.error("Unable to load file",fname); if (callback) callback( err, null ); return;
javascript
{ "resource": "" }
q5375
train
function(a,b) { var tA, tB, i; for (i=0; i<a.length; ++i) { tA = typeof a[i]; tB = typeof b[i]; if (tA === tB) { if ((tA === 'number') || (tA === 'string') || (tA === 'boolean')) { if (a[i] < b[i]) return -1; if (a[i] > b[i]) return 1; if (a[i] !== b[i]) return 1;
javascript
{ "resource": "" }
q5376
getFloatDeltaScale
train
function getFloatDeltaScale(t, scale) { if (scale === DELTASCALE.S_1) return 1.0; else if (scale === DELTASCALE.S_001) return 0.01; else { var multiplier = 1.0; if (scale === DELTASCALE.S_R00) multiplier = 100.0; // Check for INT8 target
javascript
{ "resource": "" }
q5377
isEmptyArray
train
function isEmptyArray(v) { if ((v instanceof Uint8Array) || (v instanceof Int8Array) || (v instanceof Uint16Array) || (v instanceof Int16Array) ||
javascript
{ "resource": "" }
q5378
isNumericSubclass
train
function isNumericSubclass( t, t_min, t_max, of_t ) { if ((t === NUMTYPE.NAN) || (of_t === NUMTYPE.NAN)) return false; switch (of_t) { // Parent case NUMTYPE.UINT8: switch (t) { case NUMTYPE.UINT8: return true; case NUMTYPE.INT8: return (t_min > 0); default: return false; } case NUMTYPE.INT8: switch (t) { case NUMTYPE.UINT8: return (t_max < INT8_MAX); case NUMTYPE.INT8: return true; default: return false; } case NUMTYPE.UINT16: switch (t) { case NUMTYPE.UINT8: case NUMTYPE.UINT16: return true; case NUMTYPE.INT8: case NUMTYPE.INT16: return (t_min > 0); default: return false; } case NUMTYPE.INT16: switch (t) { case NUMTYPE.UINT8: case NUMTYPE.INT8: case NUMTYPE.INT16: return true; case NUMTYPE.UINT16: return (t_max < INT16_MAX); default: return false; } case NUMTYPE.UINT32: switch (t) { case NUMTYPE.UINT8: case NUMTYPE.UINT16: case NUMTYPE.UINT32: return true; case NUMTYPE.INT8: case NUMTYPE.INT16: case NUMTYPE.INT32: return (t_min > 0); default: return false; } case NUMTYPE.INT32: switch (t) {
javascript
{ "resource": "" }
q5379
isFloatMixing
train
function isFloatMixing( a, b ) { return ( ((a < NUMTYPE.FLOAT32 ) && (b >= NUMTYPE.FLOAT32 )) ||
javascript
{ "resource": "" }
q5380
sizeOfType
train
function sizeOfType(t) { switch (t) { case NUMTYPE.UINT8: case NUMTYPE.INT8: return 1; case NUMTYPE.UINT16: case NUMTYPE.INT16: return 2; case NUMTYPE.UINT32: case NUMTYPE.INT32:
javascript
{ "resource": "" }
q5381
getTypedArrayType
train
function getTypedArrayType( v ) { if (v instanceof Float32Array) { return NUMTYPE.FLOAT32; } else if (v instanceof Float64Array) { return NUMTYPE.FLOAT64; } else if (v instanceof Uint8Array) { return NUMTYPE.UINT8; } else if (v instanceof Int8Array) { return NUMTYPE.INT8; } else if (v instanceof Uint16Array) { return NUMTYPE.UINT16; } else if (v instanceof Int16Array) { return NUMTYPE.INT16; } else if (v instanceof Uint32Array) { return NUMTYPE.UINT32; } else if (v instanceof Int32Array) { return NUMTYPE.INT32; } else if (v instanceof Array)
javascript
{ "resource": "" }
q5382
getNumType
train
function getNumType( vmin, vmax, is_float ) { if (typeof vmin !== "number") return NUMTYPE.NAN; if (typeof vmax !== "number") return NUMTYPE.NAN; if (isNaN(vmin) || isNaN(vmax)) return NUMTYPE.NAN; // If float, test only-floats if (is_float) { // Try to find smallest value for float32 minimum tests var smallest; if (vmin === 0) { // vmin is 0, which makes vmax positive, so // test vmax for smallest smallest = vmax; } else if (vmax === 0) { // if vmax is 0, it makes vmin negative, which // means we should test it's positive version smallest = -vmax; } else { // if vmin is positive, both values are positive // so get the smallest for small test (vmin) if (vmin > 0) { smallest = vmin; // if vmax is negative, both values are negative // so get the biggest for small test (vmax) } else if (vmax < 0) { smallest = -vmax; // if vmin is negative and vmax positive, get the // smallest of their absolute values } else if ((vmin < 0) && (vmax > 0)) { smallest = -vmin; if (vmax < smallest) smallest = vmax; } } // Test if float number fits on 32 or 64 bits if ((vmin > FLOAT32_NEG) && (vmax < FLOAT32_POS) && (smallest > FLOAT32_SMALL)) { return NUMTYPE.FLOAT32; } else { return NUMTYPE.FLOAT64; } } // If we have a negative value, switch to signed tests if ((vmax < 0)
javascript
{ "resource": "" }
q5383
getFloatScale
train
function getFloatScale( values, min, max, error ) { var mid = (min + max) / 2, range = mid - min, norm_8 = (range / INT8_MAX), norm_16 = (range / INT16_MAX), ok_8 = true, ok_16 = true, er_8 = 0, er_16 = 0, v, uv, er; // For the values given, check if 8-bit or 16-bit // scaling brings smaller error value for (var i=0, l=values.length; i<l; ++i) { // Test 8-bit scaling if (ok_8) { v = Math.round((values[i] - mid) / norm_8); uv = v * norm_8 + mid; er = (uv-v)/v; if (er > er_8) er_8 = er; if (er >= error) { ok_8 = false; } } // Test 16-bit scaling if (ok_16) { v = Math.round((values[i] - mid) / norm_16); uv = v * norm_16 + mid; er
javascript
{ "resource": "" }
q5384
getDownscaleType
train
function getDownscaleType( n_type, analysis ) { switch (n_type) { // Not possible to downscale from 1-byte case NUMTYPE.UINT8: case NUMTYPE.INT8: return NUMTYPE.UNKNOWN; case NUMTYPE.UINT16: switch (analysis.type) { // UINT16 -> (U)INT8 = UINT8 case NUMTYPE.INT8: // Unsigned, so always positive case NUMTYPE.UINT8: return NUMTYPE.UINT8; // Anything else is equal to or bigger than 2 bytes default: return NUMTYPE.UNKNOWN; } case NUMTYPE.INT16: switch (analysis.type) { // INT16 -> UINT8 = INT8 (if v < INT8_MAX) case NUMTYPE.UINT8: if (analysis.max < INT8_MAX) { return NUMTYPE.INT8; } else { return NUMTYPE.UNKNOWN; } // INT16 -> INT8 case NUMTYPE.INT8: return NUMTYPE.INT8; // Anything else is equal to or bigger than 2 bytes default: return NUMTYPE.UNKNOWN; } case NUMTYPE.UINT32: switch (analysis.type) { // UINT32 -> (U)INT8 [= UINT8] case NUMTYPE.INT8: case NUMTYPE.UINT8: return NUMTYPE.UINT8; // UINT32 -> (U)INT16 = UINT16 case NUMTYPE.INT16: case NUMTYPE.UINT16: return NUMTYPE.UINT16; // Anything
javascript
{ "resource": "" }
q5385
getBestBinFit
train
function getBestBinFit( start, len, blocks ) { var b, s, e, end = start + len, found = false, c, last_c = 0, last_s = 0, last_i = -1, last_bin = null; // Find the biggest chunk that can fit on these data for (var bi=0, bl=blocks.length; bi<bl; ++bi) { b = blocks[bi]; found = false; for (var i=0, il=b.length; i<il; ++i) { s = b[i][0]; e = s + b[i][1]; // Find the common region of block-scan frame if ( ((s >= start) && (s < end-1)) || // Start in bounds ((e
javascript
{ "resource": "" }
q5386
downscaleType
train
function downscaleType( fromType, toType ) { // Lookup conversion on the downscale table for (var i=0; i<NUMTYPE_DOWNSCALE.FROM.length; ++i)
javascript
{ "resource": "" }
q5387
deltaEncTypeInt
train
function deltaEncTypeInt( fromType, toType ) { // Lookup conversion on the downscale table for (var i=0; i<NUMTYPE_DELTA_INT.FROM.length; ++i)
javascript
{ "resource": "" }
q5388
deltaEncTypeFloat
train
function deltaEncTypeFloat( fromType, toType ) { // Lookup conversion on the downscale table for (var i=0; i<NUMTYPE_DELTA_FLOAT.FROM.length; ++i)
javascript
{ "resource": "" }
q5389
deltaEncodeIntegers
train
function deltaEncodeIntegers( array, numType ) { var delta = new NUMTYPE_CLASS[numType]( array.length - 1 ), l = array[0]; for (var
javascript
{ "resource": "" }
q5390
convertArray
train
function convertArray( array, numType ) { // Skip matching cases if ( ((array instanceof Uint8Array) && (numType === NUMTYPE.UINT8)) || ((array instanceof Int8Array) && (numType === NUMTYPE.INT8)) || ((array instanceof Uint16Array) && (numType === NUMTYPE.UINT16)) || ((array instanceof Int16Array) &&
javascript
{ "resource": "" }
q5391
mimeTypeFromFilename
train
function mimeTypeFromFilename( filename ) { var ext = filename.split(".").pop().toLowerCase(); return
javascript
{ "resource": "" }
q5392
bufferFromFile
train
function bufferFromFile( filename ) { console.info( ("Loading "+filename).grey ); var buf = fs.readFileSync( filename ), // Load Buffer ab = new ArrayBuffer( buf.length ), //
javascript
{ "resource": "" }
q5393
pickStream
train
function pickStream(encoder, t) { // Handle type switch (t) { case NUMTYPE.UINT8: case NUMTYPE.INT8: return encoder.stream8; case NUMTYPE.UINT16: case NUMTYPE.INT16: return encoder.stream16; case NUMTYPE.UINT32: case NUMTYPE.INT32:
javascript
{ "resource": "" }
q5394
encodeArray_NUM_DWS
train
function encodeArray_NUM_DWS( encoder, data, n_from, n_to ) { // // Downscaled Numeric Array (NUM_DWS) // // ... .... . + Data Length // 000 [DWS_TYPE] [LN] [16bit/32bit] // // Get downscale type var n_dws_type = downscaleType( n_from, n_to ); // console.log(">>>",data.constructor,":",_NUMTYPE[n_from],"->",_NUMTYPE[n_to],":",n_dws_type); encoder.counters.arr_dws+=1; encoder.log(LOG.ARR, "array.numeric.downscaled, len="+data.length+ ", from="+_NUMTYPE[n_from]+", to="+_NUMTYPE[n_to]+ ", type="+_NUMTYPE_DOWNSCALE_DWS[n_dws_type]+" ("+n_dws_type+")"); if (data.length < UINT16_MAX) { // 16-bit length prefix encoder.stream8.write( pack1b( ARR_OP.NUM_DWS | NUMTYPE_LN.UINT16 | (n_dws_type << 1) ) );
javascript
{ "resource": "" }
q5395
encodeArray_NUM_DELTA_FLOAT
train
function encodeArray_NUM_DELTA_FLOAT( encoder, data, n_from, n_to, pivot, f_scale ) { // // Pivot Float Numeric Array (NUM_DELTA_FLOAT) // // ... .... . + Data Length + Mean Value + Scale // 001 [DWS_TYPE] [LN] [16bit/32bit] [F32/F64] [F32] // // Get downscale type var n_delta_type = deltaEncTypeFloat( n_from, n_to ); if (n_delta_type === undefined) { throw new Errors.EncodeError('Non-viable float delta value from '+_NUMTYPE[n_from]+' to '+_NUMTYPE[n_to]+'!'); } encoder.counters.arr_delta_float+=1; encoder.log(LOG.ARR, "array.numeric.delta.float, len="+data.length+ ", from="+_NUMTYPE[n_from]+", to="+_NUMTYPE[n_to]+ ", type="+_NUMTYPE_DOWNSCALE_DELTA_FLOAT[n_delta_type]+" ("+n_delta_type+")"+ ",
javascript
{ "resource": "" }
q5396
encodeArray_NUM_DELTA_INT
train
function encodeArray_NUM_DELTA_INT( encoder, data, n_from, n_to ) { // // Delta Numeric Array (NUM_DELTA_INT) // // ... .... . + Data Length + Initial Value // 001 [DWS_TYPE] [LN] [16bit/32bit] [8bit/16bit/32bit] // // Get downscale type var n_delta_type = deltaEncTypeInt( n_from, n_to ); if (n_delta_type === undefined) { throw new Errors.EncodeError('Non-viable integer delta value from '+_NUMTYPE[n_from]+' to '+_NUMTYPE[n_to]+'!'); } encoder.counters.arr_delta_int+=1; encoder.log(LOG.ARR, "array.numeric.delta.int, len="+data.length+ ", from="+_NUMTYPE[n_from]+", to="+_NUMTYPE[n_to]+ ", type="+_NUMTYPE_DOWNSCALE_DELTA_INT[n_delta_type]+" ("+n_delta_type+")"); if (data.length < UINT16_MAX) { // 16-bit length prefix encoder.stream8.write( pack1b( ARR_OP.NUM_DELTA_INT | NUMTYPE_LN.UINT16 | (n_delta_type << 1) ) );
javascript
{ "resource": "" }
q5397
encodeArray_NUM_REPEATED
train
function encodeArray_NUM_REPEATED( encoder, data, n_type ) { // // Repeated Numeric Array (NUM_REPEATED) // // .... ... . + Data Length // 0100 [TYPE] [LN] [16bit/32bit] // encoder.counters.arr_num_repeated+=1; encoder.log(LOG.ARR, "array.numeric.repeated, len="+data.length+ ", type="+_NUMTYPE[n_type]+" ("+n_type+")"); if (data.length < UINT16_MAX) { // 16-bit length prefix encoder.stream8.write( pack1b( ARR_OP.NUM_REPEATED | NUMTYPE_LN.UINT16 | (n_type << 1) ) ); encoder.stream16.write( pack2b( data.length, false ) ); encoder.counters.arr_hdr+=3; } else { // 32-bit
javascript
{ "resource": "" }
q5398
encodeArray_NUM_RAW
train
function encodeArray_NUM_RAW( encoder, data, n_type ) { // // RAW Numeric Array (NUM_RAW) // // .... ... . + Data Length // 0101 [TYPE] [LN] [16bit/32bit] // encoder.counters.arr_num_raw+=1; encoder.log(LOG.ARR, "array.numeric.raw, len="+data.length+ ", type="+_NUMTYPE[n_type]+" ("+n_type+")"); if (data.length < UINT16_MAX) { // 16-bit length prefix encoder.stream8.write( pack1b( ARR_OP.NUM_RAW | NUMTYPE_LN.UINT16 | (n_type << 1) ) ); encoder.stream16.write( pack2b( data.length, false ) ); encoder.counters.arr_hdr+=3; } else { // 32-bit length prefix
javascript
{ "resource": "" }
q5399
encodeArray_NUM_SHORT
train
function encodeArray_NUM_SHORT( encoder, data, n_type ) { // // Short Numeric Array (NUM_SHORT) // // ..... ... // 01110 [TYPE] // encoder.counters.arr_num_short+=1; encoder.log(LOG.ARR, "array.numeric.short, len="+data.length+ ", type="+_NUMTYPE[n_type]+" ("+n_type+")"); // Encode primitives one after the other encoder.stream8.write( pack1b( ARR_OP.NUM_SHORT |
javascript
{ "resource": "" }