repo
stringlengths 5
67
| path
stringlengths 4
116
| func_name
stringlengths 0
58
| original_string
stringlengths 52
373k
| language
stringclasses 1
value | code
stringlengths 52
373k
| code_tokens
sequence | docstring
stringlengths 4
11.8k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 86
226
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
flowxo/flowxo-sdk | tasks/lib/run.js | function(inputs, callback) {
// Remove any empty inputs
var filteredInputs = RunUtil.filterEmptyInputs(inputs || []);
runner.run(method.slug, script, {
input: filteredInputs
}, function(err, result) {
if(err) {
callback(err);
} else {
callback(null, result);
}
});
} | javascript | function(inputs, callback) {
// Remove any empty inputs
var filteredInputs = RunUtil.filterEmptyInputs(inputs || []);
runner.run(method.slug, script, {
input: filteredInputs
}, function(err, result) {
if(err) {
callback(err);
} else {
callback(null, result);
}
});
} | [
"function",
"(",
"inputs",
",",
"callback",
")",
"{",
"var",
"filteredInputs",
"=",
"RunUtil",
".",
"filterEmptyInputs",
"(",
"inputs",
"||",
"[",
"]",
")",
";",
"runner",
".",
"run",
"(",
"method",
".",
"slug",
",",
"script",
",",
"{",
"input",
":",
"filteredInputs",
"}",
",",
"function",
"(",
"err",
",",
"result",
")",
"{",
"if",
"(",
"err",
")",
"{",
"callback",
"(",
"err",
")",
";",
"}",
"else",
"{",
"callback",
"(",
"null",
",",
"result",
")",
";",
"}",
"}",
")",
";",
"}"
] | Run the script | [
"Run",
"the",
"script"
] | 8f71dbfb25a8b57591f5c4df09937289d5c8356b | https://github.com/flowxo/flowxo-sdk/blob/8f71dbfb25a8b57591f5c4df09937289d5c8356b/tasks/lib/run.js#L640-L653 | train |
|
maxvyaznikov/imapseagull | lib/utils.js | function(flags, checkFlags, value) {
[].concat(checkFlags || []).forEach((function(flag, i) {
if (i == value) {
this.ensureFlag(flags, flag);
} else {
this.removeFlag(flags, flag);
}
}.bind(this)));
} | javascript | function(flags, checkFlags, value) {
[].concat(checkFlags || []).forEach((function(flag, i) {
if (i == value) {
this.ensureFlag(flags, flag);
} else {
this.removeFlag(flags, flag);
}
}.bind(this)));
} | [
"function",
"(",
"flags",
",",
"checkFlags",
",",
"value",
")",
"{",
"[",
"]",
".",
"concat",
"(",
"checkFlags",
"||",
"[",
"]",
")",
".",
"forEach",
"(",
"(",
"function",
"(",
"flag",
",",
"i",
")",
"{",
"if",
"(",
"i",
"==",
"value",
")",
"{",
"this",
".",
"ensureFlag",
"(",
"flags",
",",
"flag",
")",
";",
"}",
"else",
"{",
"this",
".",
"removeFlag",
"(",
"flags",
",",
"flag",
")",
";",
"}",
"}",
".",
"bind",
"(",
"this",
")",
")",
")",
";",
"}"
] | Toggles listed flags. Flags with `value` index will be turned on,
other listed fields are removed from the array
@param {Array} flags List of flags
@param {Array} checkFlags Flags to toggle
@param {Number} value Flag from checkFlags array with value index is toggled | [
"Toggles",
"listed",
"flags",
".",
"Flags",
"with",
"value",
"index",
"will",
"be",
"turned",
"on",
"other",
"listed",
"fields",
"are",
"removed",
"from",
"the",
"array"
] | 44949b7a338b4c0ace3ef7bb95a77c4794462bda | https://github.com/maxvyaznikov/imapseagull/blob/44949b7a338b4c0ace3ef7bb95a77c4794462bda/lib/utils.js#L50-L58 | train |
|
heap/heap-node | lib/client.js | Client | 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 error.
this.on("error", function() { });
if (options) {
for (var property in options) {
if (!options.hasOwnProperty(property))
continue;
this[property] = options[property];
}
}
} | javascript | 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 error.
this.on("error", function() { });
if (options) {
for (var property in options) {
if (!options.hasOwnProperty(property))
continue;
this[property] = options[property];
}
}
} | [
"function",
"Client",
"(",
"appId",
",",
"options",
")",
"{",
"this",
".",
"appId",
"=",
"appId",
";",
"this",
".",
"stubbed",
"=",
"false",
";",
"this",
".",
"userAgent",
"=",
"defaultUserAgent",
";",
"this",
".",
"_validator",
"=",
"new",
"Validator",
"(",
")",
";",
"this",
".",
"on",
"(",
"\"error\"",
",",
"function",
"(",
")",
"{",
"}",
")",
";",
"if",
"(",
"options",
")",
"{",
"for",
"(",
"var",
"property",
"in",
"options",
")",
"{",
"if",
"(",
"!",
"options",
".",
"hasOwnProperty",
"(",
"property",
")",
")",
"continue",
";",
"this",
"[",
"property",
"]",
"=",
"options",
"[",
"property",
"]",
";",
"}",
"}",
"}"
] | Creates a new client for the Heap server-side API.
@constructor
@param {string} appId the Heap application ID from
https://heapanalytics.com/app/install
@param {Object} options defined below
@param {boolean} options.stubbed if true, this client makes no Heap API
calls
@param {string} options.userAgent the User-Agent header value used by this
Heap API client
@alias heap-api.Client | [
"Creates",
"a",
"new",
"client",
"for",
"the",
"Heap",
"server",
"-",
"side",
"API",
"."
] | b4b65d3daa74f1122bbbd7921c6ed3a45bd0b858 | https://github.com/heap/heap-node/blob/b4b65d3daa74f1122bbbd7921c6ed3a45bd0b858/lib/client.js#L36-L54 | train |
jaredhanson/node-jsonsp | lib/jsonsp/parser.js | addToContainer | function addToContainer(container, key, val) {
if (container instanceof Array) {
container.push(val);
} else if (container instanceof Object) {
container[key] = val;
}
} | javascript | function addToContainer(container, key, val) {
if (container instanceof Array) {
container.push(val);
} else if (container instanceof Object) {
container[key] = val;
}
} | [
"function",
"addToContainer",
"(",
"container",
",",
"key",
",",
"val",
")",
"{",
"if",
"(",
"container",
"instanceof",
"Array",
")",
"{",
"container",
".",
"push",
"(",
"val",
")",
";",
"}",
"else",
"if",
"(",
"container",
"instanceof",
"Object",
")",
"{",
"container",
"[",
"key",
"]",
"=",
"val",
";",
"}",
"}"
] | Add `val` to `container`.
If `container` is an array, `val` will be appended. Otherwise, if
`container` is an object, `val` will be set as the value of `key`.
@param {Object|Array} container
@param {String} key
@param {Mixed} val
@api private | [
"Add",
"val",
"to",
"container",
"."
] | 9243b6a24f9e68995de8552615e9fda61f445c05 | https://github.com/jaredhanson/node-jsonsp/blob/9243b6a24f9e68995de8552615e9fda61f445c05/lib/jsonsp/parser.js#L167-L173 | train |
flowxo/flowxo-sdk | lib/service.js | 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 if(/config.js$/.test(file)) {
methods.push(file);
}
});
};
findConfigFiles(dir);
return methods;
} | javascript | 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 if(/config.js$/.test(file)) {
methods.push(file);
}
});
};
findConfigFiles(dir);
return methods;
} | [
"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",
"if",
"(",
"/",
"config.js$",
"/",
".",
"test",
"(",
"file",
")",
")",
"{",
"methods",
".",
"push",
"(",
"file",
")",
";",
"}",
"}",
")",
";",
"}",
";",
"findConfigFiles",
"(",
"dir",
")",
";",
"return",
"methods",
";",
"}"
] | Recurse through the passed method dir,
finding method config.
@param {String} dir methods root directory
@return {Array} paths to method config files | [
"Recurse",
"through",
"the",
"passed",
"method",
"dir",
"finding",
"method",
"config",
"."
] | 8f71dbfb25a8b57591f5c4df09937289d5c8356b | https://github.com/flowxo/flowxo-sdk/blob/8f71dbfb25a8b57591f5c4df09937289d5c8356b/lib/service.js#L15-L33 | train |
|
DaftMonk/generator-ng-component | src/generators/script-base.js | runCmd | function runCmd(cmd) {
return new Promise((resolve, reject) => {
exec(cmd, {}, function(err, stdout) {
if(err) {
console.error(stdout);
return reject(err);
}
return resolve(stdout);
});
});
} | javascript | function runCmd(cmd) {
return new Promise((resolve, reject) => {
exec(cmd, {}, function(err, stdout) {
if(err) {
console.error(stdout);
return reject(err);
}
return resolve(stdout);
});
});
} | [
"function",
"runCmd",
"(",
"cmd",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"exec",
"(",
"cmd",
",",
"{",
"}",
",",
"function",
"(",
"err",
",",
"stdout",
")",
"{",
"if",
"(",
"err",
")",
"{",
"console",
".",
"error",
"(",
"stdout",
")",
";",
"return",
"reject",
"(",
"err",
")",
";",
"}",
"return",
"resolve",
"(",
"stdout",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | Run the given command in a child process
@param {string} cmd - command to run
@returns {Promise} | [
"Run",
"the",
"given",
"command",
"in",
"a",
"child",
"process"
] | a8f92b1e4a35c807171443a2fab5d437e595b4f2 | https://github.com/DaftMonk/generator-ng-component/blob/a8f92b1e4a35c807171443a2fab5d437e595b4f2/src/generators/script-base.js#L18-L29 | train |
flowxo/flowxo-sdk | lib/validate.js | function(value) {
var d = FxoUtils.parseDateTimeField(value);
return d.valid ? d.parsed.getTime() : NaN;
} | javascript | function(value) {
var d = FxoUtils.parseDateTimeField(value);
return d.valid ? d.parsed.getTime() : NaN;
} | [
"function",
"(",
"value",
")",
"{",
"var",
"d",
"=",
"FxoUtils",
".",
"parseDateTimeField",
"(",
"value",
")",
";",
"return",
"d",
".",
"valid",
"?",
"d",
".",
"parsed",
".",
"getTime",
"(",
")",
":",
"NaN",
";",
"}"
] | The value is guaranteed not to be null or undefined but otherwise it could be anything. | [
"The",
"value",
"is",
"guaranteed",
"not",
"to",
"be",
"null",
"or",
"undefined",
"but",
"otherwise",
"it",
"could",
"be",
"anything",
"."
] | 8f71dbfb25a8b57591f5c4df09937289d5c8356b | https://github.com/flowxo/flowxo-sdk/blob/8f71dbfb25a8b57591f5c4df09937289d5c8356b/lib/validate.js#L29-L32 | train |
|
flowxo/flowxo-sdk | lib/validate.js | function(value, options) {
var format = options.dateOnly ?
'{yyyy}-{MM}-{dd}' :
'{yyyy}-{MM}-{dd} {hh}:{mm}:{ss}';
var d = FxoUtils.parseDateTimeField(value);
return d.parsed.format(format);
} | javascript | function(value, options) {
var format = options.dateOnly ?
'{yyyy}-{MM}-{dd}' :
'{yyyy}-{MM}-{dd} {hh}:{mm}:{ss}';
var d = FxoUtils.parseDateTimeField(value);
return d.parsed.format(format);
} | [
"function",
"(",
"value",
",",
"options",
")",
"{",
"var",
"format",
"=",
"options",
".",
"dateOnly",
"?",
"'{yyyy}-{MM}-{dd}'",
":",
"'{yyyy}-{MM}-{dd} {hh}:{mm}:{ss}'",
";",
"var",
"d",
"=",
"FxoUtils",
".",
"parseDateTimeField",
"(",
"value",
")",
";",
"return",
"d",
".",
"parsed",
".",
"format",
"(",
"format",
")",
";",
"}"
] | Input is a unix timestamp | [
"Input",
"is",
"a",
"unix",
"timestamp"
] | 8f71dbfb25a8b57591f5c4df09937289d5c8356b | https://github.com/flowxo/flowxo-sdk/blob/8f71dbfb25a8b57591f5c4df09937289d5c8356b/lib/validate.js#L34-L41 | train |
|
Gozala/test-commonjs | utils.js | source | 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,
visited);
}
else {
if (descriptor.get) {
result += offset + indent + "get " + name + " ";
accessor = source(descriptor.get, indent, _limit, indent + offset,
visited);
result += accessor.substr(accessor.indexOf("{"));
}
if (descriptor.set) {
if (descriptor.get) result += ",\n";
result += offset + indent + "set " + name + " ";
accessor = source(descriptor.set, indent, _limit, indent + offset,
visited);
result += accessor.substr(accessor.indexOf("{"));
}
}
return result;
}).join(",\n");
if (isCompact) {
if (names.length > limit && limit > 0) {
result += ",\n" + offset + indent + "//...";
}
}
else {
if (names.length)
result += ",";
result += "\n" + offset + indent + "\"__proto__\": ";
result += source(Object.getPrototypeOf(value), indent, 0,
offset + indent);
}
result += "\n" + offset + "}";
}
}
else {
result += String(value);
}
return result;
} | javascript | 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,
visited);
}
else {
if (descriptor.get) {
result += offset + indent + "get " + name + " ";
accessor = source(descriptor.get, indent, _limit, indent + offset,
visited);
result += accessor.substr(accessor.indexOf("{"));
}
if (descriptor.set) {
if (descriptor.get) result += ",\n";
result += offset + indent + "set " + name + " ";
accessor = source(descriptor.set, indent, _limit, indent + offset,
visited);
result += accessor.substr(accessor.indexOf("{"));
}
}
return result;
}).join(",\n");
if (isCompact) {
if (names.length > limit && limit > 0) {
result += ",\n" + offset + indent + "//...";
}
}
else {
if (names.length)
result += ",";
result += "\n" + offset + indent + "\"__proto__\": ";
result += source(Object.getPrototypeOf(value), indent, 0,
offset + indent);
}
result += "\n" + offset + "}";
}
}
else {
result += String(value);
}
return result;
} | [
"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",
"\"\\\"\"",
"\\\"",
"}"
] | Function returns textual representation of a value passed to it. Function
takes additional `indent` argument that is used for indentation. Also
optional `limit` argument may be passed to limit amount of detail returned.
@param {Object} value
@param {String} [indent=" "]
@param {Number} [limit] | [
"Function",
"returns",
"textual",
"representation",
"of",
"a",
"value",
"passed",
"to",
"it",
".",
"Function",
"takes",
"additional",
"indent",
"argument",
"that",
"is",
"used",
"for",
"indentation",
".",
"Also",
"optional",
"limit",
"argument",
"may",
"be",
"passed",
"to",
"limit",
"amount",
"of",
"detail",
"returned",
"."
] | db9821e28ef2289149f20d0e07b91d1caa7a15fd | https://github.com/Gozala/test-commonjs/blob/db9821e28ef2289149f20d0e07b91d1caa7a15fd/utils.js#L214-L333 | train |
heap/heap-node | lib/api_error.js | ApiError | function ApiError(response, client) {
this.name = "heap.ApiError";
this.response = response;
this.client = client;
this.message = this.toString();
Error.captureStackTrace(this, ApiError);
} | javascript | function ApiError(response, client) {
this.name = "heap.ApiError";
this.response = response;
this.client = client;
this.message = this.toString();
Error.captureStackTrace(this, ApiError);
} | [
"function",
"ApiError",
"(",
"response",
",",
"client",
")",
"{",
"this",
".",
"name",
"=",
"\"heap.ApiError\"",
";",
"this",
".",
"response",
"=",
"response",
";",
"this",
".",
"client",
"=",
"client",
";",
"this",
".",
"message",
"=",
"this",
".",
"toString",
"(",
")",
";",
"Error",
".",
"captureStackTrace",
"(",
"this",
",",
"ApiError",
")",
";",
"}"
] | Creates an exception representing an error sent by the Heap API server.
@constructor
@param {http.IncomingMessage} response the Heap API server's response
@param {heap-api.Client} client the Heap API client that received the error
@alias heap-api.ApiError | [
"Creates",
"an",
"exception",
"representing",
"an",
"error",
"sent",
"by",
"the",
"Heap",
"API",
"server",
"."
] | b4b65d3daa74f1122bbbd7921c6ed3a45bd0b858 | https://github.com/heap/heap-node/blob/b4b65d3daa74f1122bbbd7921c6ed3a45bd0b858/lib/api_error.js#L18-L24 | train |
christophebe/crawler.ninja | index.js | init | 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 (globalOptions.updateDepth) {
updateDepthFn = globalOptions.updateDepth;
}
// Init the crawl queue
endCallback = callback;
requestQueue.init(globalOptions, crawl, recrawl, endCallback, proxies);
if (logLevel) {
console.log("Change Log level into :" + logLevel);
log.level(logLevel);
}
else {
log.level("info"); // By default debug level is not activated
}
} | javascript | 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 (globalOptions.updateDepth) {
updateDepthFn = globalOptions.updateDepth;
}
// Init the crawl queue
endCallback = callback;
requestQueue.init(globalOptions, crawl, recrawl, endCallback, proxies);
if (logLevel) {
console.log("Change Log level into :" + logLevel);
log.level(logLevel);
}
else {
log.level("info"); // By default debug level is not activated
}
} | [
"function",
"init",
"(",
"options",
",",
"callback",
",",
"proxies",
",",
"logLevel",
")",
"{",
"if",
"(",
"!",
"callback",
")",
"{",
"log",
".",
"error",
"(",
"\"The end callback is not defined\"",
")",
";",
"}",
"globalOptions",
"=",
"createDefaultOptions",
"(",
")",
";",
"if",
"(",
"options",
")",
"{",
"_",
".",
"extend",
"(",
"globalOptions",
",",
"options",
")",
";",
"}",
"if",
"(",
"globalOptions",
".",
"rateLimits",
"!==",
"0",
")",
"{",
"globalOptions",
".",
"maxConnections",
"=",
"1",
";",
"}",
"store",
".",
"createStore",
"(",
"globalOptions",
".",
"storeModuleName",
",",
"globalOptions",
".",
"storeParams",
"?",
"globalOptions",
".",
"storeParams",
":",
"null",
")",
";",
"if",
"(",
"globalOptions",
".",
"updateDepth",
")",
"{",
"updateDepthFn",
"=",
"globalOptions",
".",
"updateDepth",
";",
"}",
"endCallback",
"=",
"callback",
";",
"requestQueue",
".",
"init",
"(",
"globalOptions",
",",
"crawl",
",",
"recrawl",
",",
"endCallback",
",",
"proxies",
")",
";",
"if",
"(",
"logLevel",
")",
"{",
"console",
".",
"log",
"(",
"\"Change Log level into :\"",
"+",
"logLevel",
")",
";",
"log",
".",
"level",
"(",
"logLevel",
")",
";",
"}",
"else",
"{",
"log",
".",
"level",
"(",
"\"info\"",
")",
";",
"}",
"}"
] | Init the crawler
@param options used to customize the crawler.
The current options attributes are :
- skipDuplicates : if true skips URLs that were already crawled - default is true
- maxConnections : the number of connections used to crawl - default is 5
- rateLimits : number of milliseconds to delay between each requests (Default 0).
Note that this option will force crawler to use only one connection
- externalDomains : if true crawl the external domains. This option can crawl a lot of different linked domains, default = false.
- externalHosts : if true crawl the others hosts on the same domain, default = false.
- firstExternalLinkOnly : crawl only the first link found for external domains/hosts. externalHosts or externalDomains should be = true
- scripts : if true crawl script tags
- links : if true crawl link tags
- linkTypes : the type of the links tags to crawl (match to the rel attribute), default : ["canonical", "stylesheet"]
- images : if true crawl images
- protocols : list of the protocols to crawl, default = ["http", "https"]
- timeout : timeout per requests in milliseconds (Default 20000)
- retries : number of retries if the request fails (default 3)
- retryTimeout : number of milliseconds to wait before retrying (Default 10000)
- depthLimit : the depth limit for the crawl
- followRedirect : if true, the crawl will not return the 301, it will follow directly the redirection
- proxyList : the list of proxies (see the project simple-proxies on npm)
- storeModuleName : the npm nodule name used for the store implementation, by default : memory-store
- storeParams : the params to pass to the store module when create it.
- queueModuleName : the npm module name used for the job queue. By default : async-queue
- queueParams : the params to pass to the job queue when create it.
+ all options provided by nodejs request : https://github.com/request/request
@param callback() called when all URLs have been crawled
@param proxies to used when making http requests (optional)
@param logLevel : a new log level (eg. "debug") (optional, default value is info) | [
"Init",
"the",
"crawler"
] | 99c9241cb666a92be218eb8f61a9e2fb7efee1d9 | https://github.com/christophebe/crawler.ninja/blob/99c9241cb666a92be218eb8f61a9e2fb7efee1d9/index.js#L92-L130 | train |
christophebe/crawler.ninja | index.js | queue | 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
if (_.isString(options)) {
addInQueue(addDefaultOptions({url:options}, globalOptions));
}
// Last possibility, this is a json
else {
if (! _.has(options, "url") && ! _.has(options, "url")) {
crawl({errorCode : "NO_URL_OPTION"}, {method:"GET", url : "unknown", proxy : "", error : true},
function(error){
if (requestQueue.idle()) {
endCallback();
}
});
}
else {
addInQueue(addDefaultOptions(options, globalOptions));
}
}
} | javascript | 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
if (_.isString(options)) {
addInQueue(addDefaultOptions({url:options}, globalOptions));
}
// Last possibility, this is a json
else {
if (! _.has(options, "url") && ! _.has(options, "url")) {
crawl({errorCode : "NO_URL_OPTION"}, {method:"GET", url : "unknown", proxy : "", error : true},
function(error){
if (requestQueue.idle()) {
endCallback();
}
});
}
else {
addInQueue(addDefaultOptions(options, globalOptions));
}
}
} | [
"function",
"queue",
"(",
"options",
")",
"{",
"if",
"(",
"!",
"endCallback",
")",
"{",
"console",
".",
"log",
"(",
"\"The end callback is not defined, impossible to run correctly\"",
")",
";",
"return",
";",
"}",
"if",
"(",
"!",
"options",
")",
"{",
"crawl",
"(",
"{",
"errorCode",
":",
"\"NO_OPTIONS\"",
"}",
",",
"{",
"method",
":",
"\"GET\"",
",",
"url",
":",
"\"unknown\"",
",",
"proxy",
":",
"\"\"",
",",
"error",
":",
"true",
"}",
",",
"function",
"(",
"error",
")",
"{",
"if",
"(",
"requestQueue",
".",
"idle",
"(",
")",
")",
"{",
"endCallback",
"(",
")",
";",
"}",
"}",
")",
";",
"return",
";",
"}",
"if",
"(",
"_",
".",
"isArray",
"(",
"options",
")",
")",
"{",
"options",
".",
"forEach",
"(",
"function",
"(",
"opt",
")",
"{",
"queue",
"(",
"opt",
")",
";",
"}",
")",
";",
"return",
";",
"}",
"if",
"(",
"_",
".",
"isString",
"(",
"options",
")",
")",
"{",
"addInQueue",
"(",
"addDefaultOptions",
"(",
"{",
"url",
":",
"options",
"}",
",",
"globalOptions",
")",
")",
";",
"}",
"else",
"{",
"if",
"(",
"!",
"_",
".",
"has",
"(",
"options",
",",
"\"url\"",
")",
"&&",
"!",
"_",
".",
"has",
"(",
"options",
",",
"\"url\"",
")",
")",
"{",
"crawl",
"(",
"{",
"errorCode",
":",
"\"NO_URL_OPTION\"",
"}",
",",
"{",
"method",
":",
"\"GET\"",
",",
"url",
":",
"\"unknown\"",
",",
"proxy",
":",
"\"\"",
",",
"error",
":",
"true",
"}",
",",
"function",
"(",
"error",
")",
"{",
"if",
"(",
"requestQueue",
".",
"idle",
"(",
")",
")",
"{",
"endCallback",
"(",
")",
";",
"}",
"}",
")",
";",
"}",
"else",
"{",
"addInQueue",
"(",
"addDefaultOptions",
"(",
"options",
",",
"globalOptions",
")",
")",
";",
"}",
"}",
"}"
] | Add one or more urls to crawl
@param The url(s) to crawl. This could one of the following possibilities :
- A simple String matching to an URL. In this case the default options will be used.
- An array of String matching to a list of URLs. In this case the default options will be used.
- A Crawl option object containing a URL and a set of options (see the method init to get the list)
- An array of crawl options | [
"Add",
"one",
"or",
"more",
"urls",
"to",
"crawl"
] | 99c9241cb666a92be218eb8f61a9e2fb7efee1d9 | https://github.com/christophebe/crawler.ninja/blob/99c9241cb666a92be218eb8f61a9e2fb7efee1d9/index.js#L154-L204 | train |
christophebe/crawler.ninja | index.js | addDefaultOptions | function addDefaultOptions(options, defaultOptions) {
_.defaults(options, defaultOptions);
options.currentRetries = 0;
return options;
} | javascript | function addDefaultOptions(options, defaultOptions) {
_.defaults(options, defaultOptions);
options.currentRetries = 0;
return options;
} | [
"function",
"addDefaultOptions",
"(",
"options",
",",
"defaultOptions",
")",
"{",
"_",
".",
"defaults",
"(",
"options",
",",
"defaultOptions",
")",
";",
"options",
".",
"currentRetries",
"=",
"0",
";",
"return",
"options",
";",
"}"
] | Add the default crawler options into the option used for the current request
@param the option used for the current request
@param The default options
@return the modified option object | [
"Add",
"the",
"default",
"crawler",
"options",
"into",
"the",
"option",
"used",
"for",
"the",
"current",
"request"
] | 99c9241cb666a92be218eb8f61a9e2fb7efee1d9 | https://github.com/christophebe/crawler.ninja/blob/99c9241cb666a92be218eb8f61a9e2fb7efee1d9/index.js#L248-L254 | train |
christophebe/crawler.ninja | index.js | buildNewOptions | 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 = newUrl;
o.depthLimit = options.depthLimit;
o.currentRetries = 0;
if (options.canCrawl) {
o.canCrawl = options.canCrawl;
}
return o;
} | javascript | 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 = newUrl;
o.depthLimit = options.depthLimit;
o.currentRetries = 0;
if (options.canCrawl) {
o.canCrawl = options.canCrawl;
}
return o;
} | [
"function",
"buildNewOptions",
"(",
"options",
",",
"newUrl",
")",
"{",
"var",
"o",
"=",
"_",
".",
"clone",
"(",
"options",
")",
";",
"o",
".",
"url",
"=",
"newUrl",
";",
"o",
".",
"depthLimit",
"=",
"options",
".",
"depthLimit",
";",
"o",
".",
"currentRetries",
"=",
"0",
";",
"if",
"(",
"options",
".",
"canCrawl",
")",
"{",
"o",
".",
"canCrawl",
"=",
"options",
".",
"canCrawl",
";",
"}",
"return",
"o",
";",
"}"
] | Make a copy of an option object for a specific url
@param the options object to create/copy
@param the url to apply into the new option object
@return the new options object | [
"Make",
"a",
"copy",
"of",
"an",
"option",
"object",
"for",
"a",
"specific",
"url"
] | 99c9241cb666a92be218eb8f61a9e2fb7efee1d9 | https://github.com/christophebe/crawler.ninja/blob/99c9241cb666a92be218eb8f61a9e2fb7efee1d9/index.js#L264-L288 | train |
christophebe/crawler.ninja | index.js | createDefaultOptions | 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 : DEFAULT_DEPTH_LIMIT,
followRedirect : DEFAULT_FOLLOW_301,
userAgent : DEFAULT_USER_AGENT,
domainBlackList : domainBlackList,
suffixBlackList : suffixBlackList,
retry400 : DEFAULT_RETRY_400,
isExternal : false,
storeModuleName : DEFAULT_STORE_MODULE,
queueModuleName : DEFAULT_QUEUE_MODULE,
jar : DEFAULT_JAR
};
if (url) {
options.url = url;
}
return options;
} | javascript | 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 : DEFAULT_DEPTH_LIMIT,
followRedirect : DEFAULT_FOLLOW_301,
userAgent : DEFAULT_USER_AGENT,
domainBlackList : domainBlackList,
suffixBlackList : suffixBlackList,
retry400 : DEFAULT_RETRY_400,
isExternal : false,
storeModuleName : DEFAULT_STORE_MODULE,
queueModuleName : DEFAULT_QUEUE_MODULE,
jar : DEFAULT_JAR
};
if (url) {
options.url = url;
}
return options;
} | [
"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",
":",
"DEFAULT_DEPTH_LIMIT",
",",
"followRedirect",
":",
"DEFAULT_FOLLOW_301",
",",
"userAgent",
":",
"DEFAULT_USER_AGENT",
",",
"domainBlackList",
":",
"domainBlackList",
",",
"suffixBlackList",
":",
"suffixBlackList",
",",
"retry400",
":",
"DEFAULT_RETRY_400",
",",
"isExternal",
":",
"false",
",",
"storeModuleName",
":",
"DEFAULT_STORE_MODULE",
",",
"queueModuleName",
":",
"DEFAULT_QUEUE_MODULE",
",",
"jar",
":",
"DEFAULT_JAR",
"}",
";",
"if",
"(",
"url",
")",
"{",
"options",
".",
"url",
"=",
"url",
";",
"}",
"return",
"options",
";",
"}"
] | Create the default crawl options
@returns the default crawl options | [
"Create",
"the",
"default",
"crawl",
"options"
] | 99c9241cb666a92be218eb8f61a9e2fb7efee1d9 | https://github.com/christophebe/crawler.ninja/blob/99c9241cb666a92be218eb8f61a9e2fb7efee1d9/index.js#L296-L333 | train |
christophebe/crawler.ninja | index.js | analyzeHTML | 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([
async.apply(crawlHrefs, result, $),
async.apply(crawlLinks, result, $),
async.apply(crawlScripts, result, $),
async.apply(crawlImages, result, $),
], callback);
} | javascript | 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([
async.apply(crawlHrefs, result, $),
async.apply(crawlLinks, result, $),
async.apply(crawlScripts, result, $),
async.apply(crawlImages, result, $),
], callback);
} | [
"function",
"analyzeHTML",
"(",
"result",
",",
"$",
",",
"callback",
")",
"{",
"if",
"(",
"!",
"$",
")",
"{",
"return",
"callback",
"(",
")",
";",
"}",
"log",
".",
"debug",
"(",
"{",
"\"url\"",
":",
"result",
".",
"url",
",",
"\"step\"",
":",
"\"analyzeHTML\"",
",",
"\"message\"",
":",
"\"Start check HTML code\"",
"}",
")",
";",
"async",
".",
"parallel",
"(",
"[",
"async",
".",
"apply",
"(",
"crawlHrefs",
",",
"result",
",",
"$",
")",
",",
"async",
".",
"apply",
"(",
"crawlLinks",
",",
"result",
",",
"$",
")",
",",
"async",
".",
"apply",
"(",
"crawlScripts",
",",
"result",
",",
"$",
")",
",",
"async",
".",
"apply",
"(",
"crawlImages",
",",
"result",
",",
"$",
")",
",",
"]",
",",
"callback",
")",
";",
"}"
] | Analyze an HTML page. Mainly, found a.href, links,scripts & images in the page
@param The Http response with the crawl option
@param the jquery like object for accessing to the HTML tags. Null is the resource
is not an HTML
@param callback() | [
"Analyze",
"an",
"HTML",
"page",
".",
"Mainly",
"found",
"a",
".",
"href",
"links",
"scripts",
"&",
"images",
"in",
"the",
"page"
] | 99c9241cb666a92be218eb8f61a9e2fb7efee1d9 | https://github.com/christophebe/crawler.ninja/blob/99c9241cb666a92be218eb8f61a9e2fb7efee1d9/index.js#L414-L432 | train |
christophebe/crawler.ninja | index.js | crawlHrefs | function crawlHrefs(result, $, endCallback) {
log.debug({"url" : result.url, "step" : "analyzeHTML", "message" : "CrawlHrefs"});
async.each($('a'), function(a, callback) {
crawlHref($, result, a, callback);
}, endCallback);
} | javascript | function crawlHrefs(result, $, endCallback) {
log.debug({"url" : result.url, "step" : "analyzeHTML", "message" : "CrawlHrefs"});
async.each($('a'), function(a, callback) {
crawlHref($, result, a, callback);
}, endCallback);
} | [
"function",
"crawlHrefs",
"(",
"result",
",",
"$",
",",
"endCallback",
")",
"{",
"log",
".",
"debug",
"(",
"{",
"\"url\"",
":",
"result",
".",
"url",
",",
"\"step\"",
":",
"\"analyzeHTML\"",
",",
"\"message\"",
":",
"\"CrawlHrefs\"",
"}",
")",
";",
"async",
".",
"each",
"(",
"$",
"(",
"'a'",
")",
",",
"function",
"(",
"a",
",",
"callback",
")",
"{",
"crawlHref",
"(",
"$",
",",
"result",
",",
"a",
",",
"callback",
")",
";",
"}",
",",
"endCallback",
")",
";",
"}"
] | Crawl urls that match to HTML tags a.href found in one page
@param The Http response with the crawl option
@param the jquery like object for accessing to the HTML tags.
@param callback() | [
"Crawl",
"urls",
"that",
"match",
"to",
"HTML",
"tags",
"a",
".",
"href",
"found",
"in",
"one",
"page"
] | 99c9241cb666a92be218eb8f61a9e2fb7efee1d9 | https://github.com/christophebe/crawler.ninja/blob/99c9241cb666a92be218eb8f61a9e2fb7efee1d9/index.js#L443-L450 | train |
christophebe/crawler.ninja | index.js | crawlHref | 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);
pm.crawlLink(parentUrl, linkUri, anchor, isDoFollow, function(){
addLinkToQueue(result, parentUrl, linkUri, anchor, isDoFollow, callback);
});
}
else {
callback();
}
} | javascript | 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);
pm.crawlLink(parentUrl, linkUri, anchor, isDoFollow, function(){
addLinkToQueue(result, parentUrl, linkUri, anchor, isDoFollow, callback);
});
}
else {
callback();
}
} | [
"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",
")",
";",
"pm",
".",
"crawlLink",
"(",
"parentUrl",
",",
"linkUri",
",",
"anchor",
",",
"isDoFollow",
",",
"function",
"(",
")",
"{",
"addLinkToQueue",
"(",
"result",
",",
"parentUrl",
",",
"linkUri",
",",
"anchor",
",",
"isDoFollow",
",",
"callback",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"callback",
"(",
")",
";",
"}",
"}"
] | Extract info of ahref & send the info to the plugins
@param The HTML body containing the link (Cheerio wraper)
@param The http response with the crawl options
@param The anchor tag
@param callback() | [
"Extract",
"info",
"of",
"ahref",
"&",
"send",
"the",
"info",
"to",
"the",
"plugins"
] | 99c9241cb666a92be218eb8f61a9e2fb7efee1d9 | https://github.com/christophebe/crawler.ninja/blob/99c9241cb666a92be218eb8f61a9e2fb7efee1d9/index.js#L461-L482 | train |
christophebe/crawler.ninja | index.js | crawLink | 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, linkUri, null, null, function(){
addLinkToQueue(result, parentUrl, linkUri, null, null, callback);
});
}
else {
callback();
}
}
else {
callback();
}
} | javascript | 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, linkUri, null, null, function(){
addLinkToQueue(result, parentUrl, linkUri, null, null, callback);
});
}
else {
callback();
}
}
else {
callback();
}
} | [
"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",
",",
"linkUri",
",",
"null",
",",
"null",
",",
"function",
"(",
")",
"{",
"addLinkToQueue",
"(",
"result",
",",
"parentUrl",
",",
"linkUri",
",",
"null",
",",
"null",
",",
"callback",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"callback",
"(",
")",
";",
"}",
"}",
"else",
"{",
"callback",
"(",
")",
";",
"}",
"}"
] | Extract info of html link tag & send the info to the plugins
@param The HTML body containing the link (Cheerio wraper)
@param The http response with the crawl options
@param The link tag
@param callback() | [
"Extract",
"info",
"of",
"html",
"link",
"tag",
"&",
"send",
"the",
"info",
"to",
"the",
"plugins"
] | 99c9241cb666a92be218eb8f61a9e2fb7efee1d9 | https://github.com/christophebe/crawler.ninja/blob/99c9241cb666a92be218eb8f61a9e2fb7efee1d9/index.js#L515-L537 | train |
christophebe/crawler.ninja | index.js | crawlScripts | function crawlScripts(result, $, endCallback) {
if (! result.scripts) {
return endCallback();
}
log.debug({"url" : result.url, "step" : "analyzeHTML", "message" : "CrawlScripts"});
async.each($('script'), function(script, callback) {
crawlScript($, result, script, callback);
}, endCallback);
} | javascript | function crawlScripts(result, $, endCallback) {
if (! result.scripts) {
return endCallback();
}
log.debug({"url" : result.url, "step" : "analyzeHTML", "message" : "CrawlScripts"});
async.each($('script'), function(script, callback) {
crawlScript($, result, script, callback);
}, endCallback);
} | [
"function",
"crawlScripts",
"(",
"result",
",",
"$",
",",
"endCallback",
")",
"{",
"if",
"(",
"!",
"result",
".",
"scripts",
")",
"{",
"return",
"endCallback",
"(",
")",
";",
"}",
"log",
".",
"debug",
"(",
"{",
"\"url\"",
":",
"result",
".",
"url",
",",
"\"step\"",
":",
"\"analyzeHTML\"",
",",
"\"message\"",
":",
"\"CrawlScripts\"",
"}",
")",
";",
"async",
".",
"each",
"(",
"$",
"(",
"'script'",
")",
",",
"function",
"(",
"script",
",",
"callback",
")",
"{",
"crawlScript",
"(",
"$",
",",
"result",
",",
"script",
",",
"callback",
")",
";",
"}",
",",
"endCallback",
")",
";",
"}"
] | Crawl script tags found in the HTML page
@param The HTTP response with the crawl options
@param the jquery like object for accessing to the HTML tags.
@param callback() | [
"Crawl",
"script",
"tags",
"found",
"in",
"the",
"HTML",
"page"
] | 99c9241cb666a92be218eb8f61a9e2fb7efee1d9 | https://github.com/christophebe/crawler.ninja/blob/99c9241cb666a92be218eb8f61a9e2fb7efee1d9/index.js#L547-L558 | train |
christophebe/crawler.ninja | index.js | crawlScript | 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(){
addLinkToQueue(result, parentUrl, linkUri, null, null, callback);
});
}
else {
callback();
}
} | javascript | 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(){
addLinkToQueue(result, parentUrl, linkUri, null, null, callback);
});
}
else {
callback();
}
} | [
"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",
"(",
")",
"{",
"addLinkToQueue",
"(",
"result",
",",
"parentUrl",
",",
"linkUri",
",",
"null",
",",
"null",
",",
"callback",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"callback",
"(",
")",
";",
"}",
"}"
] | Extract info of script tag & send the info to the plugins
@param The HTML body containing the script tag (Cheerio wraper)
@param The http response with the crawl options
@param The script tag
@param callback() | [
"Extract",
"info",
"of",
"script",
"tag",
"&",
"send",
"the",
"info",
"to",
"the",
"plugins"
] | 99c9241cb666a92be218eb8f61a9e2fb7efee1d9 | https://github.com/christophebe/crawler.ninja/blob/99c9241cb666a92be218eb8f61a9e2fb7efee1d9/index.js#L569-L585 | train |
christophebe/crawler.ninja | index.js | crawlImages | function crawlImages(result, $, endCallback) {
if (! result.images) {
return endCallback();
}
log.debug({"url" : result.url, "step" : "analyzeHTML", "message" : "CrawlImages"});
async.each($('img'), function(img, callback) {
crawlImage($, result, img, callback);
}, endCallback);
} | javascript | function crawlImages(result, $, endCallback) {
if (! result.images) {
return endCallback();
}
log.debug({"url" : result.url, "step" : "analyzeHTML", "message" : "CrawlImages"});
async.each($('img'), function(img, callback) {
crawlImage($, result, img, callback);
}, endCallback);
} | [
"function",
"crawlImages",
"(",
"result",
",",
"$",
",",
"endCallback",
")",
"{",
"if",
"(",
"!",
"result",
".",
"images",
")",
"{",
"return",
"endCallback",
"(",
")",
";",
"}",
"log",
".",
"debug",
"(",
"{",
"\"url\"",
":",
"result",
".",
"url",
",",
"\"step\"",
":",
"\"analyzeHTML\"",
",",
"\"message\"",
":",
"\"CrawlImages\"",
"}",
")",
";",
"async",
".",
"each",
"(",
"$",
"(",
"'img'",
")",
",",
"function",
"(",
"img",
",",
"callback",
")",
"{",
"crawlImage",
"(",
"$",
",",
"result",
",",
"img",
",",
"callback",
")",
";",
"}",
",",
"endCallback",
")",
";",
"}"
] | Crawl image tags found in the HTML page
@param The HTTP response with the crawl options
@param the jquery like object for accessing to the HTML tags.
@param callback() | [
"Crawl",
"image",
"tags",
"found",
"in",
"the",
"HTML",
"page"
] | 99c9241cb666a92be218eb8f61a9e2fb7efee1d9 | https://github.com/christophebe/crawler.ninja/blob/99c9241cb666a92be218eb8f61a9e2fb7efee1d9/index.js#L595-L606 | train |
christophebe/crawler.ninja | index.js | crawlImage | 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(){
addLinkToQueue(result, parentUrl, linkUri, null, null, callback);
});
}
else {
callback();
}
} | javascript | 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(){
addLinkToQueue(result, parentUrl, linkUri, null, null, callback);
});
}
else {
callback();
}
} | [
"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",
"(",
")",
"{",
"addLinkToQueue",
"(",
"result",
",",
"parentUrl",
",",
"linkUri",
",",
"null",
",",
"null",
",",
"callback",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"callback",
"(",
")",
";",
"}",
"}"
] | Extract info of an image tag & send the info to the plugins
@param The HTML body containing the link (Cheerio wraper)
@param The http response with the crawl options
@param The image tag
@param callback() | [
"Extract",
"info",
"of",
"an",
"image",
"tag",
"&",
"send",
"the",
"info",
"to",
"the",
"plugins"
] | 99c9241cb666a92be218eb8f61a9e2fb7efee1d9 | https://github.com/christophebe/crawler.ninja/blob/99c9241cb666a92be218eb8f61a9e2fb7efee1d9/index.js#L617-L631 | train |
christophebe/crawler.ninja | index.js | updateDepth | 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) {
if (error) {
return callback(error);
}
callback(error, result.linkDepth);
});
} | javascript | 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) {
if (error) {
return callback(error);
}
callback(error, result.linkDepth);
});
} | [
"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",
")",
"{",
"if",
"(",
"error",
")",
"{",
"return",
"callback",
"(",
"error",
")",
";",
"}",
"callback",
"(",
"error",
",",
"result",
".",
"linkDepth",
")",
";",
"}",
")",
";",
"}"
] | Compute the crawl depth for a link in function of the crawl depth
of the page that contains the link
@param The URI of page that contains the link
@param The link for which the crawl depth has to be calculated
@param callback(error, depth) | [
"Compute",
"the",
"crawl",
"depth",
"for",
"a",
"link",
"in",
"function",
"of",
"the",
"crawl",
"depth",
"of",
"the",
"page",
"that",
"contains",
"the",
"link"
] | 99c9241cb666a92be218eb8f61a9e2fb7efee1d9 | https://github.com/christophebe/crawler.ninja/blob/99c9241cb666a92be218eb8f61a9e2fb7efee1d9/index.js#L778-L790 | train |
christophebe/crawler.ninja | index.js | getDepths | 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)
],
function(error, results){
if (error) {
return callback(error);
}
depths.parentDepth = results[0];
depths.linkDepth = results[1];
callback(null, depths);
});
} | javascript | 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)
],
function(error, results){
if (error) {
return callback(error);
}
depths.parentDepth = results[0];
depths.linkDepth = results[1];
callback(null, depths);
});
} | [
"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",
")",
"]",
",",
"function",
"(",
"error",
",",
"results",
")",
"{",
"if",
"(",
"error",
")",
"{",
"return",
"callback",
"(",
"error",
")",
";",
"}",
"depths",
".",
"parentDepth",
"=",
"results",
"[",
"0",
"]",
";",
"depths",
".",
"linkDepth",
"=",
"results",
"[",
"1",
"]",
";",
"callback",
"(",
"null",
",",
"depths",
")",
";",
"}",
")",
";",
"}"
] | get the crawl depths for a parent & link uri
@param a structure containing both url
{parentUrl : parentUrl, linkUri : linkUri}
@param callback(error, depth) | [
"get",
"the",
"crawl",
"depths",
"for",
"a",
"parent",
"&",
"link",
"uri"
] | 99c9241cb666a92be218eb8f61a9e2fb7efee1d9 | https://github.com/christophebe/crawler.ninja/blob/99c9241cb666a92be218eb8f61a9e2fb7efee1d9/index.js#L800-L814 | train |
christophebe/crawler.ninja | index.js | calcultateDepths | 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 = depths.parentDepth + 1;
}
}
else {
depths.parentDepth = 0;
depths.linkDepth = 1;
}
callback(null, depths);
} | javascript | 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 = depths.parentDepth + 1;
}
}
else {
depths.parentDepth = 0;
depths.linkDepth = 1;
}
callback(null, depths);
} | [
"function",
"calcultateDepths",
"(",
"depths",
",",
"callback",
")",
"{",
"if",
"(",
"depths",
".",
"parentDepth",
")",
"{",
"if",
"(",
"!",
"depths",
".",
"linkDepth",
")",
"{",
"depths",
".",
"linkDepth",
"=",
"depths",
".",
"parentDepth",
"+",
"1",
";",
"}",
"}",
"else",
"{",
"depths",
".",
"parentDepth",
"=",
"0",
";",
"depths",
".",
"linkDepth",
"=",
"1",
";",
"}",
"callback",
"(",
"null",
",",
"depths",
")",
";",
"}"
] | Calculate the depth
@param a structure containing both url
{parentUrl : parentUrl, linkUri : linkUri}
@param callback(error, depth) | [
"Calculate",
"the",
"depth"
] | 99c9241cb666a92be218eb8f61a9e2fb7efee1d9 | https://github.com/christophebe/crawler.ninja/blob/99c9241cb666a92be218eb8f61a9e2fb7efee1d9/index.js#L825-L838 | train |
christophebe/crawler.ninja | index.js | saveDepths | 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()), depths.linkUri, depths.linkDepth )
],
function(error){
callback(error, depths);
});
} | javascript | 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()), depths.linkUri, depths.linkDepth )
],
function(error){
callback(error, depths);
});
} | [
"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",
"(",
")",
")",
",",
"depths",
".",
"linkUri",
",",
"depths",
".",
"linkDepth",
")",
"]",
",",
"function",
"(",
"error",
")",
"{",
"callback",
"(",
"error",
",",
"depths",
")",
";",
"}",
")",
";",
"}"
] | Save the crawl depths for a parent & link uri
@param a structure containing both url
{parentUrl : parentUrl, linkUri : linkUri}
@param callback(error, depth) | [
"Save",
"the",
"crawl",
"depths",
"for",
"a",
"parent",
"&",
"link",
"uri"
] | 99c9241cb666a92be218eb8f61a9e2fb7efee1d9 | https://github.com/christophebe/crawler.ninja/blob/99c9241cb666a92be218eb8f61a9e2fb7efee1d9/index.js#L848-L857 | train |
nippur72/RiotTS | riot-ts.js | extend | function extend(d, element) {
var map = Object.keys(element.prototype).reduce(function (descriptors, key) {
descriptors[key] = Object.getOwnPropertyDescriptor(element.prototype, key);
return descriptors;
}, {});
Object.defineProperties(d, map);
} | javascript | function extend(d, element) {
var map = Object.keys(element.prototype).reduce(function (descriptors, key) {
descriptors[key] = Object.getOwnPropertyDescriptor(element.prototype, key);
return descriptors;
}, {});
Object.defineProperties(d, map);
} | [
"function",
"extend",
"(",
"d",
",",
"element",
")",
"{",
"var",
"map",
"=",
"Object",
".",
"keys",
"(",
"element",
".",
"prototype",
")",
".",
"reduce",
"(",
"function",
"(",
"descriptors",
",",
"key",
")",
"{",
"descriptors",
"[",
"key",
"]",
"=",
"Object",
".",
"getOwnPropertyDescriptor",
"(",
"element",
".",
"prototype",
",",
"key",
")",
";",
"return",
"descriptors",
";",
"}",
",",
"{",
"}",
")",
";",
"Object",
".",
"defineProperties",
"(",
"d",
",",
"map",
")",
";",
"}"
] | new extend, works with getters and setters | [
"new",
"extend",
"works",
"with",
"getters",
"and",
"setters"
] | f57dd17fba5f7b32548571ea59c7a1645fa2700f | https://github.com/nippur72/RiotTS/blob/f57dd17fba5f7b32548571ea59c7a1645fa2700f/riot-ts.js#L44-L50 | train |
christophebe/crawler.ninja | lib/queue/request-queue.js | init | function init (options, crawlCallback, recrawlCallback, endCallback, proxies) {
requestQueue = require(options.queueModuleName);
requestQueue.init(options, onUrlToCrawl, endCallback);
onCrawl = crawlCallback;
onRecrawl = recrawlCallback;
proxyList = proxies;
} | javascript | function init (options, crawlCallback, recrawlCallback, endCallback, proxies) {
requestQueue = require(options.queueModuleName);
requestQueue.init(options, onUrlToCrawl, endCallback);
onCrawl = crawlCallback;
onRecrawl = recrawlCallback;
proxyList = proxies;
} | [
"function",
"init",
"(",
"options",
",",
"crawlCallback",
",",
"recrawlCallback",
",",
"endCallback",
",",
"proxies",
")",
"{",
"requestQueue",
"=",
"require",
"(",
"options",
".",
"queueModuleName",
")",
";",
"requestQueue",
".",
"init",
"(",
"options",
",",
"onUrlToCrawl",
",",
"endCallback",
")",
";",
"onCrawl",
"=",
"crawlCallback",
";",
"onRecrawl",
"=",
"recrawlCallback",
";",
"proxyList",
"=",
"proxies",
";",
"}"
] | Init the Queue
@param The number of tasks/connections that the request queue can run in parallel
@param The callback executed when a resource has been crawled
@param The callback executed when a resource has been recrawl (probably due to an error)
@param The callback executed when all tasks (urls to crawl) are completed
@param The proxies to used when making http requests | [
"Init",
"the",
"Queue"
] | 99c9241cb666a92be218eb8f61a9e2fb7efee1d9 | https://github.com/christophebe/crawler.ninja/blob/99c9241cb666a92be218eb8f61a9e2fb7efee1d9/lib/queue/request-queue.js#L34-L42 | train |
christophebe/crawler.ninja | lib/queue/request-queue.js | queue | 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();
}
});
}
else {
//numOfUrl++
//console.log("Queue length : " + requestQueue.length() + " - Running : " + requestQueue.running() + " - Total Add :" + numOfUrl + " - Total End : " + endUrl + " url : " + options.url );
log.info({"url" : options.url, "step" : "queue-resquester.queue", "message" : "Add in the request queue"});
requestQueue.push(options);
callback();
}
} | javascript | 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();
}
});
}
else {
//numOfUrl++
//console.log("Queue length : " + requestQueue.length() + " - Running : " + requestQueue.running() + " - Total Add :" + numOfUrl + " - Total End : " + endUrl + " url : " + options.url );
log.info({"url" : options.url, "step" : "queue-resquester.queue", "message" : "Add in the request queue"});
requestQueue.push(options);
callback();
}
} | [
"function",
"queue",
"(",
"options",
",",
"callback",
")",
"{",
"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",
"{",
"log",
".",
"debug",
"(",
"{",
"\"url\"",
":",
"options",
".",
"url",
",",
"\"step\"",
":",
"\"queue-resquester.queue\"",
",",
"\"message\"",
":",
"\"Add in the request queue\"",
"}",
")",
";",
"requestQueue",
".",
"push",
"(",
"options",
")",
";",
"callback",
"(",
")",
";",
"}",
"}",
")",
";",
"}",
"else",
"{",
"log",
".",
"info",
"(",
"{",
"\"url\"",
":",
"options",
".",
"url",
",",
"\"step\"",
":",
"\"queue-resquester.queue\"",
",",
"\"message\"",
":",
"\"Add in the request queue\"",
"}",
")",
";",
"requestQueue",
".",
"push",
"(",
"options",
")",
";",
"callback",
"(",
")",
";",
"}",
"}"
] | Add a new url to crawl in the queue.
Check the desired options and add it to the request queue
@param the options used to crawl the url | [
"Add",
"a",
"new",
"url",
"to",
"crawl",
"in",
"the",
"queue",
".",
"Check",
"the",
"desired",
"options",
"and",
"add",
"it",
"to",
"the",
"request",
"queue"
] | 99c9241cb666a92be218eb8f61a9e2fb7efee1d9 | https://github.com/christophebe/crawler.ninja/blob/99c9241cb666a92be218eb8f61a9e2fb7efee1d9/lib/queue/request-queue.js#L51-L84 | train |
christophebe/crawler.ninja | lib/queue/request-queue.js | execHttp | 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) {
error = new Error("40* Error");
error.code = result.statusCode;
}
if (error) {
onRequestError(error, result, function(error){
process.nextTick(function() {callback(error);});
});
}
else {
onCrawl(null, result, function(error){
process.nextTick(function() {callback(error);});
});
}
});
} | javascript | 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) {
error = new Error("40* Error");
error.code = result.statusCode;
}
if (error) {
onRequestError(error, result, function(error){
process.nextTick(function() {callback(error);});
});
}
else {
onCrawl(null, result, function(error){
process.nextTick(function() {callback(error);});
});
}
});
} | [
"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\"",
"}",
")",
";",
"if",
"(",
"result",
".",
"statusCode",
"&&",
"result",
".",
"statusCode",
">=",
"400",
"&&",
"result",
".",
"statusCode",
"<=",
"499",
"&&",
"result",
".",
"retry400",
")",
"{",
"error",
"=",
"new",
"Error",
"(",
"\"40* Error\"",
")",
";",
"error",
".",
"code",
"=",
"result",
".",
"statusCode",
";",
"}",
"if",
"(",
"error",
")",
"{",
"onRequestError",
"(",
"error",
",",
"result",
",",
"function",
"(",
"error",
")",
"{",
"process",
".",
"nextTick",
"(",
"function",
"(",
")",
"{",
"callback",
"(",
"error",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"onCrawl",
"(",
"null",
",",
"result",
",",
"function",
"(",
"error",
")",
"{",
"process",
".",
"nextTick",
"(",
"function",
"(",
")",
"{",
"callback",
"(",
"error",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
"}",
")",
";",
"}"
] | Execute an http request
@param The options to used for the request
@param callback executed when the request is finished | [
"Execute",
"an",
"http",
"request"
] | 99c9241cb666a92be218eb8f61a9e2fb7efee1d9 | https://github.com/christophebe/crawler.ninja/blob/99c9241cb666a92be218eb8f61a9e2fb7efee1d9/lib/queue/request-queue.js#L168-L199 | train |
christophebe/crawler.ninja | lib/queue/request-queue.js | retrySameUrl | 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 to support the option skipDuplicates = true
store.getStore().removeFromHistory(options.url);
// 2. Add it again in the queue with the same options
queue(options, callback);
}
else {
onCrawl(error, options, function(error){
process.nextTick(function() {callback(error);});
});
}
} | javascript | 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 to support the option skipDuplicates = true
store.getStore().removeFromHistory(options.url);
// 2. Add it again in the queue with the same options
queue(options, callback);
}
else {
onCrawl(error, options, function(error){
process.nextTick(function() {callback(error);});
});
}
} | [
"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",
";",
"store",
".",
"getStore",
"(",
")",
".",
"removeFromHistory",
"(",
"options",
".",
"url",
")",
";",
"queue",
"(",
"options",
",",
"callback",
")",
";",
"}",
"else",
"{",
"onCrawl",
"(",
"error",
",",
"options",
",",
"function",
"(",
"error",
")",
"{",
"process",
".",
"nextTick",
"(",
"function",
"(",
")",
"{",
"callback",
"(",
"error",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
"}"
] | Recrawl an url if the maximum of retries is no yet fetched.
Otherwise call the callback onCrawl
@param the HTTP error
@param the crawl options
@param callback(error) | [
"Recrawl",
"an",
"url",
"if",
"the",
"maximum",
"of",
"retries",
"is",
"no",
"yet",
"fetched",
".",
"Otherwise",
"call",
"the",
"callback",
"onCrawl"
] | 99c9241cb666a92be218eb8f61a9e2fb7efee1d9 | https://github.com/christophebe/crawler.ninja/blob/99c9241cb666a92be218eb8f61a9e2fb7efee1d9/lib/queue/request-queue.js#L247-L270 | train |
maxvyaznikov/imapseagull | lib/addressparser.js | Tokenizer | function Tokenizer(str) {
this.str = (str || '').toString();
this.operatorCurrent = '';
this.operatorExpecting = '';
this.node = null;
this.escaped = false;
this.list = [];
} | javascript | function Tokenizer(str) {
this.str = (str || '').toString();
this.operatorCurrent = '';
this.operatorExpecting = '';
this.node = null;
this.escaped = false;
this.list = [];
} | [
"function",
"Tokenizer",
"(",
"str",
")",
"{",
"this",
".",
"str",
"=",
"(",
"str",
"||",
"''",
")",
".",
"toString",
"(",
")",
";",
"this",
".",
"operatorCurrent",
"=",
"''",
";",
"this",
".",
"operatorExpecting",
"=",
"''",
";",
"this",
".",
"node",
"=",
"null",
";",
"this",
".",
"escaped",
"=",
"false",
";",
"this",
".",
"list",
"=",
"[",
"]",
";",
"}"
] | Creates a Tokenizer object for tokenizing address field strings
@constructor
@param {String} str Address field string | [
"Creates",
"a",
"Tokenizer",
"object",
"for",
"tokenizing",
"address",
"field",
"strings"
] | 44949b7a338b4c0ace3ef7bb95a77c4794462bda | https://github.com/maxvyaznikov/imapseagull/blob/44949b7a338b4c0ace3ef7bb95a77c4794462bda/lib/addressparser.js#L184-L194 | train |
christophebe/crawler.ninja | plugins/audit-plugin.js | Plugin | 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 Map();
this.unparsedLinks = new Set();
this.images = new Map();
this.errors = new Set();
this.redirects = new Map();
} | javascript | 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 Map();
this.unparsedLinks = new Set();
this.images = new Map();
this.errors = new Set();
this.redirects = new Map();
} | [
"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",
"Map",
"(",
")",
";",
"this",
".",
"unparsedLinks",
"=",
"new",
"Set",
"(",
")",
";",
"this",
".",
"images",
"=",
"new",
"Map",
"(",
")",
";",
"this",
".",
"errors",
"=",
"new",
"Set",
"(",
")",
";",
"this",
".",
"redirects",
"=",
"new",
"Map",
"(",
")",
";",
"}"
] | Basic crawler plugin that can be used to make a SEO audit for one site
This is just an example that requires some customizations
@param : the crawler engine that will emit events to this plugin | [
"Basic",
"crawler",
"plugin",
"that",
"can",
"be",
"used",
"to",
"make",
"a",
"SEO",
"audit",
"for",
"one",
"site",
"This",
"is",
"just",
"an",
"example",
"that",
"requires",
"some",
"customizations"
] | 99c9241cb666a92be218eb8f61a9e2fb7efee1d9 | https://github.com/christophebe/crawler.ninja/blob/99c9241cb666a92be218eb8f61a9e2fb7efee1d9/plugins/audit-plugin.js#L19-L33 | train |
christophebe/crawler.ninja | plugins/audit-plugin.js | function(map, key, value) {
var list = [];
if (map.has(key)) {
list = map.get(key);
if (!list) {
list = [];
}
}
list.push(value);
map.set(key, list);
} | javascript | function(map, key, value) {
var list = [];
if (map.has(key)) {
list = map.get(key);
if (!list) {
list = [];
}
}
list.push(value);
map.set(key, list);
} | [
"function",
"(",
"map",
",",
"key",
",",
"value",
")",
"{",
"var",
"list",
"=",
"[",
"]",
";",
"if",
"(",
"map",
".",
"has",
"(",
"key",
")",
")",
"{",
"list",
"=",
"map",
".",
"get",
"(",
"key",
")",
";",
"if",
"(",
"!",
"list",
")",
"{",
"list",
"=",
"[",
"]",
";",
"}",
"}",
"list",
".",
"push",
"(",
"value",
")",
";",
"map",
".",
"set",
"(",
"key",
",",
"list",
")",
";",
"}"
] | Generic method to add a new element in list which is indexed in a map
So, value of each key is a list
@param the map
@param the key
@param the new value to add to the list (the value) for that key | [
"Generic",
"method",
"to",
"add",
"a",
"new",
"element",
"in",
"list",
"which",
"is",
"indexed",
"in",
"a",
"map",
"So",
"value",
"of",
"each",
"key",
"is",
"a",
"list"
] | 99c9241cb666a92be218eb8f61a9e2fb7efee1d9 | https://github.com/christophebe/crawler.ninja/blob/99c9241cb666a92be218eb8f61a9e2fb7efee1d9/plugins/audit-plugin.js#L319-L336 | train |
|
Gozala/test-commonjs | assert.js | AssertionError | 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 ("operator" in options)
assertionError.operator = options.operator;
assertionError.message = options.message;
assertionError.stack = new Error().stack;
return assertionError;
} | javascript | 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 ("operator" in options)
assertionError.operator = options.operator;
assertionError.message = options.message;
assertionError.stack = new Error().stack;
return assertionError;
} | [
"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",
"(",
"\"operator\"",
"in",
"options",
")",
"assertionError",
".",
"operator",
"=",
"options",
".",
"operator",
";",
"assertionError",
".",
"message",
"=",
"options",
".",
"message",
";",
"assertionError",
".",
"stack",
"=",
"new",
"Error",
"(",
")",
".",
"stack",
";",
"return",
"assertionError",
";",
"}"
] | The `AssertionError` is defined in assert.
@extends Error
@example
new assert.AssertionError({
message: message,
actual: actual,
expected: expected
}) | [
"The",
"AssertionError",
"is",
"defined",
"in",
"assert",
"."
] | db9821e28ef2289149f20d0e07b91d1caa7a15fd | https://github.com/Gozala/test-commonjs/blob/db9821e28ef2289149f20d0e07b91d1caa7a15fd/assert.js#L16-L31 | train |
Gozala/test-commonjs | assert.js | equal | function equal(actual, expected, message) {
if (actual == expected) {
this.pass(message);
}
else {
this.fail({
actual: actual,
expected: expected,
message: message,
operator: "=="
});
}
} | javascript | function equal(actual, expected, message) {
if (actual == expected) {
this.pass(message);
}
else {
this.fail({
actual: actual,
expected: expected,
message: message,
operator: "=="
});
}
} | [
"function",
"equal",
"(",
"actual",
",",
"expected",
",",
"message",
")",
"{",
"if",
"(",
"actual",
"==",
"expected",
")",
"{",
"this",
".",
"pass",
"(",
"message",
")",
";",
"}",
"else",
"{",
"this",
".",
"fail",
"(",
"{",
"actual",
":",
"actual",
",",
"expected",
":",
"expected",
",",
"message",
":",
"message",
",",
"operator",
":",
"\"==\"",
"}",
")",
";",
"}",
"}"
] | The equality assertion tests shallow, coercive equality with `==`.
@example
assert.equal(1, 1, "one is one"); | [
"The",
"equality",
"assertion",
"tests",
"shallow",
"coercive",
"equality",
"with",
"==",
"."
] | db9821e28ef2289149f20d0e07b91d1caa7a15fd | https://github.com/Gozala/test-commonjs/blob/db9821e28ef2289149f20d0e07b91d1caa7a15fd/assert.js#L85-L97 | train |
Gozala/test-commonjs | assert.js | notEqual | function notEqual(actual, expected, message) {
if (actual != expected) {
this.pass(message);
}
else {
this.fail({
actual: actual,
expected: expected,
message: message,
operator: "!=",
});
}
} | javascript | function notEqual(actual, expected, message) {
if (actual != expected) {
this.pass(message);
}
else {
this.fail({
actual: actual,
expected: expected,
message: message,
operator: "!=",
});
}
} | [
"function",
"notEqual",
"(",
"actual",
",",
"expected",
",",
"message",
")",
"{",
"if",
"(",
"actual",
"!=",
"expected",
")",
"{",
"this",
".",
"pass",
"(",
"message",
")",
";",
"}",
"else",
"{",
"this",
".",
"fail",
"(",
"{",
"actual",
":",
"actual",
",",
"expected",
":",
"expected",
",",
"message",
":",
"message",
",",
"operator",
":",
"\"!=\"",
",",
"}",
")",
";",
"}",
"}"
] | The non-equality assertion tests for whether two objects are not equal
with `!=`.
@example
assert.notEqual(1, 2, "one is not two"); | [
"The",
"non",
"-",
"equality",
"assertion",
"tests",
"for",
"whether",
"two",
"objects",
"are",
"not",
"equal",
"with",
"!",
"=",
"."
] | db9821e28ef2289149f20d0e07b91d1caa7a15fd | https://github.com/Gozala/test-commonjs/blob/db9821e28ef2289149f20d0e07b91d1caa7a15fd/assert.js#L105-L117 | train |
Gozala/test-commonjs | assert.js | notStrictEqual | function notStrictEqual(actual, expected, message) {
if (actual !== expected) {
this.pass(message);
}
else {
this.fail({
actual: actual,
expected: expected,
message: message,
operator: "!=="
})
}
} | javascript | function notStrictEqual(actual, expected, message) {
if (actual !== expected) {
this.pass(message);
}
else {
this.fail({
actual: actual,
expected: expected,
message: message,
operator: "!=="
})
}
} | [
"function",
"notStrictEqual",
"(",
"actual",
",",
"expected",
",",
"message",
")",
"{",
"if",
"(",
"actual",
"!==",
"expected",
")",
"{",
"this",
".",
"pass",
"(",
"message",
")",
";",
"}",
"else",
"{",
"this",
".",
"fail",
"(",
"{",
"actual",
":",
"actual",
",",
"expected",
":",
"expected",
",",
"message",
":",
"message",
",",
"operator",
":",
"\"!==\"",
"}",
")",
"}",
"}"
] | The strict non-equality assertion tests for strict inequality, as
determined by `!==`.
@example
assert.notStrictEqual(null, undefined, "`null` is not `undefined`"); | [
"The",
"strict",
"non",
"-",
"equality",
"assertion",
"tests",
"for",
"strict",
"inequality",
"as",
"determined",
"by",
"!",
"==",
"."
] | db9821e28ef2289149f20d0e07b91d1caa7a15fd | https://github.com/Gozala/test-commonjs/blob/db9821e28ef2289149f20d0e07b91d1caa7a15fd/assert.js#L184-L196 | train |
flowxo/flowxo-sdk | tasks/lib/auth.js | function(obj) {
var cloned = {};
for(var key in obj) {
if(obj.hasOwnProperty(key)) {
cloned[key] = obj[key];
}
}
return cloned;
} | javascript | function(obj) {
var cloned = {};
for(var key in obj) {
if(obj.hasOwnProperty(key)) {
cloned[key] = obj[key];
}
}
return cloned;
} | [
"function",
"(",
"obj",
")",
"{",
"var",
"cloned",
"=",
"{",
"}",
";",
"for",
"(",
"var",
"key",
"in",
"obj",
")",
"{",
"if",
"(",
"obj",
".",
"hasOwnProperty",
"(",
"key",
")",
")",
"{",
"cloned",
"[",
"key",
"]",
"=",
"obj",
"[",
"key",
"]",
";",
"}",
"}",
"return",
"cloned",
";",
"}"
] | Return a clone of an object | [
"Return",
"a",
"clone",
"of",
"an",
"object"
] | 8f71dbfb25a8b57591f5c4df09937289d5c8356b | https://github.com/flowxo/flowxo-sdk/blob/8f71dbfb25a8b57591f5c4df09937289d5c8356b/tasks/lib/auth.js#L24-L32 | train |
|
maxvyaznikov/imapseagull | lib/plugins/condstore.js | function(prevHandler, connection, parsed, data, callback) {
if (hasCondstoreOption(parsed.attributes && parsed.attributes[1], parsed.attributes, 1)) {
connection.sessionCondstore = true;
} else if ('sessionCondstore' in connection) {
connection.sessionCondstore = false;
}
prevHandler(connection, parsed, data, callback);
} | javascript | function(prevHandler, connection, parsed, data, callback) {
if (hasCondstoreOption(parsed.attributes && parsed.attributes[1], parsed.attributes, 1)) {
connection.sessionCondstore = true;
} else if ('sessionCondstore' in connection) {
connection.sessionCondstore = false;
}
prevHandler(connection, parsed, data, callback);
} | [
"function",
"(",
"prevHandler",
",",
"connection",
",",
"parsed",
",",
"data",
",",
"callback",
")",
"{",
"if",
"(",
"hasCondstoreOption",
"(",
"parsed",
".",
"attributes",
"&&",
"parsed",
".",
"attributes",
"[",
"1",
"]",
",",
"parsed",
".",
"attributes",
",",
"1",
")",
")",
"{",
"connection",
".",
"sessionCondstore",
"=",
"true",
";",
"}",
"else",
"if",
"(",
"'sessionCondstore'",
"in",
"connection",
")",
"{",
"connection",
".",
"sessionCondstore",
"=",
"false",
";",
"}",
"prevHandler",
"(",
"connection",
",",
"parsed",
",",
"data",
",",
"callback",
")",
";",
"}"
] | Override SELECT and EXAMINE to add | [
"Override",
"SELECT",
"and",
"EXAMINE",
"to",
"add"
] | 44949b7a338b4c0ace3ef7bb95a77c4794462bda | https://github.com/maxvyaznikov/imapseagull/blob/44949b7a338b4c0ace3ef7bb95a77c4794462bda/lib/plugins/condstore.js#L34-L41 | train |
|
huafu/ember-google-map | addon/components/google-map.js | 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)) {
// it's an array of lat,lng
coords = coords.slice();
if (get$(coords, 'length')) {
bounds = new google.maps.LatLngBounds(helpers._latLngToGoogle(coords.shift()));
forEach(coords, function (point) {
bounds.extend(helpers._latLngToGoogle(point));
});
}
else {
return;
}
}
else {
// it's a bound object
bounds = helpers._boundsToGoogle(coords);
}
if (bounds) {
// finally make our map to fit
map.fitBounds(bounds);
}
} | javascript | 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)) {
// it's an array of lat,lng
coords = coords.slice();
if (get$(coords, 'length')) {
bounds = new google.maps.LatLngBounds(helpers._latLngToGoogle(coords.shift()));
forEach(coords, function (point) {
bounds.extend(helpers._latLngToGoogle(point));
});
}
else {
return;
}
}
else {
// it's a bound object
bounds = helpers._boundsToGoogle(coords);
}
if (bounds) {
// finally make our map to fit
map.fitBounds(bounds);
}
} | [
"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",
")",
")",
"{",
"coords",
"=",
"coords",
".",
"slice",
"(",
")",
";",
"if",
"(",
"get$",
"(",
"coords",
",",
"'length'",
")",
")",
"{",
"bounds",
"=",
"new",
"google",
".",
"maps",
".",
"LatLngBounds",
"(",
"helpers",
".",
"_latLngToGoogle",
"(",
"coords",
".",
"shift",
"(",
")",
")",
")",
";",
"forEach",
"(",
"coords",
",",
"function",
"(",
"point",
")",
"{",
"bounds",
".",
"extend",
"(",
"helpers",
".",
"_latLngToGoogle",
"(",
"point",
")",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"return",
";",
"}",
"}",
"else",
"{",
"bounds",
"=",
"helpers",
".",
"_boundsToGoogle",
"(",
"coords",
")",
";",
"}",
"if",
"(",
"bounds",
")",
"{",
"map",
".",
"fitBounds",
"(",
"bounds",
")",
";",
"}",
"}"
] | Fit the bounds to contain given coordinates
@method _fitBounds | [
"Fit",
"the",
"bounds",
"to",
"contain",
"given",
"coordinates"
] | c454e893ff0ca196fdac684e8369981e985d5619 | https://github.com/huafu/ember-google-map/blob/c454e893ff0ca196fdac684e8369981e985d5619/addon/components/google-map.js#L486-L521 | train |
|
rfrench/poster | lib/poster.js | head | 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;
var contentType = res.headers['content-type'].split(';')[0];
//attempt to get the filename from the url
file = sanitizeFileName(path.basename(url.pathname));
if (file) {
ext = path.extname(file);
file = file.replace(ext, '');
ext = ext.replace('.', '');
if (ext) {
mimeExt = mimetypes.extension(contentType);
if (mimeExt) {
if (ext.toLowerCase() !== '.' + mimeExt.toLowerCase()) {
ext = mimeExt;
}
}
}
}
//default file name if we couldn't parse one
if (!file) { file = 'poster'; }
//default file extension if we cannot find one (unlikely)
if (!ext) {
ext = 'unk';
if (contentType) {
mimeExt = mimetypes.extension(contentType);
if (mimeExt) {
ext = mimeExt;
}
}
}
return callback(null, url, contentLength, file + '.' + ext);
}
catch (e) {
callback(e);
}
});
req.on('error', function(e) {
callback(e);
});
req.end();
} | javascript | 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;
var contentType = res.headers['content-type'].split(';')[0];
//attempt to get the filename from the url
file = sanitizeFileName(path.basename(url.pathname));
if (file) {
ext = path.extname(file);
file = file.replace(ext, '');
ext = ext.replace('.', '');
if (ext) {
mimeExt = mimetypes.extension(contentType);
if (mimeExt) {
if (ext.toLowerCase() !== '.' + mimeExt.toLowerCase()) {
ext = mimeExt;
}
}
}
}
//default file name if we couldn't parse one
if (!file) { file = 'poster'; }
//default file extension if we cannot find one (unlikely)
if (!ext) {
ext = 'unk';
if (contentType) {
mimeExt = mimetypes.extension(contentType);
if (mimeExt) {
ext = mimeExt;
}
}
}
return callback(null, url, contentLength, file + '.' + ext);
}
catch (e) {
callback(e);
}
});
req.on('error', function(e) {
callback(e);
});
req.end();
} | [
"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",
")",
")",
"{",
"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",
")",
";",
"}",
"if",
"(",
"uploadOptions",
".",
"downloadFileName",
")",
"{",
"return",
"callback",
"(",
"null",
",",
"url",
",",
"contentLength",
",",
"uploadOptions",
".",
"downloadFileName",
")",
";",
"}",
"var",
"file",
",",
"ext",
",",
"mimeExt",
";",
"var",
"contentType",
"=",
"res",
".",
"headers",
"[",
"'content-type'",
"]",
".",
"split",
"(",
"';'",
")",
"[",
"0",
"]",
";",
"file",
"=",
"sanitizeFileName",
"(",
"path",
".",
"basename",
"(",
"url",
".",
"pathname",
")",
")",
";",
"if",
"(",
"file",
")",
"{",
"ext",
"=",
"path",
".",
"extname",
"(",
"file",
")",
";",
"file",
"=",
"file",
".",
"replace",
"(",
"ext",
",",
"''",
")",
";",
"ext",
"=",
"ext",
".",
"replace",
"(",
"'.'",
",",
"''",
")",
";",
"if",
"(",
"ext",
")",
"{",
"mimeExt",
"=",
"mimetypes",
".",
"extension",
"(",
"contentType",
")",
";",
"if",
"(",
"mimeExt",
")",
"{",
"if",
"(",
"ext",
".",
"toLowerCase",
"(",
")",
"!==",
"'.'",
"+",
"mimeExt",
".",
"toLowerCase",
"(",
")",
")",
"{",
"ext",
"=",
"mimeExt",
";",
"}",
"}",
"}",
"}",
"if",
"(",
"!",
"file",
")",
"{",
"file",
"=",
"'poster'",
";",
"}",
"if",
"(",
"!",
"ext",
")",
"{",
"ext",
"=",
"'unk'",
";",
"if",
"(",
"contentType",
")",
"{",
"mimeExt",
"=",
"mimetypes",
".",
"extension",
"(",
"contentType",
")",
";",
"if",
"(",
"mimeExt",
")",
"{",
"ext",
"=",
"mimeExt",
";",
"}",
"}",
"}",
"return",
"callback",
"(",
"null",
",",
"url",
",",
"contentLength",
",",
"file",
"+",
"'.'",
"+",
"ext",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"callback",
"(",
"e",
")",
";",
"}",
"}",
")",
";",
"req",
".",
"on",
"(",
"'error'",
",",
"function",
"(",
"e",
")",
"{",
"callback",
"(",
"e",
")",
";",
"}",
")",
";",
"req",
".",
"end",
"(",
")",
";",
"}"
] | this function is kind of hacky, but since not all web servers support chunked
encoding and we DO NOT want to buffer any of the file we're downloading into memory,
this is how we get around this so we can calculate the content-length. while this
does indeed slow down the upload, it does save us some time if the file doesn't exist
on the remote web server of if maxFileSize is provided, we can bail out if it's too large | [
"this",
"function",
"is",
"kind",
"of",
"hacky",
"but",
"since",
"not",
"all",
"web",
"servers",
"support",
"chunked",
"encoding",
"and",
"we",
"DO",
"NOT",
"want",
"to",
"buffer",
"any",
"of",
"the",
"file",
"we",
"re",
"downloading",
"into",
"memory",
"this",
"is",
"how",
"we",
"get",
"around",
"this",
"so",
"we",
"can",
"calculate",
"the",
"content",
"-",
"length",
".",
"while",
"this",
"does",
"indeed",
"slow",
"down",
"the",
"upload",
"it",
"does",
"save",
"us",
"some",
"time",
"if",
"the",
"file",
"doesn",
"t",
"exist",
"on",
"the",
"remote",
"web",
"server",
"of",
"if",
"maxFileSize",
"is",
"provided",
"we",
"can",
"bail",
"out",
"if",
"it",
"s",
"too",
"large"
] | 0e857e43e86e6cf412cc149210b522a26e95d962 | https://github.com/rfrench/poster/blob/0e857e43e86e6cf412cc149210b522a26e95d962/lib/poster.js#L90-L173 | train |
nozzle/nzTour | dist/nz-tour.js | 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) {
return false;
}
}
return true;
} | javascript | 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) {
return false;
}
}
return true;
} | [
"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",
")",
"{",
"return",
"false",
";",
"}",
"}",
"return",
"true",
";",
"}"
] | Check for valid priorities | [
"Check",
"for",
"valid",
"priorities"
] | 81d6e7f907f332cc599d94caae943572cfbf67eb | https://github.com/nozzle/nzTour/blob/81d6e7f907f332cc599d94caae943572cfbf67eb/dist/nz-tour.js#L136-L144 | train |
|
vigour-io/vjs | lib/methods/flatten.js | 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)
for (var key in flattened) {
if (key.indexOf('.val') > 0) {
var newKey = key.split('.val')[0]
flattened[newKey] = flattened[key]
delete flattened[key]
}
}
return flattened
} | javascript | 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)
for (var key in flattened) {
if (key.indexOf('.val') > 0) {
var newKey = key.split('.val')[0]
flattened[newKey] = flattened[key]
delete flattened[key]
}
}
return flattened
} | [
"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",
"}",
"var",
"flattened",
"=",
"flatten",
"(",
"obj",
")",
"for",
"(",
"var",
"key",
"in",
"flattened",
")",
"{",
"if",
"(",
"key",
".",
"indexOf",
"(",
"'.val'",
")",
">",
"0",
")",
"{",
"var",
"newKey",
"=",
"key",
".",
"split",
"(",
"'.val'",
")",
"[",
"0",
"]",
"flattened",
"[",
"newKey",
"]",
"=",
"flattened",
"[",
"key",
"]",
"delete",
"flattened",
"[",
"key",
"]",
"}",
"}",
"return",
"flattened",
"}"
] | Flatten a `Base` object
@memberOf Base#
@return {object} | [
"Flatten",
"a",
"Base",
"object"
] | f70ea438e381f225042d9a6b4e321faffcc97305 | https://github.com/vigour-io/vjs/blob/f70ea438e381f225042d9a6b4e321faffcc97305/lib/methods/flatten.js#L12-L39 | train |
|
vigour-io/vjs | lib/base/property.js | custom | 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
properties[property.override] = properties[key]
} else {
this[key] = properties[key] = prototype
prototype._parent = this
}
} else {
if (property.override) {
properties[key] = Properties.createPrimitiveProperty(property.override)
} else {
properties[key] = Properties.default
}
properties[key].call(this, property.val, void 0, void 0, key)
}
} else if (key !== '_overrides') {
if (property.type) {
let res = this.getType(property, event, key, void 0)
if (res instanceof Base) {
properties[key] = Properties
.createPropertyConstructor(new res.Constructor(property, false, this, key).Constructor, key)
return
}
}
properties[key] = Properties
.createPropertyConstructor(new this.Child(property, false, this, key).Constructor, key)
}
} | javascript | 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
properties[property.override] = properties[key]
} else {
this[key] = properties[key] = prototype
prototype._parent = this
}
} else {
if (property.override) {
properties[key] = Properties.createPrimitiveProperty(property.override)
} else {
properties[key] = Properties.default
}
properties[key].call(this, property.val, void 0, void 0, key)
}
} else if (key !== '_overrides') {
if (property.type) {
let res = this.getType(property, event, key, void 0)
if (res instanceof Base) {
properties[key] = Properties
.createPropertyConstructor(new res.Constructor(property, false, this, key).Constructor, key)
return
}
}
properties[key] = Properties
.createPropertyConstructor(new this.Child(property, false, this, key).Constructor, key)
}
} | [
"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",
"properties",
"[",
"property",
".",
"override",
"]",
"=",
"properties",
"[",
"key",
"]",
"}",
"else",
"{",
"this",
"[",
"key",
"]",
"=",
"properties",
"[",
"key",
"]",
"=",
"prototype",
"prototype",
".",
"_parent",
"=",
"this",
"}",
"}",
"else",
"{",
"if",
"(",
"property",
".",
"override",
")",
"{",
"properties",
"[",
"key",
"]",
"=",
"Properties",
".",
"createPrimitiveProperty",
"(",
"property",
".",
"override",
")",
"}",
"else",
"{",
"properties",
"[",
"key",
"]",
"=",
"Properties",
".",
"default",
"}",
"properties",
"[",
"key",
"]",
".",
"call",
"(",
"this",
",",
"property",
".",
"val",
",",
"void",
"0",
",",
"void",
"0",
",",
"key",
")",
"}",
"}",
"else",
"if",
"(",
"key",
"!==",
"'_overrides'",
")",
"{",
"if",
"(",
"property",
".",
"type",
")",
"{",
"let",
"res",
"=",
"this",
".",
"getType",
"(",
"property",
",",
"event",
",",
"key",
",",
"void",
"0",
")",
"if",
"(",
"res",
"instanceof",
"Base",
")",
"{",
"properties",
"[",
"key",
"]",
"=",
"Properties",
".",
"createPropertyConstructor",
"(",
"new",
"res",
".",
"Constructor",
"(",
"property",
",",
"false",
",",
"this",
",",
"key",
")",
".",
"Constructor",
",",
"key",
")",
"return",
"}",
"}",
"properties",
"[",
"key",
"]",
"=",
"Properties",
".",
"createPropertyConstructor",
"(",
"new",
"this",
".",
"Child",
"(",
"property",
",",
"false",
",",
"this",
",",
"key",
")",
".",
"Constructor",
",",
"key",
")",
"}",
"}"
] | make an easy option to use childconstrucor for val | [
"make",
"an",
"easy",
"option",
"to",
"use",
"childconstrucor",
"for",
"val"
] | f70ea438e381f225042d9a6b4e321faffcc97305 | https://github.com/vigour-io/vjs/blob/f70ea438e381f225042d9a6b4e321faffcc97305/lib/base/property.js#L159-L197 | train |
Joris-van-der-Wel/node-pg-large-object | lib/LargeObject.js | LargeObject | function LargeObject(query, oid, fd)
{
this._query = query;
this.oid = oid;
this._fd = fd;
} | javascript | function LargeObject(query, oid, fd)
{
this._query = query;
this.oid = oid;
this._fd = fd;
} | [
"function",
"LargeObject",
"(",
"query",
",",
"oid",
",",
"fd",
")",
"{",
"this",
".",
"_query",
"=",
"query",
";",
"this",
".",
"oid",
"=",
"oid",
";",
"this",
".",
"_fd",
"=",
"fd",
";",
"}"
] | Represents an opened large object.
@constructor
@exports pg-large-object/lib/LargeObject | [
"Represents",
"an",
"opened",
"large",
"object",
"."
] | 54484690e72fe3242faf6aa7c39c31a4eb5b7f24 | https://github.com/Joris-van-der-Wel/node-pg-large-object/blob/54484690e72fe3242faf6aa7c39c31a4eb5b7f24/lib/LargeObject.js#L13-L18 | train |
JedWatson/html-stringify | lib/htmlStringify.js | htmlStringify | 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 rtn = '',
len = Object.keys(obj).length;
if (fromRecur && !len) {
return '<' + tag + ' style="color: #999; cursor: default;">Object: {}</' + tag + '>';
}
if (fromRecur) {
rtn += '<' + tag + ' style="color: #0b89b6">Object: {</' + tag + '><div class="_stringify_recur _stringify_recur_level_' + fromRecur + '" style="padding-left: 20px;">';
}
for (var key in obj) {
if (typeof obj[key] != 'function') {
rtn += '<div><span style="padding-right: 5px; cursor: default;">' +key + ':</span>' + htmlStringify(obj[key], nextLevel) + '</div>';
}
}
if (fromRecur) {
rtn += '</div><' + tag + ' style="color: #0b89b6; cursor: default;">}</' + tag + '>';
}
return rtn;
}
return '';
} | javascript | 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 rtn = '',
len = Object.keys(obj).length;
if (fromRecur && !len) {
return '<' + tag + ' style="color: #999; cursor: default;">Object: {}</' + tag + '>';
}
if (fromRecur) {
rtn += '<' + tag + ' style="color: #0b89b6">Object: {</' + tag + '><div class="_stringify_recur _stringify_recur_level_' + fromRecur + '" style="padding-left: 20px;">';
}
for (var key in obj) {
if (typeof obj[key] != 'function') {
rtn += '<div><span style="padding-right: 5px; cursor: default;">' +key + ':</span>' + htmlStringify(obj[key], nextLevel) + '</div>';
}
}
if (fromRecur) {
rtn += '</div><' + tag + ' style="color: #0b89b6; cursor: default;">}</' + tag + '>';
}
return rtn;
}
return '';
} | [
"function",
"htmlStringify",
"(",
"obj",
",",
"fromRecur",
")",
"{",
"var",
"tag",
"=",
"(",
"fromRecur",
")",
"?",
"'span'",
":",
"'div'",
";",
"var",
"nextLevel",
"=",
"(",
"fromRecur",
"||",
"0",
")",
"+",
"1",
";",
"if",
"(",
"typeof",
"obj",
"==",
"'string'",
")",
"{",
"return",
"'<'",
"+",
"tag",
"+",
"' style=\"color: #0e4889; cursor: default;\">\"'",
"+",
"obj",
"+",
"'\"</'",
"+",
"tag",
"+",
"'>'",
";",
"}",
"else",
"if",
"(",
"typeof",
"obj",
"==",
"'boolean'",
"||",
"obj",
"===",
"null",
"||",
"obj",
"===",
"undefined",
")",
"{",
"return",
"'<'",
"+",
"tag",
"+",
"'><em style=\"color: #06624b; cursor: default;\">'",
"+",
"obj",
"+",
"'</em></'",
"+",
"tag",
"+",
"'>'",
";",
"}",
"else",
"if",
"(",
"typeof",
"obj",
"==",
"'number'",
")",
"{",
"return",
"'<'",
"+",
"tag",
"+",
"' style=\"color: #ca000a; cursor: default;\">'",
"+",
"obj",
"+",
"'</'",
"+",
"tag",
"+",
"'>'",
";",
"}",
"else",
"if",
"(",
"Object",
".",
"prototype",
".",
"toString",
".",
"call",
"(",
"obj",
")",
"==",
"'[object Date]'",
")",
"{",
"return",
"'<'",
"+",
"tag",
"+",
"' style=\"color: #009f7b; cursor: default;\">'",
"+",
"obj",
"+",
"'</'",
"+",
"tag",
"+",
"'>'",
";",
"}",
"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",
")",
";",
"if",
"(",
"i",
"<",
"obj",
".",
"length",
"-",
"1",
")",
"{",
"rtn",
"+=",
"', <br>'",
";",
"}",
"}",
"return",
"rtn",
"+",
"'</div><'",
"+",
"tag",
"+",
"' style=\"color: #666\">]</'",
"+",
"tag",
"+",
"'>'",
";",
"}",
"else",
"if",
"(",
"obj",
"&&",
"typeof",
"obj",
"==",
"'object'",
")",
"{",
"var",
"rtn",
"=",
"''",
",",
"len",
"=",
"Object",
".",
"keys",
"(",
"obj",
")",
".",
"length",
";",
"if",
"(",
"fromRecur",
"&&",
"!",
"len",
")",
"{",
"return",
"'<'",
"+",
"tag",
"+",
"' style=\"color: #999; cursor: default;\">Object: {}</'",
"+",
"tag",
"+",
"'>'",
";",
"}",
"if",
"(",
"fromRecur",
")",
"{",
"rtn",
"+=",
"'<'",
"+",
"tag",
"+",
"' style=\"color: #0b89b6\">Object: {</'",
"+",
"tag",
"+",
"'><div class=\"_stringify_recur _stringify_recur_level_'",
"+",
"fromRecur",
"+",
"'\" style=\"padding-left: 20px;\">'",
";",
"}",
"for",
"(",
"var",
"key",
"in",
"obj",
")",
"{",
"if",
"(",
"typeof",
"obj",
"[",
"key",
"]",
"!=",
"'function'",
")",
"{",
"rtn",
"+=",
"'<div><span style=\"padding-right: 5px; cursor: default;\">'",
"+",
"key",
"+",
"':</span>'",
"+",
"htmlStringify",
"(",
"obj",
"[",
"key",
"]",
",",
"nextLevel",
")",
"+",
"'</div>'",
";",
"}",
"}",
"if",
"(",
"fromRecur",
")",
"{",
"rtn",
"+=",
"'</div><'",
"+",
"tag",
"+",
"' style=\"color: #0b89b6; cursor: default;\">}</'",
"+",
"tag",
"+",
"'>'",
";",
"}",
"return",
"rtn",
";",
"}",
"return",
"''",
";",
"}"
] | Renders an object as formatted HTML
@param {Object} obj
@return {String} html
@api public | [
"Renders",
"an",
"object",
"as",
"formatted",
"HTML"
] | 7e6da7bedf28a2a724a7e32a20e406929a308090 | https://github.com/JedWatson/html-stringify/blob/7e6da7bedf28a2a724a7e32a20e406929a308090/lib/htmlStringify.js#L9-L81 | train |
repetere/stylie.treeview | lib/stylie.treeview.js | function (options) {
events.EventEmitter.call(this);
var defaultOptions = {
tree: {}
};
this.options = extend(defaultOptions, options);
// this.getTreeHTML = this.getTreeHTML;
} | javascript | function (options) {
events.EventEmitter.call(this);
var defaultOptions = {
tree: {}
};
this.options = extend(defaultOptions, options);
// this.getTreeHTML = this.getTreeHTML;
} | [
"function",
"(",
"options",
")",
"{",
"events",
".",
"EventEmitter",
".",
"call",
"(",
"this",
")",
";",
"var",
"defaultOptions",
"=",
"{",
"tree",
":",
"{",
"}",
"}",
";",
"this",
".",
"options",
"=",
"extend",
"(",
"defaultOptions",
",",
"options",
")",
";",
"}"
] | A module that represents a StylieTreeviews object, a componentTab is a page composition tool.
@{@link https://github.com/typesettin/stylie.treeview}
@author Yaw Joseph Etse
@copyright Copyright (c) 2015 Typesettin. All rights reserved.
@license MIT
@constructor StylieTreeviews
@requires module:util-extent
@requires module:util
@requires module:events
@param {object} el element of tab container
@param {object} options configuration options | [
"A",
"module",
"that",
"represents",
"a",
"StylieTreeviews",
"object",
"a",
"componentTab",
"is",
"a",
"page",
"composition",
"tool",
"."
] | 60889f1845c0c152ab105f7a801cb42a24c2580e | https://github.com/repetere/stylie.treeview/blob/60889f1845c0c152ab105f7a801cb42a24c2580e/lib/stylie.treeview.js#L26-L34 | train |
|
bbraithwaite/omdb-client | lib/search.js | 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)) {
return {
error: 'type must be: movie, series, episode.'
};
}
if (params.hasOwnProperty('year') && !validator.isNumber(params.year)) {
return {
error: 'year must be a valid number'
};
}
} | javascript | 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)) {
return {
error: 'type must be: movie, series, episode.'
};
}
if (params.hasOwnProperty('year') && !validator.isNumber(params.year)) {
return {
error: 'year must be a valid number'
};
}
} | [
"function",
"(",
"params",
")",
"{",
"if",
"(",
"!",
"params",
")",
"{",
"return",
"{",
"error",
":",
"'params cannot be null.'",
"}",
";",
"}",
"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",
")",
")",
"{",
"return",
"{",
"error",
":",
"'type must be: movie, series, episode.'",
"}",
";",
"}",
"if",
"(",
"params",
".",
"hasOwnProperty",
"(",
"'year'",
")",
"&&",
"!",
"validator",
".",
"isNumber",
"(",
"params",
".",
"year",
")",
")",
"{",
"return",
"{",
"error",
":",
"'year must be a valid number'",
"}",
";",
"}",
"}"
] | Validate the parameters for the search request.
@param {Object} params
@return {Object} validation state
@api private | [
"Validate",
"the",
"parameters",
"for",
"the",
"search",
"request",
"."
] | 55ad54606d56d98852895f8f7bd5082f62dca569 | https://github.com/bbraithwaite/omdb-client/blob/55ad54606d56d98852895f8f7bd5082f62dca569/lib/search.js#L17-L50 | train |
|
bbraithwaite/omdb-client | lib/search.js | 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) {
query += '&type='.concat(params.type);
}
if (params.apiKey) {
query += '&apikey='.concat(params.apiKey);
}
return baseUrl.concat(query, '&r=json&v=1');
} | javascript | 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) {
query += '&type='.concat(params.type);
}
if (params.apiKey) {
query += '&apikey='.concat(params.apiKey);
}
return baseUrl.concat(query, '&r=json&v=1');
} | [
"function",
"(",
"params",
")",
"{",
"var",
"baseUrl",
"=",
"'http://www.omdbapi.com/'",
";",
"var",
"query",
"=",
"'?'",
";",
"query",
"+=",
"'s='",
".",
"concat",
"(",
"encodeURIComponent",
"(",
"params",
".",
"query",
")",
")",
";",
"if",
"(",
"params",
".",
"year",
")",
"{",
"query",
"+=",
"'&y='",
".",
"concat",
"(",
"params",
".",
"year",
")",
";",
"}",
"if",
"(",
"params",
".",
"type",
")",
"{",
"query",
"+=",
"'&type='",
".",
"concat",
"(",
"params",
".",
"type",
")",
";",
"}",
"if",
"(",
"params",
".",
"apiKey",
")",
"{",
"query",
"+=",
"'&apikey='",
".",
"concat",
"(",
"params",
".",
"apiKey",
")",
";",
"}",
"return",
"baseUrl",
".",
"concat",
"(",
"query",
",",
"'&r=json&v=1'",
")",
";",
"}"
] | Build the url string from the parameters.
@param {Object} params
@return {String} url to call omdbapi.com
@api private | [
"Build",
"the",
"url",
"string",
"from",
"the",
"parameters",
"."
] | 55ad54606d56d98852895f8f7bd5082f62dca569 | https://github.com/bbraithwaite/omdb-client/blob/55ad54606d56d98852895f8f7bd5082f62dca569/lib/search.js#L59-L80 | train |
|
jaredhanson/node-notifications | lib/notifications/notification.js | Notification | function Notification(name, object, info) {
this.name = name;
this.object = object;
this.info = info;
} | javascript | function Notification(name, object, info) {
this.name = name;
this.object = object;
this.info = info;
} | [
"function",
"Notification",
"(",
"name",
",",
"object",
",",
"info",
")",
"{",
"this",
".",
"name",
"=",
"name",
";",
"this",
".",
"object",
"=",
"object",
";",
"this",
".",
"info",
"=",
"info",
";",
"}"
] | `Notification` constructor.
A `Notification` encapsulates information so that it can be broadcast to
other objects via a `NotificationCenter`. A notification contains a `name`,
`object`, and optional `info` hash. The `name` is a string that uniquely
identifies the type of notification. The `object` is any object that the
poster of the notification wants to send to the observers (typically, it is
the object that posted the notification). The `info` is any related
information, if any, contained in an object literal.
Examples:
new Notification('myClass.interestingEvent', this);
new Notification('myClass.otherInterestingEvent', this, { foo: 'bar' });
@param {String} name
@param {Object} object
@param {Object} info
@api public | [
"Notification",
"constructor",
"."
] | aeb15eca33ced56c59050c952389bc3fa82743e8 | https://github.com/jaredhanson/node-notifications/blob/aeb15eca33ced56c59050c952389bc3fa82743e8/lib/notifications/notification.js#L23-L27 | train |
sjwilliams/grunt-responsive-videos | tasks/responsive_videos.js | getName | function getName(name, width, separator) {
// handle empty separator as no separator
if (typeof separator === 'undefined') {
separator = '';
}
if (name) {
return separator + name;
} else {
return separator + width;
}
} | javascript | function getName(name, width, separator) {
// handle empty separator as no separator
if (typeof separator === 'undefined') {
separator = '';
}
if (name) {
return separator + name;
} else {
return separator + width;
}
} | [
"function",
"getName",
"(",
"name",
",",
"width",
",",
"separator",
")",
"{",
"if",
"(",
"typeof",
"separator",
"===",
"'undefined'",
")",
"{",
"separator",
"=",
"''",
";",
"}",
"if",
"(",
"name",
")",
"{",
"return",
"separator",
"+",
"name",
";",
"}",
"else",
"{",
"return",
"separator",
"+",
"width",
";",
"}",
"}"
] | create a name to suffix to our file. | [
"create",
"a",
"name",
"to",
"suffix",
"to",
"our",
"file",
"."
] | 1519b66f70374bcbce593d2882621c511273da3a | https://github.com/sjwilliams/grunt-responsive-videos/blob/1519b66f70374bcbce593d2882621c511273da3a/tasks/responsive_videos.js#L75-L87 | train |
jcassee/angular-hypermedia | dist/hypermedia.js | BlobResource | function BlobResource(uri, context) {
var instance = Resource.call(this, uri, context);
/**
* The resource data.
*
* @type {Blob}
*/
instance.data = '';
return instance;
} | javascript | function BlobResource(uri, context) {
var instance = Resource.call(this, uri, context);
/**
* The resource data.
*
* @type {Blob}
*/
instance.data = '';
return instance;
} | [
"function",
"BlobResource",
"(",
"uri",
",",
"context",
")",
"{",
"var",
"instance",
"=",
"Resource",
".",
"call",
"(",
"this",
",",
"uri",
",",
"context",
")",
";",
"instance",
".",
"data",
"=",
"''",
";",
"return",
"instance",
";",
"}"
] | Resource with a media type and some data.
@constructor
@param {string} uri the resource URI
@param {ResourceContext} context the context object | [
"Resource",
"with",
"a",
"media",
"type",
"and",
"some",
"data",
"."
] | 6e68d210bf1ca081ace95a01ff0ad9148aa4e7cc | https://github.com/jcassee/angular-hypermedia/blob/6e68d210bf1ca081ace95a01ff0ad9148aa4e7cc/dist/hypermedia.js#L33-L44 | train |
jcassee/angular-hypermedia | dist/hypermedia.js | extractAndUpdateResources | 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};
});
}
// Recurse into embedded resource
forArray(embeds, function (embedded) {
resources = resources.concat(extractAndUpdateResources(embedded, {}, rootResource, null));
});
});
delete data._embedded;
// Update resource
if (!resource) resource = rootResource.$context.get(links.self.href, rootResource.constructor);
Resource.prototype.$update.call(resource, data, links);
resources.push(resource);
return resources;
} | javascript | 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};
});
}
// Recurse into embedded resource
forArray(embeds, function (embedded) {
resources = resources.concat(extractAndUpdateResources(embedded, {}, rootResource, null));
});
});
delete data._embedded;
// Update resource
if (!resource) resource = rootResource.$context.get(links.self.href, rootResource.constructor);
Resource.prototype.$update.call(resource, data, links);
resources.push(resource);
return resources;
} | [
"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'",
")",
";",
"}",
"angular",
".",
"extend",
"(",
"links",
",",
"data",
".",
"_links",
")",
";",
"delete",
"data",
".",
"_links",
";",
"Object",
".",
"keys",
"(",
"data",
".",
"_embedded",
"||",
"{",
"}",
")",
".",
"forEach",
"(",
"function",
"(",
"rel",
")",
"{",
"var",
"embeds",
"=",
"data",
".",
"_embedded",
"[",
"rel",
"]",
";",
"if",
"(",
"!",
"(",
"rel",
"in",
"links",
")",
")",
"{",
"links",
"[",
"rel",
"]",
"=",
"forArray",
"(",
"embeds",
",",
"function",
"(",
"embedded",
")",
"{",
"return",
"{",
"href",
":",
"embedded",
".",
"_links",
".",
"self",
".",
"href",
"}",
";",
"}",
")",
";",
"}",
"forArray",
"(",
"embeds",
",",
"function",
"(",
"embedded",
")",
"{",
"resources",
"=",
"resources",
".",
"concat",
"(",
"extractAndUpdateResources",
"(",
"embedded",
",",
"{",
"}",
",",
"rootResource",
",",
"null",
")",
")",
";",
"}",
")",
";",
"}",
")",
";",
"delete",
"data",
".",
"_embedded",
";",
"if",
"(",
"!",
"resource",
")",
"resource",
"=",
"rootResource",
".",
"$context",
".",
"get",
"(",
"links",
".",
"self",
".",
"href",
",",
"rootResource",
".",
"constructor",
")",
";",
"Resource",
".",
"prototype",
".",
"$update",
".",
"call",
"(",
"resource",
",",
"data",
",",
"links",
")",
";",
"resources",
".",
"push",
"(",
"resource",
")",
";",
"return",
"resources",
";",
"}"
] | Recursively extract embedded resources and update them in the context, then update the resource itself.
@param {object} data
@param {object} [links]
@param {Resource} rootResource
@param {Resource} resource | [
"Recursively",
"extract",
"embedded",
"resources",
"and",
"update",
"them",
"in",
"the",
"context",
"then",
"update",
"the",
"resource",
"itself",
"."
] | 6e68d210bf1ca081ace95a01ff0ad9148aa4e7cc | https://github.com/jcassee/angular-hypermedia/blob/6e68d210bf1ca081ace95a01ff0ad9148aa4e7cc/dist/hypermedia.js#L447-L482 | train |
jcassee/angular-hypermedia | dist/hypermedia.js | forArray | function forArray(arg, func, context) {
if (angular.isUndefined(arg)) return undefined;
if (Array.isArray(arg)) {
return arg.map(function (elem) {
return func.call(context, elem);
});
} else {
return func.call(context, arg);
}
} | javascript | function forArray(arg, func, context) {
if (angular.isUndefined(arg)) return undefined;
if (Array.isArray(arg)) {
return arg.map(function (elem) {
return func.call(context, elem);
});
} else {
return func.call(context, arg);
}
} | [
"function",
"forArray",
"(",
"arg",
",",
"func",
",",
"context",
")",
"{",
"if",
"(",
"angular",
".",
"isUndefined",
"(",
"arg",
")",
")",
"return",
"undefined",
";",
"if",
"(",
"Array",
".",
"isArray",
"(",
"arg",
")",
")",
"{",
"return",
"arg",
".",
"map",
"(",
"function",
"(",
"elem",
")",
"{",
"return",
"func",
".",
"call",
"(",
"context",
",",
"elem",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"return",
"func",
".",
"call",
"(",
"context",
",",
"arg",
")",
";",
"}",
"}"
] | Call a function on an argument or every element of an array.
@param {Array|*|undefined} arg the variable or array of variables to apply 'func' to
@param {function} func the function
@param {object} [context] object to bind 'this' to when applying 'func'
@returns {Array|*|undefined} the result of applying 'func' to 'arg'; undefined if 'arg' is undefined | [
"Call",
"a",
"function",
"on",
"an",
"argument",
"or",
"every",
"element",
"of",
"an",
"array",
"."
] | 6e68d210bf1ca081ace95a01ff0ad9148aa4e7cc | https://github.com/jcassee/angular-hypermedia/blob/6e68d210bf1ca081ace95a01ff0ad9148aa4e7cc/dist/hypermedia.js#L1083-L1092 | train |
jcassee/angular-hypermedia | dist/hypermedia.js | defineProperties | function defineProperties(obj, props) {
props = angular.copy(props);
angular.forEach(props, function (prop) {
if (!('writable' in prop)) prop.writable = true;
});
Object.defineProperties(obj, props);
} | javascript | function defineProperties(obj, props) {
props = angular.copy(props);
angular.forEach(props, function (prop) {
if (!('writable' in prop)) prop.writable = true;
});
Object.defineProperties(obj, props);
} | [
"function",
"defineProperties",
"(",
"obj",
",",
"props",
")",
"{",
"props",
"=",
"angular",
".",
"copy",
"(",
"props",
")",
";",
"angular",
".",
"forEach",
"(",
"props",
",",
"function",
"(",
"prop",
")",
"{",
"if",
"(",
"!",
"(",
"'writable'",
"in",
"prop",
")",
")",
"prop",
".",
"writable",
"=",
"true",
";",
"}",
")",
";",
"Object",
".",
"defineProperties",
"(",
"obj",
",",
"props",
")",
";",
"}"
] | Call Object.defineProperties but configure all properties as writable. | [
"Call",
"Object",
".",
"defineProperties",
"but",
"configure",
"all",
"properties",
"as",
"writable",
"."
] | 6e68d210bf1ca081ace95a01ff0ad9148aa4e7cc | https://github.com/jcassee/angular-hypermedia/blob/6e68d210bf1ca081ace95a01ff0ad9148aa4e7cc/dist/hypermedia.js#L1097-L1103 | train |
vigour-io/vjs | lib/observable/subscribe/index.js | subscribe | 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 = subscribe(property, path, index + 1, length, type, val, id, fire, origin, event, nocontext)
} else {
let listenerType = key === 'parent' ? key : 'property'
let listener = function (data, event) {
let property = obs[key]
if (property) {
obs.off(listenerType, id, void 0, true)
subscribe(property, path, index + 1, length, type, val, id, true, origin, event, nocontext)
}
}
obs.on(listenerType, listener, id, true, event, nocontext)
}
// if sub is not fulfilled look in the reference
if (!result) {
let reference = ref(obs)
if (reference) {
subscribe(reference, path, index, length, type, val, id, fire, origin, event, nocontext)
}
}
}
} | javascript | 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 = subscribe(property, path, index + 1, length, type, val, id, fire, origin, event, nocontext)
} else {
let listenerType = key === 'parent' ? key : 'property'
let listener = function (data, event) {
let property = obs[key]
if (property) {
obs.off(listenerType, id, void 0, true)
subscribe(property, path, index + 1, length, type, val, id, true, origin, event, nocontext)
}
}
obs.on(listenerType, listener, id, true, event, nocontext)
}
// if sub is not fulfilled look in the reference
if (!result) {
let reference = ref(obs)
if (reference) {
subscribe(reference, path, index, length, type, val, id, fire, origin, event, nocontext)
}
}
}
} | [
"function",
"subscribe",
"(",
"obs",
",",
"path",
",",
"index",
",",
"length",
",",
"type",
",",
"val",
",",
"id",
",",
"fire",
",",
"origin",
",",
"event",
",",
"nocontext",
")",
"{",
"if",
"(",
"index",
"===",
"length",
")",
"{",
"if",
"(",
"obs",
".",
"on",
")",
"{",
"obs",
".",
"on",
"(",
"'remove'",
",",
"function",
"(",
")",
"{",
"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",
")",
"{",
"if",
"(",
"event",
"===",
"void",
"0",
")",
"{",
"var",
"trigger",
"=",
"true",
"event",
"=",
"new",
"Event",
"(",
"'data'",
")",
"}",
"if",
"(",
"typeof",
"val",
"===",
"'function'",
")",
"{",
"val",
".",
"call",
"(",
"obs",
",",
"obs",
".",
"__input",
",",
"event",
")",
"}",
"else",
"{",
"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",
"=",
"subscribe",
"(",
"property",
",",
"path",
",",
"index",
"+",
"1",
",",
"length",
",",
"type",
",",
"val",
",",
"id",
",",
"fire",
",",
"origin",
",",
"event",
",",
"nocontext",
")",
"}",
"else",
"{",
"let",
"listenerType",
"=",
"key",
"===",
"'parent'",
"?",
"key",
":",
"'property'",
"let",
"listener",
"=",
"function",
"(",
"data",
",",
"event",
")",
"{",
"let",
"property",
"=",
"obs",
"[",
"key",
"]",
"if",
"(",
"property",
")",
"{",
"obs",
".",
"off",
"(",
"listenerType",
",",
"id",
",",
"void",
"0",
",",
"true",
")",
"subscribe",
"(",
"property",
",",
"path",
",",
"index",
"+",
"1",
",",
"length",
",",
"type",
",",
"val",
",",
"id",
",",
"true",
",",
"origin",
",",
"event",
",",
"nocontext",
")",
"}",
"}",
"obs",
".",
"on",
"(",
"listenerType",
",",
"listener",
",",
"id",
",",
"true",
",",
"event",
",",
"nocontext",
")",
"}",
"if",
"(",
"!",
"result",
")",
"{",
"let",
"reference",
"=",
"ref",
"(",
"obs",
")",
"if",
"(",
"reference",
")",
"{",
"subscribe",
"(",
"reference",
",",
"path",
",",
"index",
",",
"length",
",",
"type",
",",
"val",
",",
"id",
",",
"fire",
",",
"origin",
",",
"event",
",",
"nocontext",
")",
"}",
"}",
"}",
"}"
] | subscriptions have to take care of references we have to add walking over the refs here | [
"subscriptions",
"have",
"to",
"take",
"care",
"of",
"references",
"we",
"have",
"to",
"add",
"walking",
"over",
"the",
"refs",
"here"
] | f70ea438e381f225042d9a6b4e321faffcc97305 | https://github.com/vigour-io/vjs/blob/f70ea438e381f225042d9a6b4e321faffcc97305/lib/observable/subscribe/index.js#L80-L139 | train |
JamesMGreene/node-dos2unix | lib/util/glob.js | function(pattern, callback) {
glob(pattern, opts, function(err, globbedFiles) {
if (isArray(globbedFiles) && globbedFiles.length && !err) {
callback(null, globbedFiles);
}
else {
console.error('The glob pattern ' + JSON.stringify(pattern) + ' did not match any files!');
callback(null, []);
}
});
} | javascript | function(pattern, callback) {
glob(pattern, opts, function(err, globbedFiles) {
if (isArray(globbedFiles) && globbedFiles.length && !err) {
callback(null, globbedFiles);
}
else {
console.error('The glob pattern ' + JSON.stringify(pattern) + ' did not match any files!');
callback(null, []);
}
});
} | [
"function",
"(",
"pattern",
",",
"callback",
")",
"{",
"glob",
"(",
"pattern",
",",
"opts",
",",
"function",
"(",
"err",
",",
"globbedFiles",
")",
"{",
"if",
"(",
"isArray",
"(",
"globbedFiles",
")",
"&&",
"globbedFiles",
".",
"length",
"&&",
"!",
"err",
")",
"{",
"callback",
"(",
"null",
",",
"globbedFiles",
")",
";",
"}",
"else",
"{",
"console",
".",
"error",
"(",
"'The glob pattern '",
"+",
"JSON",
".",
"stringify",
"(",
"pattern",
")",
"+",
"' did not match any files!'",
")",
";",
"callback",
"(",
"null",
",",
"[",
"]",
")",
";",
"}",
"}",
")",
";",
"}"
] | Relative patterns are matched against the current working directory. | [
"Relative",
"patterns",
"are",
"matched",
"against",
"the",
"current",
"working",
"directory",
"."
] | f2a0d4dbb0879cdd7ab90b120401780bef2cfcf0 | https://github.com/JamesMGreene/node-dos2unix/blob/f2a0d4dbb0879cdd7ab90b120401780bef2cfcf0/lib/util/glob.js#L57-L67 | train |
|
JamesMGreene/node-dos2unix | lib/dos2unix.js | function() {
var bomBuffer = this.read(bytesPerBom);
if (bomBuffer == null || bomBuffer.length !== bytesPerBom) {
status = 'error';
processor.emit('processing.error', {
file: filePath,
message: 'Skipping file with errors during read: Unable to read past the expected BOM'
});
return callback(null, status);
}
} | javascript | function() {
var bomBuffer = this.read(bytesPerBom);
if (bomBuffer == null || bomBuffer.length !== bytesPerBom) {
status = 'error';
processor.emit('processing.error', {
file: filePath,
message: 'Skipping file with errors during read: Unable to read past the expected BOM'
});
return callback(null, status);
}
} | [
"function",
"(",
")",
"{",
"var",
"bomBuffer",
"=",
"this",
".",
"read",
"(",
"bytesPerBom",
")",
";",
"if",
"(",
"bomBuffer",
"==",
"null",
"||",
"bomBuffer",
".",
"length",
"!==",
"bytesPerBom",
")",
"{",
"status",
"=",
"'error'",
";",
"processor",
".",
"emit",
"(",
"'processing.error'",
",",
"{",
"file",
":",
"filePath",
",",
"message",
":",
"'Skipping file with errors during read: Unable to read past the expected BOM'",
"}",
")",
";",
"return",
"callback",
"(",
"null",
",",
"status",
")",
";",
"}",
"}"
] | Fast-forward past the BOM if present | [
"Fast",
"-",
"forward",
"past",
"the",
"BOM",
"if",
"present"
] | f2a0d4dbb0879cdd7ab90b120401780bef2cfcf0 | https://github.com/JamesMGreene/node-dos2unix/blob/f2a0d4dbb0879cdd7ab90b120401780bef2cfcf0/lib/dos2unix.js#L68-L78 | train |
|
vigour-io/vjs | lib/emitter/off.js | resolveContext | 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: {} }
setObj.on[type] = {}
// base = base.set(setObj) // .on[type]
emitter = (base.set(setObj) || base)._on[type]
}
if (!emitter.hasOwnProperty(storageKey)) {
emitter.setKey(storageKey, {}, false)
}
return emitter
} | javascript | 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: {} }
setObj.on[type] = {}
// base = base.set(setObj) // .on[type]
emitter = (base.set(setObj) || base)._on[type]
}
if (!emitter.hasOwnProperty(storageKey)) {
emitter.setKey(storageKey, {}, false)
}
return emitter
} | [
"function",
"resolveContext",
"(",
"emitter",
",",
"context",
",",
"storageKey",
")",
"{",
"if",
"(",
"context",
")",
"{",
"let",
"base",
"=",
"emitter",
".",
"parent",
".",
"parent",
"let",
"type",
"=",
"emitter",
".",
"key",
"let",
"setObj",
"=",
"{",
"on",
":",
"{",
"}",
"}",
"setObj",
".",
"on",
"[",
"type",
"]",
"=",
"{",
"}",
"emitter",
"=",
"(",
"base",
".",
"set",
"(",
"setObj",
")",
"||",
"base",
")",
".",
"_on",
"[",
"type",
"]",
"}",
"if",
"(",
"!",
"emitter",
".",
"hasOwnProperty",
"(",
"storageKey",
")",
")",
"{",
"emitter",
".",
"setKey",
"(",
"storageKey",
",",
"{",
"}",
",",
"false",
")",
"}",
"return",
"emitter",
"}"
] | can become a lot faster rly a lot... | [
"can",
"become",
"a",
"lot",
"faster",
"rly",
"a",
"lot",
"..."
] | f70ea438e381f225042d9a6b4e321faffcc97305 | https://github.com/vigour-io/vjs/blob/f70ea438e381f225042d9a6b4e321faffcc97305/lib/emitter/off.js#L29-L46 | train |
hex7c0/arc4 | lib/normal/rc4a.js | gPrga | function gPrga(key, s) {
var keystream = [];
var k = 0;
var j = 0;
var len = key.length;
for (var i = 0; i < len; ++i) {
k = (k + 1) % 256;
j = (j + s[k]) % 256;
s[j] = [ s[k], s[k] = s[j] ][0];
keystream[i] = s[(s[k] + s[j]) % 256];
}
return keystream;
} | javascript | function gPrga(key, s) {
var keystream = [];
var k = 0;
var j = 0;
var len = key.length;
for (var i = 0; i < len; ++i) {
k = (k + 1) % 256;
j = (j + s[k]) % 256;
s[j] = [ s[k], s[k] = s[j] ][0];
keystream[i] = s[(s[k] + s[j]) % 256];
}
return keystream;
} | [
"function",
"gPrga",
"(",
"key",
",",
"s",
")",
"{",
"var",
"keystream",
"=",
"[",
"]",
";",
"var",
"k",
"=",
"0",
";",
"var",
"j",
"=",
"0",
";",
"var",
"len",
"=",
"key",
".",
"length",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"len",
";",
"++",
"i",
")",
"{",
"k",
"=",
"(",
"k",
"+",
"1",
")",
"%",
"256",
";",
"j",
"=",
"(",
"j",
"+",
"s",
"[",
"k",
"]",
")",
"%",
"256",
";",
"s",
"[",
"j",
"]",
"=",
"[",
"s",
"[",
"k",
"]",
",",
"s",
"[",
"k",
"]",
"=",
"s",
"[",
"j",
"]",
"]",
"[",
"0",
"]",
";",
"keystream",
"[",
"i",
"]",
"=",
"s",
"[",
"(",
"s",
"[",
"k",
"]",
"+",
"s",
"[",
"j",
"]",
")",
"%",
"256",
"]",
";",
"}",
"return",
"keystream",
";",
"}"
] | Generate PRGA.
@function gPrga
@param {Array} key - user key
@param {Array} s - s1 vector
@return {Array} | [
"Generate",
"PRGA",
"."
] | 9c7164ab44b4bc8e6123fbadc4a7f4a979509e7c | https://github.com/hex7c0/arc4/blob/9c7164ab44b4bc8e6123fbadc4a7f4a979509e7c/lib/normal/rc4a.js#L65-L79 | train |
hex7c0/arc4 | lib/normal/rc4a.js | body | 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]) % 256];
if (++y < length) {
j2 = (j2 + s2[i]) % 256;
s2[j2] = [ s2[i], s2[i] = s2[j2] ][0];
out[y] = inp[y] ^ s1[(s2[i] + s2[j1]) % 256];
}
}
return out;
} | javascript | 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]) % 256];
if (++y < length) {
j2 = (j2 + s2[i]) % 256;
s2[j2] = [ s2[i], s2[i] = s2[j2] ][0];
out[y] = inp[y] ^ s1[(s2[i] + s2[j1]) % 256];
}
}
return out;
} | [
"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",
"]",
")",
"%",
"256",
"]",
";",
"if",
"(",
"++",
"y",
"<",
"length",
")",
"{",
"j2",
"=",
"(",
"j2",
"+",
"s2",
"[",
"i",
"]",
")",
"%",
"256",
";",
"s2",
"[",
"j2",
"]",
"=",
"[",
"s2",
"[",
"i",
"]",
",",
"s2",
"[",
"i",
"]",
"=",
"s2",
"[",
"j2",
"]",
"]",
"[",
"0",
"]",
";",
"out",
"[",
"y",
"]",
"=",
"inp",
"[",
"y",
"]",
"^",
"s1",
"[",
"(",
"s2",
"[",
"i",
"]",
"+",
"s2",
"[",
"j1",
"]",
")",
"%",
"256",
"]",
";",
"}",
"}",
"return",
"out",
";",
"}"
] | Body cipher.
@function body
@param {Array|Buffer} inp - input
@param {Array} ksa - ksa box
@param {Array} prga - prga box
@param {Array|Buffer} container - out container
@param {Integer} length - limit
@return {Array|Buffer} | [
"Body",
"cipher",
"."
] | 9c7164ab44b4bc8e6123fbadc4a7f4a979509e7c | https://github.com/hex7c0/arc4/blob/9c7164ab44b4bc8e6123fbadc4a7f4a979509e7c/lib/normal/rc4a.js#L92-L111 | train |
wavesoft/jbb | decoder.js | decodeBlobURL | function decodeBlobURL( bundle, length ) {
var mimeType = bundle.readStringLT(),
blob = new Blob([ bundle.readTypedArray(NUMTYPE.UINT8, length ) ], { type: mimeType });
return DEBUG
? __debugMeta( URL.createObjectURL(blob), 'buffer', { 'mime': mimeType, 'size': length } )
: URL.createObjectURL(blob);
} | javascript | function decodeBlobURL( bundle, length ) {
var mimeType = bundle.readStringLT(),
blob = new Blob([ bundle.readTypedArray(NUMTYPE.UINT8, length ) ], { type: mimeType });
return DEBUG
? __debugMeta( URL.createObjectURL(blob), 'buffer', { 'mime': mimeType, 'size': length } )
: URL.createObjectURL(blob);
} | [
"function",
"decodeBlobURL",
"(",
"bundle",
",",
"length",
")",
"{",
"var",
"mimeType",
"=",
"bundle",
".",
"readStringLT",
"(",
")",
",",
"blob",
"=",
"new",
"Blob",
"(",
"[",
"bundle",
".",
"readTypedArray",
"(",
"NUMTYPE",
".",
"UINT8",
",",
"length",
")",
"]",
",",
"{",
"type",
":",
"mimeType",
"}",
")",
";",
"return",
"DEBUG",
"?",
"__debugMeta",
"(",
"URL",
".",
"createObjectURL",
"(",
"blob",
")",
",",
"'buffer'",
",",
"{",
"'mime'",
":",
"mimeType",
",",
"'size'",
":",
"length",
"}",
")",
":",
"URL",
".",
"createObjectURL",
"(",
"blob",
")",
";",
"}"
] | Create a blob url from the given buffer | [
"Create",
"a",
"blob",
"url",
"from",
"the",
"given",
"buffer"
] | 46c40e0bca02d74201fb99925843cde49e9fe68a | https://github.com/wavesoft/jbb/blob/46c40e0bca02d74201fb99925843cde49e9fe68a/decoder.js#L267-L273 | train |
wavesoft/jbb | decoder.js | decodeBuffer | 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');
img.src = decodeBlobURL( bundle, length );
return img;
} else if (buf_type === 4) { // SCRIPT
var img = document.createElement('script');
img.src = decodeBlobURL( bundle, length );
return img;
} else if (buf_type === 7) { // RESOURCE
return decodeBlobURL( bundle, length );
} else {
throw new Errors.AssertError('Unknown buffer type #'+buf_type+'!');
}
} | javascript | 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');
img.src = decodeBlobURL( bundle, length );
return img;
} else if (buf_type === 4) { // SCRIPT
var img = document.createElement('script');
img.src = decodeBlobURL( bundle, length );
return img;
} else if (buf_type === 7) { // RESOURCE
return decodeBlobURL( bundle, length );
} else {
throw new Errors.AssertError('Unknown buffer type #'+buf_type+'!');
}
} | [
"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",
";",
"}",
"if",
"(",
"buf_type",
"===",
"0",
")",
"{",
"ans",
"=",
"String",
".",
"fromCharCode",
".",
"apply",
"(",
"null",
",",
"bundle",
".",
"readTypedArray",
"(",
"NUMTYPE",
".",
"UINT8",
",",
"length",
")",
")",
";",
"return",
"DEBUG",
"?",
"__debugMeta",
"(",
"ans",
",",
"'string.latin'",
",",
"{",
"}",
")",
":",
"ans",
";",
"}",
"else",
"if",
"(",
"buf_type",
"===",
"1",
")",
"{",
"ans",
"=",
"String",
".",
"fromCharCode",
".",
"apply",
"(",
"null",
",",
"bundle",
".",
"readTypedArray",
"(",
"NUMTYPE",
".",
"UINT16",
",",
"length",
")",
")",
";",
"return",
"DEBUG",
"?",
"__debugMeta",
"(",
"ans",
",",
"'string.utf8'",
",",
"{",
"}",
")",
":",
"ans",
";",
"}",
"else",
"if",
"(",
"buf_type",
"===",
"2",
")",
"{",
"var",
"img",
"=",
"document",
".",
"createElement",
"(",
"'img'",
")",
";",
"img",
".",
"src",
"=",
"decodeBlobURL",
"(",
"bundle",
",",
"length",
")",
";",
"return",
"img",
";",
"}",
"else",
"if",
"(",
"buf_type",
"===",
"4",
")",
"{",
"var",
"img",
"=",
"document",
".",
"createElement",
"(",
"'script'",
")",
";",
"img",
".",
"src",
"=",
"decodeBlobURL",
"(",
"bundle",
",",
"length",
")",
";",
"return",
"img",
";",
"}",
"else",
"if",
"(",
"buf_type",
"===",
"7",
")",
"{",
"return",
"decodeBlobURL",
"(",
"bundle",
",",
"length",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"Errors",
".",
"AssertError",
"(",
"'Unknown buffer type #'",
"+",
"buf_type",
"+",
"'!'",
")",
";",
"}",
"}"
] | Read a buffer from the bundle | [
"Read",
"a",
"buffer",
"from",
"the",
"bundle"
] | 46c40e0bca02d74201fb99925843cde49e9fe68a | https://github.com/wavesoft/jbb/blob/46c40e0bca02d74201fb99925843cde49e9fe68a/decoder.js#L278-L317 | train |
wavesoft/jbb | decoder.js | decodeObject | 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 } );
return instance;
} else if ((op & 0x3C) === 0x38) { // Primitive object
var poid = (op & 0x03);
switch (poid) {
case 0:
var date = bundle.f64[bundle.i64++];
var tzOffset = bundle.s8[bundle.i8++] * 10;
// Return date
return DEBUG
? __debugMeta( new Date( date ), 'object.date', {} )
: new Date( date );
default:
throw new Errors.AssertError('Unknown primitive object with POID #'+poid+'!');
}
} else if ((op & 0x38) === 0x30) { // Simple object with known signature
// Get values
var eid = ((op & 0x07) << 8) | bundle.u8[bundle.i8++],
values = decodePrimitive( bundle, database ),
factory = bundle.factory_plain[eid];
// Check for invalid objects
if (factory === undefined)
throw new Errors.AssertError('Could not found simple object signature with id #'+eid+'!');
// Create object
return DEBUG
? __debugMeta( factory(values), 'object.plain', { 'eid': eid } )
: factory(values);
} else {
throw new Errors.AssertError('Unexpected object opcode 0x'+op.toString(16)+'!');
}
} | javascript | 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 } );
return instance;
} else if ((op & 0x3C) === 0x38) { // Primitive object
var poid = (op & 0x03);
switch (poid) {
case 0:
var date = bundle.f64[bundle.i64++];
var tzOffset = bundle.s8[bundle.i8++] * 10;
// Return date
return DEBUG
? __debugMeta( new Date( date ), 'object.date', {} )
: new Date( date );
default:
throw new Errors.AssertError('Unknown primitive object with POID #'+poid+'!');
}
} else if ((op & 0x38) === 0x30) { // Simple object with known signature
// Get values
var eid = ((op & 0x07) << 8) | bundle.u8[bundle.i8++],
values = decodePrimitive( bundle, database ),
factory = bundle.factory_plain[eid];
// Check for invalid objects
if (factory === undefined)
throw new Errors.AssertError('Could not found simple object signature with id #'+eid+'!');
// Create object
return DEBUG
? __debugMeta( factory(values), 'object.plain', { 'eid': eid } )
: factory(values);
} else {
throw new Errors.AssertError('Unexpected object opcode 0x'+op.toString(16)+'!');
}
} | [
"function",
"decodeObject",
"(",
"bundle",
",",
"database",
",",
"op",
")",
"{",
"if",
"(",
"!",
"(",
"op",
"&",
"0x20",
")",
"||",
"(",
"(",
"op",
"&",
"0x30",
")",
"===",
"0x20",
")",
")",
"{",
"var",
"eid",
"=",
"op",
";",
"if",
"(",
"op",
"&",
"0x20",
")",
"eid",
"=",
"bundle",
".",
"u8",
"[",
"bundle",
".",
"i8",
"++",
"]",
"|",
"(",
"(",
"op",
"&",
"0x0F",
")",
"<<",
"8",
")",
";",
"var",
"FACTORY",
"=",
"bundle",
".",
"profile",
".",
"decode",
"(",
"eid",
")",
";",
"if",
"(",
"FACTORY",
"===",
"undefined",
")",
"{",
"throw",
"new",
"Errors",
".",
"AssertError",
"(",
"'Could not found known object entity #'",
"+",
"eid",
"+",
"'!'",
")",
";",
"}",
"var",
"instance",
"=",
"FACTORY",
".",
"create",
"(",
")",
";",
"bundle",
".",
"iref_table",
".",
"push",
"(",
"instance",
")",
";",
"var",
"prop_table",
"=",
"decodePrimitive",
"(",
"bundle",
",",
"database",
")",
";",
"FACTORY",
".",
"init",
"(",
"instance",
",",
"prop_table",
",",
"1",
",",
"0",
")",
";",
"DEBUG",
"&&",
"__debugMeta",
"(",
"instance",
",",
"'object.known'",
",",
"{",
"'eid'",
":",
"eid",
"}",
")",
";",
"return",
"instance",
";",
"}",
"else",
"if",
"(",
"(",
"op",
"&",
"0x3C",
")",
"===",
"0x38",
")",
"{",
"var",
"poid",
"=",
"(",
"op",
"&",
"0x03",
")",
";",
"switch",
"(",
"poid",
")",
"{",
"case",
"0",
":",
"var",
"date",
"=",
"bundle",
".",
"f64",
"[",
"bundle",
".",
"i64",
"++",
"]",
";",
"var",
"tzOffset",
"=",
"bundle",
".",
"s8",
"[",
"bundle",
".",
"i8",
"++",
"]",
"*",
"10",
";",
"return",
"DEBUG",
"?",
"__debugMeta",
"(",
"new",
"Date",
"(",
"date",
")",
",",
"'object.date'",
",",
"{",
"}",
")",
":",
"new",
"Date",
"(",
"date",
")",
";",
"default",
":",
"throw",
"new",
"Errors",
".",
"AssertError",
"(",
"'Unknown primitive object with POID #'",
"+",
"poid",
"+",
"'!'",
")",
";",
"}",
"}",
"else",
"if",
"(",
"(",
"op",
"&",
"0x38",
")",
"===",
"0x30",
")",
"{",
"var",
"eid",
"=",
"(",
"(",
"op",
"&",
"0x07",
")",
"<<",
"8",
")",
"|",
"bundle",
".",
"u8",
"[",
"bundle",
".",
"i8",
"++",
"]",
",",
"values",
"=",
"decodePrimitive",
"(",
"bundle",
",",
"database",
")",
",",
"factory",
"=",
"bundle",
".",
"factory_plain",
"[",
"eid",
"]",
";",
"if",
"(",
"factory",
"===",
"undefined",
")",
"throw",
"new",
"Errors",
".",
"AssertError",
"(",
"'Could not found simple object signature with id #'",
"+",
"eid",
"+",
"'!'",
")",
";",
"return",
"DEBUG",
"?",
"__debugMeta",
"(",
"factory",
"(",
"values",
")",
",",
"'object.plain'",
",",
"{",
"'eid'",
":",
"eid",
"}",
")",
":",
"factory",
"(",
"values",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"Errors",
".",
"AssertError",
"(",
"'Unexpected object opcode 0x'",
"+",
"op",
".",
"toString",
"(",
"16",
")",
"+",
"'!'",
")",
";",
"}",
"}"
] | Read an object from the bundle | [
"Read",
"an",
"object",
"from",
"the",
"bundle"
] | 46c40e0bca02d74201fb99925843cde49e9fe68a | https://github.com/wavesoft/jbb/blob/46c40e0bca02d74201fb99925843cde49e9fe68a/decoder.js#L322-L383 | train |
wavesoft/jbb | decoder.js | decodePivotArrayFloat | 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);
// Decode
for (var i=0; i<len; ++i) {
ans[i] = pivot + (values[i] * scale);
// console.log("<<<", values[i],"->", ans[i]);
}
return DEBUG
? __debugMeta( ans, 'array.delta.float', {} )
: ans;
} | javascript | 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);
// Decode
for (var i=0; i<len; ++i) {
ans[i] = pivot + (values[i] * scale);
// console.log("<<<", values[i],"->", ans[i]);
}
return DEBUG
? __debugMeta( ans, 'array.delta.float', {} )
: ans;
} | [
"function",
"decodePivotArrayFloat",
"(",
"bundle",
",",
"database",
",",
"len",
",",
"num_type",
")",
"{",
"var",
"ans",
"=",
"new",
"NUMTYPE_CLASS",
"[",
"NUMTYPE_DELTA_FLOAT",
".",
"FROM",
"[",
"num_type",
"]",
"]",
"(",
"len",
")",
",",
"scale",
"=",
"bundle",
".",
"readFloat64",
"(",
")",
",",
"values",
"=",
"bundle",
".",
"readTypedArray",
"(",
"NUMTYPE_DELTA_FLOAT",
".",
"TO",
"[",
"num_type",
"]",
",",
"len",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"len",
";",
"++",
"i",
")",
"{",
"ans",
"[",
"i",
"]",
"=",
"pivot",
"+",
"(",
"values",
"[",
"i",
"]",
"*",
"scale",
")",
";",
"}",
"return",
"DEBUG",
"?",
"__debugMeta",
"(",
"ans",
",",
"'array.delta.float'",
",",
"{",
"}",
")",
":",
"ans",
";",
"}"
] | Decode pivot-encoded float array | [
"Decode",
"pivot",
"-",
"encoded",
"float",
"array"
] | 46c40e0bca02d74201fb99925843cde49e9fe68a | https://github.com/wavesoft/jbb/blob/46c40e0bca02d74201fb99925843cde49e9fe68a/decoder.js#L388-L405 | train |
wavesoft/jbb | decoder.js | decodeDeltaArrayInt | 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: v = bundle.f64[bundle.i64++]; break;
}
var values = bundle.readTypedArray( NUMTYPE_DELTA_INT.TO[ num_type ] , len - 1 );
// Decode array
ans[0] = v;
for (var i=0, llen=values.length; i<llen; ++i) {
v += values[i];
ans[i+1] = v;
}
// Return
return DEBUG
? __debugMeta( ans, 'array.delta.int', {} )
: ans;
} | javascript | 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: v = bundle.f64[bundle.i64++]; break;
}
var values = bundle.readTypedArray( NUMTYPE_DELTA_INT.TO[ num_type ] , len - 1 );
// Decode array
ans[0] = v;
for (var i=0, llen=values.length; i<llen; ++i) {
v += values[i];
ans[i+1] = v;
}
// Return
return DEBUG
? __debugMeta( ans, 'array.delta.int', {} )
: ans;
} | [
"function",
"decodeDeltaArrayInt",
"(",
"bundle",
",",
"database",
",",
"len",
",",
"num_type",
")",
"{",
"var",
"fromType",
"=",
"NUMTYPE_DELTA_INT",
".",
"FROM",
"[",
"num_type",
"]",
",",
"ans",
"=",
"new",
"NUMTYPE_CLASS",
"[",
"fromType",
"]",
"(",
"len",
")",
",",
"v",
"=",
"0",
";",
"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",
":",
"v",
"=",
"bundle",
".",
"f64",
"[",
"bundle",
".",
"i64",
"++",
"]",
";",
"break",
";",
"}",
"var",
"values",
"=",
"bundle",
".",
"readTypedArray",
"(",
"NUMTYPE_DELTA_INT",
".",
"TO",
"[",
"num_type",
"]",
",",
"len",
"-",
"1",
")",
";",
"ans",
"[",
"0",
"]",
"=",
"v",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"llen",
"=",
"values",
".",
"length",
";",
"i",
"<",
"llen",
";",
"++",
"i",
")",
"{",
"v",
"+=",
"values",
"[",
"i",
"]",
";",
"ans",
"[",
"i",
"+",
"1",
"]",
"=",
"v",
";",
"}",
"return",
"DEBUG",
"?",
"__debugMeta",
"(",
"ans",
",",
"'array.delta.int'",
",",
"{",
"}",
")",
":",
"ans",
";",
"}"
] | Decode delta-encoded float array | [
"Decode",
"delta",
"-",
"encoded",
"float",
"array"
] | 46c40e0bca02d74201fb99925843cde49e9fe68a | https://github.com/wavesoft/jbb/blob/46c40e0bca02d74201fb99925843cde49e9fe68a/decoder.js#L410-L439 | train |
wavesoft/jbb | decoder.js | decodePlainBulkArray | 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 = decodePrimitive( bundle, database );
// Create objects
var len=values.length/properties.length, ans = new Array(len);
for (var i=0; i<len; ++i)
ans[i] = factory(values, i);
return DEBUG
? __debugMeta( ans, 'array.primitive.bulk_plain', { 'sid': sid } )
: ans;
} | javascript | 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 = decodePrimitive( bundle, database );
// Create objects
var len=values.length/properties.length, ans = new Array(len);
for (var i=0; i<len; ++i)
ans[i] = factory(values, i);
return DEBUG
? __debugMeta( ans, 'array.primitive.bulk_plain', { 'sid': sid } )
: ans;
} | [
"function",
"decodePlainBulkArray",
"(",
"bundle",
",",
"database",
")",
"{",
"var",
"sid",
"=",
"bundle",
".",
"u16",
"[",
"bundle",
".",
"i16",
"++",
"]",
",",
"properties",
"=",
"bundle",
".",
"signature_table",
"[",
"sid",
"]",
",",
"factory",
"=",
"bundle",
".",
"factory_plain_bulk",
"[",
"sid",
"]",
";",
"if",
"(",
"factory",
"===",
"undefined",
")",
"throw",
"new",
"Errors",
".",
"AssertError",
"(",
"'Could not found simple object signature with id #'",
"+",
"sid",
"+",
"'!'",
")",
";",
"var",
"values",
"=",
"decodePrimitive",
"(",
"bundle",
",",
"database",
")",
";",
"var",
"len",
"=",
"values",
".",
"length",
"/",
"properties",
".",
"length",
",",
"ans",
"=",
"new",
"Array",
"(",
"len",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"len",
";",
"++",
"i",
")",
"ans",
"[",
"i",
"]",
"=",
"factory",
"(",
"values",
",",
"i",
")",
";",
"return",
"DEBUG",
"?",
"__debugMeta",
"(",
"ans",
",",
"'array.primitive.bulk_plain'",
",",
"{",
"'sid'",
":",
"sid",
"}",
")",
":",
"ans",
";",
"}"
] | Decode plain bulk array | [
"Decode",
"plain",
"bulk",
"array"
] | 46c40e0bca02d74201fb99925843cde49e9fe68a | https://github.com/wavesoft/jbb/blob/46c40e0bca02d74201fb99925843cde49e9fe68a/decoder.js#L444-L467 | train |
wavesoft/jbb | decoder.js | decodePrimitive | 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 7: return bundle.f64[bundle.i64++];
}
} else if ((op & 0xFC) === 0xF8) { // Simple
return PRIM_SIMPLE[ op & 0x03 ];
} else if ((op & 0xFE) === 0xFC) { // Simple_EX
return PRIM_SIMPLE_EX[ op & 0x02 ];
} else if ((op & 0xFF) === 0xFE) { // Import
var name = bundle.readStringLT();
if (database[name] === undefined)
throw new Errors.XRefError('Cannot import undefined external reference '+name+'!');
return DEBUG
? __debugMeta( database[name], 'object.string', { 'key': name } )
: database[name];
} else if ((op & 0xFF) === 0xFF) { // Extended
throw new Errors.AssertError('Encountered RESERVED primitive operator!');
}
} | javascript | 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 7: return bundle.f64[bundle.i64++];
}
} else if ((op & 0xFC) === 0xF8) { // Simple
return PRIM_SIMPLE[ op & 0x03 ];
} else if ((op & 0xFE) === 0xFC) { // Simple_EX
return PRIM_SIMPLE_EX[ op & 0x02 ];
} else if ((op & 0xFF) === 0xFE) { // Import
var name = bundle.readStringLT();
if (database[name] === undefined)
throw new Errors.XRefError('Cannot import undefined external reference '+name+'!');
return DEBUG
? __debugMeta( database[name], 'object.string', { 'key': name } )
: database[name];
} else if ((op & 0xFF) === 0xFF) { // Extended
throw new Errors.AssertError('Encountered RESERVED primitive operator!');
}
} | [
"function",
"decodePrimitive",
"(",
"bundle",
",",
"database",
")",
"{",
"var",
"op",
"=",
"bundle",
".",
"u8",
"[",
"bundle",
".",
"i8",
"++",
"]",
";",
"if",
"(",
"(",
"op",
"&",
"0x80",
")",
"===",
"0x00",
")",
"{",
"return",
"decodeArray",
"(",
"bundle",
",",
"database",
",",
"(",
"op",
"&",
"0x7F",
")",
")",
";",
"}",
"else",
"if",
"(",
"(",
"op",
"&",
"0xC0",
")",
"===",
"0x80",
")",
"{",
"return",
"decodeObject",
"(",
"bundle",
",",
"database",
",",
"(",
"op",
"&",
"0x3F",
")",
")",
";",
"}",
"else",
"if",
"(",
"(",
"op",
"&",
"0xE0",
")",
"===",
"0xC0",
")",
"{",
"return",
"decodeBuffer",
"(",
"bundle",
",",
"(",
"op",
"&",
"0x18",
")",
">>",
"3",
",",
"(",
"op",
"&",
"0x07",
")",
")",
";",
"}",
"else",
"if",
"(",
"(",
"op",
"&",
"0xF0",
")",
"===",
"0xE0",
")",
"{",
"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",
")",
"{",
"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",
"7",
":",
"return",
"bundle",
".",
"f64",
"[",
"bundle",
".",
"i64",
"++",
"]",
";",
"}",
"}",
"else",
"if",
"(",
"(",
"op",
"&",
"0xFC",
")",
"===",
"0xF8",
")",
"{",
"return",
"PRIM_SIMPLE",
"[",
"op",
"&",
"0x03",
"]",
";",
"}",
"else",
"if",
"(",
"(",
"op",
"&",
"0xFE",
")",
"===",
"0xFC",
")",
"{",
"return",
"PRIM_SIMPLE_EX",
"[",
"op",
"&",
"0x02",
"]",
";",
"}",
"else",
"if",
"(",
"(",
"op",
"&",
"0xFF",
")",
"===",
"0xFE",
")",
"{",
"var",
"name",
"=",
"bundle",
".",
"readStringLT",
"(",
")",
";",
"if",
"(",
"database",
"[",
"name",
"]",
"===",
"undefined",
")",
"throw",
"new",
"Errors",
".",
"XRefError",
"(",
"'Cannot import undefined external reference '",
"+",
"name",
"+",
"'!'",
")",
";",
"return",
"DEBUG",
"?",
"__debugMeta",
"(",
"database",
"[",
"name",
"]",
",",
"'object.string'",
",",
"{",
"'key'",
":",
"name",
"}",
")",
":",
"database",
"[",
"name",
"]",
";",
"}",
"else",
"if",
"(",
"(",
"op",
"&",
"0xFF",
")",
"===",
"0xFF",
")",
"{",
"throw",
"new",
"Errors",
".",
"AssertError",
"(",
"'Encountered RESERVED primitive operator!'",
")",
";",
"}",
"}"
] | Read a primitive from the bundle | [
"Read",
"a",
"primitive",
"from",
"the",
"bundle"
] | 46c40e0bca02d74201fb99925843cde49e9fe68a | https://github.com/wavesoft/jbb/blob/46c40e0bca02d74201fb99925843cde49e9fe68a/decoder.js#L905-L959 | train |
wavesoft/jbb | decoder.js | parseBundle | 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 );
break;
default:
throw new Errors.AssertError('Unknown control operator 0x'+op.toString(16)+' at @'+bundle.i8+'!');
}
}
} | javascript | 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 );
break;
default:
throw new Errors.AssertError('Unknown control operator 0x'+op.toString(16)+' at @'+bundle.i8+'!');
}
}
} | [
"function",
"parseBundle",
"(",
"bundle",
",",
"database",
")",
"{",
"while",
"(",
"!",
"bundle",
".",
"eof",
"(",
")",
")",
"{",
"var",
"op",
"=",
"bundle",
".",
"u8",
"[",
"bundle",
".",
"i8",
"++",
"]",
";",
"switch",
"(",
"op",
")",
"{",
"case",
"0xF8",
":",
"var",
"export_name",
"=",
"bundle",
".",
"prefix",
"+",
"bundle",
".",
"readStringLT",
"(",
")",
";",
"database",
"[",
"export_name",
"]",
"=",
"decodePrimitive",
"(",
"bundle",
",",
"database",
")",
";",
"break",
";",
"default",
":",
"throw",
"new",
"Errors",
".",
"AssertError",
"(",
"'Unknown control operator 0x'",
"+",
"op",
".",
"toString",
"(",
"16",
")",
"+",
"' at @'",
"+",
"bundle",
".",
"i8",
"+",
"'!'",
")",
";",
"}",
"}",
"}"
] | Pare the entire bundle | [
"Pare",
"the",
"entire",
"bundle"
] | 46c40e0bca02d74201fb99925843cde49e9fe68a | https://github.com/wavesoft/jbb/blob/46c40e0bca02d74201fb99925843cde49e9fe68a/decoder.js#L964-L977 | train |
wavesoft/jbb | decoder.js | 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 on browser builds
return;
}
// Check for base dir
var prefix = "";
if (this.baseDir)
prefix = this.baseDir + "/";
// Check for sparse bundle
var parts = url.split("?"), suffix = "", reqURL = [];
if (parts.length > 1) suffix = "?"+parts[1];
if (parts[0].substr(parts[0].length - 5).toLowerCase() === ".jbbp") {
var base = prefix + parts[0].substr(0, parts[0].length - 5);
reqURL = [
base + '.jbbp' + suffix,
base + '_b16.jbbp' + suffix,
base + '_b32.jbbp' + suffix,
base + '_b64.jbbp' + suffix
];
} else {
// Assume .jbb if missing (TODO: not a good idea)
var url = parts[0];
if (url.substr(url.length-4) != ".jbb") url += ".jbb";
reqURL = [ prefix + url + suffix ];
}
// Load bundle header and keep a callback
// for the remainging loading operations
var pendingBundle = {
'callback': callback,
'status': PBUND_REQUESTED,
'buffer': undefined,
'url': reqURL
};
// Keep this pending action
this.queuedRequests.push( pendingBundle );
} | javascript | 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 on browser builds
return;
}
// Check for base dir
var prefix = "";
if (this.baseDir)
prefix = this.baseDir + "/";
// Check for sparse bundle
var parts = url.split("?"), suffix = "", reqURL = [];
if (parts.length > 1) suffix = "?"+parts[1];
if (parts[0].substr(parts[0].length - 5).toLowerCase() === ".jbbp") {
var base = prefix + parts[0].substr(0, parts[0].length - 5);
reqURL = [
base + '.jbbp' + suffix,
base + '_b16.jbbp' + suffix,
base + '_b32.jbbp' + suffix,
base + '_b64.jbbp' + suffix
];
} else {
// Assume .jbb if missing (TODO: not a good idea)
var url = parts[0];
if (url.substr(url.length-4) != ".jbb") url += ".jbb";
reqURL = [ prefix + url + suffix ];
}
// Load bundle header and keep a callback
// for the remainging loading operations
var pendingBundle = {
'callback': callback,
'status': PBUND_REQUESTED,
'buffer': undefined,
'url': reqURL
};
// Keep this pending action
this.queuedRequests.push( pendingBundle );
} | [
"function",
"(",
"url",
",",
"callback",
")",
"{",
"if",
"(",
"IS_NODE",
")",
"{",
"var",
"readChunk",
"=",
"function",
"(",
"filename",
")",
"{",
"var",
"file",
"=",
"fs",
".",
"readFileSync",
"(",
"filename",
")",
",",
"u8",
"=",
"new",
"Uint8Array",
"(",
"file",
")",
";",
"return",
"u8",
".",
"buffer",
";",
"}",
"if",
"(",
"url",
".",
"substr",
"(",
"-",
"5",
")",
"===",
"\".jbbp\"",
")",
"{",
"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",
"{",
"this",
".",
"addByBuffer",
"(",
"readChunk",
"(",
"url",
")",
",",
"callback",
")",
";",
"}",
"return",
";",
"}",
"var",
"prefix",
"=",
"\"\"",
";",
"if",
"(",
"this",
".",
"baseDir",
")",
"prefix",
"=",
"this",
".",
"baseDir",
"+",
"\"/\"",
";",
"var",
"parts",
"=",
"url",
".",
"split",
"(",
"\"?\"",
")",
",",
"suffix",
"=",
"\"\"",
",",
"reqURL",
"=",
"[",
"]",
";",
"if",
"(",
"parts",
".",
"length",
">",
"1",
")",
"suffix",
"=",
"\"?\"",
"+",
"parts",
"[",
"1",
"]",
";",
"if",
"(",
"parts",
"[",
"0",
"]",
".",
"substr",
"(",
"parts",
"[",
"0",
"]",
".",
"length",
"-",
"5",
")",
".",
"toLowerCase",
"(",
")",
"===",
"\".jbbp\"",
")",
"{",
"var",
"base",
"=",
"prefix",
"+",
"parts",
"[",
"0",
"]",
".",
"substr",
"(",
"0",
",",
"parts",
"[",
"0",
"]",
".",
"length",
"-",
"5",
")",
";",
"reqURL",
"=",
"[",
"base",
"+",
"'.jbbp'",
"+",
"suffix",
",",
"base",
"+",
"'_b16.jbbp'",
"+",
"suffix",
",",
"base",
"+",
"'_b32.jbbp'",
"+",
"suffix",
",",
"base",
"+",
"'_b64.jbbp'",
"+",
"suffix",
"]",
";",
"}",
"else",
"{",
"var",
"url",
"=",
"parts",
"[",
"0",
"]",
";",
"if",
"(",
"url",
".",
"substr",
"(",
"url",
".",
"length",
"-",
"4",
")",
"!=",
"\".jbb\"",
")",
"url",
"+=",
"\".jbb\"",
";",
"reqURL",
"=",
"[",
"prefix",
"+",
"url",
"+",
"suffix",
"]",
";",
"}",
"var",
"pendingBundle",
"=",
"{",
"'callback'",
":",
"callback",
",",
"'status'",
":",
"PBUND_REQUESTED",
",",
"'buffer'",
":",
"undefined",
",",
"'url'",
":",
"reqURL",
"}",
";",
"this",
".",
"queuedRequests",
".",
"push",
"(",
"pendingBundle",
")",
";",
"}"
] | Load the specified bundle from URL and call the onsuccess callback.
If an error occures, call the onerror callback.
@param {string} url - The URL to load
@param {function} callback - The callback to fire when the bundle is loaded | [
"Load",
"the",
"specified",
"bundle",
"from",
"URL",
"and",
"call",
"the",
"onsuccess",
"callback",
".",
"If",
"an",
"error",
"occures",
"call",
"the",
"onerror",
"callback",
"."
] | 46c40e0bca02d74201fb99925843cde49e9fe68a | https://github.com/wavesoft/jbb/blob/46c40e0bca02d74201fb99925843cde49e9fe68a/decoder.js#L1083-L1156 | train |
|
wavesoft/jbb | decoder.js | function( buffer, callback ) {
// Prepare pending bundle
var pendingBundle = {
'callback': callback,
'status': PBUND_LOADED,
'buffer': buffer,
'url': undefined,
};
// Keep this pending action
this.queuedRequests.push( pendingBundle );
} | javascript | function( buffer, callback ) {
// Prepare pending bundle
var pendingBundle = {
'callback': callback,
'status': PBUND_LOADED,
'buffer': buffer,
'url': undefined,
};
// Keep this pending action
this.queuedRequests.push( pendingBundle );
} | [
"function",
"(",
"buffer",
",",
"callback",
")",
"{",
"var",
"pendingBundle",
"=",
"{",
"'callback'",
":",
"callback",
",",
"'status'",
":",
"PBUND_LOADED",
",",
"'buffer'",
":",
"buffer",
",",
"'url'",
":",
"undefined",
",",
"}",
";",
"this",
".",
"queuedRequests",
".",
"push",
"(",
"pendingBundle",
")",
";",
"}"
] | Load from buffer | [
"Load",
"from",
"buffer"
] | 46c40e0bca02d74201fb99925843cde49e9fe68a | https://github.com/wavesoft/jbb/blob/46c40e0bca02d74201fb99925843cde49e9fe68a/decoder.js#L1161-L1174 | train |
|
wavesoft/jbb | decoder.js | 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++;
req.buffer = downloadArrayBuffers(req.url, part,
(function(req) {
return function( err ) {
// Handle errors
if (err) {
if (triggeredError) return;
var errMsg = "Error downloading bundle: "+err;
if (req.callback) req.callback( errMsg, null);
if (callback) callback(errMsg, null);
triggeredError = true;
return;
}
// Keep buffer and mark as loaded
req.status = PBUND_LOADED;
// Continue
continue_callback();
}
})(req)
);
}
}
// Do not continue, we ar asynchronous
return;
}
////////////////////////////////////////////////////////
// Iteration 2 - PBUND_LOADED -> PBUND_PARSED
// ----------------------------------------------------
// Parse all loaded bundles (synchronous)
////////////////////////////////////////////////////////
for (var i=0; i<this.queuedRequests.length; ++i) {
var req = this.queuedRequests[i];
if (req.status === PBUND_LOADED) {
// try {
// Create bundle from sparse or compact format
var bundle;
if (req.buffer.length === 1) {
bundle = new BinaryBundle( req.buffer[0], self.profile );
} else {
bundle = new BinaryBundle( req.buffer, self.profile );
}
// Parse bundle
parseBundle( bundle, self.database );
// Trigger bundle callback
if (req.callback) req.callback( null, req.bundle );
// } catch (e) {
// // Update bundle status
// req.status = PBUND_ERROR;
// // Fire error callbacks and exit
// var errMsg = "Error parsing bundle: "+e.toString();
// if (req.callback) req.callback( errMsg, null);
// if (callback) callback(errMsg, null);
// return;
// }
}
}
// We are ready
this.queuedRequests = [];
callback( null, this.database );
} | javascript | 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++;
req.buffer = downloadArrayBuffers(req.url, part,
(function(req) {
return function( err ) {
// Handle errors
if (err) {
if (triggeredError) return;
var errMsg = "Error downloading bundle: "+err;
if (req.callback) req.callback( errMsg, null);
if (callback) callback(errMsg, null);
triggeredError = true;
return;
}
// Keep buffer and mark as loaded
req.status = PBUND_LOADED;
// Continue
continue_callback();
}
})(req)
);
}
}
// Do not continue, we ar asynchronous
return;
}
////////////////////////////////////////////////////////
// Iteration 2 - PBUND_LOADED -> PBUND_PARSED
// ----------------------------------------------------
// Parse all loaded bundles (synchronous)
////////////////////////////////////////////////////////
for (var i=0; i<this.queuedRequests.length; ++i) {
var req = this.queuedRequests[i];
if (req.status === PBUND_LOADED) {
// try {
// Create bundle from sparse or compact format
var bundle;
if (req.buffer.length === 1) {
bundle = new BinaryBundle( req.buffer[0], self.profile );
} else {
bundle = new BinaryBundle( req.buffer, self.profile );
}
// Parse bundle
parseBundle( bundle, self.database );
// Trigger bundle callback
if (req.callback) req.callback( null, req.bundle );
// } catch (e) {
// // Update bundle status
// req.status = PBUND_ERROR;
// // Fire error callbacks and exit
// var errMsg = "Error parsing bundle: "+e.toString();
// if (req.callback) req.callback( errMsg, null);
// if (callback) callback(errMsg, null);
// return;
// }
}
}
// We are ready
this.queuedRequests = [];
callback( null, this.database );
} | [
"function",
"(",
"callback",
")",
"{",
"var",
"self",
"=",
"this",
";",
"if",
"(",
"!",
"callback",
")",
"callback",
"=",
"function",
"(",
")",
"{",
"}",
";",
"if",
"(",
"this",
".",
"queuedRequests",
".",
"length",
"===",
"0",
")",
"{",
"callback",
"(",
"null",
",",
"this",
".",
"database",
")",
";",
"return",
";",
"}",
"var",
"pendingLoading",
"=",
"false",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"this",
".",
"queuedRequests",
".",
"length",
";",
"++",
"i",
")",
"{",
"if",
"(",
"this",
".",
"queuedRequests",
"[",
"i",
"]",
".",
"status",
"===",
"PBUND_REQUESTED",
")",
"{",
"pendingLoading",
"=",
"true",
";",
"break",
";",
"}",
"}",
"if",
"(",
"pendingLoading",
")",
"{",
"var",
"state",
"=",
"{",
"'counter'",
":",
"0",
"}",
"var",
"continue_callback",
"=",
"(",
"function",
"(",
")",
"{",
"if",
"(",
"--",
"this",
".",
"counter",
"===",
"0",
")",
"self",
".",
"__process",
"(",
"callback",
")",
";",
"}",
")",
".",
"bind",
"(",
"state",
")",
";",
"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",
")",
"{",
"state",
".",
"counter",
"++",
";",
"req",
".",
"buffer",
"=",
"downloadArrayBuffers",
"(",
"req",
".",
"url",
",",
"part",
",",
"(",
"function",
"(",
"req",
")",
"{",
"return",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"if",
"(",
"triggeredError",
")",
"return",
";",
"var",
"errMsg",
"=",
"\"Error downloading bundle: \"",
"+",
"err",
";",
"if",
"(",
"req",
".",
"callback",
")",
"req",
".",
"callback",
"(",
"errMsg",
",",
"null",
")",
";",
"if",
"(",
"callback",
")",
"callback",
"(",
"errMsg",
",",
"null",
")",
";",
"triggeredError",
"=",
"true",
";",
"return",
";",
"}",
"req",
".",
"status",
"=",
"PBUND_LOADED",
";",
"continue_callback",
"(",
")",
";",
"}",
"}",
")",
"(",
"req",
")",
")",
";",
"}",
"}",
"return",
";",
"}",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"this",
".",
"queuedRequests",
".",
"length",
";",
"++",
"i",
")",
"{",
"var",
"req",
"=",
"this",
".",
"queuedRequests",
"[",
"i",
"]",
";",
"if",
"(",
"req",
".",
"status",
"===",
"PBUND_LOADED",
")",
"{",
"var",
"bundle",
";",
"if",
"(",
"req",
".",
"buffer",
".",
"length",
"===",
"1",
")",
"{",
"bundle",
"=",
"new",
"BinaryBundle",
"(",
"req",
".",
"buffer",
"[",
"0",
"]",
",",
"self",
".",
"profile",
")",
";",
"}",
"else",
"{",
"bundle",
"=",
"new",
"BinaryBundle",
"(",
"req",
".",
"buffer",
",",
"self",
".",
"profile",
")",
";",
"}",
"parseBundle",
"(",
"bundle",
",",
"self",
".",
"database",
")",
";",
"if",
"(",
"req",
".",
"callback",
")",
"req",
".",
"callback",
"(",
"null",
",",
"req",
".",
"bundle",
")",
";",
"}",
"}",
"this",
".",
"queuedRequests",
"=",
"[",
"]",
";",
"callback",
"(",
"null",
",",
"this",
".",
"database",
")",
";",
"}"
] | Parse the stack of bundles currently loaded | [
"Parse",
"the",
"stack",
"of",
"bundles",
"currently",
"loaded"
] | 46c40e0bca02d74201fb99925843cde49e9fe68a | https://github.com/wavesoft/jbb/blob/46c40e0bca02d74201fb99925843cde49e9fe68a/decoder.js#L1200-L1316 | train |
|
wavesoft/jbb | compiler.js | compileFile | 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;
}
// Update path if missing
if (!config['path'])
config['path'] = path.dirname( sourceBundle );
// Compile
compile( JSON.parse(data), bundleFile, config, callback );
});
} | javascript | 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;
}
// Update path if missing
if (!config['path'])
config['path'] = path.dirname( sourceBundle );
// Compile
compile( JSON.parse(data), bundleFile, config, callback );
});
} | [
"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",
";",
"}",
"if",
"(",
"!",
"config",
"[",
"'path'",
"]",
")",
"config",
"[",
"'path'",
"]",
"=",
"path",
".",
"dirname",
"(",
"sourceBundle",
")",
";",
"compile",
"(",
"JSON",
".",
"parse",
"(",
"data",
")",
",",
"bundleFile",
",",
"config",
",",
"callback",
")",
";",
"}",
")",
";",
"}"
] | Wrapper function for the compile function, that first loads the
bundle specs from the source bundle file specified. | [
"Wrapper",
"function",
"for",
"the",
"compile",
"function",
"that",
"first",
"loads",
"the",
"bundle",
"specs",
"from",
"the",
"source",
"bundle",
"file",
"specified",
"."
] | 46c40e0bca02d74201fb99925843cde49e9fe68a | https://github.com/wavesoft/jbb/blob/46c40e0bca02d74201fb99925843cde49e9fe68a/compiler.js#L31-L48 | train |
wavesoft/jbb | encoder.js | 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;
/*if (a[i] == b[i]) continue;*/
} else {
if (a[i] === b[i]) continue;
return 1;
}
} else {
return 1;
}
}
return 0;
} | javascript | 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;
/*if (a[i] == b[i]) continue;*/
} else {
if (a[i] === b[i]) continue;
return 1;
}
} else {
return 1;
}
}
return 0;
} | [
"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",
";",
"}",
"else",
"{",
"if",
"(",
"a",
"[",
"i",
"]",
"===",
"b",
"[",
"i",
"]",
")",
"continue",
";",
"return",
"1",
";",
"}",
"}",
"else",
"{",
"return",
"1",
";",
"}",
"}",
"return",
"0",
";",
"}"
] | Binary Search Tree Helpers | [
"Binary",
"Search",
"Tree",
"Helpers"
] | 46c40e0bca02d74201fb99925843cde49e9fe68a | https://github.com/wavesoft/jbb/blob/46c40e0bca02d74201fb99925843cde49e9fe68a/encoder.js#L101-L120 | train |
|
wavesoft/jbb | encoder.js | getFloatDeltaScale | 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
if ( ((t >= 0) && (t <= 3)) || (t === 6) ) {
return multiplier * INT8_MAX;
} else {
return multiplier * INT16_MAX;
}
}
} | javascript | 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
if ( ((t >= 0) && (t <= 3)) || (t === 6) ) {
return multiplier * INT8_MAX;
} else {
return multiplier * INT16_MAX;
}
}
} | [
"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",
";",
"if",
"(",
"(",
"(",
"t",
">=",
"0",
")",
"&&",
"(",
"t",
"<=",
"3",
")",
")",
"||",
"(",
"t",
"===",
"6",
")",
")",
"{",
"return",
"multiplier",
"*",
"INT8_MAX",
";",
"}",
"else",
"{",
"return",
"multiplier",
"*",
"INT16_MAX",
";",
"}",
"}",
"}"
] | Get the scale factor for the specified float-based delta encoding
using the NUMTYPE_DOWNSCALE and DELTASCALE provided.
@param {int} t - The NUMTYPE_DOWNSCALE used in the encoding
@param {int} scale - The DELTASCALE used in the encoding
@return {float} - Return the scale factor | [
"Get",
"the",
"scale",
"factor",
"for",
"the",
"specified",
"float",
"-",
"based",
"delta",
"encoding",
"using",
"the",
"NUMTYPE_DOWNSCALE",
"and",
"DELTASCALE",
"provided",
"."
] | 46c40e0bca02d74201fb99925843cde49e9fe68a | https://github.com/wavesoft/jbb/blob/46c40e0bca02d74201fb99925843cde49e9fe68a/encoder.js#L601-L616 | train |
wavesoft/jbb | encoder.js | isEmptyArray | function isEmptyArray(v) {
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) ) {
return (v.length === 0);
}
return false;
} | javascript | function isEmptyArray(v) {
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) ) {
return (v.length === 0);
}
return false;
} | [
"function",
"isEmptyArray",
"(",
"v",
")",
"{",
"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",
")",
")",
"{",
"return",
"(",
"v",
".",
"length",
"===",
"0",
")",
";",
"}",
"return",
"false",
";",
"}"
] | Check if the specified object is an empty array | [
"Check",
"if",
"the",
"specified",
"object",
"is",
"an",
"empty",
"array"
] | 46c40e0bca02d74201fb99925843cde49e9fe68a | https://github.com/wavesoft/jbb/blob/46c40e0bca02d74201fb99925843cde49e9fe68a/encoder.js#L621-L630 | train |
wavesoft/jbb | encoder.js | isNumericSubclass | 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) {
case NUMTYPE.UINT8:
case NUMTYPE.INT8:
case NUMTYPE.UINT16:
case NUMTYPE.INT16:
case NUMTYPE.INT32:
return true;
case NUMTYPE.UINT32:
return (t_max < INT32_MAX);
default:
return false;
}
case NUMTYPE.FLOAT32:
switch (t) {
case NUMTYPE.UINT8:
case NUMTYPE.INT8:
case NUMTYPE.UINT16:
case NUMTYPE.INT16:
case NUMTYPE.FLOAT32:
return true;
case NUMTYPE.UINT32:
case NUMTYPE.INT32:
return (t_min > FLOAT32_NEG) && (t_max < FLOAT32_POS);
default:
return false;
}
case NUMTYPE.FLOAT64:
return true;
}
return false;
} | javascript | 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) {
case NUMTYPE.UINT8:
case NUMTYPE.INT8:
case NUMTYPE.UINT16:
case NUMTYPE.INT16:
case NUMTYPE.INT32:
return true;
case NUMTYPE.UINT32:
return (t_max < INT32_MAX);
default:
return false;
}
case NUMTYPE.FLOAT32:
switch (t) {
case NUMTYPE.UINT8:
case NUMTYPE.INT8:
case NUMTYPE.UINT16:
case NUMTYPE.INT16:
case NUMTYPE.FLOAT32:
return true;
case NUMTYPE.UINT32:
case NUMTYPE.INT32:
return (t_min > FLOAT32_NEG) && (t_max < FLOAT32_POS);
default:
return false;
}
case NUMTYPE.FLOAT64:
return true;
}
return false;
} | [
"function",
"isNumericSubclass",
"(",
"t",
",",
"t_min",
",",
"t_max",
",",
"of_t",
")",
"{",
"if",
"(",
"(",
"t",
"===",
"NUMTYPE",
".",
"NAN",
")",
"||",
"(",
"of_t",
"===",
"NUMTYPE",
".",
"NAN",
")",
")",
"return",
"false",
";",
"switch",
"(",
"of_t",
")",
"{",
"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",
")",
"{",
"case",
"NUMTYPE",
".",
"UINT8",
":",
"case",
"NUMTYPE",
".",
"INT8",
":",
"case",
"NUMTYPE",
".",
"UINT16",
":",
"case",
"NUMTYPE",
".",
"INT16",
":",
"case",
"NUMTYPE",
".",
"INT32",
":",
"return",
"true",
";",
"case",
"NUMTYPE",
".",
"UINT32",
":",
"return",
"(",
"t_max",
"<",
"INT32_MAX",
")",
";",
"default",
":",
"return",
"false",
";",
"}",
"case",
"NUMTYPE",
".",
"FLOAT32",
":",
"switch",
"(",
"t",
")",
"{",
"case",
"NUMTYPE",
".",
"UINT8",
":",
"case",
"NUMTYPE",
".",
"INT8",
":",
"case",
"NUMTYPE",
".",
"UINT16",
":",
"case",
"NUMTYPE",
".",
"INT16",
":",
"case",
"NUMTYPE",
".",
"FLOAT32",
":",
"return",
"true",
";",
"case",
"NUMTYPE",
".",
"UINT32",
":",
"case",
"NUMTYPE",
".",
"INT32",
":",
"return",
"(",
"t_min",
">",
"FLOAT32_NEG",
")",
"&&",
"(",
"t_max",
"<",
"FLOAT32_POS",
")",
";",
"default",
":",
"return",
"false",
";",
"}",
"case",
"NUMTYPE",
".",
"FLOAT64",
":",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}"
] | Check if the specified number is a subclass of an other | [
"Check",
"if",
"the",
"specified",
"number",
"is",
"a",
"subclass",
"of",
"an",
"other"
] | 46c40e0bca02d74201fb99925843cde49e9fe68a | https://github.com/wavesoft/jbb/blob/46c40e0bca02d74201fb99925843cde49e9fe68a/encoder.js#L648-L743 | train |
wavesoft/jbb | encoder.js | isFloatMixing | function isFloatMixing( a, b ) {
return (
((a < NUMTYPE.FLOAT32 ) && (b >= NUMTYPE.FLOAT32 )) ||
((a >= NUMTYPE.FLOAT32 ) && (b < NUMTYPE.FLOAT32 ))
);
} | javascript | function isFloatMixing( a, b ) {
return (
((a < NUMTYPE.FLOAT32 ) && (b >= NUMTYPE.FLOAT32 )) ||
((a >= NUMTYPE.FLOAT32 ) && (b < NUMTYPE.FLOAT32 ))
);
} | [
"function",
"isFloatMixing",
"(",
"a",
",",
"b",
")",
"{",
"return",
"(",
"(",
"(",
"a",
"<",
"NUMTYPE",
".",
"FLOAT32",
")",
"&&",
"(",
"b",
">=",
"NUMTYPE",
".",
"FLOAT32",
")",
")",
"||",
"(",
"(",
"a",
">=",
"NUMTYPE",
".",
"FLOAT32",
")",
"&&",
"(",
"b",
"<",
"NUMTYPE",
".",
"FLOAT32",
")",
")",
")",
";",
"}"
] | Check if we are mixing floats | [
"Check",
"if",
"we",
"are",
"mixing",
"floats"
] | 46c40e0bca02d74201fb99925843cde49e9fe68a | https://github.com/wavesoft/jbb/blob/46c40e0bca02d74201fb99925843cde49e9fe68a/encoder.js#L748-L753 | train |
wavesoft/jbb | encoder.js | sizeOfType | 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:
case NUMTYPE.FLOAT32:
return 4;
case NUMTYPE.FLOAT64:
return 8;
}
return 255;
} | javascript | 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:
case NUMTYPE.FLOAT32:
return 4;
case NUMTYPE.FLOAT64:
return 8;
}
return 255;
} | [
"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",
":",
"case",
"NUMTYPE",
".",
"FLOAT32",
":",
"return",
"4",
";",
"case",
"NUMTYPE",
".",
"FLOAT64",
":",
"return",
"8",
";",
"}",
"return",
"255",
";",
"}"
] | Return the array size in bytes of the specified type
@param {int} t - The NUMTYPE type to check
@returns {int} - Returns the size in bytes to hold this type | [
"Return",
"the",
"array",
"size",
"in",
"bytes",
"of",
"the",
"specified",
"type"
] | 46c40e0bca02d74201fb99925843cde49e9fe68a | https://github.com/wavesoft/jbb/blob/46c40e0bca02d74201fb99925843cde49e9fe68a/encoder.js#L761-L777 | train |
wavesoft/jbb | encoder.js | getTypedArrayType | 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) {
// Sneaky but fast way to check if array is 100% numeric
// by testing the first, last and middle elemnet
var a=0,b=v.length-1,c=Math.floor((b-a)/2);
if((typeof v[a] === "number") &&
(typeof v[b] === "number") &&
(typeof v[c] === "number")) {
return NUMTYPE.NUMERIC;
} else {
return NUMTYPE.UNKNOWN;
}
} else {
return NUMTYPE.UNKNOWN;
}
} | javascript | 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) {
// Sneaky but fast way to check if array is 100% numeric
// by testing the first, last and middle elemnet
var a=0,b=v.length-1,c=Math.floor((b-a)/2);
if((typeof v[a] === "number") &&
(typeof v[b] === "number") &&
(typeof v[c] === "number")) {
return NUMTYPE.NUMERIC;
} else {
return NUMTYPE.UNKNOWN;
}
} else {
return NUMTYPE.UNKNOWN;
}
} | [
"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",
")",
"{",
"var",
"a",
"=",
"0",
",",
"b",
"=",
"v",
".",
"length",
"-",
"1",
",",
"c",
"=",
"Math",
".",
"floor",
"(",
"(",
"b",
"-",
"a",
")",
"/",
"2",
")",
";",
"if",
"(",
"(",
"typeof",
"v",
"[",
"a",
"]",
"===",
"\"number\"",
")",
"&&",
"(",
"typeof",
"v",
"[",
"b",
"]",
"===",
"\"number\"",
")",
"&&",
"(",
"typeof",
"v",
"[",
"c",
"]",
"===",
"\"number\"",
")",
")",
"{",
"return",
"NUMTYPE",
".",
"NUMERIC",
";",
"}",
"else",
"{",
"return",
"NUMTYPE",
".",
"UNKNOWN",
";",
"}",
"}",
"else",
"{",
"return",
"NUMTYPE",
".",
"UNKNOWN",
";",
"}",
"}"
] | Get the numerical type of a typed array
@param {array} v - The TypedArray to check
@returns {int} - Returns the NUMTYPE type for the specified array or NUMTYPE.UNKNOWN if not a TypedArray | [
"Get",
"the",
"numerical",
"type",
"of",
"a",
"typed",
"array"
] | 46c40e0bca02d74201fb99925843cde49e9fe68a | https://github.com/wavesoft/jbb/blob/46c40e0bca02d74201fb99925843cde49e9fe68a/encoder.js#L785-L819 | train |
wavesoft/jbb | encoder.js | getNumType | 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) || (vmin < 0)) {
// Get absolute maximum of bound values
var amax = -vmin;
if (vmax < 0) {
if (-vmax > amax) amax = -vmax;
} else {
if (vmax > amax) amax = vmax;
}
// Test for integer bounds
if (amax < INT8_MAX) {
return NUMTYPE.INT8;
} else if (amax < INT16_MAX) {
return NUMTYPE.INT16;
} else if (amax < INT32_MAX) {
return NUMTYPE.INT32;
} else {
return NUMTYPE.FLOAT64;
}
// Otherwise perform unsigned tests
} else {
// Check for unsigned cases
if (vmax < UINT8_MAX) {
return NUMTYPE.UINT8;
} else if (vmax < UINT16_MAX) {
return NUMTYPE.UINT16;
} else if (vmax < UINT32_MAX) {
return NUMTYPE.UINT32;
} else {
return NUMTYPE.FLOAT64;
}
}
} | javascript | 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) || (vmin < 0)) {
// Get absolute maximum of bound values
var amax = -vmin;
if (vmax < 0) {
if (-vmax > amax) amax = -vmax;
} else {
if (vmax > amax) amax = vmax;
}
// Test for integer bounds
if (amax < INT8_MAX) {
return NUMTYPE.INT8;
} else if (amax < INT16_MAX) {
return NUMTYPE.INT16;
} else if (amax < INT32_MAX) {
return NUMTYPE.INT32;
} else {
return NUMTYPE.FLOAT64;
}
// Otherwise perform unsigned tests
} else {
// Check for unsigned cases
if (vmax < UINT8_MAX) {
return NUMTYPE.UINT8;
} else if (vmax < UINT16_MAX) {
return NUMTYPE.UINT16;
} else if (vmax < UINT32_MAX) {
return NUMTYPE.UINT32;
} else {
return NUMTYPE.FLOAT64;
}
}
} | [
"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",
"(",
"is_float",
")",
"{",
"var",
"smallest",
";",
"if",
"(",
"vmin",
"===",
"0",
")",
"{",
"smallest",
"=",
"vmax",
";",
"}",
"else",
"if",
"(",
"vmax",
"===",
"0",
")",
"{",
"smallest",
"=",
"-",
"vmax",
";",
"}",
"else",
"{",
"if",
"(",
"vmin",
">",
"0",
")",
"{",
"smallest",
"=",
"vmin",
";",
"}",
"else",
"if",
"(",
"vmax",
"<",
"0",
")",
"{",
"smallest",
"=",
"-",
"vmax",
";",
"}",
"else",
"if",
"(",
"(",
"vmin",
"<",
"0",
")",
"&&",
"(",
"vmax",
">",
"0",
")",
")",
"{",
"smallest",
"=",
"-",
"vmin",
";",
"if",
"(",
"vmax",
"<",
"smallest",
")",
"smallest",
"=",
"vmax",
";",
"}",
"}",
"if",
"(",
"(",
"vmin",
">",
"FLOAT32_NEG",
")",
"&&",
"(",
"vmax",
"<",
"FLOAT32_POS",
")",
"&&",
"(",
"smallest",
">",
"FLOAT32_SMALL",
")",
")",
"{",
"return",
"NUMTYPE",
".",
"FLOAT32",
";",
"}",
"else",
"{",
"return",
"NUMTYPE",
".",
"FLOAT64",
";",
"}",
"}",
"if",
"(",
"(",
"vmax",
"<",
"0",
")",
"||",
"(",
"vmin",
"<",
"0",
")",
")",
"{",
"var",
"amax",
"=",
"-",
"vmin",
";",
"if",
"(",
"vmax",
"<",
"0",
")",
"{",
"if",
"(",
"-",
"vmax",
">",
"amax",
")",
"amax",
"=",
"-",
"vmax",
";",
"}",
"else",
"{",
"if",
"(",
"vmax",
">",
"amax",
")",
"amax",
"=",
"vmax",
";",
"}",
"if",
"(",
"amax",
"<",
"INT8_MAX",
")",
"{",
"return",
"NUMTYPE",
".",
"INT8",
";",
"}",
"else",
"if",
"(",
"amax",
"<",
"INT16_MAX",
")",
"{",
"return",
"NUMTYPE",
".",
"INT16",
";",
"}",
"else",
"if",
"(",
"amax",
"<",
"INT32_MAX",
")",
"{",
"return",
"NUMTYPE",
".",
"INT32",
";",
"}",
"else",
"{",
"return",
"NUMTYPE",
".",
"FLOAT64",
";",
"}",
"}",
"else",
"{",
"if",
"(",
"vmax",
"<",
"UINT8_MAX",
")",
"{",
"return",
"NUMTYPE",
".",
"UINT8",
";",
"}",
"else",
"if",
"(",
"vmax",
"<",
"UINT16_MAX",
")",
"{",
"return",
"NUMTYPE",
".",
"UINT16",
";",
"}",
"else",
"if",
"(",
"vmax",
"<",
"UINT32_MAX",
")",
"{",
"return",
"NUMTYPE",
".",
"UINT32",
";",
"}",
"else",
"{",
"return",
"NUMTYPE",
".",
"FLOAT64",
";",
"}",
"}",
"}"
] | Get the smallest possible numeric type fits this numberic bounds
@param {number} vmin - The minimum number to check
@param {number} vmax - The maximum number to check
@param {boolean} is_float - Set to 'true' to assume that the numbers are float
@return {NUMTYPE} - The numerical type to rerutn | [
"Get",
"the",
"smallest",
"possible",
"numeric",
"type",
"fits",
"this",
"numberic",
"bounds"
] | 46c40e0bca02d74201fb99925843cde49e9fe68a | https://github.com/wavesoft/jbb/blob/46c40e0bca02d74201fb99925843cde49e9fe68a/encoder.js#L829-L921 | train |
wavesoft/jbb | encoder.js | getFloatScale | 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 = (uv-v)/v;
if (er > er_16) er_16 = er;
if (er >= error) {
ok_16 = false;
}
}
if (!ok_8 && !ok_16)
return [ 0, NUMTYPE.UNKNOWN ];
}
// Pick most appropriate normalization factor
if (ok_8 && ok_16) {
if (er_8 < er_16) {
return [ norm_8, NUMTYPE.INT8 ];
} else {
return [ norm_16, NUMTYPE.INT16 ];
}
} else if (ok_8) {
return [ norm_8, NUMTYPE.INT8 ];
} else if (ok_16) {
return [ norm_16, NUMTYPE.INT16 ];
} else {
return [ 0, NUMTYPE.UNKNOWN ];
}
} | javascript | 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 = (uv-v)/v;
if (er > er_16) er_16 = er;
if (er >= error) {
ok_16 = false;
}
}
if (!ok_8 && !ok_16)
return [ 0, NUMTYPE.UNKNOWN ];
}
// Pick most appropriate normalization factor
if (ok_8 && ok_16) {
if (er_8 < er_16) {
return [ norm_8, NUMTYPE.INT8 ];
} else {
return [ norm_16, NUMTYPE.INT16 ];
}
} else if (ok_8) {
return [ norm_8, NUMTYPE.INT8 ];
} else if (ok_16) {
return [ norm_16, NUMTYPE.INT16 ];
} else {
return [ 0, NUMTYPE.UNKNOWN ];
}
} | [
"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",
"(",
"var",
"i",
"=",
"0",
",",
"l",
"=",
"values",
".",
"length",
";",
"i",
"<",
"l",
";",
"++",
"i",
")",
"{",
"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",
";",
"}",
"}",
"if",
"(",
"ok_16",
")",
"{",
"v",
"=",
"Math",
".",
"round",
"(",
"(",
"values",
"[",
"i",
"]",
"-",
"mid",
")",
"/",
"norm_16",
")",
";",
"uv",
"=",
"v",
"*",
"norm_16",
"+",
"mid",
";",
"er",
"=",
"(",
"uv",
"-",
"v",
")",
"/",
"v",
";",
"if",
"(",
"er",
">",
"er_16",
")",
"er_16",
"=",
"er",
";",
"if",
"(",
"er",
">=",
"error",
")",
"{",
"ok_16",
"=",
"false",
";",
"}",
"}",
"if",
"(",
"!",
"ok_8",
"&&",
"!",
"ok_16",
")",
"return",
"[",
"0",
",",
"NUMTYPE",
".",
"UNKNOWN",
"]",
";",
"}",
"if",
"(",
"ok_8",
"&&",
"ok_16",
")",
"{",
"if",
"(",
"er_8",
"<",
"er_16",
")",
"{",
"return",
"[",
"norm_8",
",",
"NUMTYPE",
".",
"INT8",
"]",
";",
"}",
"else",
"{",
"return",
"[",
"norm_16",
",",
"NUMTYPE",
".",
"INT16",
"]",
";",
"}",
"}",
"else",
"if",
"(",
"ok_8",
")",
"{",
"return",
"[",
"norm_8",
",",
"NUMTYPE",
".",
"INT8",
"]",
";",
"}",
"else",
"if",
"(",
"ok_16",
")",
"{",
"return",
"[",
"norm_16",
",",
"NUMTYPE",
".",
"INT16",
"]",
";",
"}",
"else",
"{",
"return",
"[",
"0",
",",
"NUMTYPE",
".",
"UNKNOWN",
"]",
";",
"}",
"}"
] | Calculate and return the numerical type and the scale to
apply to the float values given in order to minimize the error. | [
"Calculate",
"and",
"return",
"the",
"numerical",
"type",
"and",
"the",
"scale",
"to",
"apply",
"to",
"the",
"float",
"values",
"given",
"in",
"order",
"to",
"minimize",
"the",
"error",
"."
] | 46c40e0bca02d74201fb99925843cde49e9fe68a | https://github.com/wavesoft/jbb/blob/46c40e0bca02d74201fb99925843cde49e9fe68a/encoder.js#L927-L980 | train |
wavesoft/jbb | encoder.js | getDownscaleType | 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 else is equal to or bigger than 4 bytes
default:
return NUMTYPE.UNKNOWN;
}
case NUMTYPE.INT32:
switch (analysis.type) {
// INT32 -> UINT8 = INT8/INT16 (if v < INT8_MAX)
case NUMTYPE.UINT8:
if (analysis.max < INT8_MAX) {
return NUMTYPE.INT8;
} else {
return NUMTYPE.INT16;
}
// INT32 -> INT8
case NUMTYPE.INT8:
return NUMTYPE.INT8;
// INT32 -> UINT16 = INT16 (if v < INT16_MAX)
case NUMTYPE.UINT16:
if (analysis.max < INT16_MAX) {
return NUMTYPE.INT16;
} else {
return NUMTYPE.UNKNOWN;
}
// INT32 -> INT16
case NUMTYPE.INT16:
return NUMTYPE.INT16;
// Anything else is equal to or bigger than 4 bytes
default:
return NUMTYPE.UNKNOWN;
}
case NUMTYPE.FLOAT32:
switch (analysis.type) {
// FLOAT32 -> Anything 1-2 bytes
case NUMTYPE.UINT8:
return NUMTYPE.UINT8;
case NUMTYPE.INT8:
return NUMTYPE.INT8;
case NUMTYPE.UINT16:
return NUMTYPE.UINT16
case NUMTYPE.INT16:
return NUMTYPE.INT16
// Everything else is discarded
default:
return NUMTYPE.UNKNOWN;
}
case NUMTYPE.FLOAT64:
switch (analysis.type) {
// FLOAT64 -> Anything 1-2 bytes
case NUMTYPE.UINT8:
return NUMTYPE.UINT8;
case NUMTYPE.INT8:
return NUMTYPE.INT8;
case NUMTYPE.UINT16:
return NUMTYPE.UINT16
case NUMTYPE.INT16:
return NUMTYPE.INT16
// FLOAT64 -> FLOAT32
case NUMTYPE.FLOAT32:
return NUMTYPE.FLOAT32
// Everything else is discarded
default:
return NUMTYPE.UNKNOWN;
}
}
} | javascript | 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 else is equal to or bigger than 4 bytes
default:
return NUMTYPE.UNKNOWN;
}
case NUMTYPE.INT32:
switch (analysis.type) {
// INT32 -> UINT8 = INT8/INT16 (if v < INT8_MAX)
case NUMTYPE.UINT8:
if (analysis.max < INT8_MAX) {
return NUMTYPE.INT8;
} else {
return NUMTYPE.INT16;
}
// INT32 -> INT8
case NUMTYPE.INT8:
return NUMTYPE.INT8;
// INT32 -> UINT16 = INT16 (if v < INT16_MAX)
case NUMTYPE.UINT16:
if (analysis.max < INT16_MAX) {
return NUMTYPE.INT16;
} else {
return NUMTYPE.UNKNOWN;
}
// INT32 -> INT16
case NUMTYPE.INT16:
return NUMTYPE.INT16;
// Anything else is equal to or bigger than 4 bytes
default:
return NUMTYPE.UNKNOWN;
}
case NUMTYPE.FLOAT32:
switch (analysis.type) {
// FLOAT32 -> Anything 1-2 bytes
case NUMTYPE.UINT8:
return NUMTYPE.UINT8;
case NUMTYPE.INT8:
return NUMTYPE.INT8;
case NUMTYPE.UINT16:
return NUMTYPE.UINT16
case NUMTYPE.INT16:
return NUMTYPE.INT16
// Everything else is discarded
default:
return NUMTYPE.UNKNOWN;
}
case NUMTYPE.FLOAT64:
switch (analysis.type) {
// FLOAT64 -> Anything 1-2 bytes
case NUMTYPE.UINT8:
return NUMTYPE.UINT8;
case NUMTYPE.INT8:
return NUMTYPE.INT8;
case NUMTYPE.UINT16:
return NUMTYPE.UINT16
case NUMTYPE.INT16:
return NUMTYPE.INT16
// FLOAT64 -> FLOAT32
case NUMTYPE.FLOAT32:
return NUMTYPE.FLOAT32
// Everything else is discarded
default:
return NUMTYPE.UNKNOWN;
}
}
} | [
"function",
"getDownscaleType",
"(",
"n_type",
",",
"analysis",
")",
"{",
"switch",
"(",
"n_type",
")",
"{",
"case",
"NUMTYPE",
".",
"UINT8",
":",
"case",
"NUMTYPE",
".",
"INT8",
":",
"return",
"NUMTYPE",
".",
"UNKNOWN",
";",
"case",
"NUMTYPE",
".",
"UINT16",
":",
"switch",
"(",
"analysis",
".",
"type",
")",
"{",
"case",
"NUMTYPE",
".",
"INT8",
":",
"case",
"NUMTYPE",
".",
"UINT8",
":",
"return",
"NUMTYPE",
".",
"UINT8",
";",
"default",
":",
"return",
"NUMTYPE",
".",
"UNKNOWN",
";",
"}",
"case",
"NUMTYPE",
".",
"INT16",
":",
"switch",
"(",
"analysis",
".",
"type",
")",
"{",
"case",
"NUMTYPE",
".",
"UINT8",
":",
"if",
"(",
"analysis",
".",
"max",
"<",
"INT8_MAX",
")",
"{",
"return",
"NUMTYPE",
".",
"INT8",
";",
"}",
"else",
"{",
"return",
"NUMTYPE",
".",
"UNKNOWN",
";",
"}",
"case",
"NUMTYPE",
".",
"INT8",
":",
"return",
"NUMTYPE",
".",
"INT8",
";",
"default",
":",
"return",
"NUMTYPE",
".",
"UNKNOWN",
";",
"}",
"case",
"NUMTYPE",
".",
"UINT32",
":",
"switch",
"(",
"analysis",
".",
"type",
")",
"{",
"case",
"NUMTYPE",
".",
"INT8",
":",
"case",
"NUMTYPE",
".",
"UINT8",
":",
"return",
"NUMTYPE",
".",
"UINT8",
";",
"case",
"NUMTYPE",
".",
"INT16",
":",
"case",
"NUMTYPE",
".",
"UINT16",
":",
"return",
"NUMTYPE",
".",
"UINT16",
";",
"default",
":",
"return",
"NUMTYPE",
".",
"UNKNOWN",
";",
"}",
"case",
"NUMTYPE",
".",
"INT32",
":",
"switch",
"(",
"analysis",
".",
"type",
")",
"{",
"case",
"NUMTYPE",
".",
"UINT8",
":",
"if",
"(",
"analysis",
".",
"max",
"<",
"INT8_MAX",
")",
"{",
"return",
"NUMTYPE",
".",
"INT8",
";",
"}",
"else",
"{",
"return",
"NUMTYPE",
".",
"INT16",
";",
"}",
"case",
"NUMTYPE",
".",
"INT8",
":",
"return",
"NUMTYPE",
".",
"INT8",
";",
"case",
"NUMTYPE",
".",
"UINT16",
":",
"if",
"(",
"analysis",
".",
"max",
"<",
"INT16_MAX",
")",
"{",
"return",
"NUMTYPE",
".",
"INT16",
";",
"}",
"else",
"{",
"return",
"NUMTYPE",
".",
"UNKNOWN",
";",
"}",
"case",
"NUMTYPE",
".",
"INT16",
":",
"return",
"NUMTYPE",
".",
"INT16",
";",
"default",
":",
"return",
"NUMTYPE",
".",
"UNKNOWN",
";",
"}",
"case",
"NUMTYPE",
".",
"FLOAT32",
":",
"switch",
"(",
"analysis",
".",
"type",
")",
"{",
"case",
"NUMTYPE",
".",
"UINT8",
":",
"return",
"NUMTYPE",
".",
"UINT8",
";",
"case",
"NUMTYPE",
".",
"INT8",
":",
"return",
"NUMTYPE",
".",
"INT8",
";",
"case",
"NUMTYPE",
".",
"UINT16",
":",
"return",
"NUMTYPE",
".",
"UINT16",
"case",
"NUMTYPE",
".",
"INT16",
":",
"return",
"NUMTYPE",
".",
"INT16",
"default",
":",
"return",
"NUMTYPE",
".",
"UNKNOWN",
";",
"}",
"case",
"NUMTYPE",
".",
"FLOAT64",
":",
"switch",
"(",
"analysis",
".",
"type",
")",
"{",
"case",
"NUMTYPE",
".",
"UINT8",
":",
"return",
"NUMTYPE",
".",
"UINT8",
";",
"case",
"NUMTYPE",
".",
"INT8",
":",
"return",
"NUMTYPE",
".",
"INT8",
";",
"case",
"NUMTYPE",
".",
"UINT16",
":",
"return",
"NUMTYPE",
".",
"UINT16",
"case",
"NUMTYPE",
".",
"INT16",
":",
"return",
"NUMTYPE",
".",
"INT16",
"case",
"NUMTYPE",
".",
"FLOAT32",
":",
"return",
"NUMTYPE",
".",
"FLOAT32",
"default",
":",
"return",
"NUMTYPE",
".",
"UNKNOWN",
";",
"}",
"}",
"}"
] | Get the possible downscale type based on the specified analysis | [
"Get",
"the",
"possible",
"downscale",
"type",
"based",
"on",
"the",
"specified",
"analysis"
] | 46c40e0bca02d74201fb99925843cde49e9fe68a | https://github.com/wavesoft/jbb/blob/46c40e0bca02d74201fb99925843cde49e9fe68a/encoder.js#L985-L1119 | train |
wavesoft/jbb | encoder.js | getBestBinFit | 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 >= start) && (e < end-1)) || // End in bounds
((s <= start) && (e >= end)) ) //
{
// Check bounds
if (s < start) s = start;
if (s > end-2) continue;
if (e > end) e = end;
if (s === e) continue;
// Test coverage
c = e - s;
if (c > last_c) {
last_c = c;
last_s = s;
last_bin = b[i];
found = true;
}
}
}
// Prefer priority to length across different blocks
// on the first block (repeated)
if ((bi === 0) && found)
return last_bin;
}
// Update bounds
if (last_bin) {
last_bin = last_bin.slice();
last_bin[0] = last_s;
last_bin[1] = last_c;
}
// Return last bin
return last_bin;
} | javascript | 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 >= start) && (e < end-1)) || // End in bounds
((s <= start) && (e >= end)) ) //
{
// Check bounds
if (s < start) s = start;
if (s > end-2) continue;
if (e > end) e = end;
if (s === e) continue;
// Test coverage
c = e - s;
if (c > last_c) {
last_c = c;
last_s = s;
last_bin = b[i];
found = true;
}
}
}
// Prefer priority to length across different blocks
// on the first block (repeated)
if ((bi === 0) && found)
return last_bin;
}
// Update bounds
if (last_bin) {
last_bin = last_bin.slice();
last_bin[0] = last_s;
last_bin[1] = last_c;
}
// Return last bin
return last_bin;
} | [
"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",
";",
"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",
"]",
";",
"if",
"(",
"(",
"(",
"s",
">=",
"start",
")",
"&&",
"(",
"s",
"<",
"end",
"-",
"1",
")",
")",
"||",
"(",
"(",
"e",
">=",
"start",
")",
"&&",
"(",
"e",
"<",
"end",
"-",
"1",
")",
")",
"||",
"(",
"(",
"s",
"<=",
"start",
")",
"&&",
"(",
"e",
">=",
"end",
")",
")",
")",
"{",
"if",
"(",
"s",
"<",
"start",
")",
"s",
"=",
"start",
";",
"if",
"(",
"s",
">",
"end",
"-",
"2",
")",
"continue",
";",
"if",
"(",
"e",
">",
"end",
")",
"e",
"=",
"end",
";",
"if",
"(",
"s",
"===",
"e",
")",
"continue",
";",
"c",
"=",
"e",
"-",
"s",
";",
"if",
"(",
"c",
">",
"last_c",
")",
"{",
"last_c",
"=",
"c",
";",
"last_s",
"=",
"s",
";",
"last_bin",
"=",
"b",
"[",
"i",
"]",
";",
"found",
"=",
"true",
";",
"}",
"}",
"}",
"if",
"(",
"(",
"bi",
"===",
"0",
")",
"&&",
"found",
")",
"return",
"last_bin",
";",
"}",
"if",
"(",
"last_bin",
")",
"{",
"last_bin",
"=",
"last_bin",
".",
"slice",
"(",
")",
";",
"last_bin",
"[",
"0",
"]",
"=",
"last_s",
";",
"last_bin",
"[",
"1",
"]",
"=",
"last_c",
";",
"}",
"return",
"last_bin",
";",
"}"
] | Pack the specified number of bins to the specified bounds | [
"Pack",
"the",
"specified",
"number",
"of",
"bins",
"to",
"the",
"specified",
"bounds"
] | 46c40e0bca02d74201fb99925843cde49e9fe68a | https://github.com/wavesoft/jbb/blob/46c40e0bca02d74201fb99925843cde49e9fe68a/encoder.js#L1299-L1350 | train |
wavesoft/jbb | encoder.js | downscaleType | function downscaleType( fromType, toType ) {
// Lookup conversion on the downscale table
for (var i=0; i<NUMTYPE_DOWNSCALE.FROM.length; ++i) {
if ( (NUMTYPE_DOWNSCALE.FROM[i] === fromType) &&
(NUMTYPE_DOWNSCALE.TO[i] === toType) )
return i;
}
// Nothing found
return undefined;
} | javascript | function downscaleType( fromType, toType ) {
// Lookup conversion on the downscale table
for (var i=0; i<NUMTYPE_DOWNSCALE.FROM.length; ++i) {
if ( (NUMTYPE_DOWNSCALE.FROM[i] === fromType) &&
(NUMTYPE_DOWNSCALE.TO[i] === toType) )
return i;
}
// Nothing found
return undefined;
} | [
"function",
"downscaleType",
"(",
"fromType",
",",
"toType",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"NUMTYPE_DOWNSCALE",
".",
"FROM",
".",
"length",
";",
"++",
"i",
")",
"{",
"if",
"(",
"(",
"NUMTYPE_DOWNSCALE",
".",
"FROM",
"[",
"i",
"]",
"===",
"fromType",
")",
"&&",
"(",
"NUMTYPE_DOWNSCALE",
".",
"TO",
"[",
"i",
"]",
"===",
"toType",
")",
")",
"return",
"i",
";",
"}",
"return",
"undefined",
";",
"}"
] | Pick a matching downscaling type | [
"Pick",
"a",
"matching",
"downscaling",
"type"
] | 46c40e0bca02d74201fb99925843cde49e9fe68a | https://github.com/wavesoft/jbb/blob/46c40e0bca02d74201fb99925843cde49e9fe68a/encoder.js#L1811-L1820 | train |
wavesoft/jbb | encoder.js | deltaEncTypeInt | function deltaEncTypeInt( fromType, toType ) {
// Lookup conversion on the downscale table
for (var i=0; i<NUMTYPE_DELTA_INT.FROM.length; ++i) {
if ( (NUMTYPE_DELTA_INT.FROM[i] === fromType) &&
(NUMTYPE_DELTA_INT.TO[i] === toType) )
return i;
}
// Nothing found
return undefined;
} | javascript | function deltaEncTypeInt( fromType, toType ) {
// Lookup conversion on the downscale table
for (var i=0; i<NUMTYPE_DELTA_INT.FROM.length; ++i) {
if ( (NUMTYPE_DELTA_INT.FROM[i] === fromType) &&
(NUMTYPE_DELTA_INT.TO[i] === toType) )
return i;
}
// Nothing found
return undefined;
} | [
"function",
"deltaEncTypeInt",
"(",
"fromType",
",",
"toType",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"NUMTYPE_DELTA_INT",
".",
"FROM",
".",
"length",
";",
"++",
"i",
")",
"{",
"if",
"(",
"(",
"NUMTYPE_DELTA_INT",
".",
"FROM",
"[",
"i",
"]",
"===",
"fromType",
")",
"&&",
"(",
"NUMTYPE_DELTA_INT",
".",
"TO",
"[",
"i",
"]",
"===",
"toType",
")",
")",
"return",
"i",
";",
"}",
"return",
"undefined",
";",
"}"
] | Pick a matching delta encoding delta for integers | [
"Pick",
"a",
"matching",
"delta",
"encoding",
"delta",
"for",
"integers"
] | 46c40e0bca02d74201fb99925843cde49e9fe68a | https://github.com/wavesoft/jbb/blob/46c40e0bca02d74201fb99925843cde49e9fe68a/encoder.js#L1825-L1834 | train |
wavesoft/jbb | encoder.js | deltaEncTypeFloat | function deltaEncTypeFloat( fromType, toType ) {
// Lookup conversion on the downscale table
for (var i=0; i<NUMTYPE_DELTA_FLOAT.FROM.length; ++i) {
if ( (NUMTYPE_DELTA_FLOAT.FROM[i] === fromType) &&
(NUMTYPE_DELTA_FLOAT.TO[i] === toType) )
return i;
}
// Nothing found
return undefined;
} | javascript | function deltaEncTypeFloat( fromType, toType ) {
// Lookup conversion on the downscale table
for (var i=0; i<NUMTYPE_DELTA_FLOAT.FROM.length; ++i) {
if ( (NUMTYPE_DELTA_FLOAT.FROM[i] === fromType) &&
(NUMTYPE_DELTA_FLOAT.TO[i] === toType) )
return i;
}
// Nothing found
return undefined;
} | [
"function",
"deltaEncTypeFloat",
"(",
"fromType",
",",
"toType",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"NUMTYPE_DELTA_FLOAT",
".",
"FROM",
".",
"length",
";",
"++",
"i",
")",
"{",
"if",
"(",
"(",
"NUMTYPE_DELTA_FLOAT",
".",
"FROM",
"[",
"i",
"]",
"===",
"fromType",
")",
"&&",
"(",
"NUMTYPE_DELTA_FLOAT",
".",
"TO",
"[",
"i",
"]",
"===",
"toType",
")",
")",
"return",
"i",
";",
"}",
"return",
"undefined",
";",
"}"
] | Pick a matching delta encoding delta for floats | [
"Pick",
"a",
"matching",
"delta",
"encoding",
"delta",
"for",
"floats"
] | 46c40e0bca02d74201fb99925843cde49e9fe68a | https://github.com/wavesoft/jbb/blob/46c40e0bca02d74201fb99925843cde49e9fe68a/encoder.js#L1839-L1848 | train |
wavesoft/jbb | encoder.js | deltaEncodeIntegers | function deltaEncodeIntegers( array, numType ) {
var delta = new NUMTYPE_CLASS[numType]( array.length - 1 ), l = array[0];
for (var i=1; i<array.length; ++i) {
var v = array[i]; delta[i-1] = v - l; l = v;
}
return delta;
} | javascript | function deltaEncodeIntegers( array, numType ) {
var delta = new NUMTYPE_CLASS[numType]( array.length - 1 ), l = array[0];
for (var i=1; i<array.length; ++i) {
var v = array[i]; delta[i-1] = v - l; l = v;
}
return delta;
} | [
"function",
"deltaEncodeIntegers",
"(",
"array",
",",
"numType",
")",
"{",
"var",
"delta",
"=",
"new",
"NUMTYPE_CLASS",
"[",
"numType",
"]",
"(",
"array",
".",
"length",
"-",
"1",
")",
",",
"l",
"=",
"array",
"[",
"0",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"1",
";",
"i",
"<",
"array",
".",
"length",
";",
"++",
"i",
")",
"{",
"var",
"v",
"=",
"array",
"[",
"i",
"]",
";",
"delta",
"[",
"i",
"-",
"1",
"]",
"=",
"v",
"-",
"l",
";",
"l",
"=",
"v",
";",
"}",
"return",
"delta",
";",
"}"
] | Encode an integer array with delta encoding
@param {array} - Source Array
@param {Class} - The class of the underlaying numeric array (ex. Uint8Array)
@return {array} - An array with the initial value and the delta-encoded payload | [
"Encode",
"an",
"integer",
"array",
"with",
"delta",
"encoding"
] | 46c40e0bca02d74201fb99925843cde49e9fe68a | https://github.com/wavesoft/jbb/blob/46c40e0bca02d74201fb99925843cde49e9fe68a/encoder.js#L1858-L1864 | train |
wavesoft/jbb | encoder.js | convertArray | 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) && (numType === NUMTYPE.INT16)) ||
((array instanceof Uint32Array) && (numType === NUMTYPE.UINT32)) ||
((array instanceof Int32Array) && (numType === NUMTYPE.INT32)) ||
((array instanceof Float32Array) && (numType === NUMTYPE.FLOAT32)) ||
((array instanceof Float64Array) && (numType === NUMTYPE.FLOAT64)) ) {
// Return as-is
return array;
}
// Convert
return new NUMTYPE_CLASS[numType]( array );
} | javascript | 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) && (numType === NUMTYPE.INT16)) ||
((array instanceof Uint32Array) && (numType === NUMTYPE.UINT32)) ||
((array instanceof Int32Array) && (numType === NUMTYPE.INT32)) ||
((array instanceof Float32Array) && (numType === NUMTYPE.FLOAT32)) ||
((array instanceof Float64Array) && (numType === NUMTYPE.FLOAT64)) ) {
// Return as-is
return array;
}
// Convert
return new NUMTYPE_CLASS[numType]( array );
} | [
"function",
"convertArray",
"(",
"array",
",",
"numType",
")",
"{",
"if",
"(",
"(",
"(",
"array",
"instanceof",
"Uint8Array",
")",
"&&",
"(",
"numType",
"===",
"NUMTYPE",
".",
"UINT8",
")",
")",
"||",
"(",
"(",
"array",
"instanceof",
"Int8Array",
")",
"&&",
"(",
"numType",
"===",
"NUMTYPE",
".",
"INT8",
")",
")",
"||",
"(",
"(",
"array",
"instanceof",
"Uint16Array",
")",
"&&",
"(",
"numType",
"===",
"NUMTYPE",
".",
"UINT16",
")",
")",
"||",
"(",
"(",
"array",
"instanceof",
"Int16Array",
")",
"&&",
"(",
"numType",
"===",
"NUMTYPE",
".",
"INT16",
")",
")",
"||",
"(",
"(",
"array",
"instanceof",
"Uint32Array",
")",
"&&",
"(",
"numType",
"===",
"NUMTYPE",
".",
"UINT32",
")",
")",
"||",
"(",
"(",
"array",
"instanceof",
"Int32Array",
")",
"&&",
"(",
"numType",
"===",
"NUMTYPE",
".",
"INT32",
")",
")",
"||",
"(",
"(",
"array",
"instanceof",
"Float32Array",
")",
"&&",
"(",
"numType",
"===",
"NUMTYPE",
".",
"FLOAT32",
")",
")",
"||",
"(",
"(",
"array",
"instanceof",
"Float64Array",
")",
"&&",
"(",
"numType",
"===",
"NUMTYPE",
".",
"FLOAT64",
")",
")",
")",
"{",
"return",
"array",
";",
"}",
"return",
"new",
"NUMTYPE_CLASS",
"[",
"numType",
"]",
"(",
"array",
")",
";",
"}"
] | Convert input array to the type specified
@param {array} array - The source array
@param {int} downscale_type - The downscaling conversion | [
"Convert",
"input",
"array",
"to",
"the",
"type",
"specified"
] | 46c40e0bca02d74201fb99925843cde49e9fe68a | https://github.com/wavesoft/jbb/blob/46c40e0bca02d74201fb99925843cde49e9fe68a/encoder.js#L1872-L1890 | train |
wavesoft/jbb | encoder.js | mimeTypeFromFilename | function mimeTypeFromFilename( filename ) {
var ext = filename.split(".").pop().toLowerCase();
return mime.lookup(filename) || "application/octet-stream";
} | javascript | function mimeTypeFromFilename( filename ) {
var ext = filename.split(".").pop().toLowerCase();
return mime.lookup(filename) || "application/octet-stream";
} | [
"function",
"mimeTypeFromFilename",
"(",
"filename",
")",
"{",
"var",
"ext",
"=",
"filename",
".",
"split",
"(",
"\".\"",
")",
".",
"pop",
"(",
")",
".",
"toLowerCase",
"(",
")",
";",
"return",
"mime",
".",
"lookup",
"(",
"filename",
")",
"||",
"\"application/octet-stream\"",
";",
"}"
] | Pick MIME type according to filename and known MIME Types | [
"Pick",
"MIME",
"type",
"according",
"to",
"filename",
"and",
"known",
"MIME",
"Types"
] | 46c40e0bca02d74201fb99925843cde49e9fe68a | https://github.com/wavesoft/jbb/blob/46c40e0bca02d74201fb99925843cde49e9fe68a/encoder.js#L1895-L1898 | train |
wavesoft/jbb | encoder.js | bufferFromFile | function bufferFromFile( filename ) {
console.info( ("Loading "+filename).grey );
var buf = fs.readFileSync( filename ), // Load Buffer
ab = new ArrayBuffer( buf.length ), // Create an ArrayBuffer to fit the data
view = new Uint8Array(ab); // Create an Uint8Array view
// Copy buffer into view
for (var i = 0; i < buf.length; ++i)
view[i] = buf[i];
// Return buffer view
return view;
} | javascript | function bufferFromFile( filename ) {
console.info( ("Loading "+filename).grey );
var buf = fs.readFileSync( filename ), // Load Buffer
ab = new ArrayBuffer( buf.length ), // Create an ArrayBuffer to fit the data
view = new Uint8Array(ab); // Create an Uint8Array view
// Copy buffer into view
for (var i = 0; i < buf.length; ++i)
view[i] = buf[i];
// Return buffer view
return view;
} | [
"function",
"bufferFromFile",
"(",
"filename",
")",
"{",
"console",
".",
"info",
"(",
"(",
"\"Loading \"",
"+",
"filename",
")",
".",
"grey",
")",
";",
"var",
"buf",
"=",
"fs",
".",
"readFileSync",
"(",
"filename",
")",
",",
"ab",
"=",
"new",
"ArrayBuffer",
"(",
"buf",
".",
"length",
")",
",",
"view",
"=",
"new",
"Uint8Array",
"(",
"ab",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"buf",
".",
"length",
";",
"++",
"i",
")",
"view",
"[",
"i",
"]",
"=",
"buf",
"[",
"i",
"]",
";",
"return",
"view",
";",
"}"
] | Load a Uint8Array buffer from file | [
"Load",
"a",
"Uint8Array",
"buffer",
"from",
"file"
] | 46c40e0bca02d74201fb99925843cde49e9fe68a | https://github.com/wavesoft/jbb/blob/46c40e0bca02d74201fb99925843cde49e9fe68a/encoder.js#L1903-L1915 | train |
wavesoft/jbb | encoder.js | pickStream | 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:
case NUMTYPE.FLOAT32:
return encoder.stream32;
case NUMTYPE.FLOAT64:
return encoder.stream64;
}
} | javascript | 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:
case NUMTYPE.FLOAT32:
return encoder.stream32;
case NUMTYPE.FLOAT64:
return encoder.stream64;
}
} | [
"function",
"pickStream",
"(",
"encoder",
",",
"t",
")",
"{",
"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",
":",
"case",
"NUMTYPE",
".",
"FLOAT32",
":",
"return",
"encoder",
".",
"stream32",
";",
"case",
"NUMTYPE",
".",
"FLOAT64",
":",
"return",
"encoder",
".",
"stream64",
";",
"}",
"}"
] | Select an encoder according to bit size | [
"Select",
"an",
"encoder",
"according",
"to",
"bit",
"size"
] | 46c40e0bca02d74201fb99925843cde49e9fe68a | https://github.com/wavesoft/jbb/blob/46c40e0bca02d74201fb99925843cde49e9fe68a/encoder.js#L1929-L1947 | train |
wavesoft/jbb | encoder.js | encodeArray_NUM_DWS | 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) ) );
encoder.stream16.write( pack2b( data.length, false ) );
encoder.counters.arr_hdr+=3;
} else { // 32-bit length prefix
encoder.stream8.write( pack1b( ARR_OP.NUM_DWS | NUMTYPE_LN.UINT32 | (n_dws_type << 1) ) );
encoder.stream32.write( pack4b( data.length, false ) );
encoder.counters.arr_hdr+=5;
}
// Encode value
pickStream( encoder, n_to )
.write( packTypedArray( convertArray( data, n_to ) ) );
} | javascript | 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) ) );
encoder.stream16.write( pack2b( data.length, false ) );
encoder.counters.arr_hdr+=3;
} else { // 32-bit length prefix
encoder.stream8.write( pack1b( ARR_OP.NUM_DWS | NUMTYPE_LN.UINT32 | (n_dws_type << 1) ) );
encoder.stream32.write( pack4b( data.length, false ) );
encoder.counters.arr_hdr+=5;
}
// Encode value
pickStream( encoder, n_to )
.write( packTypedArray( convertArray( data, n_to ) ) );
} | [
"function",
"encodeArray_NUM_DWS",
"(",
"encoder",
",",
"data",
",",
"n_from",
",",
"n_to",
")",
"{",
"var",
"n_dws_type",
"=",
"downscaleType",
"(",
"n_from",
",",
"n_to",
")",
";",
"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",
")",
"{",
"encoder",
".",
"stream8",
".",
"write",
"(",
"pack1b",
"(",
"ARR_OP",
".",
"NUM_DWS",
"|",
"NUMTYPE_LN",
".",
"UINT16",
"|",
"(",
"n_dws_type",
"<<",
"1",
")",
")",
")",
";",
"encoder",
".",
"stream16",
".",
"write",
"(",
"pack2b",
"(",
"data",
".",
"length",
",",
"false",
")",
")",
";",
"encoder",
".",
"counters",
".",
"arr_hdr",
"+=",
"3",
";",
"}",
"else",
"{",
"encoder",
".",
"stream8",
".",
"write",
"(",
"pack1b",
"(",
"ARR_OP",
".",
"NUM_DWS",
"|",
"NUMTYPE_LN",
".",
"UINT32",
"|",
"(",
"n_dws_type",
"<<",
"1",
")",
")",
")",
";",
"encoder",
".",
"stream32",
".",
"write",
"(",
"pack4b",
"(",
"data",
".",
"length",
",",
"false",
")",
")",
";",
"encoder",
".",
"counters",
".",
"arr_hdr",
"+=",
"5",
";",
"}",
"pickStream",
"(",
"encoder",
",",
"n_to",
")",
".",
"write",
"(",
"packTypedArray",
"(",
"convertArray",
"(",
"data",
",",
"n_to",
")",
")",
")",
";",
"}"
] | Encode array data as downscaled | [
"Encode",
"array",
"data",
"as",
"downscaled"
] | 46c40e0bca02d74201fb99925843cde49e9fe68a | https://github.com/wavesoft/jbb/blob/46c40e0bca02d74201fb99925843cde49e9fe68a/encoder.js#L1952-L1984 | train |
wavesoft/jbb | encoder.js | encodeArray_NUM_DELTA_FLOAT | 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+")"+
", pivot="+pivot+", scale="+f_scale);
if (data.length < UINT16_MAX) { // 16-bit length prefix
encoder.stream8.write( pack1b( ARR_OP.NUM_DELTA_FLOAT | NUMTYPE_LN.UINT16 | (n_delta_type << 1) ) );
encoder.stream16.write( pack2b( data.length, false ) );
encoder.counters.arr_hdr+=3;
} else { // 32-bit length prefix
encoder.stream8.write( pack1b( ARR_OP.NUM_DELTA_FLOAT | NUMTYPE_LN.UINT32 | (n_delta_type << 1) ) );
encoder.stream32.write( pack4b( data.length, false ) );
encoder.counters.arr_hdr+=5;
}
// Write pivot value
pickStream( encoder, n_from )
.write( packByNumType[n_from]( pivot ) );
// Write scale
encoder.stream64.write( pack8f( f_scale ) );
// Pivot-encode floats
var pivot_array = new NUMTYPE_CLASS[n_to]( data.length );
for (var i=1; i<data.length; ++i) {
pivot_array[i] = (data[i] - pivot) / f_scale;
// console.log(">>>", data[i],"->", pivot_array[i]);
}
// Envode pivot array
pickStream( encoder, n_to)
.write( packTypedArray( pivot_array ) );
} | javascript | 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+")"+
", pivot="+pivot+", scale="+f_scale);
if (data.length < UINT16_MAX) { // 16-bit length prefix
encoder.stream8.write( pack1b( ARR_OP.NUM_DELTA_FLOAT | NUMTYPE_LN.UINT16 | (n_delta_type << 1) ) );
encoder.stream16.write( pack2b( data.length, false ) );
encoder.counters.arr_hdr+=3;
} else { // 32-bit length prefix
encoder.stream8.write( pack1b( ARR_OP.NUM_DELTA_FLOAT | NUMTYPE_LN.UINT32 | (n_delta_type << 1) ) );
encoder.stream32.write( pack4b( data.length, false ) );
encoder.counters.arr_hdr+=5;
}
// Write pivot value
pickStream( encoder, n_from )
.write( packByNumType[n_from]( pivot ) );
// Write scale
encoder.stream64.write( pack8f( f_scale ) );
// Pivot-encode floats
var pivot_array = new NUMTYPE_CLASS[n_to]( data.length );
for (var i=1; i<data.length; ++i) {
pivot_array[i] = (data[i] - pivot) / f_scale;
// console.log(">>>", data[i],"->", pivot_array[i]);
}
// Envode pivot array
pickStream( encoder, n_to)
.write( packTypedArray( pivot_array ) );
} | [
"function",
"encodeArray_NUM_DELTA_FLOAT",
"(",
"encoder",
",",
"data",
",",
"n_from",
",",
"n_to",
",",
"pivot",
",",
"f_scale",
")",
"{",
"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",
"+",
"\")\"",
"+",
"\", pivot=\"",
"+",
"pivot",
"+",
"\", scale=\"",
"+",
"f_scale",
")",
";",
"if",
"(",
"data",
".",
"length",
"<",
"UINT16_MAX",
")",
"{",
"encoder",
".",
"stream8",
".",
"write",
"(",
"pack1b",
"(",
"ARR_OP",
".",
"NUM_DELTA_FLOAT",
"|",
"NUMTYPE_LN",
".",
"UINT16",
"|",
"(",
"n_delta_type",
"<<",
"1",
")",
")",
")",
";",
"encoder",
".",
"stream16",
".",
"write",
"(",
"pack2b",
"(",
"data",
".",
"length",
",",
"false",
")",
")",
";",
"encoder",
".",
"counters",
".",
"arr_hdr",
"+=",
"3",
";",
"}",
"else",
"{",
"encoder",
".",
"stream8",
".",
"write",
"(",
"pack1b",
"(",
"ARR_OP",
".",
"NUM_DELTA_FLOAT",
"|",
"NUMTYPE_LN",
".",
"UINT32",
"|",
"(",
"n_delta_type",
"<<",
"1",
")",
")",
")",
";",
"encoder",
".",
"stream32",
".",
"write",
"(",
"pack4b",
"(",
"data",
".",
"length",
",",
"false",
")",
")",
";",
"encoder",
".",
"counters",
".",
"arr_hdr",
"+=",
"5",
";",
"}",
"pickStream",
"(",
"encoder",
",",
"n_from",
")",
".",
"write",
"(",
"packByNumType",
"[",
"n_from",
"]",
"(",
"pivot",
")",
")",
";",
"encoder",
".",
"stream64",
".",
"write",
"(",
"pack8f",
"(",
"f_scale",
")",
")",
";",
"var",
"pivot_array",
"=",
"new",
"NUMTYPE_CLASS",
"[",
"n_to",
"]",
"(",
"data",
".",
"length",
")",
";",
"for",
"(",
"var",
"i",
"=",
"1",
";",
"i",
"<",
"data",
".",
"length",
";",
"++",
"i",
")",
"{",
"pivot_array",
"[",
"i",
"]",
"=",
"(",
"data",
"[",
"i",
"]",
"-",
"pivot",
")",
"/",
"f_scale",
";",
"}",
"pickStream",
"(",
"encoder",
",",
"n_to",
")",
".",
"write",
"(",
"packTypedArray",
"(",
"pivot_array",
")",
")",
";",
"}"
] | Pivot-encode float array | [
"Pivot",
"-",
"encode",
"float",
"array"
] | 46c40e0bca02d74201fb99925843cde49e9fe68a | https://github.com/wavesoft/jbb/blob/46c40e0bca02d74201fb99925843cde49e9fe68a/encoder.js#L1989-L2038 | train |
wavesoft/jbb | encoder.js | encodeArray_NUM_DELTA_INT | 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) ) );
encoder.stream16.write( pack2b( data.length, false ) );
encoder.counters.arr_hdr+=3;
} else { // 32-bit length prefix
encoder.stream8.write( pack1b( ARR_OP.NUM_DELTA_INT | NUMTYPE_LN.UINT32 | (n_delta_type << 1) ) );
encoder.stream32.write( pack4b( data.length, false ) );
encoder.counters.arr_hdr+=5;
}
// Write initial value
pickStream( encoder, n_from )
.write( packByNumType[n_from]( data[0] ) );
// Delta-encode integers
pickStream( encoder, n_to)
.write( packTypedArray( deltaEncodeIntegers( data, n_to ) ) );
} | javascript | 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) ) );
encoder.stream16.write( pack2b( data.length, false ) );
encoder.counters.arr_hdr+=3;
} else { // 32-bit length prefix
encoder.stream8.write( pack1b( ARR_OP.NUM_DELTA_INT | NUMTYPE_LN.UINT32 | (n_delta_type << 1) ) );
encoder.stream32.write( pack4b( data.length, false ) );
encoder.counters.arr_hdr+=5;
}
// Write initial value
pickStream( encoder, n_from )
.write( packByNumType[n_from]( data[0] ) );
// Delta-encode integers
pickStream( encoder, n_to)
.write( packTypedArray( deltaEncodeIntegers( data, n_to ) ) );
} | [
"function",
"encodeArray_NUM_DELTA_INT",
"(",
"encoder",
",",
"data",
",",
"n_from",
",",
"n_to",
")",
"{",
"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",
")",
"{",
"encoder",
".",
"stream8",
".",
"write",
"(",
"pack1b",
"(",
"ARR_OP",
".",
"NUM_DELTA_INT",
"|",
"NUMTYPE_LN",
".",
"UINT16",
"|",
"(",
"n_delta_type",
"<<",
"1",
")",
")",
")",
";",
"encoder",
".",
"stream16",
".",
"write",
"(",
"pack2b",
"(",
"data",
".",
"length",
",",
"false",
")",
")",
";",
"encoder",
".",
"counters",
".",
"arr_hdr",
"+=",
"3",
";",
"}",
"else",
"{",
"encoder",
".",
"stream8",
".",
"write",
"(",
"pack1b",
"(",
"ARR_OP",
".",
"NUM_DELTA_INT",
"|",
"NUMTYPE_LN",
".",
"UINT32",
"|",
"(",
"n_delta_type",
"<<",
"1",
")",
")",
")",
";",
"encoder",
".",
"stream32",
".",
"write",
"(",
"pack4b",
"(",
"data",
".",
"length",
",",
"false",
")",
")",
";",
"encoder",
".",
"counters",
".",
"arr_hdr",
"+=",
"5",
";",
"}",
"pickStream",
"(",
"encoder",
",",
"n_from",
")",
".",
"write",
"(",
"packByNumType",
"[",
"n_from",
"]",
"(",
"data",
"[",
"0",
"]",
")",
")",
";",
"pickStream",
"(",
"encoder",
",",
"n_to",
")",
".",
"write",
"(",
"packTypedArray",
"(",
"deltaEncodeIntegers",
"(",
"data",
",",
"n_to",
")",
")",
")",
";",
"}"
] | Encode array data as delta | [
"Encode",
"array",
"data",
"as",
"delta"
] | 46c40e0bca02d74201fb99925843cde49e9fe68a | https://github.com/wavesoft/jbb/blob/46c40e0bca02d74201fb99925843cde49e9fe68a/encoder.js#L2043-L2082 | train |
wavesoft/jbb | encoder.js | encodeArray_NUM_REPEATED | 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 length prefix
encoder.stream8.write( pack1b( ARR_OP.NUM_REPEATED | NUMTYPE_LN.UINT32 | (n_type << 1) ) );
encoder.stream32.write( pack4b( data.length, false ) );
encoder.counters.arr_hdr+=5;
}
// Write initial value
pickStream( encoder, n_type )
.write( packByNumType[n_type]( data[0] ) );
} | javascript | 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 length prefix
encoder.stream8.write( pack1b( ARR_OP.NUM_REPEATED | NUMTYPE_LN.UINT32 | (n_type << 1) ) );
encoder.stream32.write( pack4b( data.length, false ) );
encoder.counters.arr_hdr+=5;
}
// Write initial value
pickStream( encoder, n_type )
.write( packByNumType[n_type]( data[0] ) );
} | [
"function",
"encodeArray_NUM_REPEATED",
"(",
"encoder",
",",
"data",
",",
"n_type",
")",
"{",
"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",
")",
"{",
"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",
"{",
"encoder",
".",
"stream8",
".",
"write",
"(",
"pack1b",
"(",
"ARR_OP",
".",
"NUM_REPEATED",
"|",
"NUMTYPE_LN",
".",
"UINT32",
"|",
"(",
"n_type",
"<<",
"1",
")",
")",
")",
";",
"encoder",
".",
"stream32",
".",
"write",
"(",
"pack4b",
"(",
"data",
".",
"length",
",",
"false",
")",
")",
";",
"encoder",
".",
"counters",
".",
"arr_hdr",
"+=",
"5",
";",
"}",
"pickStream",
"(",
"encoder",
",",
"n_type",
")",
".",
"write",
"(",
"packByNumType",
"[",
"n_type",
"]",
"(",
"data",
"[",
"0",
"]",
")",
")",
";",
"}"
] | Encode array data as repeated | [
"Encode",
"array",
"data",
"as",
"repeated"
] | 46c40e0bca02d74201fb99925843cde49e9fe68a | https://github.com/wavesoft/jbb/blob/46c40e0bca02d74201fb99925843cde49e9fe68a/encoder.js#L2087-L2114 | train |
wavesoft/jbb | encoder.js | encodeArray_NUM_RAW | 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
encoder.stream8.write( pack1b( ARR_OP.NUM_RAW | NUMTYPE_LN.UINT32 | (n_type << 1) ) );
encoder.stream32.write( pack4b( data.length, false ) );
encoder.counters.arr_hdr+=5;
}
// Encode the short array
pickStream( encoder, n_type )
.write( packTypedArray( convertArray( data, n_type ) ) );
} | javascript | 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
encoder.stream8.write( pack1b( ARR_OP.NUM_RAW | NUMTYPE_LN.UINT32 | (n_type << 1) ) );
encoder.stream32.write( pack4b( data.length, false ) );
encoder.counters.arr_hdr+=5;
}
// Encode the short array
pickStream( encoder, n_type )
.write( packTypedArray( convertArray( data, n_type ) ) );
} | [
"function",
"encodeArray_NUM_RAW",
"(",
"encoder",
",",
"data",
",",
"n_type",
")",
"{",
"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",
")",
"{",
"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",
"{",
"encoder",
".",
"stream8",
".",
"write",
"(",
"pack1b",
"(",
"ARR_OP",
".",
"NUM_RAW",
"|",
"NUMTYPE_LN",
".",
"UINT32",
"|",
"(",
"n_type",
"<<",
"1",
")",
")",
")",
";",
"encoder",
".",
"stream32",
".",
"write",
"(",
"pack4b",
"(",
"data",
".",
"length",
",",
"false",
")",
")",
";",
"encoder",
".",
"counters",
".",
"arr_hdr",
"+=",
"5",
";",
"}",
"pickStream",
"(",
"encoder",
",",
"n_type",
")",
".",
"write",
"(",
"packTypedArray",
"(",
"convertArray",
"(",
"data",
",",
"n_type",
")",
")",
")",
";",
"}"
] | Encode array data as raw | [
"Encode",
"array",
"data",
"as",
"raw"
] | 46c40e0bca02d74201fb99925843cde49e9fe68a | https://github.com/wavesoft/jbb/blob/46c40e0bca02d74201fb99925843cde49e9fe68a/encoder.js#L2119-L2146 | train |
wavesoft/jbb | encoder.js | encodeArray_NUM_SHORT | 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 | n_type ) );
encoder.stream8.write( pack1b( data.length, false ) );
encoder.counters.arr_hdr+=2;
// Encode the short array
pickStream( encoder, n_type )
.write( packTypedArray( convertArray( data, n_type ) ) );
} | javascript | 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 | n_type ) );
encoder.stream8.write( pack1b( data.length, false ) );
encoder.counters.arr_hdr+=2;
// Encode the short array
pickStream( encoder, n_type )
.write( packTypedArray( convertArray( data, n_type ) ) );
} | [
"function",
"encodeArray_NUM_SHORT",
"(",
"encoder",
",",
"data",
",",
"n_type",
")",
"{",
"encoder",
".",
"counters",
".",
"arr_num_short",
"+=",
"1",
";",
"encoder",
".",
"log",
"(",
"LOG",
".",
"ARR",
",",
"\"array.numeric.short, len=\"",
"+",
"data",
".",
"length",
"+",
"\", type=\"",
"+",
"_NUMTYPE",
"[",
"n_type",
"]",
"+",
"\" (\"",
"+",
"n_type",
"+",
"\")\"",
")",
";",
"encoder",
".",
"stream8",
".",
"write",
"(",
"pack1b",
"(",
"ARR_OP",
".",
"NUM_SHORT",
"|",
"n_type",
")",
")",
";",
"encoder",
".",
"stream8",
".",
"write",
"(",
"pack1b",
"(",
"data",
".",
"length",
",",
"false",
")",
")",
";",
"encoder",
".",
"counters",
".",
"arr_hdr",
"+=",
"2",
";",
"pickStream",
"(",
"encoder",
",",
"n_type",
")",
".",
"write",
"(",
"packTypedArray",
"(",
"convertArray",
"(",
"data",
",",
"n_type",
")",
")",
")",
";",
"}"
] | Encode array data as short typed | [
"Encode",
"array",
"data",
"as",
"short",
"typed"
] | 46c40e0bca02d74201fb99925843cde49e9fe68a | https://github.com/wavesoft/jbb/blob/46c40e0bca02d74201fb99925843cde49e9fe68a/encoder.js#L2151-L2173 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.