_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q3400
|
SMSAPI
|
train
|
function SMSAPI(options) {
options = options || {};
if (options.proxy)
this.proxy(options.proxy);
else
this.proxy(new ProxyHttp({
server: options.server
}));
var moduleOptions = {
proxy: this.proxy()
};
// init authentication
if (options.oauth) {
// overwrite authentication object
this.authentication = new AuthenticationOAuth(
_.extend({}, moduleOptions, options.oauth)
);
this.proxy().setAuth(this.authentication);
}
else {
this.authentication = new AuthenticationSimple(moduleOptions);
}
// init modules
this.points = new Points(moduleOptions);
this.profile = new Profile(moduleOptions);
this.sender = new Sender(moduleOptions);
this.message = new Message(moduleOptions);
this.hlr = new Hlr(moduleOptions);
this.user = new User(moduleOptions);
this.template = new Template(moduleOptions);
this.push = new Push(moduleOptions);
this.contacts = new Contacts(moduleOptions);
/**
* @deprecated
* @type {Phonebook}
*/
this.phonebook = new Phonebook(moduleOptions);
this.proxy().setAuth(this.authentication);
}
|
javascript
|
{
"resource": ""
}
|
q3401
|
AuthenticationOAuth
|
train
|
function AuthenticationOAuth(options) {
AuthenticationAbstract.call(this, options);
options = options || {};
this._token = {
access: options.accessToken || null
};
}
|
javascript
|
{
"resource": ""
}
|
q3402
|
ContactsGroupsPermissionsGet
|
train
|
function ContactsGroupsPermissionsGet(options, groupId, username) {
ActionAbstract.call(this, options);
this._groupId = groupId;
this._username = username;
}
|
javascript
|
{
"resource": ""
}
|
q3403
|
ContactsGroupsAssignmentsGet
|
train
|
function ContactsGroupsAssignmentsGet(options, contactId, groupId) {
ActionAbstract.call(this, options);
this._groupId = groupId;
this._contactId = contactId;
}
|
javascript
|
{
"resource": ""
}
|
q3404
|
ContactsGroupsAssignmentsDelete
|
train
|
function ContactsGroupsAssignmentsDelete(options, contactId, groupId) {
ActionAbstract.call(this, options);
this._groupId = groupId;
this._contactId = contactId;
}
|
javascript
|
{
"resource": ""
}
|
q3405
|
ContactsGroupsMembersGet
|
train
|
function ContactsGroupsMembersGet(options, groupId, contactId) {
ActionAbstract.call(this, options);
this._groupId = groupId;
this._contactId = contactId;
}
|
javascript
|
{
"resource": ""
}
|
q3406
|
ContactsGroupsMembersDelete
|
train
|
function ContactsGroupsMembersDelete(options, groupId, contactId) {
ActionAbstract.call(this, options);
this._groupId = groupId;
this._contactId = contactId;
}
|
javascript
|
{
"resource": ""
}
|
q3407
|
ContactsGroupsAssignmentsAdd
|
train
|
function ContactsGroupsAssignmentsAdd(options, contactId, groupId) {
ActionAbstract.call(this, options);
this._groupId = groupId;
this._contactId = contactId;
}
|
javascript
|
{
"resource": ""
}
|
q3408
|
ContactsGroupsMembersAdd
|
train
|
function ContactsGroupsMembersAdd(options, groupId, contactId) {
ActionAbstract.call(this, options);
this._groupId = groupId;
this._contactId = contactId;
}
|
javascript
|
{
"resource": ""
}
|
q3409
|
ContactsGroupsPermissionsDelete
|
train
|
function ContactsGroupsPermissionsDelete(options, groupId, username) {
ActionAbstract.call(this, options);
this._groupId = groupId;
this._username = username;
}
|
javascript
|
{
"resource": ""
}
|
q3410
|
ProxyHttp
|
train
|
function ProxyHttp(options) {
ProxyAbstract.call(this, options);
this._server = options.server || 'https://api.smsapi.pl/';
this._auth = options.auth || null;
}
|
javascript
|
{
"resource": ""
}
|
q3411
|
Request
|
train
|
function Request(options) {
options = options || {};
this._server = options.server || '';
this._path = options.path || '';
this._json = options.json || false;
this._data = options.data || {};
this._auth = options.auth || null;
this._file = options.file || null;
this._method = options.method || 'post';
}
|
javascript
|
{
"resource": ""
}
|
q3412
|
ContactsGroupsPermissionsAdd
|
train
|
function ContactsGroupsPermissionsAdd(options, groupId, username) {
ActionAbstract.call(this, options);
this._groupId = groupId;
this._username = username;
}
|
javascript
|
{
"resource": ""
}
|
q3413
|
createMessageCreative
|
train
|
function createMessageCreative (message) {
return new Promise (async (resolve, reject) => {
if (!message) {
reject('Valid message object required');
}
let request_options = {
'api_version': 'v2.11',
'path': '/me/message_creatives',
'payload': {
'messages': [util.parseMessageProps(message)]
}
};
try {
let response = await this.sendGraphRequest(request_options);
resolve(response);
} catch (e) {
reject(e);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q3414
|
createCustomLabel
|
train
|
function createCustomLabel (name) {
return new Promise (async (resolve, reject) => {
if (!name) {
reject('name required');
}
let options = {
'payload': {'name': name}
};
try {
let response = await this.callCustomLabelsApi(options);
resolve(response);
} catch (e) {
reject(e);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q3415
|
getAllCustomLabels
|
train
|
function getAllCustomLabels () {
return new Promise (async (resolve, reject) => {
let options = {
'qs': {'fields': 'id,name'}
};
try {
let response = await this.callCustomLabelsApi(options);
resolve(response);
} catch (e) {
reject(e);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q3416
|
deleteCustomLabel
|
train
|
function deleteCustomLabel (label_id) {
return new Promise (async (resolve, reject) => {
if (!label_id) {
reject('label_id required');
return;
}
let options = {
'method': 'DELETE',
'path': '/' + label_id
};
try {
let response = await this.callCustomLabelsApi(options);
resolve(response);
} catch (e) {
reject(e);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q3417
|
addPsidtoCustomLabel
|
train
|
function addPsidtoCustomLabel (psid, label_id) {
return new Promise (async (resolve, reject) => {
if (!psid || !label_id) {
reject('PSID and label_id required');
return;
}
let options = {
'path': `/${label_id}/label`,
'payload': {'user': psid}
};
try {
let response = await this.callCustomLabelsApi(options);
resolve(response);
} catch (e) {
reject(e);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q3418
|
Client
|
train
|
function Client (options) {
let GraphRequest = new graphRequest(options);
Object.assign(
this,
GraphRequest,
new messages(GraphRequest),
new messengerProfile(GraphRequest),
new person(GraphRequest),
new messengerCode(GraphRequest),
new messagingInsights(GraphRequest),
new attachment(GraphRequest),
new nlp(GraphRequest),
new handoverProtocol(GraphRequest)
);
}
|
javascript
|
{
"resource": ""
}
|
q3419
|
startBroadcastReachEstimation
|
train
|
function startBroadcastReachEstimation (custom_label_id) {
return new Promise (async (resolve, reject) => {
let options = {
'custom_label_id': custom_label_id || true
};
try {
let response = await this.callBroadcastApi(options);
resolve(response);
} catch (e) {
reject(e);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q3420
|
startTag
|
train
|
function startTag(tag, attr) {
let attrStr = "";
if (attr) {
attrStr = " " + Object.keys(attr).map(function(k) {
return k + ' = "' + attr[k] + '"';
}).join(" ");
}
return "<" + tag + attrStr + ">";
}
|
javascript
|
{
"resource": ""
}
|
q3421
|
mdAstToHtml
|
train
|
function mdAstToHtml(ast, lines) {
if (lines == undefined)
lines = [];
// Adds each element of the array as markdown
function addArray(ast) {
for (let child of ast)
mdAstToHtml(child, lines);
return lines;
}
// Adds tagged content
function addTag(tag, ast, newLine) {
lines.push(startTag(tag));
if (ast instanceof Array)
addArray(ast);
else
mdAstToHtml(ast, lines);
lines.push(endTag(tag));
if (newLine)
lines.push('\r\n');
return lines;
}
function addLink(url, astOrText) {
lines.push(startTag('a', { href:url }));
if (astOrText) {
if (astOrText.children)
addArray(astOrText.children);
else
lines.push(astOrText);
}
lines.push(endTag('a')) ;
return lines;
}
function addImg(url) {
lines.push(startTag('img', { src:url }));
lines.push(endTag('img')) ;
return lines;
}
switch (ast.name)
{
case "heading":
{
let headingLevel = ast.children[0];
let restOfLine = ast.children[1];
let h = headingLevel.allText.length;
switch (h)
{
case 1: return addTag("h1", restOfLine, true);
case 2: return addTag("h2", restOfLine, true);
case 3: return addTag("h3", restOfLine, true);
case 4: return addTag("h4", restOfLine, true);
case 5: return addTag("h5", restOfLine, true);
case 6: return addTag("h6", restOfLine, true);
default: throw "Heading level must be from 1 to 6"
}
}
case "paragraph":
return addTag("p", ast.children, true);
case "unorderedList":
return addTag("ul", ast.children, true);
case "orderedList":
return addTag("ol", ast.children, true);
case "unorderedListItem":
return addTag("li", ast.children, true);
case "orderedListItem":
return addTag("li", ast.children, true);
case "inlineUrl":
return addLink(ast.allText, ast.allText);
case "bold":
return addTag("b", ast.children);
case "italic":
return addTag("i", ast.children);
case "code":
return addTag("code", ast.children);
case "codeBlock":
return addTag("pre", ast.children);
case "quote":
return addTag("blockquote", ast.children, true);
case "link":
return addLink(ast.children[1].allText, ast.children[0]);
case "image":
return addImg(ast.children[0]);
default:
if (ast.isLeaf)
lines.push(ast.allText);
else
ast.children.forEach(function(c) { mdAstToHtml(c, lines); });
}
return lines;
}
|
javascript
|
{
"resource": ""
}
|
q3422
|
addTag
|
train
|
function addTag(tag, ast, newLine) {
lines.push(startTag(tag));
if (ast instanceof Array)
addArray(ast);
else
mdAstToHtml(ast, lines);
lines.push(endTag(tag));
if (newLine)
lines.push('\r\n');
return lines;
}
|
javascript
|
{
"resource": ""
}
|
q3423
|
mdToHtml
|
train
|
function mdToHtml(input) {
let rule = myna.allRules['markdown.document'];
let ast = myna.parse(rule, input);
return mdAstToHtml(ast, []).join("");
}
|
javascript
|
{
"resource": ""
}
|
q3424
|
train
|
function () {
var r = this.cloneImplementation();
if (typeof (r) !== typeof (this))
throw new Error("Error in implementation of cloneImplementation: not returning object of correct type");
r.name = this.name;
r.grammarName = this.grammarName;
r._createAstNode = this._createAstNode;
return r;
}
|
javascript
|
{
"resource": ""
}
|
|
q3425
|
train
|
function () {
if (this.min == 0 && this.max == 1)
return this.firstChild.toString() + "?";
if (this.min == 0 && this.max == Infinity)
return this.firstChild.toString() + "*";
if (this.min == 1 && this.max == Infinity)
return this.firstChild.toString() + "+";
return this.firstChild.toString() + "{" + this.min + "," + this.max + "}";
}
|
javascript
|
{
"resource": ""
}
|
|
q3426
|
seq
|
train
|
function seq() {
var rules = [];
for (var _i = 0; _i < arguments.length; _i++) {
rules[_i - 0] = arguments[_i];
}
var rs = rules.map(RuleTypeToRule);
if (rs.length == 0)
throw new Error("At least one rule is expected when calling `seq`");
if (rs.length == 1)
return rs[0];
var rule1 = rs[0];
var rule2 = seq.apply(void 0, rs.slice(1));
if (rule1.nonAdvancing && rule2 instanceof Advance)
return new AdvanceIf(rule1);
else
return new Sequence(rule1, rule2);
}
|
javascript
|
{
"resource": ""
}
|
q3427
|
quantified
|
train
|
function quantified(rule, min, max) {
if (min === void 0) { min = 0; }
if (max === void 0) { max = Infinity; }
if (min === 0 && max === 1)
return new Optional(RuleTypeToRule(rule));
else
return new Quantified(RuleTypeToRule(rule), min, max);
}
|
javascript
|
{
"resource": ""
}
|
q3428
|
log
|
train
|
function log(msg) {
if (msg === void 0) { msg = ""; }
return action(function (p) { console.log(msg); }).setType("log");
}
|
javascript
|
{
"resource": ""
}
|
q3429
|
guardedSeq
|
train
|
function guardedSeq(condition) {
var rules = [];
for (var _i = 1; _i < arguments.length; _i++) {
rules[_i - 1] = arguments[_i];
}
return seq(condition, seq.apply(void 0, rules.map(function (r) { return assert(r); }))).setType("guardedSeq");
}
|
javascript
|
{
"resource": ""
}
|
q3430
|
keywords
|
train
|
function keywords() {
var words = [];
for (var _i = 0; _i < arguments.length; _i++) {
words[_i - 0] = arguments[_i];
}
return choice.apply(void 0, words.map(keyword));
}
|
javascript
|
{
"resource": ""
}
|
q3431
|
parse
|
train
|
function parse(r, s) {
var p = new ParseState(s, 0, []);
if (!(r instanceof AstRule))
r = r.ast;
if (!r.parser(p))
return null;
return p && p.nodes ? p.nodes[0] : null;
}
|
javascript
|
{
"resource": ""
}
|
q3432
|
allGrammarRules
|
train
|
function allGrammarRules() {
return Object.keys(Myna.allRules).sort().map(function (k) { return Myna.allRules[k]; });
}
|
javascript
|
{
"resource": ""
}
|
q3433
|
grammarToString
|
train
|
function grammarToString(grammarName) {
return grammarRules(grammarName).map(function (r) { return r.fullName + " <- " + r.definition; }).join('\n');
}
|
javascript
|
{
"resource": ""
}
|
q3434
|
astSchemaToString
|
train
|
function astSchemaToString(grammarName) {
return grammarAstRules(grammarName).map(function (r) { return r.name + " <- " + r.astRuleDefn(); }).join('\n');
}
|
javascript
|
{
"resource": ""
}
|
q3435
|
registerGrammar
|
train
|
function registerGrammar(grammarName, grammar, defaultRule) {
for (var k in grammar) {
if (grammar[k] instanceof Rule) {
var rule = grammar[k];
rule.setName(grammarName, k);
Myna.allRules[rule.fullName] = rule;
}
}
Myna.grammars[grammarName] = grammar;
if (defaultRule) {
Myna.parsers[grammarName] = function (text) { return parse(defaultRule, text); };
}
return grammar;
}
|
javascript
|
{
"resource": ""
}
|
q3436
|
RuleTypeToRule
|
train
|
function RuleTypeToRule(rule) {
if (rule instanceof Rule)
return rule;
if (typeof (rule) === "string")
return text(rule);
if (typeof (rule) === "boolean")
return rule ? Myna.truePredicate : Myna.falsePredicate;
throw new Error("Invalid rule type: " + rule);
}
|
javascript
|
{
"resource": ""
}
|
q3437
|
CreateArithmeticGrammar
|
train
|
function CreateArithmeticGrammar(myna)
{
// Setup a shorthand for the Myna parsing library object
let m = myna;
// Construct a grammar
let g = new function()
{
// These are helper rules, they do not create nodes in the parse tree.
this.fraction = m.seq(".", m.digit.zeroOrMore);
this.plusOrMinus = m.char("+-");
this.exponent = m.seq(m.char("eE"), this.plusOrMinus.opt, m.digits);
this.comma = m.text(",").ws;
// Using a lazy evaluation rule to allow recursive rule definitions
let _this = this;
this.expr = m.delay(function() { return _this.sum; });
// The following rules create nodes in the abstract syntax tree
this.number = m.seq(m.integer, this.fraction.opt, this.exponent.opt).ast;
this.parenExpr = m.parenthesized(this.expr.ws).ast;
this.leafExpr = m.choice(this.parenExpr, this.number.ws);
this.prefixOp = this.plusOrMinus.ast;
this.prefixExpr = m.seq(this.prefixOp.ws.zeroOrMore, this.leafExpr).ast;
this.divExpr = m.seq(m.char("/").ws, this.prefixExpr).ast;
this.mulExpr = m.seq(m.char("*").ws, this.prefixExpr).ast;
this.product = m.seq(this.prefixExpr.ws, this.mulExpr.or(this.divExpr).zeroOrMore).ast;
this.subExpr = m.seq(m.char("-").ws, this.product).ast;
this.addExpr = m.seq(m.char("+").ws, this.product).ast;
this.sum = m.seq(this.product, this.addExpr.or(this.subExpr).zeroOrMore).ast;
};
// Register the grammar, providing a name and the default parse rule
return myna.registerGrammar("arithmetic", g, g.expr);
}
|
javascript
|
{
"resource": ""
}
|
q3438
|
mergeObjects
|
train
|
function mergeObjects(a, b) {
var r = { };
for (var k in a)
r[k] = a[k];
for (var k in b)
r[k] = b[k];
return r;
}
|
javascript
|
{
"resource": ""
}
|
q3439
|
expandAst
|
train
|
function expandAst(ast, data, lines) {
if (lines == undefined)
lines = [];
// If there is a child "key" get the value associated with it.
let keyNode = ast.child("key");
let key = keyNode ? keyNode.allText : "";
let val = data ? (key in data ? data[key] : "") : "";
// Functions are not supported
if (typeof(val) == 'function')
throw new Exception('Functions are not supported');
switch (ast.rule.name)
{
case "document":
case "sectionContent":
ast.children.forEach(function(c) {
expandAst(c, data, lines); });
return lines;
case "comment":
return lines;
case "plainText":
lines.push(ast.allText);
return lines;
case "section":
let content = ast.child("sectionContent");
if (typeof val === "boolean" || typeof val === "number" || typeof val === "string") {
if (val)
expandAst(content, data, lines);
}
else if (val instanceof Array) {
for (let x of val)
expandAst(content, mergeObjects(data, x), lines);
}
else {
expandAst(content, mergeObjects(data, val), lines);
}
return lines;
case "invertedSection":
if (!val || ((val instanceof Array) && val.length == 0))
expandAst(ast.child("sectionContent"), data, lines);
return lines;
case "escapedVar":
if (val)
lines.push(
expand(escapeHtmlChars(String(val)), data));
return lines;
case "unescapedVar":
if (val)
lines.push(
expand(String(val), data));
return lines;
}
throw "Unrecognized AST node " + ast.rule.name;
}
|
javascript
|
{
"resource": ""
}
|
q3440
|
expand
|
train
|
function expand(template, data) {
if (template.indexOf("{{") >= 0) {
let ast = myna.parsers.mustache(template);
let lines = expandAst(ast, data);
return lines.join("");
}
else {
return template;
}
}
|
javascript
|
{
"resource": ""
}
|
q3441
|
escapeHtmlChars
|
train
|
function escapeHtmlChars(text)
{
let ast = myna.parsers.html_reserved_chars(text);
if (!ast.children)
return "";
return ast.children.map(astNodeToHtmlText).join('');
}
|
javascript
|
{
"resource": ""
}
|
q3442
|
guardedSeq
|
train
|
function guardedSeq() {
var args = Array.prototype.slice.call(arguments, 1).map(function(r) { return m.seq(m.assert(r), _this.ws); });
return m.seq(arguments[0], _this.ws, m.seq.apply(m, args));
}
|
javascript
|
{
"resource": ""
}
|
q3443
|
commaList
|
train
|
function commaList(r, trailing = true) {
var result = r.then(guardedSeq(_this.comma, r).zeroOrMore);
if (trailing) return result.then(_this.comma.opt);
else return result;
}
|
javascript
|
{
"resource": ""
}
|
q3444
|
Layout
|
train
|
function Layout(algorithmName, options) {
// Save the algorithmName as our algorithm (assume function)
var algorithm = algorithmName || 'top-down';
// If the algorithm is a string, look it up
if (typeof algorithm === 'string') {
algorithm = algorithms[algorithmName];
// Assert that the algorithm was found
assert(algorithm, 'Sorry, the \'' + algorithmName +'\' algorithm could not be loaded.');
}
// Create a new PackingSmith with our algorithm and return
var retSmith = new PackingSmith(algorithm, options);
return retSmith;
}
|
javascript
|
{
"resource": ""
}
|
q3445
|
GithubContent
|
train
|
function GithubContent(options) {
if (!(this instanceof GithubContent)) {
return new GithubContent(options);
}
// setup our specific options
var opts = extend({branch: 'master'}, options);
opts.json = false;
opts.apiurl = 'https://raw.githubusercontent.com';
GithubBase.call(this, opts);
this.options = extend({}, opts, this.options);
}
|
javascript
|
{
"resource": ""
}
|
q3446
|
train
|
function () {
// Grab the items
var items = this.items;
// Find the most negative x and y
var minX = Infinity,
minY = Infinity;
items.forEach(function (item) {
var coords = item;
minX = Math.min(minX, coords.x);
minY = Math.min(minY, coords.y);
});
// Offset each item by -minX, -minY; effectively resetting to 0, 0
items.forEach(function (item) {
var coords = item;
coords.x -= minX;
coords.y -= minY;
});
}
|
javascript
|
{
"resource": ""
}
|
|
q3447
|
normalizeFields
|
train
|
function normalizeFields(fields) {
const _fields = {};
Object.keys(fields).forEach(k => {
if (fields[k].constructor == Object && !fields[k].type) {
_fields[k] = normalizeFields(fields[k]);
} else {
_fields[k] = 1;
}
});
return _fields;
}
|
javascript
|
{
"resource": ""
}
|
q3448
|
resolve_type_define
|
train
|
function resolve_type_define(nextql, fieldValue, fieldDefine, fieldPath) {
let fd = fieldDefine;
// First phrase resolve fieldDefine is auto or function into final fieldDefine
if (fd === 1) {
if (isPrimitive(fieldValue)) {
return "*";
} else {
fd = nextql.resolveType(fieldValue);
nextql.afterResolveTypeHooks.forEach(
hook => (fd = hook(fieldValue) || fd)
);
}
}
if (typeof fd == "function") {
fd = fieldDefine(fieldValue);
}
// Second phrase resolve fieldDefine is explicit into fieldModel name;
if (fd == undefined) {
return new NextQLError(
"Cannot resolve model: " + JSON.stringify(fieldDefine),
{ path: fieldPath }
);
}
// InlineModel
if (fd.constructor && fd.constructor == Object) {
return new InlineModel(fd);
}
// ScalarModel
if (fd === "*") {
return "*";
}
// NamedModel
const model = nextql.model(fd);
if (!model) {
return new NextQLError("Model not found: " + fd, {
path: fieldPath
});
}
return model;
}
|
javascript
|
{
"resource": ""
}
|
q3449
|
resolve_scalar_value
|
train
|
function resolve_scalar_value(nextql, value, valueQuery, info) {
if (value == undefined) {
set(info.result, info.path, null);
return Promise.resolve();
}
if (valueQuery !== 1) {
const keylen = Object.keys(valueQuery).length;
const queryAsObject = valueQuery.$params ? keylen > 1 : keylen > 0;
if (queryAsObject) {
return Promise.reject(
new NextQLError("Cannot query scalar as object", info)
);
}
}
if (isPrimitive(value)) {
set(info.result, info.path, value);
return Promise.resolve();
}
// non-primitive value as scalar, not good solution yet
try {
set(info.result, info.path, JSON.parse(JSON.stringify(value)));
return Promise.resolve();
} catch (e) {
return Promise.reject(
new NextQLError("Cannot serialize return value", info)
);
}
}
|
javascript
|
{
"resource": ""
}
|
q3450
|
execute_conditional
|
train
|
function execute_conditional(
nextql,
value,
valueModel,
conditional,
query,
info,
context
) {
let model;
const modelName = valueModel.check(
value,
conditional,
query.$params,
context,
info
);
if (modelName instanceof Error) {
return Promise.reject(modelName);
}
if (modelName === true) {
model = valueModel;
}
if (typeof modelName == "string" && modelName != "*") {
model = nextql.model(modelName);
}
if (!model) return Promise.resolve();
return resolve_object_value(nextql, value, model, query, info, context);
}
|
javascript
|
{
"resource": ""
}
|
q3451
|
resolve_object_value
|
train
|
function resolve_object_value(
nextql,
value,
valueModel,
valueQuery,
info,
context
) {
if (value == undefined) {
set(info.result, info.path, null);
return Promise.resolve();
}
if (isPrimitive(value)) {
return Promise.reject(
new NextQLError("Cannot query scalar as " + valueModel.name, info)
);
}
return Promise.all(
Object.keys(valueQuery).map(path => {
if (path == "$params") return;
const fieldName = path.split(nextql.aliasSeparator, 1)[0];
//Conditional query?
if (fieldName[0] === "?") {
return execute_conditional(
nextql,
value,
valueModel,
fieldName,
valueQuery[path],
info,
context
);
}
const newInfo = info_append_path(info, path);
return valueModel
.get(
value,
fieldName,
valueQuery[path].$params,
context,
newInfo
)
.then(fieldValue => {
let fieldDef;
if (valueModel.computed[fieldName]) {
fieldDef = valueModel.fields[fieldName] || 1;
} else {
fieldDef = valueModel.fields[fieldName];
}
return resolve_value(
nextql,
fieldValue,
fieldDef,
valueQuery[path],
newInfo,
context
);
});
})
);
}
|
javascript
|
{
"resource": ""
}
|
q3452
|
buildRdpFile
|
train
|
function buildRdpFile(config) {
var deferred = Q.defer();
var fileContent = getRdpFileContent(config);
var fileName = path.normalize(os.tmpdir() + '/' + sanitize(config.address) + '.rdp');
Q.nfcall(fs.writeFile, fileName, fileContent)
.then(function() {
deferred.resolve(fileName);
})
.fail(deferred.reject);
return deferred.promise;
}
|
javascript
|
{
"resource": ""
}
|
q3453
|
magic
|
train
|
function magic(buf, cb) {
setTimeout(() => {
const sampleLength = 24;
const sample = buf.slice(0, sampleLength).toString('hex'); // lookup data
const found = Object.keys(_magicDb2.default).find(it => {
return sample.indexOf(it) != -1;
});
if (found) {
cb(null, _magicDb2.default[found]);
} else {
cb(new Error('Magic number not found'));
}
}, 0);
}
|
javascript
|
{
"resource": ""
}
|
q3454
|
encode
|
train
|
function encode(buf, options, cb) {
try {
const imageData = {
data: buf,
width: options.width,
height: options.height
};
const data = (0, _encoder2.default)(imageData, options.quality);
cb(null, data);
} catch (err) {
cb(err);
}
}
|
javascript
|
{
"resource": ""
}
|
q3455
|
toBuffer
|
train
|
function toBuffer(buf) {
if (buf instanceof ArrayBuffer) {
return arrayBufferToBuffer(buf);
} else if (Buffer.isBuffer(buf)) {
return buf;
} else if (buf instanceof Uint8Array) {
return new Buffer(buf);
} else {
return buf; // type unknown, trust the user
}
}
|
javascript
|
{
"resource": ""
}
|
q3456
|
toArrayBuffer
|
train
|
function toArrayBuffer(buf) {
if (buf instanceof ArrayBuffer) {
return buf;
} else if (Buffer.isBuffer(buf)) {
return bufferToArrayBuffer(buf);
} else if (buf instanceof Uint8Array) {
return bufferToArrayBuffer(buf);
} else {
return buf; // type unknown, trust the user
}
}
|
javascript
|
{
"resource": ""
}
|
q3457
|
toUint8Array
|
train
|
function toUint8Array(buf) {
if (buf instanceof Uint8Array) {
return buf;
} else if (buf instanceof ArrayBuffer) {
return new Uint8Array(buf);
} else if (Buffer.isBuffer(buf)) {
return new Uint8Array(buf);
} else {
return buf; // type unknown, trust the user
}
}
|
javascript
|
{
"resource": ""
}
|
q3458
|
bufferToArrayBuffer
|
train
|
function bufferToArrayBuffer(buf) {
const arr = new ArrayBuffer(buf.length);
const view = new Uint8Array(arr);
for (let i = 0; i < buf.length; ++i) {
view[i] = buf[i];
}
return arr;
}
|
javascript
|
{
"resource": ""
}
|
q3459
|
decode
|
train
|
function decode(buf, options, cb) {
function getData(j, width, height) {
const dest = {
width: width,
height: height,
data: new Uint8Array(width * height * 4)
};
j.copyToImageData(dest);
return dest.data;
}
try {
const j = new _jpg.JpegImage();
j.parse(buf);
const width = options.width || j.width;
const height = options.height || j.height;
const data = getData(j, width, height);
const result = {
width: width,
height: height,
data: data
};
cb(null, result);
} catch (err) {
if (typeof err === 'string') {
// jpg.js throws 'string' values, convert to an Error
err = new Error(err);
}
cb(err);
}
}
|
javascript
|
{
"resource": ""
}
|
q3460
|
exif
|
train
|
function exif(buf, options, cb) {
try {
const exif = new _ExifReader.ExifReader();
exif.load(buf);
// The MakerNote tag can be really large. Remove it to lower memory usage.
if (!options.hasOwnProperty('hasMakerNote') || !options.hasMakerNote) {
exif.deleteTag('MakerNote');
}
const metadata = exif.getAllTags();
cb(null, metadata);
} catch (err) {
if (err.message === 'No Exif data') {
cb(null, {});
} else {
cb(err);
}
}
}
|
javascript
|
{
"resource": ""
}
|
q3461
|
info
|
train
|
function info(buf, cb) {
setTimeout(() => {
const info = (0, _imageinfo2.default)(buf);
if (!info) {
cb(new Error('Cannot get image info'));
} else {
cb(null, {
type: info.type,
mimeType: info.mimeType,
extension: info.format.toLowerCase(),
width: info.width,
height: info.height
});
}
}, 0);
}
|
javascript
|
{
"resource": ""
}
|
q3462
|
obtainInfo
|
train
|
function obtainInfo(action, id, cb) {
request.post({
url: action,
form: {
trackingNo03: id
},
timeout: 20000
}, function (error, response, body) {
if (error || response.statusCode != 200) {
cb(utils.errorDown())
return
}
// Not found
if (body.indexOf('Please insert the correct Tracking Number.') != -1) {
cb(utils.errorNoData())
return
}
let entity = null
try {
entity = createMalaysiaPosEntity(body)
} catch (error) {
return cb(utils.errorParser(id, error.message))
}
cb(null, entity)
})
}
|
javascript
|
{
"resource": ""
}
|
q3463
|
createMalaysiaPosEntity
|
train
|
function createMalaysiaPosEntity(html) {
let $ = parser.load(html)
let id = $('#trackingNo03').get(0).children[0].data.trim()
let init = html.indexOf("var strTD")
init = html.indexOf('"', init + 1)
let fin = html.indexOf('"', init + 1)
let strTD = html.substring(init, fin)
$ = parser.load(strTD)
let trs = $('#tbDetails tbody tr')
let states = utils.tableParser(
trs,
{
'date': {
'idx': 0,
'mandatory': true,
'parser': elem => {
return moment.tz(elem, 'DD MMM YYYY HH:mm:ss', 'en', zone).format()
}
},
'state': {'idx': 1, 'mandatory': true},
'area': {'idx': 2}
},
elem => {
// On Maintenance there is a row with a td colspan=4, we want to skip it
if(elem.children[0].attribs && elem.children[0].attribs.colspan &&
elem.children[0].attribs.colspan == 4) {
return false
}
return true
})
return new MalaysiaInfo({
id: id,
state: states[0].state,
states: states
})
}
|
javascript
|
{
"resource": ""
}
|
q3464
|
createCttEntity
|
train
|
function createCttEntity(id, html, cb) {
let state = null
let messages = []
try {
html = htmlBeautify(html)
let $ = parser.load(html)
let table = $('table.full-width tr').get(1).children.filter(e => e.type == 'tag')
let dayAndHours = table[2].children[0].data.trim() + ' ' + table[3].children[0].data.trim()
state = {
date: moment.tz(dayAndHours, "YYYY/MM/DD HH:mm", zone).format()
}
if(table[4].children.length == 0) {
state['status'] = 'Sem estado'
} else {
if(table[4].children[0].data) {
state['status'] = table[4].children[0].data.trim()
} else {
state['status'] = table[4].children[0].children[0].data.trim()
}
}
let details = $('#details_0').find('tr')
let day = ""
let dayUnformated = ""
let message = {}
for(let i = 0; i < details.length; i++) {
let tr = details.get(i)
if(tr.children.length >= 8){
let idxsum = 0
if(tr.children.length >= 9) {
day = tr.children[0].children[0].data.trim()
dayUnformated = day.split(',')[1].trim()
day = moment.tz(dayUnformated, "DD MMMM YYYY", 'pt', zone).format()
message = {
day: day,
status: []
}
messages.push(message)
idxsum = 1
}
let hours = tr.children[0+idxsum].children[0].data.trim()
let time = moment.tz(dayUnformated + ' ' + hours, "DD MMMM YYYY HH:mm", 'pt', zone).format()
let add = {
time: time,
status: tr.children[2+idxsum].children[0].data.trim(),
local: tr.children[6+idxsum].children[0].data.trim()
}
message.status.push(add)
}
}
} catch (error) {
return cb(error)
}
cb(null, new CttInfo(id, state, messages))
}
|
javascript
|
{
"resource": ""
}
|
q3465
|
obtainInfo
|
train
|
function obtainInfo(id, action, cb) {
request.get({
url: action,
timeout: 20000,
strictSSL: false
}, function (error, response, body) {
if (error || response.statusCode != 200) {
cb(utils.errorDown())
return
}
// Not found
if (body.indexOf('errorMessage') != -1) {
cb(utils.errorNoData())
return
}
let entity = null
try {
entity = createParcelTrackerEntity(body)
} catch (error) {
return cb(utils.errorParser(id, error.message))
}
if(entity != null) cb(null, entity)
})
}
|
javascript
|
{
"resource": ""
}
|
q3466
|
createParcelTrackerEntity
|
train
|
function createParcelTrackerEntity(body) {
const data = JSON.parse(body)
const states = []
data.scanHistory.scanDetails.forEach((elem) => {
const state = {
state : elem.eventDescription,
date : elem.eventDate + "T" + elem.eventTime
}
if(elem.eventLocation && elem.eventLocation.country
&& elem.eventLocation.countyOrRegion
&& elem.eventLocation.city){
state.area = elem.eventLocation.country
+ " - " + elem.eventLocation.countyOrRegion
+ " - " + elem.eventLocation.city
}
states.push(state)
})
return new ParcelTrackerInfo({
attempts: 1,
id: data.packageIdentifier,
state: data.currentStatus.eventDescription,
carrier: data.carrier,
origin: data.senderLocation.country
+ " - " + data.senderLocation.countyOrRegion
+ " - " + data.senderLocation.city,
destiny: data.destinationLocation.country
+ " - " + data.destinationLocation.countyOrRegion
+ " - " + data.destinationLocation.city,
states: states
})
}
|
javascript
|
{
"resource": ""
}
|
q3467
|
train
|
function (type, error = null, id = null) {
type = type.toUpperCase()
let errors = {
'NO_DATA': 'No info for that id yet. Or maybe the data provided was wrong.',
'BUSY': 'The server providing the info is busy right now. Try again.',
'UNAVAILABLE': 'The server providing the info is unavailable right now. Try again later.',
'EMPTY': 'The provider server was parsed correctly, but has no data to show. Try Again later.',
'DOWN': 'The provider server is currently down. Try Again later.',
'PARSER': 'Something went wrong when parsing the provider website.',
'ACTION_REQUIRED': 'That tracker requires an aditional step in their website.'
}
let message = error != null ? error : errors[type]
message = id != null ? message + ' ID:' + id : message
return new Error(type + ' - ' + message)
}
|
javascript
|
{
"resource": ""
}
|
|
q3468
|
createCorreosEsEntity
|
train
|
function createCorreosEsEntity(id, html) {
let $ = parser.load(html)
let table2 = $('#Table2').get(0);
let states = []
const fields = ['date', 'info']
if (table2.children.length === 0 ||
(table2.children[1] !== undefined
&& table2.children[1].data !== undefined
&& table2.children[1].data.trim() === 'fin tabla descripciones'))
return null;
table2.children.forEach(function (elem) {
if (elem.attribs !== undefined && elem.attribs.class.trim() === 'txtCabeceraTabla') {
let state = {}
elem.children.forEach(function (_child) {
if (_child.attribs !== undefined && _child.attribs.class !== undefined) {
let _class = _child.attribs.class.trim()
if (_class === 'txtDescripcionTabla') {
state['date'] = moment.tz(_child.children[0].data.trim(), "DD/MM/YYYY", zone).format()
} else if (_class === 'txtContenidoTabla' || _class === 'txtContenidoTablaOff') {
state['state'] = _child.children[1].children[0].data.trim()
if (_child.children[1].attribs !== undefined && _child.children[1].attribs !== undefined
&& _child.children[1].attribs.title) {
state['title'] = _child.children[1].attribs.title.trim()
}
}
}
})
if (Object.keys(state).length > 0) {
states.push(state)
}
}
})
return new CorreosESInfo({
'id': id,
'state': states[states.length - 1].state,
'states': states.reverse()
})
}
|
javascript
|
{
"resource": ""
}
|
q3469
|
createCjahEntity
|
train
|
function createCjahEntity(id, html, cb) {
let entity = null
try {
let $ = parser.load(html)
let trs = $('table tbody tr')
// Not found
if (!trs || trs.length === 0) {
cb(utils.errorNoData())
return
}
let states = utils.tableParser(
trs,
{
'id': { 'idx': 1, 'mandatory': true },
'date': {'idx': 3, 'mandatory': true, 'parser': elem => { return moment.tz( elem, 'DD/MM/YYYY h:mm:ssa', 'en', zone).format()}},
'state': { 'idx': 5, 'mandatory': true }
},
elem => true)
entity = new CjahInfo({
id: states[0].id,
state: states[0].state,
states: states
})
} catch (error) {
return cb(utils.errorParser(id, error.message))
}
cb(null, entity)
}
|
javascript
|
{
"resource": ""
}
|
q3470
|
createSingpostEntity
|
train
|
function createSingpostEntity(id, html) {
let $ = parser.load(html)
let date = []
$('span.tacking-date').each(function (i, elem) {
date.push($(this).text().trim())
})
let status = []
$('div.tacking-status').each(function (i, elem) {
status.push($(this).text().trim())
})
let messages = []
for(let i = 0; i < date.length; i++) {
messages.push({
date: moment.tz(date[i], "DD-MM-YYYY", zone).format(),
state: status[i].replace(/ \(Country.+\)/ig, "").trim() // remove '(Country: PT)'
})
}
return new SingpostInfo(id, messages)
}
|
javascript
|
{
"resource": ""
}
|
q3471
|
createPanasiaEntity
|
train
|
function createPanasiaEntity(html, id) {
let $ = parser.load(html)
let td11 = $('.one-parcel .td11').contents()
let orderNumber = td11[1].data
let product = td11[3].data
let td22 = $('.one-parcel .td22').contents()
let trackingNumber = td22[1].data
let country = utils.removeChineseChars(td22[3].data).trim()
let td33 = $('.one-parcel .td33').contents()
let dates = []
for(let i = 1; i < td33.length; ++i) {
let date = td33[i].children[1].data
dates.push(moment.tz(date, "YYYY-MM-DD HH:mm:ss", zone).format())
}
let td44 = $('.one-parcel .td44').contents()
let states = []
for(let i = 0; i < td44.length; ++i) {
let s = td44[i].children[0].data
states.push(s.replace(',', ', ').replace('En tr?nsito', 'En transito'))
}
let finalStates = []
for(let i = 0; i < dates.length; ++i) {
finalStates.push({
state: states[i],
date: dates[i]
})
}
return new PanasiaInfo({
orderNumber: orderNumber,
product: product,
id: id,
country: country,
states: finalStates.sort((a, b) => {
let dateA = moment(a.date),
dateB = moment(b.date)
return dateA < dateB
})
})
}
|
javascript
|
{
"resource": ""
}
|
q3472
|
createCainiaoEntity
|
train
|
function createCainiaoEntity(id, json) {
let section = json.data[0].section3 || json.data[0].section2;
let msgs = section.detailList.map(m => {
return {
state: fixStateName(m.desc),
date: moment.tz(m.time, "YYYY-MM-DD HH:mm:ss", zone).format()
}
})
let destinyId = json.data[0].section2.mailNo || null
return new CainiaoInfo(id, msgs, destinyId)
}
|
javascript
|
{
"resource": ""
}
|
q3473
|
createExpressoEntity
|
train
|
function createExpressoEntity(html) {
let $ = parser.load(html)
let data = []
$('table span').each(function (i, elem) {
if(i >= 10 )
data.push($(this).text().trim().replace(/\s\s+/g, ' '))
})
return new ExpressoInfo({
'guide': data[0],
'origin': data[1],
'date': moment.tz(data[2], "YYYY-MM-DD", zone).format(),
'status': data[3],
'weight': data[4],
'parcels': data[5],
'receiver_name': data[6],
'address': parseAddress(data[7]),
'refund': data[8],
'ref': data[9],
})
}
|
javascript
|
{
"resource": ""
}
|
q3474
|
amqpEndpointNode
|
train
|
function amqpEndpointNode(n) {
RED.nodes.createNode(this, n);
// save node parameters
this.host = n.host;
this.port = n.port;
this.username = n.username;
this.password = n.password;
this.container_id = n.container_id;
this.rejectUnauthorized = n.rejectUnauthorized;
this.usetls = n.usetls;
if (this.usetls && n.tls) {
this.tls = RED.nodes.getNode(n.tls)
}
// build options for connection
var options = { host: this.host, port: this.port};
if (this.username) {
options.username = this.username;
}
if (this.password) {
options.password = this.password;
}
if (this.container_id) {
options.container_id = this.container_id;
} else {
options.container_id = "node-red-rhea-" + container.generate_uuid();
}
if (this.usetls && n.tls) {
options.transport = 'tls';
if (this.tls.credentials.cadata) {
options.ca = this.tls.credentials.cadata
}
}
options.rejectUnauthorized = this.rejectUnauthorized;
var node = this;
this.connected = false;
this.connecting = false;
/**
* Exposed function for connecting to the remote AMQP container
* creating an AMQP connection object
*
* @param callback function called when the connection is established
*/
this.connect = function(callback) {
// AMQP connection not established, trying to do that
if (!node.connected && !node.connecting) {
node.connecting = true;
node.connection = container.connect(options);
node.connection.on('connection_error', function(context) {
node.connecting = false;
node.connected = false;
var error = context.connection.get_error();
node.error(error);
});
node.connection.on('connection_open', function(context) {
node.connecting = false;
node.connected = true;
callback(context.connection);
});
node.connection.on('disconnected', function(context) {
node.connected = false;
});
// AMQP connection already established
} else {
callback(node.connection);
}
}
}
|
javascript
|
{
"resource": ""
}
|
q3475
|
amqpSenderNode
|
train
|
function amqpSenderNode(config) {
RED.nodes.createNode(this, config);
// get endpoint configuration
this.endpoint = RED.nodes.getNode(config.endpoint);
// get all other configuration
this.address = config.address;
this.autosettle = config.autosettle;
this.dynamic = config.dynamic;
this.sndsettlemode = config.sndsettlemode;
this.rcvsettlemode = config.rcvsettlemode;
this.durable = config.durable;
this.expirypolicy = config.expirypolicy;
var node = this;
// node not yet connected
this.status({ fill: 'red', shape: 'dot', text: 'disconnected' });
if (node.endpoint) {
node.endpoint.connect(function(connection) {
setup(connection);
});
/**
* Node setup for creating sender link
*
* @param connection Connection instance
*/
function setup(connection) {
node.connection = connection;
// node connected
node.status({ fill: 'green', shape: 'dot', text: 'connected' });
// build sender options based on node configuration
var options = {
target: {
address: node.address,
dynamic: node.dynamic,
durable: node.durable,
expiry_policy: node.expirypolicy
},
autosettle: node.autosettle,
snd_settle_mode: node.sndsettlemode,
rcv_settle_mode: node.rcvsettlemode
};
node.sender = node.connection.open_sender(options);
node.sender.on('accepted', function(context) {
var msg = outDelivery(node, context.delivery);
node.send(msg);
});
node.sender.on('released', function(context) {
var msg = outDelivery(node, context.delivery);
node.send(msg);
});
node.sender.on('rejected', function(context) {
var msg = outDelivery(node, context.delivery);
node.send(msg);
});
node.connection.on('disconnected', function(context) {
// node disconnected
node.status({fill: 'red', shape: 'dot', text: 'disconnected' });
});
node.on('input', function(msg) {
// enough credits to send
if (node.sender.sendable()) {
node.sender.send(msg.payload);
}
});
node.on('close', function() {
if (node.sender != null)
node.sender.detach();
node.connection.close();
});
}
}
}
|
javascript
|
{
"resource": ""
}
|
q3476
|
setup
|
train
|
function setup(connection) {
node.connection = connection;
// node connected
node.status({ fill: 'green', shape: 'dot', text: 'connected' });
// build sender options based on node configuration
var options = {
target: {
address: node.address,
dynamic: node.dynamic,
durable: node.durable,
expiry_policy: node.expirypolicy
},
autosettle: node.autosettle,
snd_settle_mode: node.sndsettlemode,
rcv_settle_mode: node.rcvsettlemode
};
node.sender = node.connection.open_sender(options);
node.sender.on('accepted', function(context) {
var msg = outDelivery(node, context.delivery);
node.send(msg);
});
node.sender.on('released', function(context) {
var msg = outDelivery(node, context.delivery);
node.send(msg);
});
node.sender.on('rejected', function(context) {
var msg = outDelivery(node, context.delivery);
node.send(msg);
});
node.connection.on('disconnected', function(context) {
// node disconnected
node.status({fill: 'red', shape: 'dot', text: 'disconnected' });
});
node.on('input', function(msg) {
// enough credits to send
if (node.sender.sendable()) {
node.sender.send(msg.payload);
}
});
node.on('close', function() {
if (node.sender != null)
node.sender.detach();
node.connection.close();
});
}
|
javascript
|
{
"resource": ""
}
|
q3477
|
amqpReceiverNode
|
train
|
function amqpReceiverNode(config) {
RED.nodes.createNode(this, config);
// get endpoint configuration
this.endpoint = RED.nodes.getNode(config.endpoint);
// get all other configuration
this.address = config.address;
this.autoaccept = config.autoaccept;
this.creditwindow = config.creditwindow;
this.dynamic = config.dynamic;
this.sndsettlemode = config.sndsettlemode;
this.rcvsettlemode = config.rcvsettlemode;
this.durable = config.durable;
this.expirypolicy = config.expirypolicy;
if (this.dynamic)
this.address = undefined;
var node = this;
// node not yet connected
this.status({ fill: 'red', shape: 'dot', text: 'disconnected' });
if (this.endpoint) {
node.endpoint.connect(function(connection) {
setup(connection);
});
/**
* Node setup for creating receiver link
*
* @param connection Connection instance
*/
function setup(connection) {
node.connection = connection;
// node connected
node.status({ fill: 'green', shape: 'dot', text: 'connected' });
// build receiver options based on node configuration
var options = {
source: {
address: node.address,
dynamic: node.dynamic,
durable: node.durable,
expiry_policy: node.expirypolicy
},
credit_window: node.creditwindow,
autoaccept: node.autoaccept,
snd_settle_mode: node.sndsettlemode,
rcv_settle_mode: node.rcvsettlemode
};
node.receiver = node.connection.open_receiver(options);
node.receiver.on('message', function(context) {
var msg = {
payload: context.message,
delivery: context.delivery
};
node.send(msg);
});
node.connection.on('disconnected', function(context) {
// node disconnected
node.status({fill: 'red', shape: 'dot', text: 'disconnected' });
});
node.on('input', function(msg) {
if (msg.credit) {
node.receiver.flow(msg.credit);
}
});
node.on('close', function() {
if (node.receiver != null)
node.receiver.detach();
node.connection.close();
});
}
}
}
|
javascript
|
{
"resource": ""
}
|
q3478
|
setup
|
train
|
function setup(connection) {
node.connection = connection;
// node connected
node.status({ fill: 'green', shape: 'dot', text: 'connected' });
// build receiver options based on node configuration
var options = {
source: {
address: node.address,
dynamic: node.dynamic,
durable: node.durable,
expiry_policy: node.expirypolicy
},
credit_window: node.creditwindow,
autoaccept: node.autoaccept,
snd_settle_mode: node.sndsettlemode,
rcv_settle_mode: node.rcvsettlemode
};
node.receiver = node.connection.open_receiver(options);
node.receiver.on('message', function(context) {
var msg = {
payload: context.message,
delivery: context.delivery
};
node.send(msg);
});
node.connection.on('disconnected', function(context) {
// node disconnected
node.status({fill: 'red', shape: 'dot', text: 'disconnected' });
});
node.on('input', function(msg) {
if (msg.credit) {
node.receiver.flow(msg.credit);
}
});
node.on('close', function() {
if (node.receiver != null)
node.receiver.detach();
node.connection.close();
});
}
|
javascript
|
{
"resource": ""
}
|
q3479
|
amqpRequesterNode
|
train
|
function amqpRequesterNode(config) {
RED.nodes.createNode(this, config);
//var container = rhea.create_container();
// get endpoint configuration
this.endpoint = RED.nodes.getNode(config.endpoint);
// get all other configuration
this.address = config.address;
var node = this;
// node not yet connected
this.status({ fill: 'red', shape: 'dot', text: 'disconnected' });
if (this.endpoint) {
node.endpoint.connect(function(connection) {
setup(connection);
});
/**
* Node setup for creating sender link for sending the request
* and the dynamic receiver for receiving reply
*
* @param connection Connection instance
*/
function setup(connection) {
node.connection = connection;
// node connected
node.status({ fill: 'green', shape: 'dot', text: 'connected' });
// build sender options based on node configuration
var sender_options = {
target: {
address: node.address
}
};
node.sender = node.connection.open_sender(sender_options);
node.sender.on('accepted', function(context) {
var msg = outDelivery(node, context.delivery);
node.send([msg, ]);
});
node.sender.on('released', function(context) {
var msg = outDelivery(node, context.delivery);
node.send([msg, ]);
});
node.sender.on('rejected', function(context) {
var msg = outDelivery(node, context.delivery);
node.send([msg, ]);
});
// build receiver options
var receiver_options = {
source: {
dynamic: true
}
};
node.receiver = node.connection.open_receiver(receiver_options);
node.receiver.on('message', function(context) {
var msg = {
payload: context.message,
delivery: context.delivery
};
node.send([ ,msg]);
});
node.connection.on('disconnected', function(context) {
// node disconnected
node.status({fill: 'red', shape: 'dot', text: 'disconnected' });
});
node.on('input', function(msg) {
// enough credits to send
if (node.sender.sendable()) {
if (node.receiver.source.address) {
node.sender.send({ reply_to: node.receiver.source.address, body: msg.payload.body });
}
}
});
node.on('close', function() {
if (node.sender != null)
node.sender.detach();
if (node.receiver != null)
node.receiver.detach();
node.connection.close();
})
}
}
}
|
javascript
|
{
"resource": ""
}
|
q3480
|
amqpResponderNode
|
train
|
function amqpResponderNode(config) {
RED.nodes.createNode(this, config);
// get endpoint configuration
this.endpoint = RED.nodes.getNode(config.endpoint);
// get all other configuration
this.address = config.address;
var node = this;
// node not yet connected
this.status({ fill: 'red', shape: 'dot', text: 'disconnected' });
if (this.endpoint) {
node.endpoint.connect(function(connection) {
setup(connection);
});
/**
* Node setup for creating receiver link for receiving the request
* and the sender for sending reply
*
* @param connection Connection instance
*/
function setup(connection) {
var request = undefined;
var reply_to = undefined;
var response = undefined;
node.connection = connection;
// node connected
node.status({ fill: 'green', shape: 'dot', text: 'connected' });
node.sender = node.connection.open_sender({ target: {} });
// build receiver options
var receiver_options = {
source: {
address: node.address
}
};
node.receiver = node.connection.open_receiver(receiver_options);
node.receiver.on('message', function(context) {
// save request and reply_to address on AMQP message received
request = context.message;
reply_to = request.reply_to;
// provides the request and delivery as node output
var msg = {
payload: context.message,
delivery: context.delivery
};
node.send(msg);
});
node.connection.on('disconnected', function(context) {
// node disconnected
node.status({fill: 'red', shape: 'dot', text: 'disconnected' });
});
node.on('input', function(msg) {
// enough credits to send
if (node.sender.sendable()) {
if (reply_to) {
// fill the response with the provided one as input
response = msg.payload;
response.to = reply_to;
node.sender.send(response);
}
}
});
node.on('close', function() {
if (node.sender != null)
node.sender.detach();
if (node.receiver != null)
node.receiver.detach();
node.connection.close();
})
}
}
}
|
javascript
|
{
"resource": ""
}
|
q3481
|
setup
|
train
|
function setup(connection) {
var request = undefined;
var reply_to = undefined;
var response = undefined;
node.connection = connection;
// node connected
node.status({ fill: 'green', shape: 'dot', text: 'connected' });
node.sender = node.connection.open_sender({ target: {} });
// build receiver options
var receiver_options = {
source: {
address: node.address
}
};
node.receiver = node.connection.open_receiver(receiver_options);
node.receiver.on('message', function(context) {
// save request and reply_to address on AMQP message received
request = context.message;
reply_to = request.reply_to;
// provides the request and delivery as node output
var msg = {
payload: context.message,
delivery: context.delivery
};
node.send(msg);
});
node.connection.on('disconnected', function(context) {
// node disconnected
node.status({fill: 'red', shape: 'dot', text: 'disconnected' });
});
node.on('input', function(msg) {
// enough credits to send
if (node.sender.sendable()) {
if (reply_to) {
// fill the response with the provided one as input
response = msg.payload;
response.to = reply_to;
node.sender.send(response);
}
}
});
node.on('close', function() {
if (node.sender != null)
node.sender.detach();
if (node.receiver != null)
node.receiver.detach();
node.connection.close();
})
}
|
javascript
|
{
"resource": ""
}
|
q3482
|
isNativeModule
|
train
|
function isNativeModule(targetPath, parentModule) {
const lookupPaths = Module._resolveLookupPaths(targetPath, parentModule, true);
/* istanbul ignore next */
return lookupPaths === null ||
(lookupPaths.length === 2 &&
lookupPaths[1].length === 0 &&
lookupPaths[0] === targetPath);
}
|
javascript
|
{
"resource": ""
}
|
q3483
|
isComponentWillChange
|
train
|
function isComponentWillChange(oldValue, newValue) {
const oldType = getObjectType(oldValue);
const newType = getObjectType(newValue);
return ((oldType === 'Function' || newType === 'Function') && newType !== oldType);
}
|
javascript
|
{
"resource": ""
}
|
q3484
|
updateUrl
|
train
|
function updateUrl (cb, urlNode, options) {
return cb(urlNode.url, options)
.then((response) => {
if (response) {
Object.assign(urlNode, response)
}
})
.catch(() => {
})
}
|
javascript
|
{
"resource": ""
}
|
q3485
|
getTocNode
|
train
|
function getTocNode (tree) {
const tocNode = toc(tree, { maxDepth: 3, loose: false })
if (!tocNode.map || !tocNode.map.children[0] || !tocNode.map.children[0].children[1]) {
return
}
return {
type: 'TocNode',
data: {
hName: 'div',
hProperties: {
className: ['toc-container']
}
},
children: [
{
type: 'TocTitleNode',
data: {
hName: 'h2'
},
children: [{ type: 'text', value: 'Table of contents' }]
},
tocNode.map.children[0].children[1]
]
}
}
|
javascript
|
{
"resource": ""
}
|
q3486
|
dataArray
|
train
|
function dataArray(data, context) {
data = Array.isArray(data) ? data : [data];
return context ? data.map(d => Object.assign(Object.create(context), d)) : data;
}
|
javascript
|
{
"resource": ""
}
|
q3487
|
destroyDescendant
|
train
|
function destroyDescendant() {
const instance = getInstance(this);
if (instance) {
const {
selection, datum, destroy, index,
} = instance;
destroy(selection, datum, index);
}
}
|
javascript
|
{
"resource": ""
}
|
q3488
|
destroyInstance
|
train
|
function destroyInstance() {
const {
selection, datum, destroy, index,
} = getInstance(this);
selection.selectAll('*').each(destroyDescendant);
const transition = destroy(selection, datum, index);
(transition || selection).remove();
}
|
javascript
|
{
"resource": ""
}
|
q3489
|
createInstance
|
train
|
function createInstance(datum, index) {
const selection = select(this);
setInstance(this, {
component, selection, destroy, datum, index,
});
create(selection, datum, index);
}
|
javascript
|
{
"resource": ""
}
|
q3490
|
component
|
train
|
function component(container, data, context) {
const selection = container.nodeName ? select(container) : container;
const instances = selection
.selectAll(mine)
.data(dataArray(data, context), key);
instances
.exit()
.each(destroyInstance);
return instances
.enter().append(tagName)
.attr('class', className)
.each(createInstance)
.merge(instances)
.each(renderInstance);
}
|
javascript
|
{
"resource": ""
}
|
q3491
|
SessionManager
|
train
|
function SessionManager(config, encrypter) {
/**
* The configuration object
*
* @var Object
* @protected
*/
this.__config = config;
/**
* The registered custom driver creators.
*
* @var Object
* @protected
*/
this.__customCreators = {};
/**
* The encrypter instance.
* An encrypter implements encrypt and decrypt methods.
*
* @var Object
* @protected
*/
this.__encrypter = encrypter;
/**
* The session database model instance
*
* @var Object
* @protected
*/
this.__sessionModel;
/**
* The memory session handler storage
* @type {null}
* @protected
*/
this.__memorySession = Object.create(null);
}
|
javascript
|
{
"resource": ""
}
|
q3492
|
NodeSession
|
train
|
function NodeSession(config, encrypter) {
var defaults = {
'driver': 'file',
'lifetime': 300000, // five minutes
'expireOnClose': false,
'files': process.cwd()+'/sessions',
'connection': false,
'table': 'sessions',
'lottery': [2, 100],
'cookie': 'node_session',
'path': '/',
'domain': null,
'secure': false,
'httpOnly': true,
'encrypt': false
};
/**
* The Session configuration
*
* @type {Object}
* @private
*/
this.__config = _.merge(defaults, config);
if(this.__config.trustProxy && !this.__config.trustProxyFn) {
this.__config.trustProxyFn = util.compileTrust(this.__config.trustProxy)
}
/**
* The session manager instance
* @type {SessionManager}
* @private
*/
this.__manager = new SessionManager(this.__config, encrypter);
if (!this.__config.secret) {
throw new Error('secret option required for sessions');
}
}
|
javascript
|
{
"resource": ""
}
|
q3493
|
searchPodspecFilePath
|
train
|
function searchPodspecFilePath(currentDir, callback) {
var cDir = currentDir || process.cwd();// default: cwd
fs.readdir(cDir, function (err, files) {
if (err) {
return callback(err);
}
var results = files.filter(function (file) {
return path.extname(file) === '.podspec';
});
// return first filePath
if (results.length == 0) {
callback(new Error("not found podspec file"));
} else {
var filePath = results.shift();
callback(null, filePath);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q3494
|
getFormat
|
train
|
function getFormat(formatString) {
let format = formatString.toLowerCase();
if(format == 'apa' || format == 'a') {
return CitationCore.styles.apa;
}
else if(format == 'chicago' || format == 'c') {
return CitationCore.styles.chicago;
}
else if(format == 'bibtexmisc' || format == 'bm') {
return CitationCore.styles.bibtexMisc;
}
else if(format == 'bibtexsoftware' || format == 'bs'){
return CitationCore.styles.biblatexSoftware;
}
throw new Error(formatString + ' is an unsuported citation format. Try "apa" or "chicago"');
}
|
javascript
|
{
"resource": ""
}
|
q3495
|
parseFormat
|
train
|
function parseFormat(index, args, formatOptions) {
let nextValue = args.getNextValue(index);
if(nextValue != null) {
formatOptions.style = getFormat(nextValue);
return index + 2;
}
throw new Error('No format provided');
}
|
javascript
|
{
"resource": ""
}
|
q3496
|
getType
|
train
|
function getType(val) {
switch (typeof val) {
case 'object':
return !val ? NUL : (isArray(val) ? ARY : (isMarkup(val) ? RAW : ((val instanceof Date) ? VAL : OBJ)));
case 'function':
return FUN;
case 'undefined':
return NUL;
default:
return VAL;
}
}
|
javascript
|
{
"resource": ""
}
|
q3497
|
train
|
function(elem, name, handler) {
if (name.substr(0,2) === 'on') {
name = name.substr(2);
}
switch (typeof handler) {
case 'function':
if (elem.addEventListener) {
// DOM Level 2
elem.addEventListener(name, handler, false);
} else if (elem.attachEvent && getType(elem[name]) !== NUL) {
// IE legacy events
elem.attachEvent('on'+name, handler);
} else {
// DOM Level 0
var old = elem['on'+name] || elem[name];
elem['on'+name] = elem[name] = !isFunction(old) ? handler :
function(e) {
return (old.call(this, e) !== false) && (handler.call(this, e) !== false);
};
}
break;
case 'string':
// inline functions are DOM Level 0
/*jslint evil:true */
elem['on'+name] = new Function('event', handler);
/*jslint evil:false */
break;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q3498
|
train
|
function(node, pattern) {
if (!!node && (node.nodeType === 3) && pattern.exec(node.nodeValue)) {
node.nodeValue = node.nodeValue.replace(pattern, '');
}
}
|
javascript
|
{
"resource": ""
}
|
|
q3499
|
train
|
function(elem) {
if (elem) {
while (isWhitespace(elem.firstChild)) {
// trim leading whitespace text nodes
elem.removeChild(elem.firstChild);
}
// trim leading whitespace text
trimPattern(elem.firstChild, LEADING);
while (isWhitespace(elem.lastChild)) {
// trim trailing whitespace text nodes
elem.removeChild(elem.lastChild);
}
// trim trailing whitespace text
trimPattern(elem.lastChild, TRAILING);
}
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.