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 |
---|---|---|---|---|---|---|---|---|---|---|---|
telefonicaid/logops | lib/formatters.js | colorize | function colorize(color, str) {
return str
.split('\n')
.map(part => color(part))
.join('\n');
} | javascript | function colorize(color, str) {
return str
.split('\n')
.map(part => color(part))
.join('\n');
} | [
"function",
"colorize",
"(",
"color",
",",
"str",
")",
"{",
"return",
"str",
".",
"split",
"(",
"'\\n'",
")",
".",
"\\n",
"map",
".",
"(",
"part",
"=>",
"color",
"(",
"part",
")",
")",
"join",
";",
"}"
] | Damm! colors are not applied to multilines! split, apply and join! | [
"Damm!",
"colors",
"are",
"not",
"applied",
"to",
"multilines!",
"split",
"apply",
"and",
"join!"
] | 6023d75b3531ed1bb3abe171679234f9519be082 | https://github.com/telefonicaid/logops/blob/6023d75b3531ed1bb3abe171679234f9519be082/lib/formatters.js#L116-L121 | train |
telefonicaid/logops | lib/formatters.js | formatTrace | function formatTrace(level, context, message, args, err) {
var recontext = {
time: (new Date()).toISOString(),
lvl: level,
corr: context.corr || notAvailable,
trans: context.trans || notAvailable,
op: context.op || notAvailable
};
Object.keys(context)
.filter((key) => {
return !(context[key] && Object.prototype.toString.call(context[key]) === '[object Function]');
})
.forEach((key) => {
recontext[key] = context[key] || notAvailable;
});
if (message instanceof Date || message instanceof Error) {
// Node6 related hack. See https://github.com/telefonicaid/logops/issues/36
recontext.msg = util.format(message);
} else {
recontext.msg = message;
}
var str = Object.keys(recontext)
.map((key) => key + '=' + recontext[key])
.join(' | ');
args.unshift(str);
if (err && message !== '' + err) {
args.push(err);
}
return util.format.apply(global, args);
} | javascript | function formatTrace(level, context, message, args, err) {
var recontext = {
time: (new Date()).toISOString(),
lvl: level,
corr: context.corr || notAvailable,
trans: context.trans || notAvailable,
op: context.op || notAvailable
};
Object.keys(context)
.filter((key) => {
return !(context[key] && Object.prototype.toString.call(context[key]) === '[object Function]');
})
.forEach((key) => {
recontext[key] = context[key] || notAvailable;
});
if (message instanceof Date || message instanceof Error) {
// Node6 related hack. See https://github.com/telefonicaid/logops/issues/36
recontext.msg = util.format(message);
} else {
recontext.msg = message;
}
var str = Object.keys(recontext)
.map((key) => key + '=' + recontext[key])
.join(' | ');
args.unshift(str);
if (err && message !== '' + err) {
args.push(err);
}
return util.format.apply(global, args);
} | [
"function",
"formatTrace",
"(",
"level",
",",
"context",
",",
"message",
",",
"args",
",",
"err",
")",
"{",
"var",
"recontext",
"=",
"{",
"time",
":",
"(",
"new",
"Date",
"(",
")",
")",
".",
"toISOString",
"(",
")",
",",
"lvl",
":",
"level",
",",
"corr",
":",
"context",
".",
"corr",
"||",
"notAvailable",
",",
"trans",
":",
"context",
".",
"trans",
"||",
"notAvailable",
",",
"op",
":",
"context",
".",
"op",
"||",
"notAvailable",
"}",
";",
"Object",
".",
"keys",
"(",
"context",
")",
".",
"filter",
"(",
"(",
"key",
")",
"=>",
"{",
"return",
"!",
"(",
"context",
"[",
"key",
"]",
"&&",
"Object",
".",
"prototype",
".",
"toString",
".",
"call",
"(",
"context",
"[",
"key",
"]",
")",
"===",
"'[object Function]'",
")",
";",
"}",
")",
".",
"forEach",
"(",
"(",
"key",
")",
"=>",
"{",
"recontext",
"[",
"key",
"]",
"=",
"context",
"[",
"key",
"]",
"||",
"notAvailable",
";",
"}",
")",
";",
"if",
"(",
"message",
"instanceof",
"Date",
"||",
"message",
"instanceof",
"Error",
")",
"{",
"recontext",
".",
"msg",
"=",
"util",
".",
"format",
"(",
"message",
")",
";",
"}",
"else",
"{",
"recontext",
".",
"msg",
"=",
"message",
";",
"}",
"var",
"str",
"=",
"Object",
".",
"keys",
"(",
"recontext",
")",
".",
"map",
"(",
"(",
"key",
")",
"=>",
"key",
"+",
"'='",
"+",
"recontext",
"[",
"key",
"]",
")",
".",
"join",
"(",
"' | '",
")",
";",
"args",
".",
"unshift",
"(",
"str",
")",
";",
"if",
"(",
"err",
"&&",
"message",
"!==",
"''",
"+",
"err",
")",
"{",
"args",
".",
"push",
"(",
"err",
")",
";",
"}",
"return",
"util",
".",
"format",
".",
"apply",
"(",
"global",
",",
"args",
")",
";",
"}"
] | Formats a trace message with fields separated by pipes.
DEPRECATED!
@param {String} level One of the following values
['DEBUG', 'INFO', 'WARN', 'ERROR', 'FATAL']
@param {Object} context Additional information to add to the trace
@param {String} message The main message to be added to the trace
@param {Array} args More arguments provided to the log function
@param {Error|undefined} err A cause error used to log extra information
@return {String} The trace formatted
@deprecated | [
"Formats",
"a",
"trace",
"message",
"with",
"fields",
"separated",
"by",
"pipes",
"."
] | 6023d75b3531ed1bb3abe171679234f9519be082 | https://github.com/telefonicaid/logops/blob/6023d75b3531ed1bb3abe171679234f9519be082/lib/formatters.js#L138-L173 | train |
telefonicaid/logops | lib/formatters.js | formatJsonTrace | function formatJsonTrace(level, context, message, args, err) {
return formatJsonTrace.stringify(formatJsonTrace.toObject(level, context, message, args, err));
} | javascript | function formatJsonTrace(level, context, message, args, err) {
return formatJsonTrace.stringify(formatJsonTrace.toObject(level, context, message, args, err));
} | [
"function",
"formatJsonTrace",
"(",
"level",
",",
"context",
",",
"message",
",",
"args",
",",
"err",
")",
"{",
"return",
"formatJsonTrace",
".",
"stringify",
"(",
"formatJsonTrace",
".",
"toObject",
"(",
"level",
",",
"context",
",",
"message",
",",
"args",
",",
"err",
")",
")",
";",
"}"
] | Formats a trace message in JSON format
@param {String} level One of the following values
['DEBUG', 'INFO', 'WARN', 'ERROR', 'FATAL']
@param {Object} context Additional information to add to the trace
@param {String} message The main message to be added to the trace
@param {Array} args More arguments provided to the log function
@param {Error|null} err A cause error used to log extra information
@return {String} The trace formatted | [
"Formats",
"a",
"trace",
"message",
"in",
"JSON",
"format"
] | 6023d75b3531ed1bb3abe171679234f9519be082 | https://github.com/telefonicaid/logops/blob/6023d75b3531ed1bb3abe171679234f9519be082/lib/formatters.js#L187-L189 | train |
jeffijoe/koa-respond | lib/koa-respond.js | makeRespondMiddleware | function makeRespondMiddleware(opts) {
opts = Object.assign({}, opts)
// Make the respond function.
const respond = makeRespond(opts)
/**
* Installs the functions in the context.
*
* @param {KoaContext} ctx
*/
function patch(ctx) {
const statusMethods = Object.assign({}, opts.statusMethods, statusCodeMap)
ctx.send = respond.bind(ctx, ctx)
// Bind status methods.
for (const method in statusMethods) {
const code = statusMethods[method]
ctx[method] = respond.bind(ctx, ctx, code)
}
// Bind other methods
const methods = Object.assign({}, opts.methods)
for (const method in methods) {
const fn = methods[method]
ctx[method] = fn.bind(ctx, ctx)
}
return ctx
}
/**
* The respond middleware adds the methods to the context.
*
* @param {KoaContext} ctx
*/
function respondMiddleware(ctx, next) {
patch(ctx)
return next()
}
// Tack on the patch method to allow Koa 1 users
// to install it, too.
respondMiddleware.patch = patch
return respondMiddleware
} | javascript | function makeRespondMiddleware(opts) {
opts = Object.assign({}, opts)
// Make the respond function.
const respond = makeRespond(opts)
/**
* Installs the functions in the context.
*
* @param {KoaContext} ctx
*/
function patch(ctx) {
const statusMethods = Object.assign({}, opts.statusMethods, statusCodeMap)
ctx.send = respond.bind(ctx, ctx)
// Bind status methods.
for (const method in statusMethods) {
const code = statusMethods[method]
ctx[method] = respond.bind(ctx, ctx, code)
}
// Bind other methods
const methods = Object.assign({}, opts.methods)
for (const method in methods) {
const fn = methods[method]
ctx[method] = fn.bind(ctx, ctx)
}
return ctx
}
/**
* The respond middleware adds the methods to the context.
*
* @param {KoaContext} ctx
*/
function respondMiddleware(ctx, next) {
patch(ctx)
return next()
}
// Tack on the patch method to allow Koa 1 users
// to install it, too.
respondMiddleware.patch = patch
return respondMiddleware
} | [
"function",
"makeRespondMiddleware",
"(",
"opts",
")",
"{",
"opts",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"opts",
")",
"const",
"respond",
"=",
"makeRespond",
"(",
"opts",
")",
"function",
"patch",
"(",
"ctx",
")",
"{",
"const",
"statusMethods",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"opts",
".",
"statusMethods",
",",
"statusCodeMap",
")",
"ctx",
".",
"send",
"=",
"respond",
".",
"bind",
"(",
"ctx",
",",
"ctx",
")",
"for",
"(",
"const",
"method",
"in",
"statusMethods",
")",
"{",
"const",
"code",
"=",
"statusMethods",
"[",
"method",
"]",
"ctx",
"[",
"method",
"]",
"=",
"respond",
".",
"bind",
"(",
"ctx",
",",
"ctx",
",",
"code",
")",
"}",
"const",
"methods",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"opts",
".",
"methods",
")",
"for",
"(",
"const",
"method",
"in",
"methods",
")",
"{",
"const",
"fn",
"=",
"methods",
"[",
"method",
"]",
"ctx",
"[",
"method",
"]",
"=",
"fn",
".",
"bind",
"(",
"ctx",
",",
"ctx",
")",
"}",
"return",
"ctx",
"}",
"function",
"respondMiddleware",
"(",
"ctx",
",",
"next",
")",
"{",
"patch",
"(",
"ctx",
")",
"return",
"next",
"(",
")",
"}",
"respondMiddleware",
".",
"patch",
"=",
"patch",
"return",
"respondMiddleware",
"}"
] | Makes the respond middleware. All options are optional.
@param {object} opts
Options object.
@param {object} opts.statusMethods
An object where keys maps to method names, and
values map to the status code.
@return {Function} | [
"Makes",
"the",
"respond",
"middleware",
".",
"All",
"options",
"are",
"optional",
"."
] | e38498949fc07e63f6e7609903b48b54884ae8e1 | https://github.com/jeffijoe/koa-respond/blob/e38498949fc07e63f6e7609903b48b54884ae8e1/lib/koa-respond.js#L35-L80 | train |
jeffijoe/koa-respond | lib/koa-respond.js | patch | function patch(ctx) {
const statusMethods = Object.assign({}, opts.statusMethods, statusCodeMap)
ctx.send = respond.bind(ctx, ctx)
// Bind status methods.
for (const method in statusMethods) {
const code = statusMethods[method]
ctx[method] = respond.bind(ctx, ctx, code)
}
// Bind other methods
const methods = Object.assign({}, opts.methods)
for (const method in methods) {
const fn = methods[method]
ctx[method] = fn.bind(ctx, ctx)
}
return ctx
} | javascript | function patch(ctx) {
const statusMethods = Object.assign({}, opts.statusMethods, statusCodeMap)
ctx.send = respond.bind(ctx, ctx)
// Bind status methods.
for (const method in statusMethods) {
const code = statusMethods[method]
ctx[method] = respond.bind(ctx, ctx, code)
}
// Bind other methods
const methods = Object.assign({}, opts.methods)
for (const method in methods) {
const fn = methods[method]
ctx[method] = fn.bind(ctx, ctx)
}
return ctx
} | [
"function",
"patch",
"(",
"ctx",
")",
"{",
"const",
"statusMethods",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"opts",
".",
"statusMethods",
",",
"statusCodeMap",
")",
"ctx",
".",
"send",
"=",
"respond",
".",
"bind",
"(",
"ctx",
",",
"ctx",
")",
"for",
"(",
"const",
"method",
"in",
"statusMethods",
")",
"{",
"const",
"code",
"=",
"statusMethods",
"[",
"method",
"]",
"ctx",
"[",
"method",
"]",
"=",
"respond",
".",
"bind",
"(",
"ctx",
",",
"ctx",
",",
"code",
")",
"}",
"const",
"methods",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"opts",
".",
"methods",
")",
"for",
"(",
"const",
"method",
"in",
"methods",
")",
"{",
"const",
"fn",
"=",
"methods",
"[",
"method",
"]",
"ctx",
"[",
"method",
"]",
"=",
"fn",
".",
"bind",
"(",
"ctx",
",",
"ctx",
")",
"}",
"return",
"ctx",
"}"
] | Installs the functions in the context.
@param {KoaContext} ctx | [
"Installs",
"the",
"functions",
"in",
"the",
"context",
"."
] | e38498949fc07e63f6e7609903b48b54884ae8e1 | https://github.com/jeffijoe/koa-respond/blob/e38498949fc07e63f6e7609903b48b54884ae8e1/lib/koa-respond.js#L46-L64 | train |
blueberryapps/radium-bootstrap-grid | example_app/tools/bundle.js | bundle | function bundle() {
return new Promise((resolve, reject) => {
webpack(webpackConfig).run((err, stats) => {
if (err) {
return reject(err);
}
console.log(stats.toString(webpackConfig[0].stats));
return resolve();
});
});
} | javascript | function bundle() {
return new Promise((resolve, reject) => {
webpack(webpackConfig).run((err, stats) => {
if (err) {
return reject(err);
}
console.log(stats.toString(webpackConfig[0].stats));
return resolve();
});
});
} | [
"function",
"bundle",
"(",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"webpack",
"(",
"webpackConfig",
")",
".",
"run",
"(",
"(",
"err",
",",
"stats",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"reject",
"(",
"err",
")",
";",
"}",
"console",
".",
"log",
"(",
"stats",
".",
"toString",
"(",
"webpackConfig",
"[",
"0",
"]",
".",
"stats",
")",
")",
";",
"return",
"resolve",
"(",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | Creates application bundles from the source files. | [
"Creates",
"application",
"bundles",
"from",
"the",
"source",
"files",
"."
] | b06fa043dd791577fc5dd5695609b210a9e1a26d | https://github.com/blueberryapps/radium-bootstrap-grid/blob/b06fa043dd791577fc5dd5695609b210a9e1a26d/example_app/tools/bundle.js#L16-L27 | train |
emailjs/emailjs-mime-types | dist/mimetypes.js | detectExtension | function detectExtension() {
var mimeType = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
var favoredExtension = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
mimeType = mimeType.toString().toLowerCase().replace(/\s/g, '');
if (!(mimeType in _listTypes.types)) {
return 'bin';
}
if (typeof _listTypes.types[mimeType] === 'string') {
return _listTypes.types[mimeType];
}
favoredExtension = favoredExtension.toString().toLowerCase().replace(/\s/g, '');
if (favoredExtension && _listTypes.types[mimeType].includes(favoredExtension)) {
return favoredExtension;
}
// search for name match
var mimePart = mimeType.split('/')[1];
for (var i = 0, len = _listTypes.types[mimeType].length; i < len; i++) {
if (mimePart === _listTypes.types[mimeType][i]) {
return _listTypes.types[mimeType][i];
}
}
// use the first one
return _listTypes.types[mimeType][0];
} | javascript | function detectExtension() {
var mimeType = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
var favoredExtension = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
mimeType = mimeType.toString().toLowerCase().replace(/\s/g, '');
if (!(mimeType in _listTypes.types)) {
return 'bin';
}
if (typeof _listTypes.types[mimeType] === 'string') {
return _listTypes.types[mimeType];
}
favoredExtension = favoredExtension.toString().toLowerCase().replace(/\s/g, '');
if (favoredExtension && _listTypes.types[mimeType].includes(favoredExtension)) {
return favoredExtension;
}
// search for name match
var mimePart = mimeType.split('/')[1];
for (var i = 0, len = _listTypes.types[mimeType].length; i < len; i++) {
if (mimePart === _listTypes.types[mimeType][i]) {
return _listTypes.types[mimeType][i];
}
}
// use the first one
return _listTypes.types[mimeType][0];
} | [
"function",
"detectExtension",
"(",
")",
"{",
"var",
"mimeType",
"=",
"arguments",
".",
"length",
">",
"0",
"&&",
"arguments",
"[",
"0",
"]",
"!==",
"undefined",
"?",
"arguments",
"[",
"0",
"]",
":",
"''",
";",
"var",
"favoredExtension",
"=",
"arguments",
".",
"length",
">",
"1",
"&&",
"arguments",
"[",
"1",
"]",
"!==",
"undefined",
"?",
"arguments",
"[",
"1",
"]",
":",
"''",
";",
"mimeType",
"=",
"mimeType",
".",
"toString",
"(",
")",
".",
"toLowerCase",
"(",
")",
".",
"replace",
"(",
"/",
"\\s",
"/",
"g",
",",
"''",
")",
";",
"if",
"(",
"!",
"(",
"mimeType",
"in",
"_listTypes",
".",
"types",
")",
")",
"{",
"return",
"'bin'",
";",
"}",
"if",
"(",
"typeof",
"_listTypes",
".",
"types",
"[",
"mimeType",
"]",
"===",
"'string'",
")",
"{",
"return",
"_listTypes",
".",
"types",
"[",
"mimeType",
"]",
";",
"}",
"favoredExtension",
"=",
"favoredExtension",
".",
"toString",
"(",
")",
".",
"toLowerCase",
"(",
")",
".",
"replace",
"(",
"/",
"\\s",
"/",
"g",
",",
"''",
")",
";",
"if",
"(",
"favoredExtension",
"&&",
"_listTypes",
".",
"types",
"[",
"mimeType",
"]",
".",
"includes",
"(",
"favoredExtension",
")",
")",
"{",
"return",
"favoredExtension",
";",
"}",
"var",
"mimePart",
"=",
"mimeType",
".",
"split",
"(",
"'/'",
")",
"[",
"1",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"len",
"=",
"_listTypes",
".",
"types",
"[",
"mimeType",
"]",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"if",
"(",
"mimePart",
"===",
"_listTypes",
".",
"types",
"[",
"mimeType",
"]",
"[",
"i",
"]",
")",
"{",
"return",
"_listTypes",
".",
"types",
"[",
"mimeType",
"]",
"[",
"i",
"]",
";",
"}",
"}",
"return",
"_listTypes",
".",
"types",
"[",
"mimeType",
"]",
"[",
"0",
"]",
";",
"}"
] | Returns file extension for a content type string. If no suitable extensions
are found, 'bin' is used as the default extension
@param {String} mimeType Content type to be checked for
@return {String} File extension | [
"Returns",
"file",
"extension",
"for",
"a",
"content",
"type",
"string",
".",
"If",
"no",
"suitable",
"extensions",
"are",
"found",
"bin",
"is",
"used",
"as",
"the",
"default",
"extension"
] | b457f6072e9ee8a47ad4952fa2ef6bf87a9c8ca7 | https://github.com/emailjs/emailjs-mime-types/blob/b457f6072e9ee8a47ad4952fa2ef6bf87a9c8ca7/dist/mimetypes.js#L20-L48 | train |
seznam/IMA.js-gulp-tasks | tasks/compile.js | mapSync | function mapSync(transformation) {
return through2.obj(function write(chunk, _, callback) {
let mappedData;
try {
mappedData = transformation(chunk);
} catch (error) {
callback(error);
}
if (mappedData !== undefined) {
this.push(mappedData);
}
callback();
});
} | javascript | function mapSync(transformation) {
return through2.obj(function write(chunk, _, callback) {
let mappedData;
try {
mappedData = transformation(chunk);
} catch (error) {
callback(error);
}
if (mappedData !== undefined) {
this.push(mappedData);
}
callback();
});
} | [
"function",
"mapSync",
"(",
"transformation",
")",
"{",
"return",
"through2",
".",
"obj",
"(",
"function",
"write",
"(",
"chunk",
",",
"_",
",",
"callback",
")",
"{",
"let",
"mappedData",
";",
"try",
"{",
"mappedData",
"=",
"transformation",
"(",
"chunk",
")",
";",
"}",
"catch",
"(",
"error",
")",
"{",
"callback",
"(",
"error",
")",
";",
"}",
"if",
"(",
"mappedData",
"!==",
"undefined",
")",
"{",
"this",
".",
"push",
"(",
"mappedData",
")",
";",
"}",
"callback",
"(",
")",
";",
"}",
")",
";",
"}"
] | Apply method for stream.
@param {function} transformation
@return {Stream<File>} Stream processor for files. | [
"Apply",
"method",
"for",
"stream",
"."
] | 442d5b66d34cb62aa1db3da5a44dd14d431e30f8 | https://github.com/seznam/IMA.js-gulp-tasks/blob/442d5b66d34cb62aa1db3da5a44dd14d431e30f8/tasks/compile.js#L359-L373 | train |
seznam/IMA.js-gulp-tasks | tasks/compile.js | resolveNewPath | function resolveNewPath(newBase) {
return mapSync(file => {
file.cwd += newBase;
file.base = file.cwd;
return file;
});
} | javascript | function resolveNewPath(newBase) {
return mapSync(file => {
file.cwd += newBase;
file.base = file.cwd;
return file;
});
} | [
"function",
"resolveNewPath",
"(",
"newBase",
")",
"{",
"return",
"mapSync",
"(",
"file",
"=>",
"{",
"file",
".",
"cwd",
"+=",
"newBase",
";",
"file",
".",
"base",
"=",
"file",
".",
"cwd",
";",
"return",
"file",
";",
"}",
")",
";",
"}"
] | "Fix" file path for the babel task to get better-looking module names.
@param {string} newBase The base directory against which the file path
should be matched.
@return {Stream<File>} Stream processor for files. | [
"Fix",
"file",
"path",
"for",
"the",
"babel",
"task",
"to",
"get",
"better",
"-",
"looking",
"module",
"names",
"."
] | 442d5b66d34cb62aa1db3da5a44dd14d431e30f8 | https://github.com/seznam/IMA.js-gulp-tasks/blob/442d5b66d34cb62aa1db3da5a44dd14d431e30f8/tasks/compile.js#L382-L388 | train |
welldone-software/gulp-durandal | examples/HTML StarterKit/lib/durandal/js/viewLocator.js | function(modulesPath, viewsPath, areasPath) {
modulesPath = modulesPath || 'viewmodels';
viewsPath = viewsPath || 'views';
areasPath = areasPath || viewsPath;
var reg = new RegExp(escape(modulesPath), 'gi');
this.convertModuleIdToViewId = function (moduleId) {
return moduleId.replace(reg, viewsPath);
};
this.translateViewIdToArea = function (viewId, area) {
if (!area || area == 'partial') {
return areasPath + '/' + viewId;
}
return areasPath + '/' + area + '/' + viewId;
};
} | javascript | function(modulesPath, viewsPath, areasPath) {
modulesPath = modulesPath || 'viewmodels';
viewsPath = viewsPath || 'views';
areasPath = areasPath || viewsPath;
var reg = new RegExp(escape(modulesPath), 'gi');
this.convertModuleIdToViewId = function (moduleId) {
return moduleId.replace(reg, viewsPath);
};
this.translateViewIdToArea = function (viewId, area) {
if (!area || area == 'partial') {
return areasPath + '/' + viewId;
}
return areasPath + '/' + area + '/' + viewId;
};
} | [
"function",
"(",
"modulesPath",
",",
"viewsPath",
",",
"areasPath",
")",
"{",
"modulesPath",
"=",
"modulesPath",
"||",
"'viewmodels'",
";",
"viewsPath",
"=",
"viewsPath",
"||",
"'views'",
";",
"areasPath",
"=",
"areasPath",
"||",
"viewsPath",
";",
"var",
"reg",
"=",
"new",
"RegExp",
"(",
"escape",
"(",
"modulesPath",
")",
",",
"'gi'",
")",
";",
"this",
".",
"convertModuleIdToViewId",
"=",
"function",
"(",
"moduleId",
")",
"{",
"return",
"moduleId",
".",
"replace",
"(",
"reg",
",",
"viewsPath",
")",
";",
"}",
";",
"this",
".",
"translateViewIdToArea",
"=",
"function",
"(",
"viewId",
",",
"area",
")",
"{",
"if",
"(",
"!",
"area",
"||",
"area",
"==",
"'partial'",
")",
"{",
"return",
"areasPath",
"+",
"'/'",
"+",
"viewId",
";",
"}",
"return",
"areasPath",
"+",
"'/'",
"+",
"area",
"+",
"'/'",
"+",
"viewId",
";",
"}",
";",
"}"
] | Allows you to set up a convention for mapping module folders to view folders. It is a convenience method that customizes `convertModuleIdToViewId` and `translateViewIdToArea` under the covers.
@method useConvention
@param {string} [modulesPath] A string to match in the path and replace with the viewsPath. If not specified, the match is 'viewmodels'.
@param {string} [viewsPath] The replacement for the modulesPath. If not specified, the replacement is 'views'.
@param {string} [areasPath] Partial views are mapped to the "views" folder if not specified. Use this parameter to change their location. | [
"Allows",
"you",
"to",
"set",
"up",
"a",
"convention",
"for",
"mapping",
"module",
"folders",
"to",
"view",
"folders",
".",
"It",
"is",
"a",
"convenience",
"method",
"that",
"customizes",
"convertModuleIdToViewId",
"and",
"translateViewIdToArea",
"under",
"the",
"covers",
"."
] | 4eacd22fcc567a372e04e6de443b0228572d6400 | https://github.com/welldone-software/gulp-durandal/blob/4eacd22fcc567a372e04e6de443b0228572d6400/examples/HTML StarterKit/lib/durandal/js/viewLocator.js#L39-L57 | train |
|
welldone-software/gulp-durandal | examples/HTML StarterKit/lib/durandal/js/viewLocator.js | function(obj, area, elementsToSearch) {
var view;
if (obj.getView) {
view = obj.getView();
if (view) {
return this.locateView(view, area, elementsToSearch);
}
}
if (obj.viewUrl) {
return this.locateView(obj.viewUrl, area, elementsToSearch);
}
var id = system.getModuleId(obj);
if (id) {
return this.locateView(this.convertModuleIdToViewId(id), area, elementsToSearch);
}
return this.locateView(this.determineFallbackViewId(obj), area, elementsToSearch);
} | javascript | function(obj, area, elementsToSearch) {
var view;
if (obj.getView) {
view = obj.getView();
if (view) {
return this.locateView(view, area, elementsToSearch);
}
}
if (obj.viewUrl) {
return this.locateView(obj.viewUrl, area, elementsToSearch);
}
var id = system.getModuleId(obj);
if (id) {
return this.locateView(this.convertModuleIdToViewId(id), area, elementsToSearch);
}
return this.locateView(this.determineFallbackViewId(obj), area, elementsToSearch);
} | [
"function",
"(",
"obj",
",",
"area",
",",
"elementsToSearch",
")",
"{",
"var",
"view",
";",
"if",
"(",
"obj",
".",
"getView",
")",
"{",
"view",
"=",
"obj",
".",
"getView",
"(",
")",
";",
"if",
"(",
"view",
")",
"{",
"return",
"this",
".",
"locateView",
"(",
"view",
",",
"area",
",",
"elementsToSearch",
")",
";",
"}",
"}",
"if",
"(",
"obj",
".",
"viewUrl",
")",
"{",
"return",
"this",
".",
"locateView",
"(",
"obj",
".",
"viewUrl",
",",
"area",
",",
"elementsToSearch",
")",
";",
"}",
"var",
"id",
"=",
"system",
".",
"getModuleId",
"(",
"obj",
")",
";",
"if",
"(",
"id",
")",
"{",
"return",
"this",
".",
"locateView",
"(",
"this",
".",
"convertModuleIdToViewId",
"(",
"id",
")",
",",
"area",
",",
"elementsToSearch",
")",
";",
"}",
"return",
"this",
".",
"locateView",
"(",
"this",
".",
"determineFallbackViewId",
"(",
"obj",
")",
",",
"area",
",",
"elementsToSearch",
")",
";",
"}"
] | Maps an object instance to a view instance.
@method locateViewForObject
@param {object} obj The object to locate the view for.
@param {string} [area] The area to translate the view to.
@param {DOMElement[]} [elementsToSearch] An existing set of elements to search first.
@return {Promise} A promise of the view. | [
"Maps",
"an",
"object",
"instance",
"to",
"a",
"view",
"instance",
"."
] | 4eacd22fcc567a372e04e6de443b0228572d6400 | https://github.com/welldone-software/gulp-durandal/blob/4eacd22fcc567a372e04e6de443b0228572d6400/examples/HTML StarterKit/lib/durandal/js/viewLocator.js#L66-L86 | train |
|
welldone-software/gulp-durandal | examples/HTML StarterKit/lib/durandal/js/viewLocator.js | function (obj) {
var funcNameRegex = /function (.{1,})\(/;
var results = (funcNameRegex).exec((obj).constructor.toString());
var typeName = (results && results.length > 1) ? results[1] : "";
return 'views/' + typeName;
} | javascript | function (obj) {
var funcNameRegex = /function (.{1,})\(/;
var results = (funcNameRegex).exec((obj).constructor.toString());
var typeName = (results && results.length > 1) ? results[1] : "";
return 'views/' + typeName;
} | [
"function",
"(",
"obj",
")",
"{",
"var",
"funcNameRegex",
"=",
"/",
"function (.{1,})\\(",
"/",
";",
"var",
"results",
"=",
"(",
"funcNameRegex",
")",
".",
"exec",
"(",
"(",
"obj",
")",
".",
"constructor",
".",
"toString",
"(",
")",
")",
";",
"var",
"typeName",
"=",
"(",
"results",
"&&",
"results",
".",
"length",
">",
"1",
")",
"?",
"results",
"[",
"1",
"]",
":",
"\"\"",
";",
"return",
"'views/'",
"+",
"typeName",
";",
"}"
] | If no view id can be determined, this function is called to genreate one. By default it attempts to determine the object's type and use that.
@method determineFallbackViewId
@param {object} obj The object to determine the fallback id for.
@return {string} The view id. | [
"If",
"no",
"view",
"id",
"can",
"be",
"determined",
"this",
"function",
"is",
"called",
"to",
"genreate",
"one",
".",
"By",
"default",
"it",
"attempts",
"to",
"determine",
"the",
"object",
"s",
"type",
"and",
"use",
"that",
"."
] | 4eacd22fcc567a372e04e6de443b0228572d6400 | https://github.com/welldone-software/gulp-durandal/blob/4eacd22fcc567a372e04e6de443b0228572d6400/examples/HTML StarterKit/lib/durandal/js/viewLocator.js#L102-L108 | train |
|
welldone-software/gulp-durandal | examples/HTML StarterKit/lib/durandal/js/viewLocator.js | function(viewOrUrlOrId, area, elementsToSearch) {
if (typeof viewOrUrlOrId === 'string') {
var viewId;
if (viewEngine.isViewUrl(viewOrUrlOrId)) {
viewId = viewEngine.convertViewUrlToViewId(viewOrUrlOrId);
} else {
viewId = viewOrUrlOrId;
}
if (area) {
viewId = this.translateViewIdToArea(viewId, area);
}
if (elementsToSearch) {
var existing = findInElements(elementsToSearch, viewId);
if (existing) {
return system.defer(function(dfd) {
dfd.resolve(existing);
}).promise();
}
}
return viewEngine.createView(viewId);
}
return system.defer(function(dfd) {
dfd.resolve(viewOrUrlOrId);
}).promise();
} | javascript | function(viewOrUrlOrId, area, elementsToSearch) {
if (typeof viewOrUrlOrId === 'string') {
var viewId;
if (viewEngine.isViewUrl(viewOrUrlOrId)) {
viewId = viewEngine.convertViewUrlToViewId(viewOrUrlOrId);
} else {
viewId = viewOrUrlOrId;
}
if (area) {
viewId = this.translateViewIdToArea(viewId, area);
}
if (elementsToSearch) {
var existing = findInElements(elementsToSearch, viewId);
if (existing) {
return system.defer(function(dfd) {
dfd.resolve(existing);
}).promise();
}
}
return viewEngine.createView(viewId);
}
return system.defer(function(dfd) {
dfd.resolve(viewOrUrlOrId);
}).promise();
} | [
"function",
"(",
"viewOrUrlOrId",
",",
"area",
",",
"elementsToSearch",
")",
"{",
"if",
"(",
"typeof",
"viewOrUrlOrId",
"===",
"'string'",
")",
"{",
"var",
"viewId",
";",
"if",
"(",
"viewEngine",
".",
"isViewUrl",
"(",
"viewOrUrlOrId",
")",
")",
"{",
"viewId",
"=",
"viewEngine",
".",
"convertViewUrlToViewId",
"(",
"viewOrUrlOrId",
")",
";",
"}",
"else",
"{",
"viewId",
"=",
"viewOrUrlOrId",
";",
"}",
"if",
"(",
"area",
")",
"{",
"viewId",
"=",
"this",
".",
"translateViewIdToArea",
"(",
"viewId",
",",
"area",
")",
";",
"}",
"if",
"(",
"elementsToSearch",
")",
"{",
"var",
"existing",
"=",
"findInElements",
"(",
"elementsToSearch",
",",
"viewId",
")",
";",
"if",
"(",
"existing",
")",
"{",
"return",
"system",
".",
"defer",
"(",
"function",
"(",
"dfd",
")",
"{",
"dfd",
".",
"resolve",
"(",
"existing",
")",
";",
"}",
")",
".",
"promise",
"(",
")",
";",
"}",
"}",
"return",
"viewEngine",
".",
"createView",
"(",
"viewId",
")",
";",
"}",
"return",
"system",
".",
"defer",
"(",
"function",
"(",
"dfd",
")",
"{",
"dfd",
".",
"resolve",
"(",
"viewOrUrlOrId",
")",
";",
"}",
")",
".",
"promise",
"(",
")",
";",
"}"
] | Locates the specified view.
@method locateView
@param {string|DOMElement} viewOrUrlOrId A view, view url or view id to locate.
@param {string} [area] The area to translate the view to.
@param {DOMElement[]} [elementsToSearch] An existing set of elements to search first.
@return {Promise} A promise of the view. | [
"Locates",
"the",
"specified",
"view",
"."
] | 4eacd22fcc567a372e04e6de443b0228572d6400 | https://github.com/welldone-software/gulp-durandal/blob/4eacd22fcc567a372e04e6de443b0228572d6400/examples/HTML StarterKit/lib/durandal/js/viewLocator.js#L127-L156 | train |
|
OpenBCI/OpenBCI_JavaScript_Utilities | src/utilities.js | processCompressedData | function processCompressedData (o) {
// Save the packet counter
o.lastSampleNumber = parseInt(o.rawDataPacket[0]);
const samples = [];
// Decompress the buffer into array
if (o.lastSampleNumber <= k.OBCIGanglionByteId18Bit.max) {
decompressSamples(o, decompressDeltas18Bit(o.rawDataPacket.slice(k.OBCIGanglionPacket18Bit.dataStart, k.OBCIGanglionPacket18Bit.dataStop)));
samples.push(buildSample(o.lastSampleNumber * 2 - 1, o.decompressedSamples[1], o.sendCounts));
samples.push(buildSample(o.lastSampleNumber * 2, o.decompressedSamples[2], o.sendCounts));
switch (o.lastSampleNumber % 10) {
case k.OBCIGanglionAccelAxisX:
o.accelArray[0] = o.sendCounts ? o.rawDataPacket.readInt8(k.OBCIGanglionPacket18Bit.auxByte - 1) : o.rawDataPacket.readInt8(k.OBCIGanglionPacket18Bit.auxByte - 1) * k.OBCIGanglionAccelScaleFactor;
break;
case k.OBCIGanglionAccelAxisY:
o.accelArray[1] = o.sendCounts ? o.rawDataPacket.readInt8(k.OBCIGanglionPacket18Bit.auxByte - 1) : o.rawDataPacket.readInt8(k.OBCIGanglionPacket18Bit.auxByte - 1) * k.OBCIGanglionAccelScaleFactor;
break;
case k.OBCIGanglionAccelAxisZ:
o.accelArray[2] = o.sendCounts ? o.rawDataPacket.readInt8(k.OBCIGanglionPacket18Bit.auxByte - 1) : o.rawDataPacket.readInt8(k.OBCIGanglionPacket18Bit.auxByte - 1) * k.OBCIGanglionAccelScaleFactor;
if (o.sendCounts) {
samples[0].accelData = o.accelArray;
} else {
samples[0].accelDataCounts = o.accelArray;
}
break;
default:
break;
}
} else {
decompressSamples(o, decompressDeltas19Bit(o.rawDataPacket.slice(k.OBCIGanglionPacket19Bit.dataStart, k.OBCIGanglionPacket19Bit.dataStop)));
samples.push(buildSample((o.lastSampleNumber - 100) * 2 - 1, o.decompressedSamples[1], o.sendCounts));
samples.push(buildSample((o.lastSampleNumber - 100) * 2, o.decompressedSamples[2], o.sendCounts));
}
// Rotate the 0 position for next time
for (let i = 0; i < k.OBCINumberOfChannelsGanglion; i++) {
o.decompressedSamples[0][i] = o.decompressedSamples[2][i];
}
return samples;
} | javascript | function processCompressedData (o) {
// Save the packet counter
o.lastSampleNumber = parseInt(o.rawDataPacket[0]);
const samples = [];
// Decompress the buffer into array
if (o.lastSampleNumber <= k.OBCIGanglionByteId18Bit.max) {
decompressSamples(o, decompressDeltas18Bit(o.rawDataPacket.slice(k.OBCIGanglionPacket18Bit.dataStart, k.OBCIGanglionPacket18Bit.dataStop)));
samples.push(buildSample(o.lastSampleNumber * 2 - 1, o.decompressedSamples[1], o.sendCounts));
samples.push(buildSample(o.lastSampleNumber * 2, o.decompressedSamples[2], o.sendCounts));
switch (o.lastSampleNumber % 10) {
case k.OBCIGanglionAccelAxisX:
o.accelArray[0] = o.sendCounts ? o.rawDataPacket.readInt8(k.OBCIGanglionPacket18Bit.auxByte - 1) : o.rawDataPacket.readInt8(k.OBCIGanglionPacket18Bit.auxByte - 1) * k.OBCIGanglionAccelScaleFactor;
break;
case k.OBCIGanglionAccelAxisY:
o.accelArray[1] = o.sendCounts ? o.rawDataPacket.readInt8(k.OBCIGanglionPacket18Bit.auxByte - 1) : o.rawDataPacket.readInt8(k.OBCIGanglionPacket18Bit.auxByte - 1) * k.OBCIGanglionAccelScaleFactor;
break;
case k.OBCIGanglionAccelAxisZ:
o.accelArray[2] = o.sendCounts ? o.rawDataPacket.readInt8(k.OBCIGanglionPacket18Bit.auxByte - 1) : o.rawDataPacket.readInt8(k.OBCIGanglionPacket18Bit.auxByte - 1) * k.OBCIGanglionAccelScaleFactor;
if (o.sendCounts) {
samples[0].accelData = o.accelArray;
} else {
samples[0].accelDataCounts = o.accelArray;
}
break;
default:
break;
}
} else {
decompressSamples(o, decompressDeltas19Bit(o.rawDataPacket.slice(k.OBCIGanglionPacket19Bit.dataStart, k.OBCIGanglionPacket19Bit.dataStop)));
samples.push(buildSample((o.lastSampleNumber - 100) * 2 - 1, o.decompressedSamples[1], o.sendCounts));
samples.push(buildSample((o.lastSampleNumber - 100) * 2, o.decompressedSamples[2], o.sendCounts));
}
// Rotate the 0 position for next time
for (let i = 0; i < k.OBCINumberOfChannelsGanglion; i++) {
o.decompressedSamples[0][i] = o.decompressedSamples[2][i];
}
return samples;
} | [
"function",
"processCompressedData",
"(",
"o",
")",
"{",
"o",
".",
"lastSampleNumber",
"=",
"parseInt",
"(",
"o",
".",
"rawDataPacket",
"[",
"0",
"]",
")",
";",
"const",
"samples",
"=",
"[",
"]",
";",
"if",
"(",
"o",
".",
"lastSampleNumber",
"<=",
"k",
".",
"OBCIGanglionByteId18Bit",
".",
"max",
")",
"{",
"decompressSamples",
"(",
"o",
",",
"decompressDeltas18Bit",
"(",
"o",
".",
"rawDataPacket",
".",
"slice",
"(",
"k",
".",
"OBCIGanglionPacket18Bit",
".",
"dataStart",
",",
"k",
".",
"OBCIGanglionPacket18Bit",
".",
"dataStop",
")",
")",
")",
";",
"samples",
".",
"push",
"(",
"buildSample",
"(",
"o",
".",
"lastSampleNumber",
"*",
"2",
"-",
"1",
",",
"o",
".",
"decompressedSamples",
"[",
"1",
"]",
",",
"o",
".",
"sendCounts",
")",
")",
";",
"samples",
".",
"push",
"(",
"buildSample",
"(",
"o",
".",
"lastSampleNumber",
"*",
"2",
",",
"o",
".",
"decompressedSamples",
"[",
"2",
"]",
",",
"o",
".",
"sendCounts",
")",
")",
";",
"switch",
"(",
"o",
".",
"lastSampleNumber",
"%",
"10",
")",
"{",
"case",
"k",
".",
"OBCIGanglionAccelAxisX",
":",
"o",
".",
"accelArray",
"[",
"0",
"]",
"=",
"o",
".",
"sendCounts",
"?",
"o",
".",
"rawDataPacket",
".",
"readInt8",
"(",
"k",
".",
"OBCIGanglionPacket18Bit",
".",
"auxByte",
"-",
"1",
")",
":",
"o",
".",
"rawDataPacket",
".",
"readInt8",
"(",
"k",
".",
"OBCIGanglionPacket18Bit",
".",
"auxByte",
"-",
"1",
")",
"*",
"k",
".",
"OBCIGanglionAccelScaleFactor",
";",
"break",
";",
"case",
"k",
".",
"OBCIGanglionAccelAxisY",
":",
"o",
".",
"accelArray",
"[",
"1",
"]",
"=",
"o",
".",
"sendCounts",
"?",
"o",
".",
"rawDataPacket",
".",
"readInt8",
"(",
"k",
".",
"OBCIGanglionPacket18Bit",
".",
"auxByte",
"-",
"1",
")",
":",
"o",
".",
"rawDataPacket",
".",
"readInt8",
"(",
"k",
".",
"OBCIGanglionPacket18Bit",
".",
"auxByte",
"-",
"1",
")",
"*",
"k",
".",
"OBCIGanglionAccelScaleFactor",
";",
"break",
";",
"case",
"k",
".",
"OBCIGanglionAccelAxisZ",
":",
"o",
".",
"accelArray",
"[",
"2",
"]",
"=",
"o",
".",
"sendCounts",
"?",
"o",
".",
"rawDataPacket",
".",
"readInt8",
"(",
"k",
".",
"OBCIGanglionPacket18Bit",
".",
"auxByte",
"-",
"1",
")",
":",
"o",
".",
"rawDataPacket",
".",
"readInt8",
"(",
"k",
".",
"OBCIGanglionPacket18Bit",
".",
"auxByte",
"-",
"1",
")",
"*",
"k",
".",
"OBCIGanglionAccelScaleFactor",
";",
"if",
"(",
"o",
".",
"sendCounts",
")",
"{",
"samples",
"[",
"0",
"]",
".",
"accelData",
"=",
"o",
".",
"accelArray",
";",
"}",
"else",
"{",
"samples",
"[",
"0",
"]",
".",
"accelDataCounts",
"=",
"o",
".",
"accelArray",
";",
"}",
"break",
";",
"default",
":",
"break",
";",
"}",
"}",
"else",
"{",
"decompressSamples",
"(",
"o",
",",
"decompressDeltas19Bit",
"(",
"o",
".",
"rawDataPacket",
".",
"slice",
"(",
"k",
".",
"OBCIGanglionPacket19Bit",
".",
"dataStart",
",",
"k",
".",
"OBCIGanglionPacket19Bit",
".",
"dataStop",
")",
")",
")",
";",
"samples",
".",
"push",
"(",
"buildSample",
"(",
"(",
"o",
".",
"lastSampleNumber",
"-",
"100",
")",
"*",
"2",
"-",
"1",
",",
"o",
".",
"decompressedSamples",
"[",
"1",
"]",
",",
"o",
".",
"sendCounts",
")",
")",
";",
"samples",
".",
"push",
"(",
"buildSample",
"(",
"(",
"o",
".",
"lastSampleNumber",
"-",
"100",
")",
"*",
"2",
",",
"o",
".",
"decompressedSamples",
"[",
"2",
"]",
",",
"o",
".",
"sendCounts",
")",
")",
";",
"}",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"k",
".",
"OBCINumberOfChannelsGanglion",
";",
"i",
"++",
")",
"{",
"o",
".",
"decompressedSamples",
"[",
"0",
"]",
"[",
"i",
"]",
"=",
"o",
".",
"decompressedSamples",
"[",
"2",
"]",
"[",
"i",
"]",
";",
"}",
"return",
"samples",
";",
"}"
] | Process an compressed packet of data.
@param o {RawDataToSample} - Used to hold data and configuration settings
@private | [
"Process",
"an",
"compressed",
"packet",
"of",
"data",
"."
] | 37886da7a07ea523b13a46448f56e1e1528748b7 | https://github.com/OpenBCI/OpenBCI_JavaScript_Utilities/blob/37886da7a07ea523b13a46448f56e1e1528748b7/src/utilities.js#L769-L811 | train |
OpenBCI/OpenBCI_JavaScript_Utilities | src/utilities.js | processImpedanceData | function processImpedanceData (o) {
const byteId = parseInt(o.rawDataPacket[0]);
let channelNumber;
switch (byteId) {
case k.OBCIGanglionByteIdImpedanceChannel1:
channelNumber = 1;
break;
case k.OBCIGanglionByteIdImpedanceChannel2:
channelNumber = 2;
break;
case k.OBCIGanglionByteIdImpedanceChannel3:
channelNumber = 3;
break;
case k.OBCIGanglionByteIdImpedanceChannel4:
channelNumber = 4;
break;
case k.OBCIGanglionByteIdImpedanceChannelReference:
channelNumber = 0;
break;
}
let output = {
channelNumber: channelNumber,
impedanceValue: 0
};
let end = o.rawDataPacket.length;
while (Number.isNaN(Number(o.rawDataPacket.slice(1, end))) && end !== 0) {
end--;
}
if (end !== 0) {
output.impedanceValue = Number(o.rawDataPacket.slice(1, end));
}
return output;
} | javascript | function processImpedanceData (o) {
const byteId = parseInt(o.rawDataPacket[0]);
let channelNumber;
switch (byteId) {
case k.OBCIGanglionByteIdImpedanceChannel1:
channelNumber = 1;
break;
case k.OBCIGanglionByteIdImpedanceChannel2:
channelNumber = 2;
break;
case k.OBCIGanglionByteIdImpedanceChannel3:
channelNumber = 3;
break;
case k.OBCIGanglionByteIdImpedanceChannel4:
channelNumber = 4;
break;
case k.OBCIGanglionByteIdImpedanceChannelReference:
channelNumber = 0;
break;
}
let output = {
channelNumber: channelNumber,
impedanceValue: 0
};
let end = o.rawDataPacket.length;
while (Number.isNaN(Number(o.rawDataPacket.slice(1, end))) && end !== 0) {
end--;
}
if (end !== 0) {
output.impedanceValue = Number(o.rawDataPacket.slice(1, end));
}
return output;
} | [
"function",
"processImpedanceData",
"(",
"o",
")",
"{",
"const",
"byteId",
"=",
"parseInt",
"(",
"o",
".",
"rawDataPacket",
"[",
"0",
"]",
")",
";",
"let",
"channelNumber",
";",
"switch",
"(",
"byteId",
")",
"{",
"case",
"k",
".",
"OBCIGanglionByteIdImpedanceChannel1",
":",
"channelNumber",
"=",
"1",
";",
"break",
";",
"case",
"k",
".",
"OBCIGanglionByteIdImpedanceChannel2",
":",
"channelNumber",
"=",
"2",
";",
"break",
";",
"case",
"k",
".",
"OBCIGanglionByteIdImpedanceChannel3",
":",
"channelNumber",
"=",
"3",
";",
"break",
";",
"case",
"k",
".",
"OBCIGanglionByteIdImpedanceChannel4",
":",
"channelNumber",
"=",
"4",
";",
"break",
";",
"case",
"k",
".",
"OBCIGanglionByteIdImpedanceChannelReference",
":",
"channelNumber",
"=",
"0",
";",
"break",
";",
"}",
"let",
"output",
"=",
"{",
"channelNumber",
":",
"channelNumber",
",",
"impedanceValue",
":",
"0",
"}",
";",
"let",
"end",
"=",
"o",
".",
"rawDataPacket",
".",
"length",
";",
"while",
"(",
"Number",
".",
"isNaN",
"(",
"Number",
"(",
"o",
".",
"rawDataPacket",
".",
"slice",
"(",
"1",
",",
"end",
")",
")",
")",
"&&",
"end",
"!==",
"0",
")",
"{",
"end",
"--",
";",
"}",
"if",
"(",
"end",
"!==",
"0",
")",
"{",
"output",
".",
"impedanceValue",
"=",
"Number",
"(",
"o",
".",
"rawDataPacket",
".",
"slice",
"(",
"1",
",",
"end",
")",
")",
";",
"}",
"return",
"output",
";",
"}"
] | Process and emit an impedance value
@param o {RawDataToSample} - Used to hold data and configuration settings
@private | [
"Process",
"and",
"emit",
"an",
"impedance",
"value"
] | 37886da7a07ea523b13a46448f56e1e1528748b7 | https://github.com/OpenBCI/OpenBCI_JavaScript_Utilities/blob/37886da7a07ea523b13a46448f56e1e1528748b7/src/utilities.js#L818-L855 | train |
OpenBCI/OpenBCI_JavaScript_Utilities | src/utilities.js | processMultiBytePacket | function processMultiBytePacket (o) {
if (o.multiPacketBuffer) {
o.multiPacketBuffer = Buffer.concat([Buffer.from(o.multiPacketBuffer), Buffer.from(o.rawDataPacket.slice(k.OBCIGanglionPacket19Bit.dataStart, k.OBCIGanglionPacket19Bit.dataStop))]);
} else {
o.multiPacketBuffer = o.rawDataPacket.slice(k.OBCIGanglionPacket19Bit.dataStart, k.OBCIGanglionPacket19Bit.dataStop);
}
} | javascript | function processMultiBytePacket (o) {
if (o.multiPacketBuffer) {
o.multiPacketBuffer = Buffer.concat([Buffer.from(o.multiPacketBuffer), Buffer.from(o.rawDataPacket.slice(k.OBCIGanglionPacket19Bit.dataStart, k.OBCIGanglionPacket19Bit.dataStop))]);
} else {
o.multiPacketBuffer = o.rawDataPacket.slice(k.OBCIGanglionPacket19Bit.dataStart, k.OBCIGanglionPacket19Bit.dataStop);
}
} | [
"function",
"processMultiBytePacket",
"(",
"o",
")",
"{",
"if",
"(",
"o",
".",
"multiPacketBuffer",
")",
"{",
"o",
".",
"multiPacketBuffer",
"=",
"Buffer",
".",
"concat",
"(",
"[",
"Buffer",
".",
"from",
"(",
"o",
".",
"multiPacketBuffer",
")",
",",
"Buffer",
".",
"from",
"(",
"o",
".",
"rawDataPacket",
".",
"slice",
"(",
"k",
".",
"OBCIGanglionPacket19Bit",
".",
"dataStart",
",",
"k",
".",
"OBCIGanglionPacket19Bit",
".",
"dataStop",
")",
")",
"]",
")",
";",
"}",
"else",
"{",
"o",
".",
"multiPacketBuffer",
"=",
"o",
".",
"rawDataPacket",
".",
"slice",
"(",
"k",
".",
"OBCIGanglionPacket19Bit",
".",
"dataStart",
",",
"k",
".",
"OBCIGanglionPacket19Bit",
".",
"dataStop",
")",
";",
"}",
"}"
] | Used to stack multi packet buffers into the multi packet buffer. This is finally emitted when a stop packet byte id
is received.
@param o {RawDataToSample} - Used to hold data and configuration settings
@private | [
"Used",
"to",
"stack",
"multi",
"packet",
"buffers",
"into",
"the",
"multi",
"packet",
"buffer",
".",
"This",
"is",
"finally",
"emitted",
"when",
"a",
"stop",
"packet",
"byte",
"id",
"is",
"received",
"."
] | 37886da7a07ea523b13a46448f56e1e1528748b7 | https://github.com/OpenBCI/OpenBCI_JavaScript_Utilities/blob/37886da7a07ea523b13a46448f56e1e1528748b7/src/utilities.js#L863-L869 | train |
OpenBCI/OpenBCI_JavaScript_Utilities | src/utilities.js | processMultiBytePacketStop | function processMultiBytePacketStop (o) {
processMultiBytePacket(o);
const str = o.multiPacketBuffer.toString();
o.multiPacketBuffer = null;
return {
'message': str
};
} | javascript | function processMultiBytePacketStop (o) {
processMultiBytePacket(o);
const str = o.multiPacketBuffer.toString();
o.multiPacketBuffer = null;
return {
'message': str
};
} | [
"function",
"processMultiBytePacketStop",
"(",
"o",
")",
"{",
"processMultiBytePacket",
"(",
"o",
")",
";",
"const",
"str",
"=",
"o",
".",
"multiPacketBuffer",
".",
"toString",
"(",
")",
";",
"o",
".",
"multiPacketBuffer",
"=",
"null",
";",
"return",
"{",
"'message'",
":",
"str",
"}",
";",
"}"
] | Adds the `data` buffer to the multi packet buffer and emits the buffer as 'message'
@param o {RawDataToSample} - Used to hold data and configuration settings
@private | [
"Adds",
"the",
"data",
"buffer",
"to",
"the",
"multi",
"packet",
"buffer",
"and",
"emits",
"the",
"buffer",
"as",
"message"
] | 37886da7a07ea523b13a46448f56e1e1528748b7 | https://github.com/OpenBCI/OpenBCI_JavaScript_Utilities/blob/37886da7a07ea523b13a46448f56e1e1528748b7/src/utilities.js#L876-L883 | train |
OpenBCI/OpenBCI_JavaScript_Utilities | src/utilities.js | decompressSamples | function decompressSamples (o, receivedDeltas) {
// add the delta to the previous value
for (let i = 1; i < 3; i++) {
for (let j = 0; j < 4; j++) {
o.decompressedSamples[i][j] = o.decompressedSamples[i - 1][j] - receivedDeltas[i - 1][j];
}
}
} | javascript | function decompressSamples (o, receivedDeltas) {
// add the delta to the previous value
for (let i = 1; i < 3; i++) {
for (let j = 0; j < 4; j++) {
o.decompressedSamples[i][j] = o.decompressedSamples[i - 1][j] - receivedDeltas[i - 1][j];
}
}
} | [
"function",
"decompressSamples",
"(",
"o",
",",
"receivedDeltas",
")",
"{",
"for",
"(",
"let",
"i",
"=",
"1",
";",
"i",
"<",
"3",
";",
"i",
"++",
")",
"{",
"for",
"(",
"let",
"j",
"=",
"0",
";",
"j",
"<",
"4",
";",
"j",
"++",
")",
"{",
"o",
".",
"decompressedSamples",
"[",
"i",
"]",
"[",
"j",
"]",
"=",
"o",
".",
"decompressedSamples",
"[",
"i",
"-",
"1",
"]",
"[",
"j",
"]",
"-",
"receivedDeltas",
"[",
"i",
"-",
"1",
"]",
"[",
"j",
"]",
";",
"}",
"}",
"}"
] | Utilize `receivedDeltas` to get actual count values.
@param receivedDeltas {Array} - An array of deltas
of shape 2x4 (2 samples per packet and 4 channels per sample.)
@private | [
"Utilize",
"receivedDeltas",
"to",
"get",
"actual",
"count",
"values",
"."
] | 37886da7a07ea523b13a46448f56e1e1528748b7 | https://github.com/OpenBCI/OpenBCI_JavaScript_Utilities/blob/37886da7a07ea523b13a46448f56e1e1528748b7/src/utilities.js#L891-L898 | train |
OpenBCI/OpenBCI_JavaScript_Utilities | src/utilities.js | buildSample | function buildSample (sampleNumber, rawData, sendCounts) {
let sample;
if (sendCounts) {
sample = newSampleNoScale(sampleNumber);
sample.channelDataCounts = rawData;
} else {
sample = newSample(sampleNumber);
for (let j = 0; j < k.OBCINumberOfChannelsGanglion; j++) {
sample.channelData.push(rawData[j] * k.OBCIGanglionScaleFactorPerCountVolts);
}
}
sample.timestamp = Date.now();
return sample;
} | javascript | function buildSample (sampleNumber, rawData, sendCounts) {
let sample;
if (sendCounts) {
sample = newSampleNoScale(sampleNumber);
sample.channelDataCounts = rawData;
} else {
sample = newSample(sampleNumber);
for (let j = 0; j < k.OBCINumberOfChannelsGanglion; j++) {
sample.channelData.push(rawData[j] * k.OBCIGanglionScaleFactorPerCountVolts);
}
}
sample.timestamp = Date.now();
return sample;
} | [
"function",
"buildSample",
"(",
"sampleNumber",
",",
"rawData",
",",
"sendCounts",
")",
"{",
"let",
"sample",
";",
"if",
"(",
"sendCounts",
")",
"{",
"sample",
"=",
"newSampleNoScale",
"(",
"sampleNumber",
")",
";",
"sample",
".",
"channelDataCounts",
"=",
"rawData",
";",
"}",
"else",
"{",
"sample",
"=",
"newSample",
"(",
"sampleNumber",
")",
";",
"for",
"(",
"let",
"j",
"=",
"0",
";",
"j",
"<",
"k",
".",
"OBCINumberOfChannelsGanglion",
";",
"j",
"++",
")",
"{",
"sample",
".",
"channelData",
".",
"push",
"(",
"rawData",
"[",
"j",
"]",
"*",
"k",
".",
"OBCIGanglionScaleFactorPerCountVolts",
")",
";",
"}",
"}",
"sample",
".",
"timestamp",
"=",
"Date",
".",
"now",
"(",
")",
";",
"return",
"sample",
";",
"}"
] | Builds a sample object from an array and sample number.
@param o {RawDataToSample} - Used to hold data and configuration settings
@return {Array}
@private | [
"Builds",
"a",
"sample",
"object",
"from",
"an",
"array",
"and",
"sample",
"number",
"."
] | 37886da7a07ea523b13a46448f56e1e1528748b7 | https://github.com/OpenBCI/OpenBCI_JavaScript_Utilities/blob/37886da7a07ea523b13a46448f56e1e1528748b7/src/utilities.js#L906-L919 | train |
OpenBCI/OpenBCI_JavaScript_Utilities | src/utilities.js | processRouteSampleData | function processRouteSampleData (o) {
if (parseInt(o.rawDataPacket[0]) === k.OBCIGanglionByteIdUncompressed) {
return processUncompressedData(o);
} else {
return processCompressedData(o);
}
} | javascript | function processRouteSampleData (o) {
if (parseInt(o.rawDataPacket[0]) === k.OBCIGanglionByteIdUncompressed) {
return processUncompressedData(o);
} else {
return processCompressedData(o);
}
} | [
"function",
"processRouteSampleData",
"(",
"o",
")",
"{",
"if",
"(",
"parseInt",
"(",
"o",
".",
"rawDataPacket",
"[",
"0",
"]",
")",
"===",
"k",
".",
"OBCIGanglionByteIdUncompressed",
")",
"{",
"return",
"processUncompressedData",
"(",
"o",
")",
";",
"}",
"else",
"{",
"return",
"processCompressedData",
"(",
"o",
")",
";",
"}",
"}"
] | Used to route samples for Ganglion
@param o {RawDataToSample} - Used to hold data and configuration settings
@returns {*} | [
"Used",
"to",
"route",
"samples",
"for",
"Ganglion"
] | 37886da7a07ea523b13a46448f56e1e1528748b7 | https://github.com/OpenBCI/OpenBCI_JavaScript_Utilities/blob/37886da7a07ea523b13a46448f56e1e1528748b7/src/utilities.js#L926-L932 | train |
OpenBCI/OpenBCI_JavaScript_Utilities | src/utilities.js | processUncompressedData | function processUncompressedData (o) {
// Resets the packet counter back to zero
o.lastSampleNumber = k.OBCIGanglionByteIdUncompressed; // used to find dropped packets
for (let i = 0; i < 4; i++) {
o.decompressedSamples[0][i] = utilitiesModule.interpret24bitAsInt32(o.rawDataPacket.slice(1 + (i * 3), 1 + (i * 3) + 3)); // seed the decompressor
}
return [buildSample(0, o.decompressedSamples[0], o.sendCounts)];
} | javascript | function processUncompressedData (o) {
// Resets the packet counter back to zero
o.lastSampleNumber = k.OBCIGanglionByteIdUncompressed; // used to find dropped packets
for (let i = 0; i < 4; i++) {
o.decompressedSamples[0][i] = utilitiesModule.interpret24bitAsInt32(o.rawDataPacket.slice(1 + (i * 3), 1 + (i * 3) + 3)); // seed the decompressor
}
return [buildSample(0, o.decompressedSamples[0], o.sendCounts)];
} | [
"function",
"processUncompressedData",
"(",
"o",
")",
"{",
"o",
".",
"lastSampleNumber",
"=",
"k",
".",
"OBCIGanglionByteIdUncompressed",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"4",
";",
"i",
"++",
")",
"{",
"o",
".",
"decompressedSamples",
"[",
"0",
"]",
"[",
"i",
"]",
"=",
"utilitiesModule",
".",
"interpret24bitAsInt32",
"(",
"o",
".",
"rawDataPacket",
".",
"slice",
"(",
"1",
"+",
"(",
"i",
"*",
"3",
")",
",",
"1",
"+",
"(",
"i",
"*",
"3",
")",
"+",
"3",
")",
")",
";",
"}",
"return",
"[",
"buildSample",
"(",
"0",
",",
"o",
".",
"decompressedSamples",
"[",
"0",
"]",
",",
"o",
".",
"sendCounts",
")",
"]",
";",
"}"
] | Process an uncompressed packet of data.
@param o {RawDataToSample} - Used to hold data and configuration settings
@private | [
"Process",
"an",
"uncompressed",
"packet",
"of",
"data",
"."
] | 37886da7a07ea523b13a46448f56e1e1528748b7 | https://github.com/OpenBCI/OpenBCI_JavaScript_Utilities/blob/37886da7a07ea523b13a46448f56e1e1528748b7/src/utilities.js#L939-L948 | train |
OpenBCI/OpenBCI_JavaScript_Utilities | src/utilities.js | convertGanglionArrayToBuffer | function convertGanglionArrayToBuffer (arr, data) {
for (let i = 0; i < k.OBCINumberOfChannelsGanglion; i++) {
data.writeInt16BE(arr[i] >> 8, (i * 3));
data.writeInt8(arr[i] & 255, (i * 3) + 2);
}
} | javascript | function convertGanglionArrayToBuffer (arr, data) {
for (let i = 0; i < k.OBCINumberOfChannelsGanglion; i++) {
data.writeInt16BE(arr[i] >> 8, (i * 3));
data.writeInt8(arr[i] & 255, (i * 3) + 2);
}
} | [
"function",
"convertGanglionArrayToBuffer",
"(",
"arr",
",",
"data",
")",
"{",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"k",
".",
"OBCINumberOfChannelsGanglion",
";",
"i",
"++",
")",
"{",
"data",
".",
"writeInt16BE",
"(",
"arr",
"[",
"i",
"]",
">>",
"8",
",",
"(",
"i",
"*",
"3",
")",
")",
";",
"data",
".",
"writeInt8",
"(",
"arr",
"[",
"i",
"]",
"&",
"255",
",",
"(",
"i",
"*",
"3",
")",
"+",
"2",
")",
";",
"}",
"}"
] | Used to convert a ganglions decompressed back into a buffer
@param arr {Array} - An array of four numbers
@param data {Buffer} - A buffer to store into | [
"Used",
"to",
"convert",
"a",
"ganglions",
"decompressed",
"back",
"into",
"a",
"buffer"
] | 37886da7a07ea523b13a46448f56e1e1528748b7 | https://github.com/OpenBCI/OpenBCI_JavaScript_Utilities/blob/37886da7a07ea523b13a46448f56e1e1528748b7/src/utilities.js#L1279-L1284 | train |
OpenBCI/OpenBCI_JavaScript_Utilities | src/utilities.js | getBooleanFromRegisterQuery | function getBooleanFromRegisterQuery (str, regEx, offset) {
let regExArr = str.match(regEx);
if (regExArr) {
const num = parseInt(str.charAt(regExArr.index + offset));
if (!Number.isNaN(num)) {
return Boolean(num);
} else {
throw new Error(k.OBCIErrorInvalidData);
}
} else {
throw new Error(k.OBCIErrorMissingRegisterSetting);
}
} | javascript | function getBooleanFromRegisterQuery (str, regEx, offset) {
let regExArr = str.match(regEx);
if (regExArr) {
const num = parseInt(str.charAt(regExArr.index + offset));
if (!Number.isNaN(num)) {
return Boolean(num);
} else {
throw new Error(k.OBCIErrorInvalidData);
}
} else {
throw new Error(k.OBCIErrorMissingRegisterSetting);
}
} | [
"function",
"getBooleanFromRegisterQuery",
"(",
"str",
",",
"regEx",
",",
"offset",
")",
"{",
"let",
"regExArr",
"=",
"str",
".",
"match",
"(",
"regEx",
")",
";",
"if",
"(",
"regExArr",
")",
"{",
"const",
"num",
"=",
"parseInt",
"(",
"str",
".",
"charAt",
"(",
"regExArr",
".",
"index",
"+",
"offset",
")",
")",
";",
"if",
"(",
"!",
"Number",
".",
"isNaN",
"(",
"num",
")",
")",
"{",
"return",
"Boolean",
"(",
"num",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"k",
".",
"OBCIErrorInvalidData",
")",
";",
"}",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"k",
".",
"OBCIErrorMissingRegisterSetting",
")",
";",
"}",
"}"
] | Use reg ex to parse a `str` register query for a boolean `offset` from index. Throws errors
@param str {String} - The string to search
@param regEx {RegExp} - The key to match to
@param offset {Number} - The number of bytes to offset from the index of the reg ex hit
@returns {boolean} The converted and parsed value from `str` | [
"Use",
"reg",
"ex",
"to",
"parse",
"a",
"str",
"register",
"query",
"for",
"a",
"boolean",
"offset",
"from",
"index",
".",
"Throws",
"errors"
] | 37886da7a07ea523b13a46448f56e1e1528748b7 | https://github.com/OpenBCI/OpenBCI_JavaScript_Utilities/blob/37886da7a07ea523b13a46448f56e1e1528748b7/src/utilities.js#L1545-L1557 | train |
OpenBCI/OpenBCI_JavaScript_Utilities | src/utilities.js | getNumFromThreeCSVADSRegisterQuery | function getNumFromThreeCSVADSRegisterQuery (str, regEx, offset) {
let regExArr = str.match(regEx);
if (regExArr) {
const bit2 = parseInt(str.charAt(regExArr.index + offset));
const bit1 = parseInt(str.charAt(regExArr.index + offset + 3));
const bit0 = parseInt(str.charAt(regExArr.index + offset + 6));
if (!Number.isNaN(bit2) && !Number.isNaN(bit1) && !Number.isNaN(bit0)) {
return bit2 << 2 | bit1 << 1 | bit0;
} else {
throw new Error(k.OBCIErrorInvalidData);
}
} else {
throw new Error(k.OBCIErrorMissingRegisterSetting);
}
} | javascript | function getNumFromThreeCSVADSRegisterQuery (str, regEx, offset) {
let regExArr = str.match(regEx);
if (regExArr) {
const bit2 = parseInt(str.charAt(regExArr.index + offset));
const bit1 = parseInt(str.charAt(regExArr.index + offset + 3));
const bit0 = parseInt(str.charAt(regExArr.index + offset + 6));
if (!Number.isNaN(bit2) && !Number.isNaN(bit1) && !Number.isNaN(bit0)) {
return bit2 << 2 | bit1 << 1 | bit0;
} else {
throw new Error(k.OBCIErrorInvalidData);
}
} else {
throw new Error(k.OBCIErrorMissingRegisterSetting);
}
} | [
"function",
"getNumFromThreeCSVADSRegisterQuery",
"(",
"str",
",",
"regEx",
",",
"offset",
")",
"{",
"let",
"regExArr",
"=",
"str",
".",
"match",
"(",
"regEx",
")",
";",
"if",
"(",
"regExArr",
")",
"{",
"const",
"bit2",
"=",
"parseInt",
"(",
"str",
".",
"charAt",
"(",
"regExArr",
".",
"index",
"+",
"offset",
")",
")",
";",
"const",
"bit1",
"=",
"parseInt",
"(",
"str",
".",
"charAt",
"(",
"regExArr",
".",
"index",
"+",
"offset",
"+",
"3",
")",
")",
";",
"const",
"bit0",
"=",
"parseInt",
"(",
"str",
".",
"charAt",
"(",
"regExArr",
".",
"index",
"+",
"offset",
"+",
"6",
")",
")",
";",
"if",
"(",
"!",
"Number",
".",
"isNaN",
"(",
"bit2",
")",
"&&",
"!",
"Number",
".",
"isNaN",
"(",
"bit1",
")",
"&&",
"!",
"Number",
".",
"isNaN",
"(",
"bit0",
")",
")",
"{",
"return",
"bit2",
"<<",
"2",
"|",
"bit1",
"<<",
"1",
"|",
"bit0",
";",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"k",
".",
"OBCIErrorInvalidData",
")",
";",
"}",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"k",
".",
"OBCIErrorMissingRegisterSetting",
")",
";",
"}",
"}"
] | Used to get a number from the raw query data
@param str {String} - The raw query data
@param regEx {RegExp} - The regular expression to index off of
@param offset {Number} - The number of bytes offset from index to start | [
"Used",
"to",
"get",
"a",
"number",
"from",
"the",
"raw",
"query",
"data"
] | 37886da7a07ea523b13a46448f56e1e1528748b7 | https://github.com/OpenBCI/OpenBCI_JavaScript_Utilities/blob/37886da7a07ea523b13a46448f56e1e1528748b7/src/utilities.js#L1584-L1598 | train |
OpenBCI/OpenBCI_JavaScript_Utilities | src/utilities.js | setChSetFromADSRegisterQuery | function setChSetFromADSRegisterQuery (str, channelSettings) {
let key = k.OBCIRegisterQueryNameCHnSET[channelSettings.channelNumber];
if (key === undefined) key = k.OBCIRegisterQueryNameCHnSET[channelSettings.channelNumber - k.OBCINumberOfChannelsCyton];
channelSettings.powerDown = getBooleanFromRegisterQuery(str, key, 16);
channelSettings.gain = k.gainForCommand(getNumFromThreeCSVADSRegisterQuery(str, key, 19));
channelSettings.inputType = k.inputTypeForCommand(getNumFromThreeCSVADSRegisterQuery(str, key, 31));
channelSettings.srb2 = getBooleanFromRegisterQuery(str, key, 28);
} | javascript | function setChSetFromADSRegisterQuery (str, channelSettings) {
let key = k.OBCIRegisterQueryNameCHnSET[channelSettings.channelNumber];
if (key === undefined) key = k.OBCIRegisterQueryNameCHnSET[channelSettings.channelNumber - k.OBCINumberOfChannelsCyton];
channelSettings.powerDown = getBooleanFromRegisterQuery(str, key, 16);
channelSettings.gain = k.gainForCommand(getNumFromThreeCSVADSRegisterQuery(str, key, 19));
channelSettings.inputType = k.inputTypeForCommand(getNumFromThreeCSVADSRegisterQuery(str, key, 31));
channelSettings.srb2 = getBooleanFromRegisterQuery(str, key, 28);
} | [
"function",
"setChSetFromADSRegisterQuery",
"(",
"str",
",",
"channelSettings",
")",
"{",
"let",
"key",
"=",
"k",
".",
"OBCIRegisterQueryNameCHnSET",
"[",
"channelSettings",
".",
"channelNumber",
"]",
";",
"if",
"(",
"key",
"===",
"undefined",
")",
"key",
"=",
"k",
".",
"OBCIRegisterQueryNameCHnSET",
"[",
"channelSettings",
".",
"channelNumber",
"-",
"k",
".",
"OBCINumberOfChannelsCyton",
"]",
";",
"channelSettings",
".",
"powerDown",
"=",
"getBooleanFromRegisterQuery",
"(",
"str",
",",
"key",
",",
"16",
")",
";",
"channelSettings",
".",
"gain",
"=",
"k",
".",
"gainForCommand",
"(",
"getNumFromThreeCSVADSRegisterQuery",
"(",
"str",
",",
"key",
",",
"19",
")",
")",
";",
"channelSettings",
".",
"inputType",
"=",
"k",
".",
"inputTypeForCommand",
"(",
"getNumFromThreeCSVADSRegisterQuery",
"(",
"str",
",",
"key",
",",
"31",
")",
")",
";",
"channelSettings",
".",
"srb2",
"=",
"getBooleanFromRegisterQuery",
"(",
"str",
",",
"key",
",",
"28",
")",
";",
"}"
] | Used to get bias setting from raw query
@param str {String} - The raw query data
@param channelSettings {ChannelSettingsObject} - Just your standard channel setting object
@returns {boolean} | [
"Used",
"to",
"get",
"bias",
"setting",
"from",
"raw",
"query"
] | 37886da7a07ea523b13a46448f56e1e1528748b7 | https://github.com/OpenBCI/OpenBCI_JavaScript_Utilities/blob/37886da7a07ea523b13a46448f56e1e1528748b7/src/utilities.js#L1606-L1613 | train |
OpenBCI/OpenBCI_JavaScript_Utilities | src/utilities.js | getFirmware | function getFirmware (dataBuffer) {
const regexPattern = /v\d.\d*.\d*/;
const ret = dataBuffer.toString().match(regexPattern);
if (ret) {
const elems = ret[0].split('.');
return {
major: Number(elems[0][1]),
minor: Number(elems[1]),
patch: Number(elems[2]),
raw: ret[0]
};
} else return ret;
} | javascript | function getFirmware (dataBuffer) {
const regexPattern = /v\d.\d*.\d*/;
const ret = dataBuffer.toString().match(regexPattern);
if (ret) {
const elems = ret[0].split('.');
return {
major: Number(elems[0][1]),
minor: Number(elems[1]),
patch: Number(elems[2]),
raw: ret[0]
};
} else return ret;
} | [
"function",
"getFirmware",
"(",
"dataBuffer",
")",
"{",
"const",
"regexPattern",
"=",
"/",
"v\\d.\\d*.\\d*",
"/",
";",
"const",
"ret",
"=",
"dataBuffer",
".",
"toString",
"(",
")",
".",
"match",
"(",
"regexPattern",
")",
";",
"if",
"(",
"ret",
")",
"{",
"const",
"elems",
"=",
"ret",
"[",
"0",
"]",
".",
"split",
"(",
"'.'",
")",
";",
"return",
"{",
"major",
":",
"Number",
"(",
"elems",
"[",
"0",
"]",
"[",
"1",
"]",
")",
",",
"minor",
":",
"Number",
"(",
"elems",
"[",
"1",
"]",
")",
",",
"patch",
":",
"Number",
"(",
"elems",
"[",
"2",
"]",
")",
",",
"raw",
":",
"ret",
"[",
"0",
"]",
"}",
";",
"}",
"else",
"return",
"ret",
";",
"}"
] | Used to extract the major version from
@param dataBuffer
@return {*} | [
"Used",
"to",
"extract",
"the",
"major",
"version",
"from"
] | 37886da7a07ea523b13a46448f56e1e1528748b7 | https://github.com/OpenBCI/OpenBCI_JavaScript_Utilities/blob/37886da7a07ea523b13a46448f56e1e1528748b7/src/utilities.js#L2166-L2178 | train |
welldone-software/gulp-durandal | examples/HTML StarterKit/lib/durandal/js/system.js | function(obj) {
if (!obj) {
return null;
}
if (typeof obj == 'function') {
return obj.prototype.__moduleId__;
}
if (typeof obj == 'string') {
return null;
}
return obj.__moduleId__;
} | javascript | function(obj) {
if (!obj) {
return null;
}
if (typeof obj == 'function') {
return obj.prototype.__moduleId__;
}
if (typeof obj == 'string') {
return null;
}
return obj.__moduleId__;
} | [
"function",
"(",
"obj",
")",
"{",
"if",
"(",
"!",
"obj",
")",
"{",
"return",
"null",
";",
"}",
"if",
"(",
"typeof",
"obj",
"==",
"'function'",
")",
"{",
"return",
"obj",
".",
"prototype",
".",
"__moduleId__",
";",
"}",
"if",
"(",
"typeof",
"obj",
"==",
"'string'",
")",
"{",
"return",
"null",
";",
"}",
"return",
"obj",
".",
"__moduleId__",
";",
"}"
] | Gets the module id for the specified object.
@method getModuleId
@param {object} obj The object whose module id you wish to determine.
@return {string} The module id. | [
"Gets",
"the",
"module",
"id",
"for",
"the",
"specified",
"object",
"."
] | 4eacd22fcc567a372e04e6de443b0228572d6400 | https://github.com/welldone-software/gulp-durandal/blob/4eacd22fcc567a372e04e6de443b0228572d6400/examples/HTML StarterKit/lib/durandal/js/system.js#L116-L130 | train |
|
welldone-software/gulp-durandal | examples/HTML StarterKit/lib/durandal/js/system.js | function(obj, id) {
if (!obj) {
return;
}
if (typeof obj == 'function') {
obj.prototype.__moduleId__ = id;
return;
}
if (typeof obj == 'string') {
return;
}
obj.__moduleId__ = id;
} | javascript | function(obj, id) {
if (!obj) {
return;
}
if (typeof obj == 'function') {
obj.prototype.__moduleId__ = id;
return;
}
if (typeof obj == 'string') {
return;
}
obj.__moduleId__ = id;
} | [
"function",
"(",
"obj",
",",
"id",
")",
"{",
"if",
"(",
"!",
"obj",
")",
"{",
"return",
";",
"}",
"if",
"(",
"typeof",
"obj",
"==",
"'function'",
")",
"{",
"obj",
".",
"prototype",
".",
"__moduleId__",
"=",
"id",
";",
"return",
";",
"}",
"if",
"(",
"typeof",
"obj",
"==",
"'string'",
")",
"{",
"return",
";",
"}",
"obj",
".",
"__moduleId__",
"=",
"id",
";",
"}"
] | Sets the module id for the specified object.
@method setModuleId
@param {object} obj The object whose module id you wish to set.
@param {string} id The id to set for the specified object. | [
"Sets",
"the",
"module",
"id",
"for",
"the",
"specified",
"object",
"."
] | 4eacd22fcc567a372e04e6de443b0228572d6400 | https://github.com/welldone-software/gulp-durandal/blob/4eacd22fcc567a372e04e6de443b0228572d6400/examples/HTML StarterKit/lib/durandal/js/system.js#L137-L152 | train |
|
welldone-software/gulp-durandal | examples/HTML StarterKit/lib/durandal/js/system.js | function() {
var modules,
first = arguments[0],
arrayRequest = false;
if(system.isArray(first)){
modules = first;
arrayRequest = true;
}else{
modules = slice.call(arguments, 0);
}
return this.defer(function(dfd) {
require(modules, function() {
var args = arguments;
setTimeout(function() {
if(args.length > 1 || arrayRequest){
dfd.resolve(slice.call(args, 0));
}else{
dfd.resolve(args[0]);
}
}, 1);
}, function(err){
dfd.reject(err);
});
}).promise();
} | javascript | function() {
var modules,
first = arguments[0],
arrayRequest = false;
if(system.isArray(first)){
modules = first;
arrayRequest = true;
}else{
modules = slice.call(arguments, 0);
}
return this.defer(function(dfd) {
require(modules, function() {
var args = arguments;
setTimeout(function() {
if(args.length > 1 || arrayRequest){
dfd.resolve(slice.call(args, 0));
}else{
dfd.resolve(args[0]);
}
}, 1);
}, function(err){
dfd.reject(err);
});
}).promise();
} | [
"function",
"(",
")",
"{",
"var",
"modules",
",",
"first",
"=",
"arguments",
"[",
"0",
"]",
",",
"arrayRequest",
"=",
"false",
";",
"if",
"(",
"system",
".",
"isArray",
"(",
"first",
")",
")",
"{",
"modules",
"=",
"first",
";",
"arrayRequest",
"=",
"true",
";",
"}",
"else",
"{",
"modules",
"=",
"slice",
".",
"call",
"(",
"arguments",
",",
"0",
")",
";",
"}",
"return",
"this",
".",
"defer",
"(",
"function",
"(",
"dfd",
")",
"{",
"require",
"(",
"modules",
",",
"function",
"(",
")",
"{",
"var",
"args",
"=",
"arguments",
";",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"if",
"(",
"args",
".",
"length",
">",
"1",
"||",
"arrayRequest",
")",
"{",
"dfd",
".",
"resolve",
"(",
"slice",
".",
"call",
"(",
"args",
",",
"0",
")",
")",
";",
"}",
"else",
"{",
"dfd",
".",
"resolve",
"(",
"args",
"[",
"0",
"]",
")",
";",
"}",
"}",
",",
"1",
")",
";",
"}",
",",
"function",
"(",
"err",
")",
"{",
"dfd",
".",
"reject",
"(",
"err",
")",
";",
"}",
")",
";",
"}",
")",
".",
"promise",
"(",
")",
";",
"}"
] | Uses require.js to obtain a module. This function returns a promise which resolves with the module instance. You can pass more than one module id to this function or an array of ids. If more than one or an array is passed, then the promise will resolve with an array of module instances.
@method acquire
@param {string|string[]} moduleId The id(s) of the modules to load.
@return {Promise} A promise for the loaded module(s). | [
"Uses",
"require",
".",
"js",
"to",
"obtain",
"a",
"module",
".",
"This",
"function",
"returns",
"a",
"promise",
"which",
"resolves",
"with",
"the",
"module",
"instance",
".",
"You",
"can",
"pass",
"more",
"than",
"one",
"module",
"id",
"to",
"this",
"function",
"or",
"an",
"array",
"of",
"ids",
".",
"If",
"more",
"than",
"one",
"or",
"an",
"array",
"is",
"passed",
"then",
"the",
"promise",
"will",
"resolve",
"with",
"an",
"array",
"of",
"module",
"instances",
"."
] | 4eacd22fcc567a372e04e6de443b0228572d6400 | https://github.com/welldone-software/gulp-durandal/blob/4eacd22fcc567a372e04e6de443b0228572d6400/examples/HTML StarterKit/lib/durandal/js/system.js#L237-L263 | train |
|
welldone-software/gulp-durandal | examples/HTML StarterKit/lib/durandal/js/system.js | function(obj) {
var rest = slice.call(arguments, 1);
for (var i = 0; i < rest.length; i++) {
var source = rest[i];
if (source) {
for (var prop in source) {
obj[prop] = source[prop];
}
}
}
return obj;
} | javascript | function(obj) {
var rest = slice.call(arguments, 1);
for (var i = 0; i < rest.length; i++) {
var source = rest[i];
if (source) {
for (var prop in source) {
obj[prop] = source[prop];
}
}
}
return obj;
} | [
"function",
"(",
"obj",
")",
"{",
"var",
"rest",
"=",
"slice",
".",
"call",
"(",
"arguments",
",",
"1",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"rest",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"source",
"=",
"rest",
"[",
"i",
"]",
";",
"if",
"(",
"source",
")",
"{",
"for",
"(",
"var",
"prop",
"in",
"source",
")",
"{",
"obj",
"[",
"prop",
"]",
"=",
"source",
"[",
"prop",
"]",
";",
"}",
"}",
"}",
"return",
"obj",
";",
"}"
] | Extends the first object with the properties of the following objects.
@method extend
@param {object} obj The target object to extend.
@param {object} extension* Uses to extend the target object. | [
"Extends",
"the",
"first",
"object",
"with",
"the",
"properties",
"of",
"the",
"following",
"objects",
"."
] | 4eacd22fcc567a372e04e6de443b0228572d6400 | https://github.com/welldone-software/gulp-durandal/blob/4eacd22fcc567a372e04e6de443b0228572d6400/examples/HTML StarterKit/lib/durandal/js/system.js#L270-L284 | train |
|
raisch/chai-joi | index.js | validation | function validation() {
const target = this._obj;
this.assert(_.isObject(target), '#{this} is not a Joi validation because it must be an object');
this.assert(!_.isEmpty(target), '#{this} is not a Joi validation because it is an empty object');
const fields = _.keys(target);
const allFieldsPresent = _.every(FIELDS_TO_VALIDATE.map(field => _.includes(fields, field)));
this.assert(
allFieldsPresent,
`${this} is not a validation because it does not contain expected keys`
);
} | javascript | function validation() {
const target = this._obj;
this.assert(_.isObject(target), '#{this} is not a Joi validation because it must be an object');
this.assert(!_.isEmpty(target), '#{this} is not a Joi validation because it is an empty object');
const fields = _.keys(target);
const allFieldsPresent = _.every(FIELDS_TO_VALIDATE.map(field => _.includes(fields, field)));
this.assert(
allFieldsPresent,
`${this} is not a validation because it does not contain expected keys`
);
} | [
"function",
"validation",
"(",
")",
"{",
"const",
"target",
"=",
"this",
".",
"_obj",
";",
"this",
".",
"assert",
"(",
"_",
".",
"isObject",
"(",
"target",
")",
",",
"'#{this} is not a Joi validation because it must be an object'",
")",
";",
"this",
".",
"assert",
"(",
"!",
"_",
".",
"isEmpty",
"(",
"target",
")",
",",
"'#{this} is not a Joi validation because it is an empty object'",
")",
";",
"const",
"fields",
"=",
"_",
".",
"keys",
"(",
"target",
")",
";",
"const",
"allFieldsPresent",
"=",
"_",
".",
"every",
"(",
"FIELDS_TO_VALIDATE",
".",
"map",
"(",
"field",
"=>",
"_",
".",
"includes",
"(",
"fields",
",",
"field",
")",
")",
")",
";",
"this",
".",
"assert",
"(",
"allFieldsPresent",
",",
"`",
"${",
"this",
"}",
"`",
")",
";",
"}"
] | Assert that target is a Joi validation
@example
expect(target).to.[not].be.a.validation
target.should.[not].be.a.validation | [
"Assert",
"that",
"target",
"is",
"a",
"Joi",
"validation"
] | feba7ab5e75d53a84d4552397c02351d801f8612 | https://github.com/raisch/chai-joi/blob/feba7ab5e75d53a84d4552397c02351d801f8612/index.js#L77-L88 | train |
raisch/chai-joi | index.js | validate | function validate() {
const target = this._obj;
isValidation(target);
this.assert(_.has(target, 'error') && null === target.error,
'#{this} should validate but does not because '+getErrorMessages(target),
'#{this} should not validate but it does'
);
} | javascript | function validate() {
const target = this._obj;
isValidation(target);
this.assert(_.has(target, 'error') && null === target.error,
'#{this} should validate but does not because '+getErrorMessages(target),
'#{this} should not validate but it does'
);
} | [
"function",
"validate",
"(",
")",
"{",
"const",
"target",
"=",
"this",
".",
"_obj",
";",
"isValidation",
"(",
"target",
")",
";",
"this",
".",
"assert",
"(",
"_",
".",
"has",
"(",
"target",
",",
"'error'",
")",
"&&",
"null",
"===",
"target",
".",
"error",
",",
"'#{this} should validate but does not because '",
"+",
"getErrorMessages",
"(",
"target",
")",
",",
"'#{this} should not validate but it does'",
")",
";",
"}"
] | Assert that target validates correctly
@example
expect(target).should.[not].validate
target.should.[not].validate | [
"Assert",
"that",
"target",
"validates",
"correctly"
] | feba7ab5e75d53a84d4552397c02351d801f8612 | https://github.com/raisch/chai-joi/blob/feba7ab5e75d53a84d4552397c02351d801f8612/index.js#L96-L104 | train |
raisch/chai-joi | index.js | value | function value(utils) {
const target = this._obj,
value = target.value || null;
isValidation(target);
this.assert(null !== value,
'#{this} should have value',
'#{this} should not have value'
);
utils.flag(this, 'object', value);
} | javascript | function value(utils) {
const target = this._obj,
value = target.value || null;
isValidation(target);
this.assert(null !== value,
'#{this} should have value',
'#{this} should not have value'
);
utils.flag(this, 'object', value);
} | [
"function",
"value",
"(",
"utils",
")",
"{",
"const",
"target",
"=",
"this",
".",
"_obj",
",",
"value",
"=",
"target",
".",
"value",
"||",
"null",
";",
"isValidation",
"(",
"target",
")",
";",
"this",
".",
"assert",
"(",
"null",
"!==",
"value",
",",
"'#{this} should have value'",
",",
"'#{this} should not have value'",
")",
";",
"utils",
".",
"flag",
"(",
"this",
",",
"'object'",
",",
"value",
")",
";",
"}"
] | Assert that target contains a value.
Mutates current chainable object to be target.value.
@example
expect(target).to.[not].have.a.value
target.should.[not].have.a.value | [
"Assert",
"that",
"target",
"contains",
"a",
"value",
".",
"Mutates",
"current",
"chainable",
"object",
"to",
"be",
"target",
".",
"value",
"."
] | feba7ab5e75d53a84d4552397c02351d801f8612 | https://github.com/raisch/chai-joi/blob/feba7ab5e75d53a84d4552397c02351d801f8612/index.js#L132-L141 | train |
welldone-software/gulp-durandal | examples/HTML StarterKit/lib/durandal/js/app.js | function(config, baseUrl){
var pluginIds = system.keys(config);
baseUrl = baseUrl || 'plugins/';
if(baseUrl.indexOf('/', baseUrl.length - 1) === -1){
baseUrl += '/';
}
for(var i = 0; i < pluginIds.length; i++){
var key = pluginIds[i];
allPluginIds.push(baseUrl + key);
allPluginConfigs.push(config[key]);
}
} | javascript | function(config, baseUrl){
var pluginIds = system.keys(config);
baseUrl = baseUrl || 'plugins/';
if(baseUrl.indexOf('/', baseUrl.length - 1) === -1){
baseUrl += '/';
}
for(var i = 0; i < pluginIds.length; i++){
var key = pluginIds[i];
allPluginIds.push(baseUrl + key);
allPluginConfigs.push(config[key]);
}
} | [
"function",
"(",
"config",
",",
"baseUrl",
")",
"{",
"var",
"pluginIds",
"=",
"system",
".",
"keys",
"(",
"config",
")",
";",
"baseUrl",
"=",
"baseUrl",
"||",
"'plugins/'",
";",
"if",
"(",
"baseUrl",
".",
"indexOf",
"(",
"'/'",
",",
"baseUrl",
".",
"length",
"-",
"1",
")",
"===",
"-",
"1",
")",
"{",
"baseUrl",
"+=",
"'/'",
";",
"}",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"pluginIds",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"key",
"=",
"pluginIds",
"[",
"i",
"]",
";",
"allPluginIds",
".",
"push",
"(",
"baseUrl",
"+",
"key",
")",
";",
"allPluginConfigs",
".",
"push",
"(",
"config",
"[",
"key",
"]",
")",
";",
"}",
"}"
] | Configures one or more plugins to be loaded and installed into the application.
@method configurePlugins
@param {object} config Keys are plugin names. Values can be truthy, to simply install the plugin, or a configuration object to pass to the plugin.
@param {string} [baseUrl] The base url to load the plugins from. | [
"Configures",
"one",
"or",
"more",
"plugins",
"to",
"be",
"loaded",
"and",
"installed",
"into",
"the",
"application",
"."
] | 4eacd22fcc567a372e04e6de443b0228572d6400 | https://github.com/welldone-software/gulp-durandal/blob/4eacd22fcc567a372e04e6de443b0228572d6400/examples/HTML StarterKit/lib/durandal/js/app.js#L68-L81 | train |
|
welldone-software/gulp-durandal | examples/HTML StarterKit/lib/durandal/js/app.js | function() {
system.log('Application:Starting');
if (this.title) {
document.title = this.title;
}
return system.defer(function (dfd) {
$(function() {
loadPlugins().then(function(){
dfd.resolve();
system.log('Application:Started');
});
});
}).promise();
} | javascript | function() {
system.log('Application:Starting');
if (this.title) {
document.title = this.title;
}
return system.defer(function (dfd) {
$(function() {
loadPlugins().then(function(){
dfd.resolve();
system.log('Application:Started');
});
});
}).promise();
} | [
"function",
"(",
")",
"{",
"system",
".",
"log",
"(",
"'Application:Starting'",
")",
";",
"if",
"(",
"this",
".",
"title",
")",
"{",
"document",
".",
"title",
"=",
"this",
".",
"title",
";",
"}",
"return",
"system",
".",
"defer",
"(",
"function",
"(",
"dfd",
")",
"{",
"$",
"(",
"function",
"(",
")",
"{",
"loadPlugins",
"(",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"dfd",
".",
"resolve",
"(",
")",
";",
"system",
".",
"log",
"(",
"'Application:Started'",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
")",
".",
"promise",
"(",
")",
";",
"}"
] | Starts the application.
@method start
@return {promise} | [
"Starts",
"the",
"application",
"."
] | 4eacd22fcc567a372e04e6de443b0228572d6400 | https://github.com/welldone-software/gulp-durandal/blob/4eacd22fcc567a372e04e6de443b0228572d6400/examples/HTML StarterKit/lib/durandal/js/app.js#L87-L102 | train |
|
IBM/node-ibmapm-restclient | lib/tools/k8sutil.js | K8sutil | function K8sutil() {
// this.getNamespace();
podName = os.hostname();
podGenerateName = podName.substr(0, podName.lastIndexOf('-'));
logger.debug('k8sutil', 'K8sutil()', 'The pod name: ', podName);
fetchContainerID();
try {
// var kubeconfig = Api.config.fromKubeconfig();
var kubeconfig = Api.config.getInCluster();
kubeconfig.promises = true;
// kubeconfig.namespace = 'default';
logger.debug('k8sutil', 'K8sutil()', 'Kubeconfig', kubeconfig);
core = new Api.Core(kubeconfig);
ext = new Api.Extensions(kubeconfig);
namespace = core.namespaces.namespace;
logger.info('k8sutil', 'K8sutil()', 'Current namespace', namespace);
if (!podJson) {
core.ns(namespace).pods(this.getPodName()).get().then(parsePodInfo).catch(
function(err) {
logger.error('k8sutil', 'K8sutil()', err.message);
}
);
}
} catch (e) {
logger.debug('k8sutil', 'K8sutil()',
'Failed to load K8S configuration, is not a ICp environment.');
}
findIngressSvc();
setNodeIPs();
} | javascript | function K8sutil() {
// this.getNamespace();
podName = os.hostname();
podGenerateName = podName.substr(0, podName.lastIndexOf('-'));
logger.debug('k8sutil', 'K8sutil()', 'The pod name: ', podName);
fetchContainerID();
try {
// var kubeconfig = Api.config.fromKubeconfig();
var kubeconfig = Api.config.getInCluster();
kubeconfig.promises = true;
// kubeconfig.namespace = 'default';
logger.debug('k8sutil', 'K8sutil()', 'Kubeconfig', kubeconfig);
core = new Api.Core(kubeconfig);
ext = new Api.Extensions(kubeconfig);
namespace = core.namespaces.namespace;
logger.info('k8sutil', 'K8sutil()', 'Current namespace', namespace);
if (!podJson) {
core.ns(namespace).pods(this.getPodName()).get().then(parsePodInfo).catch(
function(err) {
logger.error('k8sutil', 'K8sutil()', err.message);
}
);
}
} catch (e) {
logger.debug('k8sutil', 'K8sutil()',
'Failed to load K8S configuration, is not a ICp environment.');
}
findIngressSvc();
setNodeIPs();
} | [
"function",
"K8sutil",
"(",
")",
"{",
"podName",
"=",
"os",
".",
"hostname",
"(",
")",
";",
"podGenerateName",
"=",
"podName",
".",
"substr",
"(",
"0",
",",
"podName",
".",
"lastIndexOf",
"(",
"'-'",
")",
")",
";",
"logger",
".",
"debug",
"(",
"'k8sutil'",
",",
"'K8sutil()'",
",",
"'The pod name: '",
",",
"podName",
")",
";",
"fetchContainerID",
"(",
")",
";",
"try",
"{",
"var",
"kubeconfig",
"=",
"Api",
".",
"config",
".",
"getInCluster",
"(",
")",
";",
"kubeconfig",
".",
"promises",
"=",
"true",
";",
"logger",
".",
"debug",
"(",
"'k8sutil'",
",",
"'K8sutil()'",
",",
"'Kubeconfig'",
",",
"kubeconfig",
")",
";",
"core",
"=",
"new",
"Api",
".",
"Core",
"(",
"kubeconfig",
")",
";",
"ext",
"=",
"new",
"Api",
".",
"Extensions",
"(",
"kubeconfig",
")",
";",
"namespace",
"=",
"core",
".",
"namespaces",
".",
"namespace",
";",
"logger",
".",
"info",
"(",
"'k8sutil'",
",",
"'K8sutil()'",
",",
"'Current namespace'",
",",
"namespace",
")",
";",
"if",
"(",
"!",
"podJson",
")",
"{",
"core",
".",
"ns",
"(",
"namespace",
")",
".",
"pods",
"(",
"this",
".",
"getPodName",
"(",
")",
")",
".",
"get",
"(",
")",
".",
"then",
"(",
"parsePodInfo",
")",
".",
"catch",
"(",
"function",
"(",
"err",
")",
"{",
"logger",
".",
"error",
"(",
"'k8sutil'",
",",
"'K8sutil()'",
",",
"err",
".",
"message",
")",
";",
"}",
")",
";",
"}",
"}",
"catch",
"(",
"e",
")",
"{",
"logger",
".",
"debug",
"(",
"'k8sutil'",
",",
"'K8sutil()'",
",",
"'Failed to load K8S configuration, is not a ICp environment.'",
")",
";",
"}",
"findIngressSvc",
"(",
")",
";",
"setNodeIPs",
"(",
")",
";",
"}"
] | var NAMESPACE_DEFAULT = 'default'; | [
"var",
"NAMESPACE_DEFAULT",
"=",
"default",
";"
] | a36fd460c8b270ee8dae8c16ce18ed28f2e1c120 | https://github.com/IBM/node-ibmapm-restclient/blob/a36fd460c8b270ee8dae8c16ce18ed28f2e1c120/lib/tools/k8sutil.js#L39-L69 | train |
gridcontrol/gridcontrol | src/network/secure-socket-router.js | Actor | function Actor(stream) {
if (!(this instanceof Actor)) return new Actor(stream);
var that = this;
this.parser = new amp.Stream;
this.parser.on('data', this.onmessage.bind(this));
stream.pipe(this.parser);
this.stream = stream;
this.callbacks = {};
this.ids = 0;
this.id = ++ids;
this.secret_key = null;
Actor.emit('actor', this);
} | javascript | function Actor(stream) {
if (!(this instanceof Actor)) return new Actor(stream);
var that = this;
this.parser = new amp.Stream;
this.parser.on('data', this.onmessage.bind(this));
stream.pipe(this.parser);
this.stream = stream;
this.callbacks = {};
this.ids = 0;
this.id = ++ids;
this.secret_key = null;
Actor.emit('actor', this);
} | [
"function",
"Actor",
"(",
"stream",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"Actor",
")",
")",
"return",
"new",
"Actor",
"(",
"stream",
")",
";",
"var",
"that",
"=",
"this",
";",
"this",
".",
"parser",
"=",
"new",
"amp",
".",
"Stream",
";",
"this",
".",
"parser",
".",
"on",
"(",
"'data'",
",",
"this",
".",
"onmessage",
".",
"bind",
"(",
"this",
")",
")",
";",
"stream",
".",
"pipe",
"(",
"this",
".",
"parser",
")",
";",
"this",
".",
"stream",
"=",
"stream",
";",
"this",
".",
"callbacks",
"=",
"{",
"}",
";",
"this",
".",
"ids",
"=",
"0",
";",
"this",
".",
"id",
"=",
"++",
"ids",
";",
"this",
".",
"secret_key",
"=",
"null",
";",
"Actor",
".",
"emit",
"(",
"'actor'",
",",
"this",
")",
";",
"}"
] | Initialize an actor for the given `Stream`.
@param {Stream} stream
@api public | [
"Initialize",
"an",
"actor",
"for",
"the",
"given",
"Stream",
"."
] | b3f5cc27c5fb24df010133cc34ba101d1561c9e0 | https://github.com/gridcontrol/gridcontrol/blob/b3f5cc27c5fb24df010133cc34ba101d1561c9e0/src/network/secure-socket-router.js#L43-L55 | train |
gridcontrol/gridcontrol | src/network/secure-socket-router.js | reply | function reply(id, args) {
var msg = new Array(2 + args.length);
msg[0] = '_reply_';
msg[1] = id;
for (var i = 0; i < args.length; i++) {
msg[i + 2] = args[i];
}
return msg;
} | javascript | function reply(id, args) {
var msg = new Array(2 + args.length);
msg[0] = '_reply_';
msg[1] = id;
for (var i = 0; i < args.length; i++) {
msg[i + 2] = args[i];
}
return msg;
} | [
"function",
"reply",
"(",
"id",
",",
"args",
")",
"{",
"var",
"msg",
"=",
"new",
"Array",
"(",
"2",
"+",
"args",
".",
"length",
")",
";",
"msg",
"[",
"0",
"]",
"=",
"'_reply_'",
";",
"msg",
"[",
"1",
"]",
"=",
"id",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"args",
".",
"length",
";",
"i",
"++",
")",
"{",
"msg",
"[",
"i",
"+",
"2",
"]",
"=",
"args",
"[",
"i",
"]",
";",
"}",
"return",
"msg",
";",
"}"
] | Return a reply message for `id` and `args`.
@param {String} id
@param {Array} args
@return {Array}
@api private | [
"Return",
"a",
"reply",
"message",
"for",
"id",
"and",
"args",
"."
] | b3f5cc27c5fb24df010133cc34ba101d1561c9e0 | https://github.com/gridcontrol/gridcontrol/blob/b3f5cc27c5fb24df010133cc34ba101d1561c9e0/src/network/secure-socket-router.js#L177-L188 | train |
OpenBCI/OpenBCI_JavaScript_Utilities | src/constants.js | inputTypeForCommand | function inputTypeForCommand (cmd) {
switch (String(cmd)) {
case obciChannelCmdADCNormal:
return obciStringADCNormal;
case obciChannelCmdADCShorted:
return obciStringADCShorted;
case obciChannelCmdADCBiasMethod:
return obciStringADCBiasMethod;
case obciChannelCmdADCMVDD:
return obciStringADCMvdd;
case obciChannelCmdADCTemp:
return obciStringADCTemp;
case obciChannelCmdADCTestSig:
return obciStringADCTestSig;
case obciChannelCmdADCBiasDRP:
return obciStringADCBiasDrp;
case obciChannelCmdADCBiasDRN:
return obciStringADCBiasDrn;
default:
throw new Error('Invalid input type, must be less than 8');
}
} | javascript | function inputTypeForCommand (cmd) {
switch (String(cmd)) {
case obciChannelCmdADCNormal:
return obciStringADCNormal;
case obciChannelCmdADCShorted:
return obciStringADCShorted;
case obciChannelCmdADCBiasMethod:
return obciStringADCBiasMethod;
case obciChannelCmdADCMVDD:
return obciStringADCMvdd;
case obciChannelCmdADCTemp:
return obciStringADCTemp;
case obciChannelCmdADCTestSig:
return obciStringADCTestSig;
case obciChannelCmdADCBiasDRP:
return obciStringADCBiasDrp;
case obciChannelCmdADCBiasDRN:
return obciStringADCBiasDrn;
default:
throw new Error('Invalid input type, must be less than 8');
}
} | [
"function",
"inputTypeForCommand",
"(",
"cmd",
")",
"{",
"switch",
"(",
"String",
"(",
"cmd",
")",
")",
"{",
"case",
"obciChannelCmdADCNormal",
":",
"return",
"obciStringADCNormal",
";",
"case",
"obciChannelCmdADCShorted",
":",
"return",
"obciStringADCShorted",
";",
"case",
"obciChannelCmdADCBiasMethod",
":",
"return",
"obciStringADCBiasMethod",
";",
"case",
"obciChannelCmdADCMVDD",
":",
"return",
"obciStringADCMvdd",
";",
"case",
"obciChannelCmdADCTemp",
":",
"return",
"obciStringADCTemp",
";",
"case",
"obciChannelCmdADCTestSig",
":",
"return",
"obciStringADCTestSig",
";",
"case",
"obciChannelCmdADCBiasDRP",
":",
"return",
"obciStringADCBiasDrp",
";",
"case",
"obciChannelCmdADCBiasDRN",
":",
"return",
"obciStringADCBiasDrn",
";",
"default",
":",
"throw",
"new",
"Error",
"(",
"'Invalid input type, must be less than 8'",
")",
";",
"}",
"}"
] | Returns the input type for the given command
@param cmd {Number} The command
@returns {String} | [
"Returns",
"the",
"input",
"type",
"for",
"the",
"given",
"command"
] | 37886da7a07ea523b13a46448f56e1e1528748b7 | https://github.com/OpenBCI/OpenBCI_JavaScript_Utilities/blob/37886da7a07ea523b13a46448f56e1e1528748b7/src/constants.js#L1528-L1549 | train |
OpenBCI/OpenBCI_JavaScript_Utilities | src/constants.js | gainForCommand | function gainForCommand (cmd) {
switch (String(cmd)) {
case obciChannelCmdGain1:
return 1;
case obciChannelCmdGain2:
return 2;
case obciChannelCmdGain4:
return 4;
case obciChannelCmdGain6:
return 6;
case obciChannelCmdGain8:
return 8;
case obciChannelCmdGain12:
return 12;
case obciChannelCmdGain24:
return 24;
default:
throw new Error(`Invalid gain setting of ${cmd} gain must be (0,1,2,3,4,5,6)`);
}
} | javascript | function gainForCommand (cmd) {
switch (String(cmd)) {
case obciChannelCmdGain1:
return 1;
case obciChannelCmdGain2:
return 2;
case obciChannelCmdGain4:
return 4;
case obciChannelCmdGain6:
return 6;
case obciChannelCmdGain8:
return 8;
case obciChannelCmdGain12:
return 12;
case obciChannelCmdGain24:
return 24;
default:
throw new Error(`Invalid gain setting of ${cmd} gain must be (0,1,2,3,4,5,6)`);
}
} | [
"function",
"gainForCommand",
"(",
"cmd",
")",
"{",
"switch",
"(",
"String",
"(",
"cmd",
")",
")",
"{",
"case",
"obciChannelCmdGain1",
":",
"return",
"1",
";",
"case",
"obciChannelCmdGain2",
":",
"return",
"2",
";",
"case",
"obciChannelCmdGain4",
":",
"return",
"4",
";",
"case",
"obciChannelCmdGain6",
":",
"return",
"6",
";",
"case",
"obciChannelCmdGain8",
":",
"return",
"8",
";",
"case",
"obciChannelCmdGain12",
":",
"return",
"12",
";",
"case",
"obciChannelCmdGain24",
":",
"return",
"24",
";",
"default",
":",
"throw",
"new",
"Error",
"(",
"`",
"${",
"cmd",
"}",
"`",
")",
";",
"}",
"}"
] | Get the gain
@param cmd {Number}
@returns {Number} | [
"Get",
"the",
"gain"
] | 37886da7a07ea523b13a46448f56e1e1528748b7 | https://github.com/OpenBCI/OpenBCI_JavaScript_Utilities/blob/37886da7a07ea523b13a46448f56e1e1528748b7/src/constants.js#L1587-L1606 | train |
welldone-software/gulp-durandal | examples/HTML StarterKit/lib/durandal/js/plugins/router.js | handleGuardedRoute | function handleGuardedRoute(activator, instance, instruction) {
var resultOrPromise = router.guardRoute(instance, instruction);
if (resultOrPromise) {
if (resultOrPromise.then) {
resultOrPromise.then(function(result) {
if (result) {
if (system.isString(result)) {
redirect(result);
} else {
activateRoute(activator, instance, instruction);
}
} else {
cancelNavigation(instance, instruction);
}
});
} else {
if (system.isString(resultOrPromise)) {
redirect(resultOrPromise);
} else {
activateRoute(activator, instance, instruction);
}
}
} else {
cancelNavigation(instance, instruction);
}
} | javascript | function handleGuardedRoute(activator, instance, instruction) {
var resultOrPromise = router.guardRoute(instance, instruction);
if (resultOrPromise) {
if (resultOrPromise.then) {
resultOrPromise.then(function(result) {
if (result) {
if (system.isString(result)) {
redirect(result);
} else {
activateRoute(activator, instance, instruction);
}
} else {
cancelNavigation(instance, instruction);
}
});
} else {
if (system.isString(resultOrPromise)) {
redirect(resultOrPromise);
} else {
activateRoute(activator, instance, instruction);
}
}
} else {
cancelNavigation(instance, instruction);
}
} | [
"function",
"handleGuardedRoute",
"(",
"activator",
",",
"instance",
",",
"instruction",
")",
"{",
"var",
"resultOrPromise",
"=",
"router",
".",
"guardRoute",
"(",
"instance",
",",
"instruction",
")",
";",
"if",
"(",
"resultOrPromise",
")",
"{",
"if",
"(",
"resultOrPromise",
".",
"then",
")",
"{",
"resultOrPromise",
".",
"then",
"(",
"function",
"(",
"result",
")",
"{",
"if",
"(",
"result",
")",
"{",
"if",
"(",
"system",
".",
"isString",
"(",
"result",
")",
")",
"{",
"redirect",
"(",
"result",
")",
";",
"}",
"else",
"{",
"activateRoute",
"(",
"activator",
",",
"instance",
",",
"instruction",
")",
";",
"}",
"}",
"else",
"{",
"cancelNavigation",
"(",
"instance",
",",
"instruction",
")",
";",
"}",
"}",
")",
";",
"}",
"else",
"{",
"if",
"(",
"system",
".",
"isString",
"(",
"resultOrPromise",
")",
")",
"{",
"redirect",
"(",
"resultOrPromise",
")",
";",
"}",
"else",
"{",
"activateRoute",
"(",
"activator",
",",
"instance",
",",
"instruction",
")",
";",
"}",
"}",
"}",
"else",
"{",
"cancelNavigation",
"(",
"instance",
",",
"instruction",
")",
";",
"}",
"}"
] | Inspects routes and modules before activation. Can be used to protect access by cancelling navigation or redirecting.
@method guardRoute
@param {object} instance The module instance that is about to be activated by the router.
@param {object} instruction The route instruction. The instruction object has config, fragment, queryString, params and queryParams properties.
@return {Promise|Boolean|String} If a boolean, determines whether or not the route should activate or be cancelled. If a string, causes a redirect to the specified route. Can also be a promise for either of these value types. | [
"Inspects",
"routes",
"and",
"modules",
"before",
"activation",
".",
"Can",
"be",
"used",
"to",
"protect",
"access",
"by",
"cancelling",
"navigation",
"or",
"redirecting",
"."
] | 4eacd22fcc567a372e04e6de443b0228572d6400 | https://github.com/welldone-software/gulp-durandal/blob/4eacd22fcc567a372e04e6de443b0228572d6400/examples/HTML StarterKit/lib/durandal/js/plugins/router.js#L297-L322 | train |
narirou/gulp-develop-server | index.js | function( error ) {
if( error instanceof Buffer && error.toString().match( app.options.errorMessage ) ) {
initialized( 'Development server has error.' );
}
} | javascript | function( error ) {
if( error instanceof Buffer && error.toString().match( app.options.errorMessage ) ) {
initialized( 'Development server has error.' );
}
} | [
"function",
"(",
"error",
")",
"{",
"if",
"(",
"error",
"instanceof",
"Buffer",
"&&",
"error",
".",
"toString",
"(",
")",
".",
"match",
"(",
"app",
".",
"options",
".",
"errorMessage",
")",
")",
"{",
"initialized",
"(",
"'Development server has error.'",
")",
";",
"}",
"}"
] | initialized by `errorMessage` if server printed error | [
"initialized",
"by",
"errorMessage",
"if",
"server",
"printed",
"error"
] | 59039d87f1778ec9eddb023527520b35252f77c1 | https://github.com/narirou/gulp-develop-server/blob/59039d87f1778ec9eddb023527520b35252f77c1/index.js#L179-L183 | train |
|
welldone-software/gulp-durandal | examples/HTML StarterKit/lib/durandal/js/plugins/widget.js | function(kind) {
ko.bindingHandlers[kind] = {
init: function() {
return { controlsDescendantBindings: true };
},
update: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var settings = widget.getSettings(valueAccessor);
settings.kind = kind;
extractParts(element, settings);
widget.create(element, settings, bindingContext, true);
}
};
ko.virtualElements.allowedBindings[kind] = true;
composition.composeBindings.push(kind + ':');
} | javascript | function(kind) {
ko.bindingHandlers[kind] = {
init: function() {
return { controlsDescendantBindings: true };
},
update: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var settings = widget.getSettings(valueAccessor);
settings.kind = kind;
extractParts(element, settings);
widget.create(element, settings, bindingContext, true);
}
};
ko.virtualElements.allowedBindings[kind] = true;
composition.composeBindings.push(kind + ':');
} | [
"function",
"(",
"kind",
")",
"{",
"ko",
".",
"bindingHandlers",
"[",
"kind",
"]",
"=",
"{",
"init",
":",
"function",
"(",
")",
"{",
"return",
"{",
"controlsDescendantBindings",
":",
"true",
"}",
";",
"}",
",",
"update",
":",
"function",
"(",
"element",
",",
"valueAccessor",
",",
"allBindingsAccessor",
",",
"viewModel",
",",
"bindingContext",
")",
"{",
"var",
"settings",
"=",
"widget",
".",
"getSettings",
"(",
"valueAccessor",
")",
";",
"settings",
".",
"kind",
"=",
"kind",
";",
"extractParts",
"(",
"element",
",",
"settings",
")",
";",
"widget",
".",
"create",
"(",
"element",
",",
"settings",
",",
"bindingContext",
",",
"true",
")",
";",
"}",
"}",
";",
"ko",
".",
"virtualElements",
".",
"allowedBindings",
"[",
"kind",
"]",
"=",
"true",
";",
"composition",
".",
"composeBindings",
".",
"push",
"(",
"kind",
"+",
"':'",
")",
";",
"}"
] | Creates a ko binding handler for the specified kind.
@method registerKind
@param {string} kind The kind to create a custom binding handler for. | [
"Creates",
"a",
"ko",
"binding",
"handler",
"for",
"the",
"specified",
"kind",
"."
] | 4eacd22fcc567a372e04e6de443b0228572d6400 | https://github.com/welldone-software/gulp-durandal/blob/4eacd22fcc567a372e04e6de443b0228572d6400/examples/HTML StarterKit/lib/durandal/js/plugins/widget.js#L62-L77 | train |
|
welldone-software/gulp-durandal | examples/HTML StarterKit/lib/durandal/js/plugins/widget.js | function(kind, viewId, moduleId) {
if (viewId) {
kindViewMaps[kind] = viewId;
}
if (moduleId) {
kindModuleMaps[kind] = moduleId;
}
} | javascript | function(kind, viewId, moduleId) {
if (viewId) {
kindViewMaps[kind] = viewId;
}
if (moduleId) {
kindModuleMaps[kind] = moduleId;
}
} | [
"function",
"(",
"kind",
",",
"viewId",
",",
"moduleId",
")",
"{",
"if",
"(",
"viewId",
")",
"{",
"kindViewMaps",
"[",
"kind",
"]",
"=",
"viewId",
";",
"}",
"if",
"(",
"moduleId",
")",
"{",
"kindModuleMaps",
"[",
"kind",
"]",
"=",
"moduleId",
";",
"}",
"}"
] | Maps views and module to the kind identifier if a non-standard pattern is desired.
@method mapKind
@param {string} kind The kind name.
@param {string} [viewId] The unconventional view id to map the kind to.
@param {string} [moduleId] The unconventional module id to map the kind to. | [
"Maps",
"views",
"and",
"module",
"to",
"the",
"kind",
"identifier",
"if",
"a",
"non",
"-",
"standard",
"pattern",
"is",
"desired",
"."
] | 4eacd22fcc567a372e04e6de443b0228572d6400 | https://github.com/welldone-software/gulp-durandal/blob/4eacd22fcc567a372e04e6de443b0228572d6400/examples/HTML StarterKit/lib/durandal/js/plugins/widget.js#L85-L93 | train |
|
welldone-software/gulp-durandal | examples/HTML StarterKit/lib/durandal/js/plugins/widget.js | function(element, settings, bindingContext, fromBinding) {
if(!fromBinding){
settings = widget.getSettings(function() { return settings; }, element);
}
var compositionSettings = widget.createCompositionSettings(element, settings);
composition.compose(element, compositionSettings, bindingContext);
} | javascript | function(element, settings, bindingContext, fromBinding) {
if(!fromBinding){
settings = widget.getSettings(function() { return settings; }, element);
}
var compositionSettings = widget.createCompositionSettings(element, settings);
composition.compose(element, compositionSettings, bindingContext);
} | [
"function",
"(",
"element",
",",
"settings",
",",
"bindingContext",
",",
"fromBinding",
")",
"{",
"if",
"(",
"!",
"fromBinding",
")",
"{",
"settings",
"=",
"widget",
".",
"getSettings",
"(",
"function",
"(",
")",
"{",
"return",
"settings",
";",
"}",
",",
"element",
")",
";",
"}",
"var",
"compositionSettings",
"=",
"widget",
".",
"createCompositionSettings",
"(",
"element",
",",
"settings",
")",
";",
"composition",
".",
"compose",
"(",
"element",
",",
"compositionSettings",
",",
"bindingContext",
")",
";",
"}"
] | Creates a widget.
@method create
@param {DOMElement} element The DOMElement or knockout virtual element that serves as the target element for the widget.
@param {object} settings The widget settings.
@param {object} [bindingContext] The current binding context. | [
"Creates",
"a",
"widget",
"."
] | 4eacd22fcc567a372e04e6de443b0228572d6400 | https://github.com/welldone-software/gulp-durandal/blob/4eacd22fcc567a372e04e6de443b0228572d6400/examples/HTML StarterKit/lib/durandal/js/plugins/widget.js#L153-L161 | train |
|
welldone-software/gulp-durandal | examples/HTML StarterKit/lib/durandal/js/plugins/widget.js | function(config){
config.bindingName = config.bindingName || 'widget';
if(config.kinds){
var toRegister = config.kinds;
for(var i = 0; i < toRegister.length; i++){
widget.registerKind(toRegister[i]);
}
}
ko.bindingHandlers[config.bindingName] = {
init: function() {
return { controlsDescendantBindings: true };
},
update: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var settings = widget.getSettings(valueAccessor);
extractParts(element, settings);
widget.create(element, settings, bindingContext, true);
}
};
composition.composeBindings.push(config.bindingName + ':');
ko.virtualElements.allowedBindings[config.bindingName] = true;
} | javascript | function(config){
config.bindingName = config.bindingName || 'widget';
if(config.kinds){
var toRegister = config.kinds;
for(var i = 0; i < toRegister.length; i++){
widget.registerKind(toRegister[i]);
}
}
ko.bindingHandlers[config.bindingName] = {
init: function() {
return { controlsDescendantBindings: true };
},
update: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var settings = widget.getSettings(valueAccessor);
extractParts(element, settings);
widget.create(element, settings, bindingContext, true);
}
};
composition.composeBindings.push(config.bindingName + ':');
ko.virtualElements.allowedBindings[config.bindingName] = true;
} | [
"function",
"(",
"config",
")",
"{",
"config",
".",
"bindingName",
"=",
"config",
".",
"bindingName",
"||",
"'widget'",
";",
"if",
"(",
"config",
".",
"kinds",
")",
"{",
"var",
"toRegister",
"=",
"config",
".",
"kinds",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"toRegister",
".",
"length",
";",
"i",
"++",
")",
"{",
"widget",
".",
"registerKind",
"(",
"toRegister",
"[",
"i",
"]",
")",
";",
"}",
"}",
"ko",
".",
"bindingHandlers",
"[",
"config",
".",
"bindingName",
"]",
"=",
"{",
"init",
":",
"function",
"(",
")",
"{",
"return",
"{",
"controlsDescendantBindings",
":",
"true",
"}",
";",
"}",
",",
"update",
":",
"function",
"(",
"element",
",",
"valueAccessor",
",",
"allBindingsAccessor",
",",
"viewModel",
",",
"bindingContext",
")",
"{",
"var",
"settings",
"=",
"widget",
".",
"getSettings",
"(",
"valueAccessor",
")",
";",
"extractParts",
"(",
"element",
",",
"settings",
")",
";",
"widget",
".",
"create",
"(",
"element",
",",
"settings",
",",
"bindingContext",
",",
"true",
")",
";",
"}",
"}",
";",
"composition",
".",
"composeBindings",
".",
"push",
"(",
"config",
".",
"bindingName",
"+",
"':'",
")",
";",
"ko",
".",
"virtualElements",
".",
"allowedBindings",
"[",
"config",
".",
"bindingName",
"]",
"=",
"true",
";",
"}"
] | Installs the widget module by adding the widget binding handler and optionally registering kinds.
@method install
@param {object} config The module config. Add a `kinds` array with the names of widgets to automatically register. You can also specify a `bindingName` if you wish to use another name for the widget binding, such as "control" for example. | [
"Installs",
"the",
"widget",
"module",
"by",
"adding",
"the",
"widget",
"binding",
"handler",
"and",
"optionally",
"registering",
"kinds",
"."
] | 4eacd22fcc567a372e04e6de443b0228572d6400 | https://github.com/welldone-software/gulp-durandal/blob/4eacd22fcc567a372e04e6de443b0228572d6400/examples/HTML StarterKit/lib/durandal/js/plugins/widget.js#L167-L191 | train |
|
welldone-software/gulp-durandal | examples/HTML StarterKit/lib/durandal/js/activator.js | function(value) {
if(system.isObject(value)) {
value = value.can || false;
}
if(system.isString(value)) {
return ko.utils.arrayIndexOf(this.affirmations, value.toLowerCase()) !== -1;
}
return value;
} | javascript | function(value) {
if(system.isObject(value)) {
value = value.can || false;
}
if(system.isString(value)) {
return ko.utils.arrayIndexOf(this.affirmations, value.toLowerCase()) !== -1;
}
return value;
} | [
"function",
"(",
"value",
")",
"{",
"if",
"(",
"system",
".",
"isObject",
"(",
"value",
")",
")",
"{",
"value",
"=",
"value",
".",
"can",
"||",
"false",
";",
"}",
"if",
"(",
"system",
".",
"isString",
"(",
"value",
")",
")",
"{",
"return",
"ko",
".",
"utils",
".",
"arrayIndexOf",
"(",
"this",
".",
"affirmations",
",",
"value",
".",
"toLowerCase",
"(",
")",
")",
"!==",
"-",
"1",
";",
"}",
"return",
"value",
";",
"}"
] | Interprets the response of a `canActivate` or `canDeactivate` call using the known affirmative values in the `affirmations` array.
@method interpretResponse
@param {object} value
@return {boolean} | [
"Interprets",
"the",
"response",
"of",
"a",
"canActivate",
"or",
"canDeactivate",
"call",
"using",
"the",
"known",
"affirmative",
"values",
"in",
"the",
"affirmations",
"array",
"."
] | 4eacd22fcc567a372e04e6de443b0228572d6400 | https://github.com/welldone-software/gulp-durandal/blob/4eacd22fcc567a372e04e6de443b0228572d6400/examples/HTML StarterKit/lib/durandal/js/activator.js#L542-L552 | train |
|
gridcontrol/gridcontrol | src/lib/tools.js | cloneWrap | function cloneWrap(obj, circularValue) {
circularValue = safeDeepClone(undefined, [], circularValue);
return safeDeepClone(circularValue, [], obj);
} | javascript | function cloneWrap(obj, circularValue) {
circularValue = safeDeepClone(undefined, [], circularValue);
return safeDeepClone(circularValue, [], obj);
} | [
"function",
"cloneWrap",
"(",
"obj",
",",
"circularValue",
")",
"{",
"circularValue",
"=",
"safeDeepClone",
"(",
"undefined",
",",
"[",
"]",
",",
"circularValue",
")",
";",
"return",
"safeDeepClone",
"(",
"circularValue",
",",
"[",
"]",
",",
"obj",
")",
";",
"}"
] | method to wrap the cloning method | [
"method",
"to",
"wrap",
"the",
"cloning",
"method"
] | b3f5cc27c5fb24df010133cc34ba101d1561c9e0 | https://github.com/gridcontrol/gridcontrol/blob/b3f5cc27c5fb24df010133cc34ba101d1561c9e0/src/lib/tools.js#L121-L124 | train |
gridcontrol/gridcontrol | src/api.js | function(opts) {
this.load_balancer = opts.load_balancer;
this.task_manager = opts.task_manager;
this.file_manager = opts.file_manager;
this.net_manager = opts.net_manager;
this.port = opts.port || 10000;
this.tls = opts.tls;
} | javascript | function(opts) {
this.load_balancer = opts.load_balancer;
this.task_manager = opts.task_manager;
this.file_manager = opts.file_manager;
this.net_manager = opts.net_manager;
this.port = opts.port || 10000;
this.tls = opts.tls;
} | [
"function",
"(",
"opts",
")",
"{",
"this",
".",
"load_balancer",
"=",
"opts",
".",
"load_balancer",
";",
"this",
".",
"task_manager",
"=",
"opts",
".",
"task_manager",
";",
"this",
".",
"file_manager",
"=",
"opts",
".",
"file_manager",
";",
"this",
".",
"net_manager",
"=",
"opts",
".",
"net_manager",
";",
"this",
".",
"port",
"=",
"opts",
".",
"port",
"||",
"10000",
";",
"this",
".",
"tls",
"=",
"opts",
".",
"tls",
";",
"}"
] | Set API default values
@constructor
@this {API}
@param opts {object} options
@param opts.port Port to listen on
@param opts.task_manager Task manager object
@param opts.file_manager File manager object
@param opts.file_manager Network manager (cloudfunctions.js) object
@param opts.tls TLS keys | [
"Set",
"API",
"default",
"values"
] | b3f5cc27c5fb24df010133cc34ba101d1561c9e0 | https://github.com/gridcontrol/gridcontrol/blob/b3f5cc27c5fb24df010133cc34ba101d1561c9e0/src/api.js#L27-L34 | train |
|
welldone-software/gulp-durandal | examples/HTML StarterKit/lib/durandal/js/binder.js | function(bindingContext, view, obj) {
if (obj && bindingContext) {
bindingContext = bindingContext.createChildContext(obj);
}
return doBind(obj, view, bindingContext, obj || (bindingContext ? bindingContext.$data : null));
} | javascript | function(bindingContext, view, obj) {
if (obj && bindingContext) {
bindingContext = bindingContext.createChildContext(obj);
}
return doBind(obj, view, bindingContext, obj || (bindingContext ? bindingContext.$data : null));
} | [
"function",
"(",
"bindingContext",
",",
"view",
",",
"obj",
")",
"{",
"if",
"(",
"obj",
"&&",
"bindingContext",
")",
"{",
"bindingContext",
"=",
"bindingContext",
".",
"createChildContext",
"(",
"obj",
")",
";",
"}",
"return",
"doBind",
"(",
"obj",
",",
"view",
",",
"bindingContext",
",",
"obj",
"||",
"(",
"bindingContext",
"?",
"bindingContext",
".",
"$data",
":",
"null",
")",
")",
";",
"}"
] | Binds the view, preserving the existing binding context. Optionally, a new context can be created, parented to the previous context.
@method bindContext
@param {KnockoutBindingContext} bindingContext The current binding context.
@param {DOMElement} view The view to bind.
@param {object} [obj] The data to bind to, causing the creation of a child binding context if present. | [
"Binds",
"the",
"view",
"preserving",
"the",
"existing",
"binding",
"context",
".",
"Optionally",
"a",
"new",
"context",
"can",
"be",
"created",
"parented",
"to",
"the",
"previous",
"context",
"."
] | 4eacd22fcc567a372e04e6de443b0228572d6400 | https://github.com/welldone-software/gulp-durandal/blob/4eacd22fcc567a372e04e6de443b0228572d6400/examples/HTML StarterKit/lib/durandal/js/binder.js#L134-L140 | train |
|
welldone-software/gulp-durandal | examples/HTML StarterKit/lib/durandal/js/viewEngine.js | function(allElements){
if (allElements.length == 1) {
return allElements[0];
}
var withoutCommentsOrEmptyText = [];
for (var i = 0; i < allElements.length; i++) {
var current = allElements[i];
if (current.nodeType != 8) {
if (current.nodeType == 3) {
var result = /\S/.test(current.nodeValue);
if (!result) {
continue;
}
}
withoutCommentsOrEmptyText.push(current);
}
}
if (withoutCommentsOrEmptyText.length > 1) {
return $(withoutCommentsOrEmptyText).wrapAll('<div class="durandal-wrapper"></div>').parent().get(0);
}
return withoutCommentsOrEmptyText[0];
} | javascript | function(allElements){
if (allElements.length == 1) {
return allElements[0];
}
var withoutCommentsOrEmptyText = [];
for (var i = 0; i < allElements.length; i++) {
var current = allElements[i];
if (current.nodeType != 8) {
if (current.nodeType == 3) {
var result = /\S/.test(current.nodeValue);
if (!result) {
continue;
}
}
withoutCommentsOrEmptyText.push(current);
}
}
if (withoutCommentsOrEmptyText.length > 1) {
return $(withoutCommentsOrEmptyText).wrapAll('<div class="durandal-wrapper"></div>').parent().get(0);
}
return withoutCommentsOrEmptyText[0];
} | [
"function",
"(",
"allElements",
")",
"{",
"if",
"(",
"allElements",
".",
"length",
"==",
"1",
")",
"{",
"return",
"allElements",
"[",
"0",
"]",
";",
"}",
"var",
"withoutCommentsOrEmptyText",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"allElements",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"current",
"=",
"allElements",
"[",
"i",
"]",
";",
"if",
"(",
"current",
".",
"nodeType",
"!=",
"8",
")",
"{",
"if",
"(",
"current",
".",
"nodeType",
"==",
"3",
")",
"{",
"var",
"result",
"=",
"/",
"\\S",
"/",
".",
"test",
"(",
"current",
".",
"nodeValue",
")",
";",
"if",
"(",
"!",
"result",
")",
"{",
"continue",
";",
"}",
"}",
"withoutCommentsOrEmptyText",
".",
"push",
"(",
"current",
")",
";",
"}",
"}",
"if",
"(",
"withoutCommentsOrEmptyText",
".",
"length",
">",
"1",
")",
"{",
"return",
"$",
"(",
"withoutCommentsOrEmptyText",
")",
".",
"wrapAll",
"(",
"'<div class=\"durandal-wrapper\"></div>'",
")",
".",
"parent",
"(",
")",
".",
"get",
"(",
"0",
")",
";",
"}",
"return",
"withoutCommentsOrEmptyText",
"[",
"0",
"]",
";",
"}"
] | Converts an array of elements into a single element. White space and comments are removed. If a single element does not remain, then the elements are wrapped.
@method ensureSingleElement
@param {DOMElement[]} allElements The elements.
@return {DOMElement} A single element. | [
"Converts",
"an",
"array",
"of",
"elements",
"into",
"a",
"single",
"element",
".",
"White",
"space",
"and",
"comments",
"are",
"removed",
".",
"If",
"a",
"single",
"element",
"does",
"not",
"remain",
"then",
"the",
"elements",
"are",
"wrapped",
"."
] | 4eacd22fcc567a372e04e6de443b0228572d6400 | https://github.com/welldone-software/gulp-durandal/blob/4eacd22fcc567a372e04e6de443b0228572d6400/examples/HTML StarterKit/lib/durandal/js/viewEngine.js#L92-L118 | train |
|
welldone-software/gulp-durandal | examples/HTML StarterKit/lib/durandal/js/viewEngine.js | function(viewId) {
var that = this;
var requirePath = this.convertViewIdToRequirePath(viewId);
return system.defer(function(dfd) {
system.acquire(requirePath).then(function(markup) {
var element = that.processMarkup(markup);
element.setAttribute('data-view', viewId);
dfd.resolve(element);
}).fail(function(err){
that.createFallbackView(viewId, requirePath, err).then(function(element){
element.setAttribute('data-view', viewId);
dfd.resolve(element);
});
});
}).promise();
} | javascript | function(viewId) {
var that = this;
var requirePath = this.convertViewIdToRequirePath(viewId);
return system.defer(function(dfd) {
system.acquire(requirePath).then(function(markup) {
var element = that.processMarkup(markup);
element.setAttribute('data-view', viewId);
dfd.resolve(element);
}).fail(function(err){
that.createFallbackView(viewId, requirePath, err).then(function(element){
element.setAttribute('data-view', viewId);
dfd.resolve(element);
});
});
}).promise();
} | [
"function",
"(",
"viewId",
")",
"{",
"var",
"that",
"=",
"this",
";",
"var",
"requirePath",
"=",
"this",
".",
"convertViewIdToRequirePath",
"(",
"viewId",
")",
";",
"return",
"system",
".",
"defer",
"(",
"function",
"(",
"dfd",
")",
"{",
"system",
".",
"acquire",
"(",
"requirePath",
")",
".",
"then",
"(",
"function",
"(",
"markup",
")",
"{",
"var",
"element",
"=",
"that",
".",
"processMarkup",
"(",
"markup",
")",
";",
"element",
".",
"setAttribute",
"(",
"'data-view'",
",",
"viewId",
")",
";",
"dfd",
".",
"resolve",
"(",
"element",
")",
";",
"}",
")",
".",
"fail",
"(",
"function",
"(",
"err",
")",
"{",
"that",
".",
"createFallbackView",
"(",
"viewId",
",",
"requirePath",
",",
"err",
")",
".",
"then",
"(",
"function",
"(",
"element",
")",
"{",
"element",
".",
"setAttribute",
"(",
"'data-view'",
",",
"viewId",
")",
";",
"dfd",
".",
"resolve",
"(",
"element",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
")",
".",
"promise",
"(",
")",
";",
"}"
] | Creates the view associated with the view id.
@method createView
@param {string} viewId The view id whose view should be created.
@return {Promise} A promise of the view. | [
"Creates",
"the",
"view",
"associated",
"with",
"the",
"view",
"id",
"."
] | 4eacd22fcc567a372e04e6de443b0228572d6400 | https://github.com/welldone-software/gulp-durandal/blob/4eacd22fcc567a372e04e6de443b0228572d6400/examples/HTML StarterKit/lib/durandal/js/viewEngine.js#L125-L141 | train |
|
welldone-software/gulp-durandal | examples/HTML StarterKit/lib/durandal/js/viewEngine.js | function (viewId, requirePath, err) {
var that = this,
message = 'View Not Found. Searched for "' + viewId + '" via path "' + requirePath + '".';
return system.defer(function(dfd) {
dfd.resolve(that.processMarkup('<div class="durandal-view-404">' + message + '</div>'));
}).promise();
} | javascript | function (viewId, requirePath, err) {
var that = this,
message = 'View Not Found. Searched for "' + viewId + '" via path "' + requirePath + '".';
return system.defer(function(dfd) {
dfd.resolve(that.processMarkup('<div class="durandal-view-404">' + message + '</div>'));
}).promise();
} | [
"function",
"(",
"viewId",
",",
"requirePath",
",",
"err",
")",
"{",
"var",
"that",
"=",
"this",
",",
"message",
"=",
"'View Not Found. Searched for \"'",
"+",
"viewId",
"+",
"'\" via path \"'",
"+",
"requirePath",
"+",
"'\".'",
";",
"return",
"system",
".",
"defer",
"(",
"function",
"(",
"dfd",
")",
"{",
"dfd",
".",
"resolve",
"(",
"that",
".",
"processMarkup",
"(",
"'<div class=\"durandal-view-404\">'",
"+",
"message",
"+",
"'</div>'",
")",
")",
";",
"}",
")",
".",
"promise",
"(",
")",
";",
"}"
] | Called when a view cannot be found to provide the opportunity to locate or generate a fallback view. Mainly used to ease development.
@method createFallbackView
@param {string} viewId The view id whose view should be created.
@param {string} requirePath The require path that was attempted.
@param {Error} requirePath The error that was returned from the attempt to locate the default view.
@return {Promise} A promise for the fallback view. | [
"Called",
"when",
"a",
"view",
"cannot",
"be",
"found",
"to",
"provide",
"the",
"opportunity",
"to",
"locate",
"or",
"generate",
"a",
"fallback",
"view",
".",
"Mainly",
"used",
"to",
"ease",
"development",
"."
] | 4eacd22fcc567a372e04e6de443b0228572d6400 | https://github.com/welldone-software/gulp-durandal/blob/4eacd22fcc567a372e04e6de443b0228572d6400/examples/HTML StarterKit/lib/durandal/js/viewEngine.js#L150-L157 | train |
|
welldone-software/gulp-durandal | examples/HTML StarterKit/lib/durandal/js/plugins/dialog.js | function(message, title, options) {
this.message = message;
this.title = title || MessageBox.defaultTitle;
this.options = options || MessageBox.defaultOptions;
} | javascript | function(message, title, options) {
this.message = message;
this.title = title || MessageBox.defaultTitle;
this.options = options || MessageBox.defaultOptions;
} | [
"function",
"(",
"message",
",",
"title",
",",
"options",
")",
"{",
"this",
".",
"message",
"=",
"message",
";",
"this",
".",
"title",
"=",
"title",
"||",
"MessageBox",
".",
"defaultTitle",
";",
"this",
".",
"options",
"=",
"options",
"||",
"MessageBox",
".",
"defaultOptions",
";",
"}"
] | Models a message box's message, title and options.
@class MessageBox | [
"Models",
"a",
"message",
"box",
"s",
"message",
"title",
"and",
"options",
"."
] | 4eacd22fcc567a372e04e6de443b0228572d6400 | https://github.com/welldone-software/gulp-durandal/blob/4eacd22fcc567a372e04e6de443b0228572d6400/examples/HTML StarterKit/lib/durandal/js/plugins/dialog.js#L26-L30 | train |
|
welldone-software/gulp-durandal | examples/HTML StarterKit/lib/durandal/js/plugins/dialog.js | function(obj){
var theDialog = this.getDialog(obj);
if(theDialog){
var rest = Array.prototype.slice.call(arguments, 1);
theDialog.close.apply(theDialog, rest);
}
} | javascript | function(obj){
var theDialog = this.getDialog(obj);
if(theDialog){
var rest = Array.prototype.slice.call(arguments, 1);
theDialog.close.apply(theDialog, rest);
}
} | [
"function",
"(",
"obj",
")",
"{",
"var",
"theDialog",
"=",
"this",
".",
"getDialog",
"(",
"obj",
")",
";",
"if",
"(",
"theDialog",
")",
"{",
"var",
"rest",
"=",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"arguments",
",",
"1",
")",
";",
"theDialog",
".",
"close",
".",
"apply",
"(",
"theDialog",
",",
"rest",
")",
";",
"}",
"}"
] | Closes the dialog associated with the specified object.
@method close
@param {object} obj The object whose dialog should be closed.
@param {object} results* The results to return back to the dialog caller after closing. | [
"Closes",
"the",
"dialog",
"associated",
"with",
"the",
"specified",
"object",
"."
] | 4eacd22fcc567a372e04e6de443b0228572d6400 | https://github.com/welldone-software/gulp-durandal/blob/4eacd22fcc567a372e04e6de443b0228572d6400/examples/HTML StarterKit/lib/durandal/js/plugins/dialog.js#L201-L207 | train |
|
welldone-software/gulp-durandal | examples/HTML StarterKit/lib/durandal/js/plugins/dialog.js | function(obj, activationData, context) {
var that = this;
var dialogContext = contexts[context || 'default'];
return system.defer(function(dfd) {
ensureDialogInstance(obj).then(function(instance) {
var dialogActivator = activator.create();
dialogActivator.activateItem(instance, activationData).then(function (success) {
if (success) {
var theDialog = instance.__dialog__ = {
owner: instance,
context: dialogContext,
activator: dialogActivator,
close: function () {
var args = arguments;
dialogActivator.deactivateItem(instance, true).then(function (closeSuccess) {
if (closeSuccess) {
dialogCount--;
dialogContext.removeHost(theDialog);
delete instance.__dialog__;
if (args.length === 0) {
dfd.resolve();
} else if (args.length === 1) {
dfd.resolve(args[0]);
} else {
dfd.resolve.apply(dfd, args);
}
}
});
}
};
theDialog.settings = that.createCompositionSettings(instance, dialogContext);
dialogContext.addHost(theDialog);
dialogCount++;
composition.compose(theDialog.host, theDialog.settings);
} else {
dfd.resolve(false);
}
});
});
}).promise();
} | javascript | function(obj, activationData, context) {
var that = this;
var dialogContext = contexts[context || 'default'];
return system.defer(function(dfd) {
ensureDialogInstance(obj).then(function(instance) {
var dialogActivator = activator.create();
dialogActivator.activateItem(instance, activationData).then(function (success) {
if (success) {
var theDialog = instance.__dialog__ = {
owner: instance,
context: dialogContext,
activator: dialogActivator,
close: function () {
var args = arguments;
dialogActivator.deactivateItem(instance, true).then(function (closeSuccess) {
if (closeSuccess) {
dialogCount--;
dialogContext.removeHost(theDialog);
delete instance.__dialog__;
if (args.length === 0) {
dfd.resolve();
} else if (args.length === 1) {
dfd.resolve(args[0]);
} else {
dfd.resolve.apply(dfd, args);
}
}
});
}
};
theDialog.settings = that.createCompositionSettings(instance, dialogContext);
dialogContext.addHost(theDialog);
dialogCount++;
composition.compose(theDialog.host, theDialog.settings);
} else {
dfd.resolve(false);
}
});
});
}).promise();
} | [
"function",
"(",
"obj",
",",
"activationData",
",",
"context",
")",
"{",
"var",
"that",
"=",
"this",
";",
"var",
"dialogContext",
"=",
"contexts",
"[",
"context",
"||",
"'default'",
"]",
";",
"return",
"system",
".",
"defer",
"(",
"function",
"(",
"dfd",
")",
"{",
"ensureDialogInstance",
"(",
"obj",
")",
".",
"then",
"(",
"function",
"(",
"instance",
")",
"{",
"var",
"dialogActivator",
"=",
"activator",
".",
"create",
"(",
")",
";",
"dialogActivator",
".",
"activateItem",
"(",
"instance",
",",
"activationData",
")",
".",
"then",
"(",
"function",
"(",
"success",
")",
"{",
"if",
"(",
"success",
")",
"{",
"var",
"theDialog",
"=",
"instance",
".",
"__dialog__",
"=",
"{",
"owner",
":",
"instance",
",",
"context",
":",
"dialogContext",
",",
"activator",
":",
"dialogActivator",
",",
"close",
":",
"function",
"(",
")",
"{",
"var",
"args",
"=",
"arguments",
";",
"dialogActivator",
".",
"deactivateItem",
"(",
"instance",
",",
"true",
")",
".",
"then",
"(",
"function",
"(",
"closeSuccess",
")",
"{",
"if",
"(",
"closeSuccess",
")",
"{",
"dialogCount",
"--",
";",
"dialogContext",
".",
"removeHost",
"(",
"theDialog",
")",
";",
"delete",
"instance",
".",
"__dialog__",
";",
"if",
"(",
"args",
".",
"length",
"===",
"0",
")",
"{",
"dfd",
".",
"resolve",
"(",
")",
";",
"}",
"else",
"if",
"(",
"args",
".",
"length",
"===",
"1",
")",
"{",
"dfd",
".",
"resolve",
"(",
"args",
"[",
"0",
"]",
")",
";",
"}",
"else",
"{",
"dfd",
".",
"resolve",
".",
"apply",
"(",
"dfd",
",",
"args",
")",
";",
"}",
"}",
"}",
")",
";",
"}",
"}",
";",
"theDialog",
".",
"settings",
"=",
"that",
".",
"createCompositionSettings",
"(",
"instance",
",",
"dialogContext",
")",
";",
"dialogContext",
".",
"addHost",
"(",
"theDialog",
")",
";",
"dialogCount",
"++",
";",
"composition",
".",
"compose",
"(",
"theDialog",
".",
"host",
",",
"theDialog",
".",
"settings",
")",
";",
"}",
"else",
"{",
"dfd",
".",
"resolve",
"(",
"false",
")",
";",
"}",
"}",
")",
";",
"}",
")",
";",
"}",
")",
".",
"promise",
"(",
")",
";",
"}"
] | Shows a dialog.
@method show
@param {object|string} obj The object (or moduleId) to display as a dialog.
@param {object} [activationData] The data that should be passed to the object upon activation.
@param {string} [context] The name of the dialog context to use. Uses the default context if none is specified.
@return {Promise} A promise that resolves when the dialog is closed and returns any data passed at the time of closing. | [
"Shows",
"a",
"dialog",
"."
] | 4eacd22fcc567a372e04e6de443b0228572d6400 | https://github.com/welldone-software/gulp-durandal/blob/4eacd22fcc567a372e04e6de443b0228572d6400/examples/HTML StarterKit/lib/durandal/js/plugins/dialog.js#L216-L261 | train |
|
welldone-software/gulp-durandal | examples/HTML StarterKit/lib/durandal/js/plugins/dialog.js | function(message, title, options){
if(system.isString(this.MessageBox)){
return dialog.show(this.MessageBox, [
message,
title || MessageBox.defaultTitle,
options || MessageBox.defaultOptions
]);
}
return dialog.show(new this.MessageBox(message, title, options));
} | javascript | function(message, title, options){
if(system.isString(this.MessageBox)){
return dialog.show(this.MessageBox, [
message,
title || MessageBox.defaultTitle,
options || MessageBox.defaultOptions
]);
}
return dialog.show(new this.MessageBox(message, title, options));
} | [
"function",
"(",
"message",
",",
"title",
",",
"options",
")",
"{",
"if",
"(",
"system",
".",
"isString",
"(",
"this",
".",
"MessageBox",
")",
")",
"{",
"return",
"dialog",
".",
"show",
"(",
"this",
".",
"MessageBox",
",",
"[",
"message",
",",
"title",
"||",
"MessageBox",
".",
"defaultTitle",
",",
"options",
"||",
"MessageBox",
".",
"defaultOptions",
"]",
")",
";",
"}",
"return",
"dialog",
".",
"show",
"(",
"new",
"this",
".",
"MessageBox",
"(",
"message",
",",
"title",
",",
"options",
")",
")",
";",
"}"
] | Shows a message box.
@method showMessage
@param {string} message The message to display in the dialog.
@param {string} [title] The title message.
@param {string[]} [options] The options to provide to the user.
@return {Promise} A promise that resolves when the message box is closed and returns the selected option. | [
"Shows",
"a",
"message",
"box",
"."
] | 4eacd22fcc567a372e04e6de443b0228572d6400 | https://github.com/welldone-software/gulp-durandal/blob/4eacd22fcc567a372e04e6de443b0228572d6400/examples/HTML StarterKit/lib/durandal/js/plugins/dialog.js#L270-L280 | train |
|
welldone-software/gulp-durandal | examples/HTML StarterKit/lib/durandal/js/plugins/dialog.js | function(config){
app.showDialog = function(obj, activationData, context) {
return dialog.show(obj, activationData, context);
};
app.showMessage = function(message, title, options) {
return dialog.showMessage(message, title, options);
};
if(config.messageBox){
dialog.MessageBox = config.messageBox;
}
if(config.messageBoxView){
dialog.MessageBox.prototype.getView = function(){
return config.messageBoxView;
};
}
} | javascript | function(config){
app.showDialog = function(obj, activationData, context) {
return dialog.show(obj, activationData, context);
};
app.showMessage = function(message, title, options) {
return dialog.showMessage(message, title, options);
};
if(config.messageBox){
dialog.MessageBox = config.messageBox;
}
if(config.messageBoxView){
dialog.MessageBox.prototype.getView = function(){
return config.messageBoxView;
};
}
} | [
"function",
"(",
"config",
")",
"{",
"app",
".",
"showDialog",
"=",
"function",
"(",
"obj",
",",
"activationData",
",",
"context",
")",
"{",
"return",
"dialog",
".",
"show",
"(",
"obj",
",",
"activationData",
",",
"context",
")",
";",
"}",
";",
"app",
".",
"showMessage",
"=",
"function",
"(",
"message",
",",
"title",
",",
"options",
")",
"{",
"return",
"dialog",
".",
"showMessage",
"(",
"message",
",",
"title",
",",
"options",
")",
";",
"}",
";",
"if",
"(",
"config",
".",
"messageBox",
")",
"{",
"dialog",
".",
"MessageBox",
"=",
"config",
".",
"messageBox",
";",
"}",
"if",
"(",
"config",
".",
"messageBoxView",
")",
"{",
"dialog",
".",
"MessageBox",
".",
"prototype",
".",
"getView",
"=",
"function",
"(",
")",
"{",
"return",
"config",
".",
"messageBoxView",
";",
"}",
";",
"}",
"}"
] | Installs this module into Durandal; called by the framework. Adds `app.showDialog` and `app.showMessage` convenience methods.
@method install
@param {object} [config] Add a `messageBox` property to supply a custom message box constructor. Add a `messageBoxView` property to supply custom view markup for the built-in message box. | [
"Installs",
"this",
"module",
"into",
"Durandal",
";",
"called",
"by",
"the",
"framework",
".",
"Adds",
"app",
".",
"showDialog",
"and",
"app",
".",
"showMessage",
"convenience",
"methods",
"."
] | 4eacd22fcc567a372e04e6de443b0228572d6400 | https://github.com/welldone-software/gulp-durandal/blob/4eacd22fcc567a372e04e6de443b0228572d6400/examples/HTML StarterKit/lib/durandal/js/plugins/dialog.js#L286-L304 | train |
|
welldone-software/gulp-durandal | examples/HTML StarterKit/lib/durandal/js/plugins/dialog.js | function(theDialog) {
var body = $('body');
var blockout = $('<div class="modalBlockout"></div>')
.css({ 'z-index': dialog.getNextZIndex(), 'opacity': this.blockoutOpacity })
.appendTo(body);
var host = $('<div class="modalHost"></div>')
.css({ 'z-index': dialog.getNextZIndex() })
.appendTo(body);
theDialog.host = host.get(0);
theDialog.blockout = blockout.get(0);
if (!dialog.isOpen()) {
theDialog.oldBodyMarginRight = body.css("margin-right");
theDialog.oldInlineMarginRight = body.get(0).style.marginRight;
var html = $("html");
var oldBodyOuterWidth = body.outerWidth(true);
var oldScrollTop = html.scrollTop();
$("html").css("overflow-y", "hidden");
var newBodyOuterWidth = $("body").outerWidth(true);
body.css("margin-right", (newBodyOuterWidth - oldBodyOuterWidth + parseInt(theDialog.oldBodyMarginRight, 10)) + "px");
html.scrollTop(oldScrollTop); // necessary for Firefox
}
} | javascript | function(theDialog) {
var body = $('body');
var blockout = $('<div class="modalBlockout"></div>')
.css({ 'z-index': dialog.getNextZIndex(), 'opacity': this.blockoutOpacity })
.appendTo(body);
var host = $('<div class="modalHost"></div>')
.css({ 'z-index': dialog.getNextZIndex() })
.appendTo(body);
theDialog.host = host.get(0);
theDialog.blockout = blockout.get(0);
if (!dialog.isOpen()) {
theDialog.oldBodyMarginRight = body.css("margin-right");
theDialog.oldInlineMarginRight = body.get(0).style.marginRight;
var html = $("html");
var oldBodyOuterWidth = body.outerWidth(true);
var oldScrollTop = html.scrollTop();
$("html").css("overflow-y", "hidden");
var newBodyOuterWidth = $("body").outerWidth(true);
body.css("margin-right", (newBodyOuterWidth - oldBodyOuterWidth + parseInt(theDialog.oldBodyMarginRight, 10)) + "px");
html.scrollTop(oldScrollTop); // necessary for Firefox
}
} | [
"function",
"(",
"theDialog",
")",
"{",
"var",
"body",
"=",
"$",
"(",
"'body'",
")",
";",
"var",
"blockout",
"=",
"$",
"(",
"'<div class=\"modalBlockout\"></div>'",
")",
".",
"css",
"(",
"{",
"'z-index'",
":",
"dialog",
".",
"getNextZIndex",
"(",
")",
",",
"'opacity'",
":",
"this",
".",
"blockoutOpacity",
"}",
")",
".",
"appendTo",
"(",
"body",
")",
";",
"var",
"host",
"=",
"$",
"(",
"'<div class=\"modalHost\"></div>'",
")",
".",
"css",
"(",
"{",
"'z-index'",
":",
"dialog",
".",
"getNextZIndex",
"(",
")",
"}",
")",
".",
"appendTo",
"(",
"body",
")",
";",
"theDialog",
".",
"host",
"=",
"host",
".",
"get",
"(",
"0",
")",
";",
"theDialog",
".",
"blockout",
"=",
"blockout",
".",
"get",
"(",
"0",
")",
";",
"if",
"(",
"!",
"dialog",
".",
"isOpen",
"(",
")",
")",
"{",
"theDialog",
".",
"oldBodyMarginRight",
"=",
"body",
".",
"css",
"(",
"\"margin-right\"",
")",
";",
"theDialog",
".",
"oldInlineMarginRight",
"=",
"body",
".",
"get",
"(",
"0",
")",
".",
"style",
".",
"marginRight",
";",
"var",
"html",
"=",
"$",
"(",
"\"html\"",
")",
";",
"var",
"oldBodyOuterWidth",
"=",
"body",
".",
"outerWidth",
"(",
"true",
")",
";",
"var",
"oldScrollTop",
"=",
"html",
".",
"scrollTop",
"(",
")",
";",
"$",
"(",
"\"html\"",
")",
".",
"css",
"(",
"\"overflow-y\"",
",",
"\"hidden\"",
")",
";",
"var",
"newBodyOuterWidth",
"=",
"$",
"(",
"\"body\"",
")",
".",
"outerWidth",
"(",
"true",
")",
";",
"body",
".",
"css",
"(",
"\"margin-right\"",
",",
"(",
"newBodyOuterWidth",
"-",
"oldBodyOuterWidth",
"+",
"parseInt",
"(",
"theDialog",
".",
"oldBodyMarginRight",
",",
"10",
")",
")",
"+",
"\"px\"",
")",
";",
"html",
".",
"scrollTop",
"(",
"oldScrollTop",
")",
";",
"}",
"}"
] | In this function, you are expected to add a DOM element to the tree which will serve as the "host" for the modal's composed view. You must add a property called host to the modalWindow object which references the dom element. It is this host which is passed to the composition module.
@method addHost
@param {Dialog} theDialog The dialog model. | [
"In",
"this",
"function",
"you",
"are",
"expected",
"to",
"add",
"a",
"DOM",
"element",
"to",
"the",
"tree",
"which",
"will",
"serve",
"as",
"the",
"host",
"for",
"the",
"modal",
"s",
"composed",
"view",
".",
"You",
"must",
"add",
"a",
"property",
"called",
"host",
"to",
"the",
"modalWindow",
"object",
"which",
"references",
"the",
"dom",
"element",
".",
"It",
"is",
"this",
"host",
"which",
"is",
"passed",
"to",
"the",
"composition",
"module",
"."
] | 4eacd22fcc567a372e04e6de443b0228572d6400 | https://github.com/welldone-software/gulp-durandal/blob/4eacd22fcc567a372e04e6de443b0228572d6400/examples/HTML StarterKit/lib/durandal/js/plugins/dialog.js#L318-L343 | train |
|
welldone-software/gulp-durandal | examples/HTML StarterKit/lib/durandal/js/plugins/dialog.js | function(theDialog) {
$(theDialog.host).css('opacity', 0);
$(theDialog.blockout).css('opacity', 0);
setTimeout(function() {
ko.removeNode(theDialog.host);
ko.removeNode(theDialog.blockout);
}, this.removeDelay);
if (!dialog.isOpen()) {
var html = $("html");
var oldScrollTop = html.scrollTop(); // necessary for Firefox.
html.css("overflow-y", "").scrollTop(oldScrollTop);
if(theDialog.oldInlineMarginRight) {
$("body").css("margin-right", theDialog.oldBodyMarginRight);
} else {
$("body").css("margin-right", '');
}
}
} | javascript | function(theDialog) {
$(theDialog.host).css('opacity', 0);
$(theDialog.blockout).css('opacity', 0);
setTimeout(function() {
ko.removeNode(theDialog.host);
ko.removeNode(theDialog.blockout);
}, this.removeDelay);
if (!dialog.isOpen()) {
var html = $("html");
var oldScrollTop = html.scrollTop(); // necessary for Firefox.
html.css("overflow-y", "").scrollTop(oldScrollTop);
if(theDialog.oldInlineMarginRight) {
$("body").css("margin-right", theDialog.oldBodyMarginRight);
} else {
$("body").css("margin-right", '');
}
}
} | [
"function",
"(",
"theDialog",
")",
"{",
"$",
"(",
"theDialog",
".",
"host",
")",
".",
"css",
"(",
"'opacity'",
",",
"0",
")",
";",
"$",
"(",
"theDialog",
".",
"blockout",
")",
".",
"css",
"(",
"'opacity'",
",",
"0",
")",
";",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"ko",
".",
"removeNode",
"(",
"theDialog",
".",
"host",
")",
";",
"ko",
".",
"removeNode",
"(",
"theDialog",
".",
"blockout",
")",
";",
"}",
",",
"this",
".",
"removeDelay",
")",
";",
"if",
"(",
"!",
"dialog",
".",
"isOpen",
"(",
")",
")",
"{",
"var",
"html",
"=",
"$",
"(",
"\"html\"",
")",
";",
"var",
"oldScrollTop",
"=",
"html",
".",
"scrollTop",
"(",
")",
";",
"html",
".",
"css",
"(",
"\"overflow-y\"",
",",
"\"\"",
")",
".",
"scrollTop",
"(",
"oldScrollTop",
")",
";",
"if",
"(",
"theDialog",
".",
"oldInlineMarginRight",
")",
"{",
"$",
"(",
"\"body\"",
")",
".",
"css",
"(",
"\"margin-right\"",
",",
"theDialog",
".",
"oldBodyMarginRight",
")",
";",
"}",
"else",
"{",
"$",
"(",
"\"body\"",
")",
".",
"css",
"(",
"\"margin-right\"",
",",
"''",
")",
";",
"}",
"}",
"}"
] | This function is expected to remove any DOM machinery associated with the specified dialog and do any other necessary cleanup.
@method removeHost
@param {Dialog} theDialog The dialog model. | [
"This",
"function",
"is",
"expected",
"to",
"remove",
"any",
"DOM",
"machinery",
"associated",
"with",
"the",
"specified",
"dialog",
"and",
"do",
"any",
"other",
"necessary",
"cleanup",
"."
] | 4eacd22fcc567a372e04e6de443b0228572d6400 | https://github.com/welldone-software/gulp-durandal/blob/4eacd22fcc567a372e04e6de443b0228572d6400/examples/HTML StarterKit/lib/durandal/js/plugins/dialog.js#L349-L369 | train |
|
welldone-software/gulp-durandal | examples/HTML StarterKit/lib/durandal/js/plugins/dialog.js | function (child, parent, context) {
var theDialog = dialog.getDialog(context.model);
var $child = $(child);
var loadables = $child.find("img").filter(function () {
//Remove images with known width and height
var $this = $(this);
return !(this.style.width && this.style.height) && !($this.attr("width") && $this.attr("height"));
});
$child.data("predefinedWidth", $child.get(0).style.width);
var setDialogPosition = function () {
//Setting a short timeout is need in IE8, otherwise we could do this straight away
setTimeout(function () {
//We will clear and then set width for dialogs without width set
if (!$child.data("predefinedWidth")) {
$child.css({ width: '' }); //Reset width
}
var width = $child.outerWidth(false);
var height = $child.outerHeight(false);
var windowHeight = $(window).height();
var constrainedHeight = Math.min(height, windowHeight);
$child.css({
'margin-top': (-constrainedHeight / 2).toString() + 'px',
'margin-left': (-width / 2).toString() + 'px'
});
if (!$child.data("predefinedWidth")) {
//Ensure the correct width after margin-left has been set
$child.outerWidth(width);
}
if (height > windowHeight) {
$child.css("overflow-y", "auto");
} else {
$child.css("overflow-y", "");
}
$(theDialog.host).css('opacity', 1);
$child.css("visibility", "visible");
$child.find('.autofocus').first().focus();
}, 1);
};
setDialogPosition();
loadables.load(setDialogPosition);
if ($child.hasClass('autoclose')) {
$(theDialog.blockout).click(function () {
theDialog.close();
});
}
} | javascript | function (child, parent, context) {
var theDialog = dialog.getDialog(context.model);
var $child = $(child);
var loadables = $child.find("img").filter(function () {
//Remove images with known width and height
var $this = $(this);
return !(this.style.width && this.style.height) && !($this.attr("width") && $this.attr("height"));
});
$child.data("predefinedWidth", $child.get(0).style.width);
var setDialogPosition = function () {
//Setting a short timeout is need in IE8, otherwise we could do this straight away
setTimeout(function () {
//We will clear and then set width for dialogs without width set
if (!$child.data("predefinedWidth")) {
$child.css({ width: '' }); //Reset width
}
var width = $child.outerWidth(false);
var height = $child.outerHeight(false);
var windowHeight = $(window).height();
var constrainedHeight = Math.min(height, windowHeight);
$child.css({
'margin-top': (-constrainedHeight / 2).toString() + 'px',
'margin-left': (-width / 2).toString() + 'px'
});
if (!$child.data("predefinedWidth")) {
//Ensure the correct width after margin-left has been set
$child.outerWidth(width);
}
if (height > windowHeight) {
$child.css("overflow-y", "auto");
} else {
$child.css("overflow-y", "");
}
$(theDialog.host).css('opacity', 1);
$child.css("visibility", "visible");
$child.find('.autofocus').first().focus();
}, 1);
};
setDialogPosition();
loadables.load(setDialogPosition);
if ($child.hasClass('autoclose')) {
$(theDialog.blockout).click(function () {
theDialog.close();
});
}
} | [
"function",
"(",
"child",
",",
"parent",
",",
"context",
")",
"{",
"var",
"theDialog",
"=",
"dialog",
".",
"getDialog",
"(",
"context",
".",
"model",
")",
";",
"var",
"$child",
"=",
"$",
"(",
"child",
")",
";",
"var",
"loadables",
"=",
"$child",
".",
"find",
"(",
"\"img\"",
")",
".",
"filter",
"(",
"function",
"(",
")",
"{",
"var",
"$this",
"=",
"$",
"(",
"this",
")",
";",
"return",
"!",
"(",
"this",
".",
"style",
".",
"width",
"&&",
"this",
".",
"style",
".",
"height",
")",
"&&",
"!",
"(",
"$this",
".",
"attr",
"(",
"\"width\"",
")",
"&&",
"$this",
".",
"attr",
"(",
"\"height\"",
")",
")",
";",
"}",
")",
";",
"$child",
".",
"data",
"(",
"\"predefinedWidth\"",
",",
"$child",
".",
"get",
"(",
"0",
")",
".",
"style",
".",
"width",
")",
";",
"var",
"setDialogPosition",
"=",
"function",
"(",
")",
"{",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"if",
"(",
"!",
"$child",
".",
"data",
"(",
"\"predefinedWidth\"",
")",
")",
"{",
"$child",
".",
"css",
"(",
"{",
"width",
":",
"''",
"}",
")",
";",
"}",
"var",
"width",
"=",
"$child",
".",
"outerWidth",
"(",
"false",
")",
";",
"var",
"height",
"=",
"$child",
".",
"outerHeight",
"(",
"false",
")",
";",
"var",
"windowHeight",
"=",
"$",
"(",
"window",
")",
".",
"height",
"(",
")",
";",
"var",
"constrainedHeight",
"=",
"Math",
".",
"min",
"(",
"height",
",",
"windowHeight",
")",
";",
"$child",
".",
"css",
"(",
"{",
"'margin-top'",
":",
"(",
"-",
"constrainedHeight",
"/",
"2",
")",
".",
"toString",
"(",
")",
"+",
"'px'",
",",
"'margin-left'",
":",
"(",
"-",
"width",
"/",
"2",
")",
".",
"toString",
"(",
")",
"+",
"'px'",
"}",
")",
";",
"if",
"(",
"!",
"$child",
".",
"data",
"(",
"\"predefinedWidth\"",
")",
")",
"{",
"$child",
".",
"outerWidth",
"(",
"width",
")",
";",
"}",
"if",
"(",
"height",
">",
"windowHeight",
")",
"{",
"$child",
".",
"css",
"(",
"\"overflow-y\"",
",",
"\"auto\"",
")",
";",
"}",
"else",
"{",
"$child",
".",
"css",
"(",
"\"overflow-y\"",
",",
"\"\"",
")",
";",
"}",
"$",
"(",
"theDialog",
".",
"host",
")",
".",
"css",
"(",
"'opacity'",
",",
"1",
")",
";",
"$child",
".",
"css",
"(",
"\"visibility\"",
",",
"\"visible\"",
")",
";",
"$child",
".",
"find",
"(",
"'.autofocus'",
")",
".",
"first",
"(",
")",
".",
"focus",
"(",
")",
";",
"}",
",",
"1",
")",
";",
"}",
";",
"setDialogPosition",
"(",
")",
";",
"loadables",
".",
"load",
"(",
"setDialogPosition",
")",
";",
"if",
"(",
"$child",
".",
"hasClass",
"(",
"'autoclose'",
")",
")",
"{",
"$",
"(",
"theDialog",
".",
"blockout",
")",
".",
"click",
"(",
"function",
"(",
")",
"{",
"theDialog",
".",
"close",
"(",
")",
";",
"}",
")",
";",
"}",
"}"
] | This function is called after the modal is fully composed into the DOM, allowing your implementation to do any final modifications, such as positioning or animation. You can obtain the original dialog object by using `getDialog` on context.model.
@method compositionComplete
@param {DOMElement} child The dialog view.
@param {DOMElement} parent The parent view.
@param {object} context The composition context. | [
"This",
"function",
"is",
"called",
"after",
"the",
"modal",
"is",
"fully",
"composed",
"into",
"the",
"DOM",
"allowing",
"your",
"implementation",
"to",
"do",
"any",
"final",
"modifications",
"such",
"as",
"positioning",
"or",
"animation",
".",
"You",
"can",
"obtain",
"the",
"original",
"dialog",
"object",
"by",
"using",
"getDialog",
"on",
"context",
".",
"model",
"."
] | 4eacd22fcc567a372e04e6de443b0228572d6400 | https://github.com/welldone-software/gulp-durandal/blob/4eacd22fcc567a372e04e6de443b0228572d6400/examples/HTML StarterKit/lib/durandal/js/plugins/dialog.js#L381-L435 | train |
|
welldone-software/gulp-durandal | examples/HTML StarterKit/lib/durandal/js/composition.js | function(name, config, initOptionsFactory){
var key,
dataKey = 'composition-handler-' + name,
handler;
config = config || ko.bindingHandlers[name];
initOptionsFactory = initOptionsFactory || function(){ return undefined; };
handler = ko.bindingHandlers[name] = {
init: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
if(compositionCount > 0){
var data = {
trigger:ko.observable(null)
};
composition.current.complete(function(){
if(config.init){
config.init(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext);
}
if(config.update){
ko.utils.domData.set(element, dataKey, config);
data.trigger('trigger');
}
});
ko.utils.domData.set(element, dataKey, data);
}else{
ko.utils.domData.set(element, dataKey, config);
if(config.init){
config.init(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext);
}
}
return initOptionsFactory(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext);
},
update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var data = ko.utils.domData.get(element, dataKey);
if(data.update){
return data.update(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext);
}
if(data.trigger){
data.trigger();
}
}
};
for (key in config) {
if (key !== "init" && key !== "update") {
handler[key] = config[key];
}
}
} | javascript | function(name, config, initOptionsFactory){
var key,
dataKey = 'composition-handler-' + name,
handler;
config = config || ko.bindingHandlers[name];
initOptionsFactory = initOptionsFactory || function(){ return undefined; };
handler = ko.bindingHandlers[name] = {
init: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
if(compositionCount > 0){
var data = {
trigger:ko.observable(null)
};
composition.current.complete(function(){
if(config.init){
config.init(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext);
}
if(config.update){
ko.utils.domData.set(element, dataKey, config);
data.trigger('trigger');
}
});
ko.utils.domData.set(element, dataKey, data);
}else{
ko.utils.domData.set(element, dataKey, config);
if(config.init){
config.init(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext);
}
}
return initOptionsFactory(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext);
},
update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var data = ko.utils.domData.get(element, dataKey);
if(data.update){
return data.update(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext);
}
if(data.trigger){
data.trigger();
}
}
};
for (key in config) {
if (key !== "init" && key !== "update") {
handler[key] = config[key];
}
}
} | [
"function",
"(",
"name",
",",
"config",
",",
"initOptionsFactory",
")",
"{",
"var",
"key",
",",
"dataKey",
"=",
"'composition-handler-'",
"+",
"name",
",",
"handler",
";",
"config",
"=",
"config",
"||",
"ko",
".",
"bindingHandlers",
"[",
"name",
"]",
";",
"initOptionsFactory",
"=",
"initOptionsFactory",
"||",
"function",
"(",
")",
"{",
"return",
"undefined",
";",
"}",
";",
"handler",
"=",
"ko",
".",
"bindingHandlers",
"[",
"name",
"]",
"=",
"{",
"init",
":",
"function",
"(",
"element",
",",
"valueAccessor",
",",
"allBindingsAccessor",
",",
"viewModel",
",",
"bindingContext",
")",
"{",
"if",
"(",
"compositionCount",
">",
"0",
")",
"{",
"var",
"data",
"=",
"{",
"trigger",
":",
"ko",
".",
"observable",
"(",
"null",
")",
"}",
";",
"composition",
".",
"current",
".",
"complete",
"(",
"function",
"(",
")",
"{",
"if",
"(",
"config",
".",
"init",
")",
"{",
"config",
".",
"init",
"(",
"element",
",",
"valueAccessor",
",",
"allBindingsAccessor",
",",
"viewModel",
",",
"bindingContext",
")",
";",
"}",
"if",
"(",
"config",
".",
"update",
")",
"{",
"ko",
".",
"utils",
".",
"domData",
".",
"set",
"(",
"element",
",",
"dataKey",
",",
"config",
")",
";",
"data",
".",
"trigger",
"(",
"'trigger'",
")",
";",
"}",
"}",
")",
";",
"ko",
".",
"utils",
".",
"domData",
".",
"set",
"(",
"element",
",",
"dataKey",
",",
"data",
")",
";",
"}",
"else",
"{",
"ko",
".",
"utils",
".",
"domData",
".",
"set",
"(",
"element",
",",
"dataKey",
",",
"config",
")",
";",
"if",
"(",
"config",
".",
"init",
")",
"{",
"config",
".",
"init",
"(",
"element",
",",
"valueAccessor",
",",
"allBindingsAccessor",
",",
"viewModel",
",",
"bindingContext",
")",
";",
"}",
"}",
"return",
"initOptionsFactory",
"(",
"element",
",",
"valueAccessor",
",",
"allBindingsAccessor",
",",
"viewModel",
",",
"bindingContext",
")",
";",
"}",
",",
"update",
":",
"function",
"(",
"element",
",",
"valueAccessor",
",",
"allBindingsAccessor",
",",
"viewModel",
",",
"bindingContext",
")",
"{",
"var",
"data",
"=",
"ko",
".",
"utils",
".",
"domData",
".",
"get",
"(",
"element",
",",
"dataKey",
")",
";",
"if",
"(",
"data",
".",
"update",
")",
"{",
"return",
"data",
".",
"update",
"(",
"element",
",",
"valueAccessor",
",",
"allBindingsAccessor",
",",
"viewModel",
",",
"bindingContext",
")",
";",
"}",
"if",
"(",
"data",
".",
"trigger",
")",
"{",
"data",
".",
"trigger",
"(",
")",
";",
"}",
"}",
"}",
";",
"for",
"(",
"key",
"in",
"config",
")",
"{",
"if",
"(",
"key",
"!==",
"\"init\"",
"&&",
"key",
"!==",
"\"update\"",
")",
"{",
"handler",
"[",
"key",
"]",
"=",
"config",
"[",
"key",
"]",
";",
"}",
"}",
"}"
] | Registers a binding handler that will be invoked when the current composition transaction is complete.
@method addBindingHandler
@param {string} name The name of the binding handler.
@param {object} [config] The binding handler instance. If none is provided, the name will be used to look up an existing handler which will then be converted to a composition handler.
@param {function} [initOptionsFactory] If the registered binding needs to return options from its init call back to knockout, this function will server as a factory for those options. It will receive the same parameters that the init function does. | [
"Registers",
"a",
"binding",
"handler",
"that",
"will",
"be",
"invoked",
"when",
"the",
"current",
"composition",
"transaction",
"is",
"complete",
"."
] | 4eacd22fcc567a372e04e6de443b0228572d6400 | https://github.com/welldone-software/gulp-durandal/blob/4eacd22fcc567a372e04e6de443b0228572d6400/examples/HTML StarterKit/lib/durandal/js/composition.js#L287-L342 | train |
|
welldone-software/gulp-durandal | examples/HTML StarterKit/lib/durandal/js/composition.js | function(elements, parts, isReplacementSearch) {
parts = parts || {};
if (!elements) {
return parts;
}
if (elements.length === undefined) {
elements = [elements];
}
for (var i = 0, length = elements.length; i < length; i++) {
var element = elements[i];
if (element.getAttribute) {
if(!isReplacementSearch && hasComposition(element)){
continue;
}
var id = element.getAttribute(partAttributeName);
if (id) {
parts[id] = element;
}
if(!isReplacementSearch && element.hasChildNodes()){
composition.getParts(element.childNodes, parts);
}
}
}
return parts;
} | javascript | function(elements, parts, isReplacementSearch) {
parts = parts || {};
if (!elements) {
return parts;
}
if (elements.length === undefined) {
elements = [elements];
}
for (var i = 0, length = elements.length; i < length; i++) {
var element = elements[i];
if (element.getAttribute) {
if(!isReplacementSearch && hasComposition(element)){
continue;
}
var id = element.getAttribute(partAttributeName);
if (id) {
parts[id] = element;
}
if(!isReplacementSearch && element.hasChildNodes()){
composition.getParts(element.childNodes, parts);
}
}
}
return parts;
} | [
"function",
"(",
"elements",
",",
"parts",
",",
"isReplacementSearch",
")",
"{",
"parts",
"=",
"parts",
"||",
"{",
"}",
";",
"if",
"(",
"!",
"elements",
")",
"{",
"return",
"parts",
";",
"}",
"if",
"(",
"elements",
".",
"length",
"===",
"undefined",
")",
"{",
"elements",
"=",
"[",
"elements",
"]",
";",
"}",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"length",
"=",
"elements",
".",
"length",
";",
"i",
"<",
"length",
";",
"i",
"++",
")",
"{",
"var",
"element",
"=",
"elements",
"[",
"i",
"]",
";",
"if",
"(",
"element",
".",
"getAttribute",
")",
"{",
"if",
"(",
"!",
"isReplacementSearch",
"&&",
"hasComposition",
"(",
"element",
")",
")",
"{",
"continue",
";",
"}",
"var",
"id",
"=",
"element",
".",
"getAttribute",
"(",
"partAttributeName",
")",
";",
"if",
"(",
"id",
")",
"{",
"parts",
"[",
"id",
"]",
"=",
"element",
";",
"}",
"if",
"(",
"!",
"isReplacementSearch",
"&&",
"element",
".",
"hasChildNodes",
"(",
")",
")",
"{",
"composition",
".",
"getParts",
"(",
"element",
".",
"childNodes",
",",
"parts",
")",
";",
"}",
"}",
"}",
"return",
"parts",
";",
"}"
] | Gets an object keyed with all the elements that are replacable parts, found within the supplied elements. The key will be the part name and the value will be the element itself.
@method getParts
@param {DOMElement\DOMElement[]} elements The element(s) to search for parts.
@return {object} An object keyed by part. | [
"Gets",
"an",
"object",
"keyed",
"with",
"all",
"the",
"elements",
"that",
"are",
"replacable",
"parts",
"found",
"within",
"the",
"supplied",
"elements",
".",
"The",
"key",
"will",
"be",
"the",
"part",
"name",
"and",
"the",
"value",
"will",
"be",
"the",
"element",
"itself",
"."
] | 4eacd22fcc567a372e04e6de443b0228572d6400 | https://github.com/welldone-software/gulp-durandal/blob/4eacd22fcc567a372e04e6de443b0228572d6400/examples/HTML StarterKit/lib/durandal/js/composition.js#L349-L380 | train |
|
welldone-software/gulp-durandal | examples/HTML StarterKit/lib/durandal/js/composition.js | function (element, settings, bindingContext, fromBinding) {
compositionCount++;
if(!fromBinding){
settings = composition.getSettings(function() { return settings; }, element);
}
if (settings.compositionComplete) {
compositionCompleteCallbacks.push(function () {
settings.compositionComplete(settings.child, settings.parent, settings);
});
}
compositionCompleteCallbacks.push(function () {
if(settings.composingNewView && settings.model && settings.model.compositionComplete){
settings.model.compositionComplete(settings.child, settings.parent, settings);
}
});
var hostState = getHostState(element);
settings.activeView = hostState.activeView;
settings.parent = element;
settings.triggerAttach = triggerAttach;
settings.bindingContext = bindingContext;
if (settings.cacheViews && !settings.viewElements) {
settings.viewElements = hostState.childElements;
}
if (!settings.model) {
if (!settings.view) {
this.bindAndShow(null, settings);
} else {
settings.area = settings.area || 'partial';
settings.preserveContext = true;
viewLocator.locateView(settings.view, settings.area, settings.viewElements).then(function (child) {
composition.bindAndShow(child, settings);
});
}
} else if (system.isString(settings.model)) {
system.acquire(settings.model).then(function (module) {
settings.model = system.resolveObject(module);
composition.inject(settings);
}).fail(function(err){
system.error('Failed to load composed module (' + settings.model + '). Details: ' + err.message);
});
} else {
composition.inject(settings);
}
} | javascript | function (element, settings, bindingContext, fromBinding) {
compositionCount++;
if(!fromBinding){
settings = composition.getSettings(function() { return settings; }, element);
}
if (settings.compositionComplete) {
compositionCompleteCallbacks.push(function () {
settings.compositionComplete(settings.child, settings.parent, settings);
});
}
compositionCompleteCallbacks.push(function () {
if(settings.composingNewView && settings.model && settings.model.compositionComplete){
settings.model.compositionComplete(settings.child, settings.parent, settings);
}
});
var hostState = getHostState(element);
settings.activeView = hostState.activeView;
settings.parent = element;
settings.triggerAttach = triggerAttach;
settings.bindingContext = bindingContext;
if (settings.cacheViews && !settings.viewElements) {
settings.viewElements = hostState.childElements;
}
if (!settings.model) {
if (!settings.view) {
this.bindAndShow(null, settings);
} else {
settings.area = settings.area || 'partial';
settings.preserveContext = true;
viewLocator.locateView(settings.view, settings.area, settings.viewElements).then(function (child) {
composition.bindAndShow(child, settings);
});
}
} else if (system.isString(settings.model)) {
system.acquire(settings.model).then(function (module) {
settings.model = system.resolveObject(module);
composition.inject(settings);
}).fail(function(err){
system.error('Failed to load composed module (' + settings.model + '). Details: ' + err.message);
});
} else {
composition.inject(settings);
}
} | [
"function",
"(",
"element",
",",
"settings",
",",
"bindingContext",
",",
"fromBinding",
")",
"{",
"compositionCount",
"++",
";",
"if",
"(",
"!",
"fromBinding",
")",
"{",
"settings",
"=",
"composition",
".",
"getSettings",
"(",
"function",
"(",
")",
"{",
"return",
"settings",
";",
"}",
",",
"element",
")",
";",
"}",
"if",
"(",
"settings",
".",
"compositionComplete",
")",
"{",
"compositionCompleteCallbacks",
".",
"push",
"(",
"function",
"(",
")",
"{",
"settings",
".",
"compositionComplete",
"(",
"settings",
".",
"child",
",",
"settings",
".",
"parent",
",",
"settings",
")",
";",
"}",
")",
";",
"}",
"compositionCompleteCallbacks",
".",
"push",
"(",
"function",
"(",
")",
"{",
"if",
"(",
"settings",
".",
"composingNewView",
"&&",
"settings",
".",
"model",
"&&",
"settings",
".",
"model",
".",
"compositionComplete",
")",
"{",
"settings",
".",
"model",
".",
"compositionComplete",
"(",
"settings",
".",
"child",
",",
"settings",
".",
"parent",
",",
"settings",
")",
";",
"}",
"}",
")",
";",
"var",
"hostState",
"=",
"getHostState",
"(",
"element",
")",
";",
"settings",
".",
"activeView",
"=",
"hostState",
".",
"activeView",
";",
"settings",
".",
"parent",
"=",
"element",
";",
"settings",
".",
"triggerAttach",
"=",
"triggerAttach",
";",
"settings",
".",
"bindingContext",
"=",
"bindingContext",
";",
"if",
"(",
"settings",
".",
"cacheViews",
"&&",
"!",
"settings",
".",
"viewElements",
")",
"{",
"settings",
".",
"viewElements",
"=",
"hostState",
".",
"childElements",
";",
"}",
"if",
"(",
"!",
"settings",
".",
"model",
")",
"{",
"if",
"(",
"!",
"settings",
".",
"view",
")",
"{",
"this",
".",
"bindAndShow",
"(",
"null",
",",
"settings",
")",
";",
"}",
"else",
"{",
"settings",
".",
"area",
"=",
"settings",
".",
"area",
"||",
"'partial'",
";",
"settings",
".",
"preserveContext",
"=",
"true",
";",
"viewLocator",
".",
"locateView",
"(",
"settings",
".",
"view",
",",
"settings",
".",
"area",
",",
"settings",
".",
"viewElements",
")",
".",
"then",
"(",
"function",
"(",
"child",
")",
"{",
"composition",
".",
"bindAndShow",
"(",
"child",
",",
"settings",
")",
";",
"}",
")",
";",
"}",
"}",
"else",
"if",
"(",
"system",
".",
"isString",
"(",
"settings",
".",
"model",
")",
")",
"{",
"system",
".",
"acquire",
"(",
"settings",
".",
"model",
")",
".",
"then",
"(",
"function",
"(",
"module",
")",
"{",
"settings",
".",
"model",
"=",
"system",
".",
"resolveObject",
"(",
"module",
")",
";",
"composition",
".",
"inject",
"(",
"settings",
")",
";",
"}",
")",
".",
"fail",
"(",
"function",
"(",
"err",
")",
"{",
"system",
".",
"error",
"(",
"'Failed to load composed module ('",
"+",
"settings",
".",
"model",
"+",
"'). Details: '",
"+",
"err",
".",
"message",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"composition",
".",
"inject",
"(",
"settings",
")",
";",
"}",
"}"
] | Initiates a composition.
@method compose
@param {DOMElement} element The DOMElement or knockout virtual element that serves as the parent for the composition.
@param {object} settings The composition settings.
@param {object} [bindingContext] The current binding context. | [
"Initiates",
"a",
"composition",
"."
] | 4eacd22fcc567a372e04e6de443b0228572d6400 | https://github.com/welldone-software/gulp-durandal/blob/4eacd22fcc567a372e04e6de443b0228572d6400/examples/HTML StarterKit/lib/durandal/js/composition.js#L603-L654 | train |
|
particle-iot/particle-library-manager | src/librepo_fs.js | removeFailedPredicate | function removeFailedPredicate(predicates, items) {
return items.filter((_,i) => predicates[i]===true);
} | javascript | function removeFailedPredicate(predicates, items) {
return items.filter((_,i) => predicates[i]===true);
} | [
"function",
"removeFailedPredicate",
"(",
"predicates",
",",
"items",
")",
"{",
"return",
"items",
".",
"filter",
"(",
"(",
"_",
",",
"i",
")",
"=>",
"predicates",
"[",
"i",
"]",
"===",
"true",
")",
";",
"}"
] | Filters a given array and removes all with a non-truthy vale in the corresponding predicate index.
@param {Array} predicates The predicates for each item to filter.
@param {Array} items The items to filter.
@returns {Array<T>} The itmes array with all those that didn't satisfy the predicate removed. | [
"Filters",
"a",
"given",
"array",
"and",
"removes",
"all",
"with",
"a",
"non",
"-",
"truthy",
"vale",
"in",
"the",
"corresponding",
"predicate",
"index",
"."
] | 5501feabc31f5f7572203a5fc4b262e249627e90 | https://github.com/particle-iot/particle-library-manager/blob/5501feabc31f5f7572203a5fc4b262e249627e90/src/librepo_fs.js#L64-L66 | train |
welldone-software/gulp-durandal | examples/HTML StarterKit/lib/durandal/js/plugins/serializer.js | function(object, settings) {
settings = (settings === undefined) ? {} : settings;
if(system.isString(settings) || system.isNumber(settings)) {
settings = { space: settings };
}
return JSON.stringify(object, settings.replacer || this.replacer, settings.space || this.space);
} | javascript | function(object, settings) {
settings = (settings === undefined) ? {} : settings;
if(system.isString(settings) || system.isNumber(settings)) {
settings = { space: settings };
}
return JSON.stringify(object, settings.replacer || this.replacer, settings.space || this.space);
} | [
"function",
"(",
"object",
",",
"settings",
")",
"{",
"settings",
"=",
"(",
"settings",
"===",
"undefined",
")",
"?",
"{",
"}",
":",
"settings",
";",
"if",
"(",
"system",
".",
"isString",
"(",
"settings",
")",
"||",
"system",
".",
"isNumber",
"(",
"settings",
")",
")",
"{",
"settings",
"=",
"{",
"space",
":",
"settings",
"}",
";",
"}",
"return",
"JSON",
".",
"stringify",
"(",
"object",
",",
"settings",
".",
"replacer",
"||",
"this",
".",
"replacer",
",",
"settings",
".",
"space",
"||",
"this",
".",
"space",
")",
";",
"}"
] | Serializes the object.
@method serialize
@param {object} object The object to serialize.
@param {object} [settings] Settings can specify a replacer or space to override the serializer defaults.
@return {string} The JSON string. | [
"Serializes",
"the",
"object",
"."
] | 4eacd22fcc567a372e04e6de443b0228572d6400 | https://github.com/welldone-software/gulp-durandal/blob/4eacd22fcc567a372e04e6de443b0228572d6400/examples/HTML StarterKit/lib/durandal/js/plugins/serializer.js#L53-L61 | train |
|
welldone-software/gulp-durandal | examples/HTML StarterKit/lib/durandal/js/plugins/serializer.js | function(key, value, getTypeId, getConstructor) {
var typeId = getTypeId(value);
if (typeId) {
var ctor = getConstructor(typeId);
if (ctor) {
if (ctor.fromJSON) {
return ctor.fromJSON(value);
}
return new ctor(value);
}
}
return value;
} | javascript | function(key, value, getTypeId, getConstructor) {
var typeId = getTypeId(value);
if (typeId) {
var ctor = getConstructor(typeId);
if (ctor) {
if (ctor.fromJSON) {
return ctor.fromJSON(value);
}
return new ctor(value);
}
}
return value;
} | [
"function",
"(",
"key",
",",
"value",
",",
"getTypeId",
",",
"getConstructor",
")",
"{",
"var",
"typeId",
"=",
"getTypeId",
"(",
"value",
")",
";",
"if",
"(",
"typeId",
")",
"{",
"var",
"ctor",
"=",
"getConstructor",
"(",
"typeId",
")",
";",
"if",
"(",
"ctor",
")",
"{",
"if",
"(",
"ctor",
".",
"fromJSON",
")",
"{",
"return",
"ctor",
".",
"fromJSON",
"(",
"value",
")",
";",
"}",
"return",
"new",
"ctor",
"(",
"value",
")",
";",
"}",
"}",
"return",
"value",
";",
"}"
] | The default reviver function used during deserialization. By default is detects type properties on objects and uses them to re-construct the correct object using the provided constructor mapping.
@method reviver
@param {string} key The attribute key.
@param {object} value The object value associated with the key.
@param {function} getTypeId A custom function used to get the type id from a value.
@param {object} getConstructor A custom function used to get the constructor function associated with a type id.
@return {object} The value. | [
"The",
"default",
"reviver",
"function",
"used",
"during",
"deserialization",
".",
"By",
"default",
"is",
"detects",
"type",
"properties",
"on",
"objects",
"and",
"uses",
"them",
"to",
"re",
"-",
"construct",
"the",
"correct",
"object",
"using",
"the",
"provided",
"constructor",
"mapping",
"."
] | 4eacd22fcc567a372e04e6de443b0228572d6400 | https://github.com/welldone-software/gulp-durandal/blob/4eacd22fcc567a372e04e6de443b0228572d6400/examples/HTML StarterKit/lib/durandal/js/plugins/serializer.js#L105-L119 | train |
|
welldone-software/gulp-durandal | examples/HTML StarterKit/lib/durandal/js/plugins/serializer.js | function(text, settings) {
var that = this;
settings = settings || {};
var getTypeId = settings.getTypeId || function(object) { return that.getTypeId(object); };
var getConstructor = settings.getConstructor || function(id) { return that.typeMap[id]; };
var reviver = settings.reviver || function(key, value) { return that.reviver(key, value, getTypeId, getConstructor); };
return JSON.parse(text, reviver);
} | javascript | function(text, settings) {
var that = this;
settings = settings || {};
var getTypeId = settings.getTypeId || function(object) { return that.getTypeId(object); };
var getConstructor = settings.getConstructor || function(id) { return that.typeMap[id]; };
var reviver = settings.reviver || function(key, value) { return that.reviver(key, value, getTypeId, getConstructor); };
return JSON.parse(text, reviver);
} | [
"function",
"(",
"text",
",",
"settings",
")",
"{",
"var",
"that",
"=",
"this",
";",
"settings",
"=",
"settings",
"||",
"{",
"}",
";",
"var",
"getTypeId",
"=",
"settings",
".",
"getTypeId",
"||",
"function",
"(",
"object",
")",
"{",
"return",
"that",
".",
"getTypeId",
"(",
"object",
")",
";",
"}",
";",
"var",
"getConstructor",
"=",
"settings",
".",
"getConstructor",
"||",
"function",
"(",
"id",
")",
"{",
"return",
"that",
".",
"typeMap",
"[",
"id",
"]",
";",
"}",
";",
"var",
"reviver",
"=",
"settings",
".",
"reviver",
"||",
"function",
"(",
"key",
",",
"value",
")",
"{",
"return",
"that",
".",
"reviver",
"(",
"key",
",",
"value",
",",
"getTypeId",
",",
"getConstructor",
")",
";",
"}",
";",
"return",
"JSON",
".",
"parse",
"(",
"text",
",",
"reviver",
")",
";",
"}"
] | Deserialize the JSON.
@method deserialize
@param {string} text The JSON string.
@param {object} [settings] Settings can specify a reviver, getTypeId function or getConstructor function.
@return {object} The deserialized object. | [
"Deserialize",
"the",
"JSON",
"."
] | 4eacd22fcc567a372e04e6de443b0228572d6400 | https://github.com/welldone-software/gulp-durandal/blob/4eacd22fcc567a372e04e6de443b0228572d6400/examples/HTML StarterKit/lib/durandal/js/plugins/serializer.js#L127-L136 | train |
|
gridcontrol/gridcontrol | src/tasks_manager/task_manager.js | function(opts) {
if (!opts) opts = {};
this.port_offset = opts.port_offset ? parseInt(opts.port_offset) : 10001;
this.task_list = {};
this.can_accept_queries = false;
this.can_local_compute = true;
this.app_folder = opts.app_folder;
var pm2_opts = {};
if (process.env.NODE_ENV == 'test') {
pm2_opts = {
independent : true,
daemon_mode : true
};
}
this.pm2 = new PM2.custom(pm2_opts);
// Defaults values
this.task_meta = {
instances : 0,
json_conf : null,
task_folder : 'tasks',
env : {}
};
if (opts.task_meta)
this.task_meta = opts.task_meta;
this.controller = Controller;
} | javascript | function(opts) {
if (!opts) opts = {};
this.port_offset = opts.port_offset ? parseInt(opts.port_offset) : 10001;
this.task_list = {};
this.can_accept_queries = false;
this.can_local_compute = true;
this.app_folder = opts.app_folder;
var pm2_opts = {};
if (process.env.NODE_ENV == 'test') {
pm2_opts = {
independent : true,
daemon_mode : true
};
}
this.pm2 = new PM2.custom(pm2_opts);
// Defaults values
this.task_meta = {
instances : 0,
json_conf : null,
task_folder : 'tasks',
env : {}
};
if (opts.task_meta)
this.task_meta = opts.task_meta;
this.controller = Controller;
} | [
"function",
"(",
"opts",
")",
"{",
"if",
"(",
"!",
"opts",
")",
"opts",
"=",
"{",
"}",
";",
"this",
".",
"port_offset",
"=",
"opts",
".",
"port_offset",
"?",
"parseInt",
"(",
"opts",
".",
"port_offset",
")",
":",
"10001",
";",
"this",
".",
"task_list",
"=",
"{",
"}",
";",
"this",
".",
"can_accept_queries",
"=",
"false",
";",
"this",
".",
"can_local_compute",
"=",
"true",
";",
"this",
".",
"app_folder",
"=",
"opts",
".",
"app_folder",
";",
"var",
"pm2_opts",
"=",
"{",
"}",
";",
"if",
"(",
"process",
".",
"env",
".",
"NODE_ENV",
"==",
"'test'",
")",
"{",
"pm2_opts",
"=",
"{",
"independent",
":",
"true",
",",
"daemon_mode",
":",
"true",
"}",
";",
"}",
"this",
".",
"pm2",
"=",
"new",
"PM2",
".",
"custom",
"(",
"pm2_opts",
")",
";",
"this",
".",
"task_meta",
"=",
"{",
"instances",
":",
"0",
",",
"json_conf",
":",
"null",
",",
"task_folder",
":",
"'tasks'",
",",
"env",
":",
"{",
"}",
"}",
";",
"if",
"(",
"opts",
".",
"task_meta",
")",
"this",
".",
"task_meta",
"=",
"opts",
".",
"task_meta",
";",
"this",
".",
"controller",
"=",
"Controller",
";",
"}"
] | The Task Manager manage Tasks and PM2
@constructor
@param {Object} opts options
@param {Integer} opts.port_offset Port to start on
@param {String} opts.app_folder application to cwd to | [
"The",
"Task",
"Manager",
"manage",
"Tasks",
"and",
"PM2"
] | b3f5cc27c5fb24df010133cc34ba101d1561c9e0 | https://github.com/gridcontrol/gridcontrol/blob/b3f5cc27c5fb24df010133cc34ba101d1561c9e0/src/tasks_manager/task_manager.js#L19-L51 | train |
|
welldone-software/gulp-durandal | examples/HTML StarterKit/lib/durandal/js/plugins/observable.js | convertProperty | function convertProperty(obj, propertyName, original){
var observable,
isArray,
lookup = obj.__observable__ || (obj.__observable__ = {});
if(original === undefined){
original = obj[propertyName];
}
if (system.isArray(original)) {
observable = ko.observableArray(original);
makeObservableArray(original, observable);
isArray = true;
} else if (typeof original == "function") {
if(ko.isObservable(original)){
observable = original;
}else{
return null;
}
} else if(system.isPromise(original)) {
observable = ko.observable();
original.then(function (result) {
if(system.isArray(result)) {
var oa = ko.observableArray(result);
makeObservableArray(result, oa);
result = oa;
}
observable(result);
});
} else {
observable = ko.observable(original);
convertObject(original);
}
Object.defineProperty(obj, propertyName, {
configurable: true,
enumerable: true,
get: observable,
set: ko.isWriteableObservable(observable) ? (function (newValue) {
if (newValue && system.isPromise(newValue)) {
newValue.then(function (result) {
innerSetter(observable, result, system.isArray(result));
});
} else {
innerSetter(observable, newValue, isArray);
}
}) : undefined
});
lookup[propertyName] = observable;
return observable;
} | javascript | function convertProperty(obj, propertyName, original){
var observable,
isArray,
lookup = obj.__observable__ || (obj.__observable__ = {});
if(original === undefined){
original = obj[propertyName];
}
if (system.isArray(original)) {
observable = ko.observableArray(original);
makeObservableArray(original, observable);
isArray = true;
} else if (typeof original == "function") {
if(ko.isObservable(original)){
observable = original;
}else{
return null;
}
} else if(system.isPromise(original)) {
observable = ko.observable();
original.then(function (result) {
if(system.isArray(result)) {
var oa = ko.observableArray(result);
makeObservableArray(result, oa);
result = oa;
}
observable(result);
});
} else {
observable = ko.observable(original);
convertObject(original);
}
Object.defineProperty(obj, propertyName, {
configurable: true,
enumerable: true,
get: observable,
set: ko.isWriteableObservable(observable) ? (function (newValue) {
if (newValue && system.isPromise(newValue)) {
newValue.then(function (result) {
innerSetter(observable, result, system.isArray(result));
});
} else {
innerSetter(observable, newValue, isArray);
}
}) : undefined
});
lookup[propertyName] = observable;
return observable;
} | [
"function",
"convertProperty",
"(",
"obj",
",",
"propertyName",
",",
"original",
")",
"{",
"var",
"observable",
",",
"isArray",
",",
"lookup",
"=",
"obj",
".",
"__observable__",
"||",
"(",
"obj",
".",
"__observable__",
"=",
"{",
"}",
")",
";",
"if",
"(",
"original",
"===",
"undefined",
")",
"{",
"original",
"=",
"obj",
"[",
"propertyName",
"]",
";",
"}",
"if",
"(",
"system",
".",
"isArray",
"(",
"original",
")",
")",
"{",
"observable",
"=",
"ko",
".",
"observableArray",
"(",
"original",
")",
";",
"makeObservableArray",
"(",
"original",
",",
"observable",
")",
";",
"isArray",
"=",
"true",
";",
"}",
"else",
"if",
"(",
"typeof",
"original",
"==",
"\"function\"",
")",
"{",
"if",
"(",
"ko",
".",
"isObservable",
"(",
"original",
")",
")",
"{",
"observable",
"=",
"original",
";",
"}",
"else",
"{",
"return",
"null",
";",
"}",
"}",
"else",
"if",
"(",
"system",
".",
"isPromise",
"(",
"original",
")",
")",
"{",
"observable",
"=",
"ko",
".",
"observable",
"(",
")",
";",
"original",
".",
"then",
"(",
"function",
"(",
"result",
")",
"{",
"if",
"(",
"system",
".",
"isArray",
"(",
"result",
")",
")",
"{",
"var",
"oa",
"=",
"ko",
".",
"observableArray",
"(",
"result",
")",
";",
"makeObservableArray",
"(",
"result",
",",
"oa",
")",
";",
"result",
"=",
"oa",
";",
"}",
"observable",
"(",
"result",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"observable",
"=",
"ko",
".",
"observable",
"(",
"original",
")",
";",
"convertObject",
"(",
"original",
")",
";",
"}",
"Object",
".",
"defineProperty",
"(",
"obj",
",",
"propertyName",
",",
"{",
"configurable",
":",
"true",
",",
"enumerable",
":",
"true",
",",
"get",
":",
"observable",
",",
"set",
":",
"ko",
".",
"isWriteableObservable",
"(",
"observable",
")",
"?",
"(",
"function",
"(",
"newValue",
")",
"{",
"if",
"(",
"newValue",
"&&",
"system",
".",
"isPromise",
"(",
"newValue",
")",
")",
"{",
"newValue",
".",
"then",
"(",
"function",
"(",
"result",
")",
"{",
"innerSetter",
"(",
"observable",
",",
"result",
",",
"system",
".",
"isArray",
"(",
"result",
")",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"innerSetter",
"(",
"observable",
",",
"newValue",
",",
"isArray",
")",
";",
"}",
"}",
")",
":",
"undefined",
"}",
")",
";",
"lookup",
"[",
"propertyName",
"]",
"=",
"observable",
";",
"return",
"observable",
";",
"}"
] | Converts a normal property into an observable property using ES5 getters and setters.
@method convertProperty
@param {object} obj The target object on which the property to convert lives.
@param {string} propertyName The name of the property to convert.
@param {object} [original] The original value of the property. If not specified, it will be retrieved from the object.
@return {KnockoutObservable} The underlying observable. | [
"Converts",
"a",
"normal",
"property",
"into",
"an",
"observable",
"property",
"using",
"ES5",
"getters",
"and",
"setters",
"."
] | 4eacd22fcc567a372e04e6de443b0228572d6400 | https://github.com/welldone-software/gulp-durandal/blob/4eacd22fcc567a372e04e6de443b0228572d6400/examples/HTML StarterKit/lib/durandal/js/plugins/observable.js#L200-L253 | train |
welldone-software/gulp-durandal | examples/HTML StarterKit/lib/durandal/js/plugins/observable.js | defineProperty | function defineProperty(obj, propertyName, evaluatorOrOptions) {
var computedOptions = { owner: obj, deferEvaluation: true },
computed;
if (typeof evaluatorOrOptions === 'function') {
computedOptions.read = evaluatorOrOptions;
} else {
if ('value' in evaluatorOrOptions) {
system.error('For defineProperty, you must not specify a "value" for the property. You must provide a "get" function.');
}
if (typeof evaluatorOrOptions.get !== 'function') {
system.error('For defineProperty, the third parameter must be either an evaluator function, or an options object containing a function called "get".');
}
computedOptions.read = evaluatorOrOptions.get;
computedOptions.write = evaluatorOrOptions.set;
}
computed = ko.computed(computedOptions);
obj[propertyName] = computed;
return convertProperty(obj, propertyName, computed);
} | javascript | function defineProperty(obj, propertyName, evaluatorOrOptions) {
var computedOptions = { owner: obj, deferEvaluation: true },
computed;
if (typeof evaluatorOrOptions === 'function') {
computedOptions.read = evaluatorOrOptions;
} else {
if ('value' in evaluatorOrOptions) {
system.error('For defineProperty, you must not specify a "value" for the property. You must provide a "get" function.');
}
if (typeof evaluatorOrOptions.get !== 'function') {
system.error('For defineProperty, the third parameter must be either an evaluator function, or an options object containing a function called "get".');
}
computedOptions.read = evaluatorOrOptions.get;
computedOptions.write = evaluatorOrOptions.set;
}
computed = ko.computed(computedOptions);
obj[propertyName] = computed;
return convertProperty(obj, propertyName, computed);
} | [
"function",
"defineProperty",
"(",
"obj",
",",
"propertyName",
",",
"evaluatorOrOptions",
")",
"{",
"var",
"computedOptions",
"=",
"{",
"owner",
":",
"obj",
",",
"deferEvaluation",
":",
"true",
"}",
",",
"computed",
";",
"if",
"(",
"typeof",
"evaluatorOrOptions",
"===",
"'function'",
")",
"{",
"computedOptions",
".",
"read",
"=",
"evaluatorOrOptions",
";",
"}",
"else",
"{",
"if",
"(",
"'value'",
"in",
"evaluatorOrOptions",
")",
"{",
"system",
".",
"error",
"(",
"'For defineProperty, you must not specify a \"value\" for the property. You must provide a \"get\" function.'",
")",
";",
"}",
"if",
"(",
"typeof",
"evaluatorOrOptions",
".",
"get",
"!==",
"'function'",
")",
"{",
"system",
".",
"error",
"(",
"'For defineProperty, the third parameter must be either an evaluator function, or an options object containing a function called \"get\".'",
")",
";",
"}",
"computedOptions",
".",
"read",
"=",
"evaluatorOrOptions",
".",
"get",
";",
"computedOptions",
".",
"write",
"=",
"evaluatorOrOptions",
".",
"set",
";",
"}",
"computed",
"=",
"ko",
".",
"computed",
"(",
"computedOptions",
")",
";",
"obj",
"[",
"propertyName",
"]",
"=",
"computed",
";",
"return",
"convertProperty",
"(",
"obj",
",",
"propertyName",
",",
"computed",
")",
";",
"}"
] | Defines a computed property using ES5 getters and setters.
@method defineProperty
@param {object} obj The target object on which to create the property.
@param {string} propertyName The name of the property to define.
@param {function|object} evaluatorOrOptions The Knockout computed function or computed options object.
@return {KnockoutObservable} The underlying computed observable. | [
"Defines",
"a",
"computed",
"property",
"using",
"ES5",
"getters",
"and",
"setters",
"."
] | 4eacd22fcc567a372e04e6de443b0228572d6400 | https://github.com/welldone-software/gulp-durandal/blob/4eacd22fcc567a372e04e6de443b0228572d6400/examples/HTML StarterKit/lib/durandal/js/plugins/observable.js#L263-L286 | train |
particle-iot/particle-library-manager | src/validation.js | _libraryFiles | function _libraryFiles(directory) {
return new Promise((fulfill) => {
const files = [];
klaw(directory)
.on('data', (item) => {
const relativePath = path.relative(directory, item.path);
files.push(relativePath);
})
.on('end', () => {
fulfill(files);
});
});
} | javascript | function _libraryFiles(directory) {
return new Promise((fulfill) => {
const files = [];
klaw(directory)
.on('data', (item) => {
const relativePath = path.relative(directory, item.path);
files.push(relativePath);
})
.on('end', () => {
fulfill(files);
});
});
} | [
"function",
"_libraryFiles",
"(",
"directory",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"fulfill",
")",
"=>",
"{",
"const",
"files",
"=",
"[",
"]",
";",
"klaw",
"(",
"directory",
")",
".",
"on",
"(",
"'data'",
",",
"(",
"item",
")",
"=>",
"{",
"const",
"relativePath",
"=",
"path",
".",
"relative",
"(",
"directory",
",",
"item",
".",
"path",
")",
";",
"files",
".",
"push",
"(",
"relativePath",
")",
";",
"}",
")",
".",
"on",
"(",
"'end'",
",",
"(",
")",
"=>",
"{",
"fulfill",
"(",
"files",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | Enumerate all files relative to the root of the library
@param {string} directory - root of the library
@returns {Promise} - resolves to array of relative paths
@private | [
"Enumerate",
"all",
"files",
"relative",
"to",
"the",
"root",
"of",
"the",
"library"
] | 5501feabc31f5f7572203a5fc4b262e249627e90 | https://github.com/particle-iot/particle-library-manager/blob/5501feabc31f5f7572203a5fc4b262e249627e90/src/validation.js#L174-L186 | train |
welldone-software/gulp-durandal | examples/HTML StarterKit/lib/durandal/js/plugins/http.js | function (url, query, callbackParam) {
if (url.indexOf('=?') == -1) {
callbackParam = callbackParam || this.callbackParam;
if (url.indexOf('?') == -1) {
url += '?';
} else {
url += '&';
}
url += callbackParam + '=?';
}
return $.ajax({
url: url,
dataType:'jsonp',
data:query
});
} | javascript | function (url, query, callbackParam) {
if (url.indexOf('=?') == -1) {
callbackParam = callbackParam || this.callbackParam;
if (url.indexOf('?') == -1) {
url += '?';
} else {
url += '&';
}
url += callbackParam + '=?';
}
return $.ajax({
url: url,
dataType:'jsonp',
data:query
});
} | [
"function",
"(",
"url",
",",
"query",
",",
"callbackParam",
")",
"{",
"if",
"(",
"url",
".",
"indexOf",
"(",
"'=?'",
")",
"==",
"-",
"1",
")",
"{",
"callbackParam",
"=",
"callbackParam",
"||",
"this",
".",
"callbackParam",
";",
"if",
"(",
"url",
".",
"indexOf",
"(",
"'?'",
")",
"==",
"-",
"1",
")",
"{",
"url",
"+=",
"'?'",
";",
"}",
"else",
"{",
"url",
"+=",
"'&'",
";",
"}",
"url",
"+=",
"callbackParam",
"+",
"'=?'",
";",
"}",
"return",
"$",
".",
"ajax",
"(",
"{",
"url",
":",
"url",
",",
"dataType",
":",
"'jsonp'",
",",
"data",
":",
"query",
"}",
")",
";",
"}"
] | Makes an JSONP request.
@method jsonp
@param {string} url The url to send the get request to.
@param {object} [query] An optional key/value object to transform into query string parameters.
@param {string} [callbackParam] The name of the callback parameter the api expects (overrides the default callbackParam).
@return {Promise} A promise of the response data. | [
"Makes",
"an",
"JSONP",
"request",
"."
] | 4eacd22fcc567a372e04e6de443b0228572d6400 | https://github.com/welldone-software/gulp-durandal/blob/4eacd22fcc567a372e04e6de443b0228572d6400/examples/HTML StarterKit/lib/durandal/js/plugins/http.js#L42-L60 | train |
|
welldone-software/gulp-durandal | examples/HTML StarterKit/lib/durandal/js/plugins/http.js | function(url, data) {
return $.ajax({
url: url,
data: ko.toJSON(data),
type: 'POST',
contentType: 'application/json',
dataType: 'json'
});
} | javascript | function(url, data) {
return $.ajax({
url: url,
data: ko.toJSON(data),
type: 'POST',
contentType: 'application/json',
dataType: 'json'
});
} | [
"function",
"(",
"url",
",",
"data",
")",
"{",
"return",
"$",
".",
"ajax",
"(",
"{",
"url",
":",
"url",
",",
"data",
":",
"ko",
".",
"toJSON",
"(",
"data",
")",
",",
"type",
":",
"'POST'",
",",
"contentType",
":",
"'application/json'",
",",
"dataType",
":",
"'json'",
"}",
")",
";",
"}"
] | Makes an HTTP POST request.
@method post
@param {string} url The url to send the post request to.
@param {object} data The data to post. It will be converted to JSON. If the data contains Knockout observables, they will be converted into normal properties before serialization.
@return {Promise} A promise of the response data. | [
"Makes",
"an",
"HTTP",
"POST",
"request",
"."
] | 4eacd22fcc567a372e04e6de443b0228572d6400 | https://github.com/welldone-software/gulp-durandal/blob/4eacd22fcc567a372e04e6de443b0228572d6400/examples/HTML StarterKit/lib/durandal/js/plugins/http.js#L68-L76 | train |
|
yoshuawuyts/fsm-event | index.js | fsmEvent | function fsmEvent (start, events) {
if (typeof start === 'object') {
events = start
start = 'START'
}
assert.equal(typeof start, 'string')
assert.equal(typeof events, 'object')
assert.ok(events[start], 'invalid starting state ' + start)
assert.ok(fsm.validate(events))
const emitter = new EventEmitter()
emit._graph = fsm.reachable(events)
emit._emitter = emitter
emit._events = events
emit._state = start
emit.emit = emit
emit.on = on
return emit
// set a state listener
// str, fn -> null
function on (event, cb) {
emitter.on(event, cb)
}
// change the state
// str -> null
function emit (str) {
const nwState = emit._events[emit._state][str]
if (!reach(emit._state, nwState, emit._graph)) {
const err = 'invalid transition: ' + emit._state + ' -> ' + str
return emitter.emit('error', err)
}
const leaveEv = emit._state + ':leave'
const enterEv = nwState + ':enter'
if (!emit._state) return enter()
return leave()
function leave () {
if (!emitter._events[leaveEv]) enter()
else emitter.emit(leaveEv, enter)
}
function enter () {
if (!emitter._events[enterEv]) done()
else emitter.emit(enterEv, done)
}
function done () {
emit._state = nwState
emitter.emit(nwState)
emitter.emit('done')
}
}
} | javascript | function fsmEvent (start, events) {
if (typeof start === 'object') {
events = start
start = 'START'
}
assert.equal(typeof start, 'string')
assert.equal(typeof events, 'object')
assert.ok(events[start], 'invalid starting state ' + start)
assert.ok(fsm.validate(events))
const emitter = new EventEmitter()
emit._graph = fsm.reachable(events)
emit._emitter = emitter
emit._events = events
emit._state = start
emit.emit = emit
emit.on = on
return emit
// set a state listener
// str, fn -> null
function on (event, cb) {
emitter.on(event, cb)
}
// change the state
// str -> null
function emit (str) {
const nwState = emit._events[emit._state][str]
if (!reach(emit._state, nwState, emit._graph)) {
const err = 'invalid transition: ' + emit._state + ' -> ' + str
return emitter.emit('error', err)
}
const leaveEv = emit._state + ':leave'
const enterEv = nwState + ':enter'
if (!emit._state) return enter()
return leave()
function leave () {
if (!emitter._events[leaveEv]) enter()
else emitter.emit(leaveEv, enter)
}
function enter () {
if (!emitter._events[enterEv]) done()
else emitter.emit(enterEv, done)
}
function done () {
emit._state = nwState
emitter.emit(nwState)
emitter.emit('done')
}
}
} | [
"function",
"fsmEvent",
"(",
"start",
",",
"events",
")",
"{",
"if",
"(",
"typeof",
"start",
"===",
"'object'",
")",
"{",
"events",
"=",
"start",
"start",
"=",
"'START'",
"}",
"assert",
".",
"equal",
"(",
"typeof",
"start",
",",
"'string'",
")",
"assert",
".",
"equal",
"(",
"typeof",
"events",
",",
"'object'",
")",
"assert",
".",
"ok",
"(",
"events",
"[",
"start",
"]",
",",
"'invalid starting state '",
"+",
"start",
")",
"assert",
".",
"ok",
"(",
"fsm",
".",
"validate",
"(",
"events",
")",
")",
"const",
"emitter",
"=",
"new",
"EventEmitter",
"(",
")",
"emit",
".",
"_graph",
"=",
"fsm",
".",
"reachable",
"(",
"events",
")",
"emit",
".",
"_emitter",
"=",
"emitter",
"emit",
".",
"_events",
"=",
"events",
"emit",
".",
"_state",
"=",
"start",
"emit",
".",
"emit",
"=",
"emit",
"emit",
".",
"on",
"=",
"on",
"return",
"emit",
"function",
"on",
"(",
"event",
",",
"cb",
")",
"{",
"emitter",
".",
"on",
"(",
"event",
",",
"cb",
")",
"}",
"function",
"emit",
"(",
"str",
")",
"{",
"const",
"nwState",
"=",
"emit",
".",
"_events",
"[",
"emit",
".",
"_state",
"]",
"[",
"str",
"]",
"if",
"(",
"!",
"reach",
"(",
"emit",
".",
"_state",
",",
"nwState",
",",
"emit",
".",
"_graph",
")",
")",
"{",
"const",
"err",
"=",
"'invalid transition: '",
"+",
"emit",
".",
"_state",
"+",
"' -> '",
"+",
"str",
"return",
"emitter",
".",
"emit",
"(",
"'error'",
",",
"err",
")",
"}",
"const",
"leaveEv",
"=",
"emit",
".",
"_state",
"+",
"':leave'",
"const",
"enterEv",
"=",
"nwState",
"+",
"':enter'",
"if",
"(",
"!",
"emit",
".",
"_state",
")",
"return",
"enter",
"(",
")",
"return",
"leave",
"(",
")",
"function",
"leave",
"(",
")",
"{",
"if",
"(",
"!",
"emitter",
".",
"_events",
"[",
"leaveEv",
"]",
")",
"enter",
"(",
")",
"else",
"emitter",
".",
"emit",
"(",
"leaveEv",
",",
"enter",
")",
"}",
"function",
"enter",
"(",
")",
"{",
"if",
"(",
"!",
"emitter",
".",
"_events",
"[",
"enterEv",
"]",
")",
"done",
"(",
")",
"else",
"emitter",
".",
"emit",
"(",
"enterEv",
",",
"done",
")",
"}",
"function",
"done",
"(",
")",
"{",
"emit",
".",
"_state",
"=",
"nwState",
"emitter",
".",
"emit",
"(",
"nwState",
")",
"emitter",
".",
"emit",
"(",
"'done'",
")",
"}",
"}",
"}"
] | create an fsmEvent instance obj -> fn | [
"create",
"an",
"fsmEvent",
"instance",
"obj",
"-",
">",
"fn"
] | a3ab9e692d39c01c2bdd88d9de9e2a0e07089f85 | https://github.com/yoshuawuyts/fsm-event/blob/a3ab9e692d39c01c2bdd88d9de9e2a0e07089f85/index.js#L9-L66 | train |
yoshuawuyts/fsm-event | index.js | emit | function emit (str) {
const nwState = emit._events[emit._state][str]
if (!reach(emit._state, nwState, emit._graph)) {
const err = 'invalid transition: ' + emit._state + ' -> ' + str
return emitter.emit('error', err)
}
const leaveEv = emit._state + ':leave'
const enterEv = nwState + ':enter'
if (!emit._state) return enter()
return leave()
function leave () {
if (!emitter._events[leaveEv]) enter()
else emitter.emit(leaveEv, enter)
}
function enter () {
if (!emitter._events[enterEv]) done()
else emitter.emit(enterEv, done)
}
function done () {
emit._state = nwState
emitter.emit(nwState)
emitter.emit('done')
}
} | javascript | function emit (str) {
const nwState = emit._events[emit._state][str]
if (!reach(emit._state, nwState, emit._graph)) {
const err = 'invalid transition: ' + emit._state + ' -> ' + str
return emitter.emit('error', err)
}
const leaveEv = emit._state + ':leave'
const enterEv = nwState + ':enter'
if (!emit._state) return enter()
return leave()
function leave () {
if (!emitter._events[leaveEv]) enter()
else emitter.emit(leaveEv, enter)
}
function enter () {
if (!emitter._events[enterEv]) done()
else emitter.emit(enterEv, done)
}
function done () {
emit._state = nwState
emitter.emit(nwState)
emitter.emit('done')
}
} | [
"function",
"emit",
"(",
"str",
")",
"{",
"const",
"nwState",
"=",
"emit",
".",
"_events",
"[",
"emit",
".",
"_state",
"]",
"[",
"str",
"]",
"if",
"(",
"!",
"reach",
"(",
"emit",
".",
"_state",
",",
"nwState",
",",
"emit",
".",
"_graph",
")",
")",
"{",
"const",
"err",
"=",
"'invalid transition: '",
"+",
"emit",
".",
"_state",
"+",
"' -> '",
"+",
"str",
"return",
"emitter",
".",
"emit",
"(",
"'error'",
",",
"err",
")",
"}",
"const",
"leaveEv",
"=",
"emit",
".",
"_state",
"+",
"':leave'",
"const",
"enterEv",
"=",
"nwState",
"+",
"':enter'",
"if",
"(",
"!",
"emit",
".",
"_state",
")",
"return",
"enter",
"(",
")",
"return",
"leave",
"(",
")",
"function",
"leave",
"(",
")",
"{",
"if",
"(",
"!",
"emitter",
".",
"_events",
"[",
"leaveEv",
"]",
")",
"enter",
"(",
")",
"else",
"emitter",
".",
"emit",
"(",
"leaveEv",
",",
"enter",
")",
"}",
"function",
"enter",
"(",
")",
"{",
"if",
"(",
"!",
"emitter",
".",
"_events",
"[",
"enterEv",
"]",
")",
"done",
"(",
")",
"else",
"emitter",
".",
"emit",
"(",
"enterEv",
",",
"done",
")",
"}",
"function",
"done",
"(",
")",
"{",
"emit",
".",
"_state",
"=",
"nwState",
"emitter",
".",
"emit",
"(",
"nwState",
")",
"emitter",
".",
"emit",
"(",
"'done'",
")",
"}",
"}"
] | change the state str -> null | [
"change",
"the",
"state",
"str",
"-",
">",
"null"
] | a3ab9e692d39c01c2bdd88d9de9e2a0e07089f85 | https://github.com/yoshuawuyts/fsm-event/blob/a3ab9e692d39c01c2bdd88d9de9e2a0e07089f85/index.js#L37-L65 | train |
yoshuawuyts/fsm-event | index.js | reach | function reach (curr, next, reachable) {
if (!next) return false
if (!curr) return true
const here = reachable[curr]
if (!here || !here[next]) return false
return here[next].length === 1
} | javascript | function reach (curr, next, reachable) {
if (!next) return false
if (!curr) return true
const here = reachable[curr]
if (!here || !here[next]) return false
return here[next].length === 1
} | [
"function",
"reach",
"(",
"curr",
",",
"next",
",",
"reachable",
")",
"{",
"if",
"(",
"!",
"next",
")",
"return",
"false",
"if",
"(",
"!",
"curr",
")",
"return",
"true",
"const",
"here",
"=",
"reachable",
"[",
"curr",
"]",
"if",
"(",
"!",
"here",
"||",
"!",
"here",
"[",
"next",
"]",
")",
"return",
"false",
"return",
"here",
"[",
"next",
"]",
".",
"length",
"===",
"1",
"}"
] | check if state can reach in reach str, str, obj -> bool | [
"check",
"if",
"state",
"can",
"reach",
"in",
"reach",
"str",
"str",
"obj",
"-",
">",
"bool"
] | a3ab9e692d39c01c2bdd88d9de9e2a0e07089f85 | https://github.com/yoshuawuyts/fsm-event/blob/a3ab9e692d39c01c2bdd88d9de9e2a0e07089f85/index.js#L70-L77 | train |
kartotherian/babel | lib/LanguagePicker.js | LanguagePicker | function LanguagePicker(lang = 'en', config = {}) {
const scripts = ls.adjust({ override: dataOverrides });
this.userLang = lang;
this.nameTag = config.nameTag;
// The prefix is either given or is the nameTag
// with an underscore
// See Babel.js#24
this.prefix = config.multiTag || (this.nameTag && `${this.nameTag}_`) || '';
this.forceLocal = !!config.forceLocal;
if (this.forceLocal) {
// If we are forcing a local language, we don't need
// any of the fallback calculations
return;
}
// Store language script
this.langScript = scripts[lang] || 'Latn';
// Add known fallbacks for the language
let fallbacks;
if (config.languageMap) {
fallbacks = config.languageMap[lang];
if (fallbacks && !Array.isArray(fallbacks)) {
fallbacks = [fallbacks];
}
}
if (!fallbacks) {
fallbacks = [];
}
// Use the given language as first choice
fallbacks = [lang].concat(fallbacks);
// Remove duplicates
fallbacks = fallbacks.filter((item, i) => fallbacks.indexOf(item) === i);
// Add prefix to all languages if exists
// eslint-disable-next-line arrow-body-style
fallbacks = fallbacks.map((code) => {
return code === this.nameTag ? code : this.prefix + code;
});
// Store initial fallbacks
this.fallbacks = fallbacks;
this.prefixedEnglish = this.prefix ? `${this.prefix}en` : 'en';
this.prefixedLangScript = `-${this.langScript}`;
} | javascript | function LanguagePicker(lang = 'en', config = {}) {
const scripts = ls.adjust({ override: dataOverrides });
this.userLang = lang;
this.nameTag = config.nameTag;
// The prefix is either given or is the nameTag
// with an underscore
// See Babel.js#24
this.prefix = config.multiTag || (this.nameTag && `${this.nameTag}_`) || '';
this.forceLocal = !!config.forceLocal;
if (this.forceLocal) {
// If we are forcing a local language, we don't need
// any of the fallback calculations
return;
}
// Store language script
this.langScript = scripts[lang] || 'Latn';
// Add known fallbacks for the language
let fallbacks;
if (config.languageMap) {
fallbacks = config.languageMap[lang];
if (fallbacks && !Array.isArray(fallbacks)) {
fallbacks = [fallbacks];
}
}
if (!fallbacks) {
fallbacks = [];
}
// Use the given language as first choice
fallbacks = [lang].concat(fallbacks);
// Remove duplicates
fallbacks = fallbacks.filter((item, i) => fallbacks.indexOf(item) === i);
// Add prefix to all languages if exists
// eslint-disable-next-line arrow-body-style
fallbacks = fallbacks.map((code) => {
return code === this.nameTag ? code : this.prefix + code;
});
// Store initial fallbacks
this.fallbacks = fallbacks;
this.prefixedEnglish = this.prefix ? `${this.prefix}en` : 'en';
this.prefixedLangScript = `-${this.langScript}`;
} | [
"function",
"LanguagePicker",
"(",
"lang",
"=",
"'en'",
",",
"config",
"=",
"{",
"}",
")",
"{",
"const",
"scripts",
"=",
"ls",
".",
"adjust",
"(",
"{",
"override",
":",
"dataOverrides",
"}",
")",
";",
"this",
".",
"userLang",
"=",
"lang",
";",
"this",
".",
"nameTag",
"=",
"config",
".",
"nameTag",
";",
"this",
".",
"prefix",
"=",
"config",
".",
"multiTag",
"||",
"(",
"this",
".",
"nameTag",
"&&",
"`",
"${",
"this",
".",
"nameTag",
"}",
"`",
")",
"||",
"''",
";",
"this",
".",
"forceLocal",
"=",
"!",
"!",
"config",
".",
"forceLocal",
";",
"if",
"(",
"this",
".",
"forceLocal",
")",
"{",
"return",
";",
"}",
"this",
".",
"langScript",
"=",
"scripts",
"[",
"lang",
"]",
"||",
"'Latn'",
";",
"let",
"fallbacks",
";",
"if",
"(",
"config",
".",
"languageMap",
")",
"{",
"fallbacks",
"=",
"config",
".",
"languageMap",
"[",
"lang",
"]",
";",
"if",
"(",
"fallbacks",
"&&",
"!",
"Array",
".",
"isArray",
"(",
"fallbacks",
")",
")",
"{",
"fallbacks",
"=",
"[",
"fallbacks",
"]",
";",
"}",
"}",
"if",
"(",
"!",
"fallbacks",
")",
"{",
"fallbacks",
"=",
"[",
"]",
";",
"}",
"fallbacks",
"=",
"[",
"lang",
"]",
".",
"concat",
"(",
"fallbacks",
")",
";",
"fallbacks",
"=",
"fallbacks",
".",
"filter",
"(",
"(",
"item",
",",
"i",
")",
"=>",
"fallbacks",
".",
"indexOf",
"(",
"item",
")",
"===",
"i",
")",
";",
"fallbacks",
"=",
"fallbacks",
".",
"map",
"(",
"(",
"code",
")",
"=>",
"{",
"return",
"code",
"===",
"this",
".",
"nameTag",
"?",
"code",
":",
"this",
".",
"prefix",
"+",
"code",
";",
"}",
")",
";",
"this",
".",
"fallbacks",
"=",
"fallbacks",
";",
"this",
".",
"prefixedEnglish",
"=",
"this",
".",
"prefix",
"?",
"`",
"${",
"this",
".",
"prefix",
"}",
"`",
":",
"'en'",
";",
"this",
".",
"prefixedLangScript",
"=",
"`",
"${",
"this",
".",
"langScript",
"}",
"`",
";",
"}"
] | Define a language picker with fallback rules.
@param {String} [lang='en'] Requested language.
@param {Object} [config] Optional configuration object
@cfg {string} [nameTag] A tag that defines the local value in a label.
If specified, will also be used as the prefix for other languages if
a prefix is not already specified with `multiTag`.
@cfg {string} [multiTag] A specified prefix for the language keys
@cfg {Object} [languageMap] An object representing language fallbacks; languages
may have more than one fallback, represented in a string or an array of strings.
Example:
{
'langA': [ 'lang1', 'lang2' ]
'langB': 'lang3'
}
@cfg {boolean} [forceLocal] Force the system to fetch a local representation
of the labels, if it exists. This will only work if there is a nameTag specified,
since that tag dictates the key of the local value. If the value doesn't exist
or if the nameTag is not specified, the system will return the first value given.
Note: All fallbacks are skipped if this parameter is truthy!
@constructor | [
"Define",
"a",
"language",
"picker",
"with",
"fallback",
"rules",
"."
] | f5d447002e35facf3f6f169e0cc9765b4e7fc7b6 | https://github.com/kartotherian/babel/blob/f5d447002e35facf3f6f169e0cc9765b4e7fc7b6/lib/LanguagePicker.js#L27-L75 | train |
kartotherian/babel | lib/PbfSplicer.js | PbfSplicer | function PbfSplicer(options) {
// tag which will be auto-removed and auto-injected. Usually 'name'
this.nameTag = options.nameTag;
// tag that contains JSON initially, and which works as a prefix for multiple values
this.multiTag = options.multiTag;
// If options.namePicker is given, this class converts multiple language tags into one
// Otherwise, it assumes that a single name_ tag exists with JSON content, and it will replace
// it with multiple tags "name_en", "name_fr", ... depending on the JSON language codes
this.namePicker = options.namePicker;
// Flag to make requested_name (local_name) form
this.combineName = options.combineName;
} | javascript | function PbfSplicer(options) {
// tag which will be auto-removed and auto-injected. Usually 'name'
this.nameTag = options.nameTag;
// tag that contains JSON initially, and which works as a prefix for multiple values
this.multiTag = options.multiTag;
// If options.namePicker is given, this class converts multiple language tags into one
// Otherwise, it assumes that a single name_ tag exists with JSON content, and it will replace
// it with multiple tags "name_en", "name_fr", ... depending on the JSON language codes
this.namePicker = options.namePicker;
// Flag to make requested_name (local_name) form
this.combineName = options.combineName;
} | [
"function",
"PbfSplicer",
"(",
"options",
")",
"{",
"this",
".",
"nameTag",
"=",
"options",
".",
"nameTag",
";",
"this",
".",
"multiTag",
"=",
"options",
".",
"multiTag",
";",
"this",
".",
"namePicker",
"=",
"options",
".",
"namePicker",
";",
"this",
".",
"combineName",
"=",
"options",
".",
"combineName",
";",
"}"
] | Transform vector tile tags
@param {object} options
@param {string} options.nameTag
@param {string} options.multiTag
@param {LanguagePicker} [options.namePicker]
@constructor | [
"Transform",
"vector",
"tile",
"tags"
] | f5d447002e35facf3f6f169e0cc9765b4e7fc7b6 | https://github.com/kartotherian/babel/blob/f5d447002e35facf3f6f169e0cc9765b4e7fc7b6/lib/PbfSplicer.js#L36-L49 | train |
anodejs/node-gits | lib/gitsync.js | function(cb) {
var lockFile = path.join(repoDir, '.git', 'index.lock');
path.exists(lockFile, function(exists) {
if (exists) {
fs.unlink(lockFile, function(err) {
if (err) {
log.warn('removing file ' + lockFile + ' failed with:', err);
}
else {
log.info('removed lock file: ' + lockFile);
}
cb(err, {removelock: 'remove git lock ' + lockFile + ', result ' + err});
});
return;
}
log.log('There is no lock file left, which is a good thing');
cb(null, {removelock: 'no lock was present'});
});
} | javascript | function(cb) {
var lockFile = path.join(repoDir, '.git', 'index.lock');
path.exists(lockFile, function(exists) {
if (exists) {
fs.unlink(lockFile, function(err) {
if (err) {
log.warn('removing file ' + lockFile + ' failed with:', err);
}
else {
log.info('removed lock file: ' + lockFile);
}
cb(err, {removelock: 'remove git lock ' + lockFile + ', result ' + err});
});
return;
}
log.log('There is no lock file left, which is a good thing');
cb(null, {removelock: 'no lock was present'});
});
} | [
"function",
"(",
"cb",
")",
"{",
"var",
"lockFile",
"=",
"path",
".",
"join",
"(",
"repoDir",
",",
"'.git'",
",",
"'index.lock'",
")",
";",
"path",
".",
"exists",
"(",
"lockFile",
",",
"function",
"(",
"exists",
")",
"{",
"if",
"(",
"exists",
")",
"{",
"fs",
".",
"unlink",
"(",
"lockFile",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"log",
".",
"warn",
"(",
"'removing file '",
"+",
"lockFile",
"+",
"' failed with:'",
",",
"err",
")",
";",
"}",
"else",
"{",
"log",
".",
"info",
"(",
"'removed lock file: '",
"+",
"lockFile",
")",
";",
"}",
"cb",
"(",
"err",
",",
"{",
"removelock",
":",
"'remove git lock '",
"+",
"lockFile",
"+",
"', result '",
"+",
"err",
"}",
")",
";",
"}",
")",
";",
"return",
";",
"}",
"log",
".",
"log",
"(",
"'There is no lock file left, which is a good thing'",
")",
";",
"cb",
"(",
"null",
",",
"{",
"removelock",
":",
"'no lock was present'",
"}",
")",
";",
"}",
")",
";",
"}"
] | Remove git lock file to recover if git operation was aborted during previous run. | [
"Remove",
"git",
"lock",
"file",
"to",
"recover",
"if",
"git",
"operation",
"was",
"aborted",
"during",
"previous",
"run",
"."
] | 621c41d663663e2f05a246a07522267b07c7a804 | https://github.com/anodejs/node-gits/blob/621c41d663663e2f05a246a07522267b07c7a804/lib/gitsync.js#L41-L59 | train |
|
anodejs/node-gits | lib/gitsync.js | function(cb) {
git(repoDir, ['status'], function(err, stdout, stderr) {
if (err) {
log.warn('git status failed on ' + repoDir + ":", err.msg);
var indexFile = path.join(repoDir, '.git', 'index');
path.exists(indexFile, function(exists) {
if (exists) {
fs.unlink(indexFile, function(err) {
if (err) {
log.warn('removing file ' + indexFile + ' failed with:', err);
}
else {
log.info('removed index file: ' + indexFile);
}
cb(err, {status: {stdout: stdout, stderr: stderr}, removeIndex: 'remove git index ' + indexFile + ', result ' + err});
});
return;
}
log.warn('No index file ' + indexFile);
cb(err, {status: {stdout: stdout, stderr: stderr}, removeIndex: 'no index present'});
});
return;
}
cb(null, {status: {stdout: stdout, stderr: stderr}});
});
} | javascript | function(cb) {
git(repoDir, ['status'], function(err, stdout, stderr) {
if (err) {
log.warn('git status failed on ' + repoDir + ":", err.msg);
var indexFile = path.join(repoDir, '.git', 'index');
path.exists(indexFile, function(exists) {
if (exists) {
fs.unlink(indexFile, function(err) {
if (err) {
log.warn('removing file ' + indexFile + ' failed with:', err);
}
else {
log.info('removed index file: ' + indexFile);
}
cb(err, {status: {stdout: stdout, stderr: stderr}, removeIndex: 'remove git index ' + indexFile + ', result ' + err});
});
return;
}
log.warn('No index file ' + indexFile);
cb(err, {status: {stdout: stdout, stderr: stderr}, removeIndex: 'no index present'});
});
return;
}
cb(null, {status: {stdout: stdout, stderr: stderr}});
});
} | [
"function",
"(",
"cb",
")",
"{",
"git",
"(",
"repoDir",
",",
"[",
"'status'",
"]",
",",
"function",
"(",
"err",
",",
"stdout",
",",
"stderr",
")",
"{",
"if",
"(",
"err",
")",
"{",
"log",
".",
"warn",
"(",
"'git status failed on '",
"+",
"repoDir",
"+",
"\":\"",
",",
"err",
".",
"msg",
")",
";",
"var",
"indexFile",
"=",
"path",
".",
"join",
"(",
"repoDir",
",",
"'.git'",
",",
"'index'",
")",
";",
"path",
".",
"exists",
"(",
"indexFile",
",",
"function",
"(",
"exists",
")",
"{",
"if",
"(",
"exists",
")",
"{",
"fs",
".",
"unlink",
"(",
"indexFile",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"log",
".",
"warn",
"(",
"'removing file '",
"+",
"indexFile",
"+",
"' failed with:'",
",",
"err",
")",
";",
"}",
"else",
"{",
"log",
".",
"info",
"(",
"'removed index file: '",
"+",
"indexFile",
")",
";",
"}",
"cb",
"(",
"err",
",",
"{",
"status",
":",
"{",
"stdout",
":",
"stdout",
",",
"stderr",
":",
"stderr",
"}",
",",
"removeIndex",
":",
"'remove git index '",
"+",
"indexFile",
"+",
"', result '",
"+",
"err",
"}",
")",
";",
"}",
")",
";",
"return",
";",
"}",
"log",
".",
"warn",
"(",
"'No index file '",
"+",
"indexFile",
")",
";",
"cb",
"(",
"err",
",",
"{",
"status",
":",
"{",
"stdout",
":",
"stdout",
",",
"stderr",
":",
"stderr",
"}",
",",
"removeIndex",
":",
"'no index present'",
"}",
")",
";",
"}",
")",
";",
"return",
";",
"}",
"cb",
"(",
"null",
",",
"{",
"status",
":",
"{",
"stdout",
":",
"stdout",
",",
"stderr",
":",
"stderr",
"}",
"}",
")",
";",
"}",
")",
";",
"}"
] | Remove git index if it appears corrupted | [
"Remove",
"git",
"index",
"if",
"it",
"appears",
"corrupted"
] | 621c41d663663e2f05a246a07522267b07c7a804 | https://github.com/anodejs/node-gits/blob/621c41d663663e2f05a246a07522267b07c7a804/lib/gitsync.js#L61-L86 | train |
|
anodejs/node-gits | lib/gitsync.js | function(cb) {
log.log('git remote prune origin ' + repoDir);
self.pruneOrigin(repoDir, function(err, stdout, stderr) {
if (err) {
log.warn(err.msg + ":", err.err.msg);
}
cb(null, {prune: {stdout: stdout, stderr: stderr}});
});
} | javascript | function(cb) {
log.log('git remote prune origin ' + repoDir);
self.pruneOrigin(repoDir, function(err, stdout, stderr) {
if (err) {
log.warn(err.msg + ":", err.err.msg);
}
cb(null, {prune: {stdout: stdout, stderr: stderr}});
});
} | [
"function",
"(",
"cb",
")",
"{",
"log",
".",
"log",
"(",
"'git remote prune origin '",
"+",
"repoDir",
")",
";",
"self",
".",
"pruneOrigin",
"(",
"repoDir",
",",
"function",
"(",
"err",
",",
"stdout",
",",
"stderr",
")",
"{",
"if",
"(",
"err",
")",
"{",
"log",
".",
"warn",
"(",
"err",
".",
"msg",
"+",
"\":\"",
",",
"err",
".",
"err",
".",
"msg",
")",
";",
"}",
"cb",
"(",
"null",
",",
"{",
"prune",
":",
"{",
"stdout",
":",
"stdout",
",",
"stderr",
":",
"stderr",
"}",
"}",
")",
";",
"}",
")",
";",
"}"
] | Prune non-existing remote tracking branches | [
"Prune",
"non",
"-",
"existing",
"remote",
"tracking",
"branches"
] | 621c41d663663e2f05a246a07522267b07c7a804 | https://github.com/anodejs/node-gits/blob/621c41d663663e2f05a246a07522267b07c7a804/lib/gitsync.js#L118-L126 | train |
|
anodejs/node-gits | lib/gitsync.js | function(cb) {
log.log('git fetch origin ' + repoDir);
git(repoDir, ['fetch', 'origin'], function(err, stdout, stderr) {
if (err) {
log.error('Unable to fetch at ' + repoDir + ':', err.msg);
}
cb(null, {fetch: {stdout: stdout, stderr: stderr}})
});
} | javascript | function(cb) {
log.log('git fetch origin ' + repoDir);
git(repoDir, ['fetch', 'origin'], function(err, stdout, stderr) {
if (err) {
log.error('Unable to fetch at ' + repoDir + ':', err.msg);
}
cb(null, {fetch: {stdout: stdout, stderr: stderr}})
});
} | [
"function",
"(",
"cb",
")",
"{",
"log",
".",
"log",
"(",
"'git fetch origin '",
"+",
"repoDir",
")",
";",
"git",
"(",
"repoDir",
",",
"[",
"'fetch'",
",",
"'origin'",
"]",
",",
"function",
"(",
"err",
",",
"stdout",
",",
"stderr",
")",
"{",
"if",
"(",
"err",
")",
"{",
"log",
".",
"error",
"(",
"'Unable to fetch at '",
"+",
"repoDir",
"+",
"':'",
",",
"err",
".",
"msg",
")",
";",
"}",
"cb",
"(",
"null",
",",
"{",
"fetch",
":",
"{",
"stdout",
":",
"stdout",
",",
"stderr",
":",
"stderr",
"}",
"}",
")",
"}",
")",
";",
"}"
] | Fetch to update the latest remote state of the repo. | [
"Fetch",
"to",
"update",
"the",
"latest",
"remote",
"state",
"of",
"the",
"repo",
"."
] | 621c41d663663e2f05a246a07522267b07c7a804 | https://github.com/anodejs/node-gits/blob/621c41d663663e2f05a246a07522267b07c7a804/lib/gitsync.js#L128-L136 | train |
|
anodejs/node-gits | lib/gitsync.js | _ensureExists | function _ensureExists(dir, callback) {
dir = path.resolve(dir); // make full path
path.exists(dir, function(exists) {
if (!exists) {
// ensure that the parent dir exists
_ensureExists(path.dirname(dir), function(err) {
if (err) {
callback(err);
return;
}
// make the dir
log.log('Creating ' + dir);
fs.mkdir(dir, function(err) {
if (err) {
callback(err);
return;
}
callback(null);
});
});
}
else {
callback(null);
}
});
} | javascript | function _ensureExists(dir, callback) {
dir = path.resolve(dir); // make full path
path.exists(dir, function(exists) {
if (!exists) {
// ensure that the parent dir exists
_ensureExists(path.dirname(dir), function(err) {
if (err) {
callback(err);
return;
}
// make the dir
log.log('Creating ' + dir);
fs.mkdir(dir, function(err) {
if (err) {
callback(err);
return;
}
callback(null);
});
});
}
else {
callback(null);
}
});
} | [
"function",
"_ensureExists",
"(",
"dir",
",",
"callback",
")",
"{",
"dir",
"=",
"path",
".",
"resolve",
"(",
"dir",
")",
";",
"path",
".",
"exists",
"(",
"dir",
",",
"function",
"(",
"exists",
")",
"{",
"if",
"(",
"!",
"exists",
")",
"{",
"_ensureExists",
"(",
"path",
".",
"dirname",
"(",
"dir",
")",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"callback",
"(",
"err",
")",
";",
"return",
";",
"}",
"log",
".",
"log",
"(",
"'Creating '",
"+",
"dir",
")",
";",
"fs",
".",
"mkdir",
"(",
"dir",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"callback",
"(",
"err",
")",
";",
"return",
";",
"}",
"callback",
"(",
"null",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"callback",
"(",
"null",
")",
";",
"}",
"}",
")",
";",
"}"
] | Ensures that a directory exists. If it doesn't, creates it and it's parents if needed. | [
"Ensures",
"that",
"a",
"directory",
"exists",
".",
"If",
"it",
"doesn",
"t",
"creates",
"it",
"and",
"it",
"s",
"parents",
"if",
"needed",
"."
] | 621c41d663663e2f05a246a07522267b07c7a804 | https://github.com/anodejs/node-gits/blob/621c41d663663e2f05a246a07522267b07c7a804/lib/gitsync.js#L601-L629 | train |
amper5and/secrets.js | secrets.js | combine | function combine(at, shares){
var setBits, share, x = [], y = [], result = '', idx;
for(var i=0, len = shares.length; i<len; i++){
share = processShare(shares[i]);
if(typeof setBits === 'undefined'){
setBits = share['bits'];
}else if(share['bits'] !== setBits){
throw new Error('Mismatched shares: Different bit settings.')
}
if(config.bits !== setBits){
init(setBits);
}
if(inArray(x, share['id'])){ // repeated x value?
continue;
}
idx = x.push(share['id']) - 1;
share = split(hex2bin(share['value']));
for(var j=0, len2 = share.length; j<len2; j++){
y[j] = y[j] || [];
y[j][idx] = share[j];
}
}
for(var i=0, len=y.length; i<len; i++){
result = padLeft(lagrange(at, x, y[i]).toString(2)) + result;
}
if(at===0){// reconstructing the secret
var idx = result.indexOf('1'); //find the first 1
return bin2hex(result.slice(idx+1));
}else{// generating a new share
return bin2hex(result);
}
} | javascript | function combine(at, shares){
var setBits, share, x = [], y = [], result = '', idx;
for(var i=0, len = shares.length; i<len; i++){
share = processShare(shares[i]);
if(typeof setBits === 'undefined'){
setBits = share['bits'];
}else if(share['bits'] !== setBits){
throw new Error('Mismatched shares: Different bit settings.')
}
if(config.bits !== setBits){
init(setBits);
}
if(inArray(x, share['id'])){ // repeated x value?
continue;
}
idx = x.push(share['id']) - 1;
share = split(hex2bin(share['value']));
for(var j=0, len2 = share.length; j<len2; j++){
y[j] = y[j] || [];
y[j][idx] = share[j];
}
}
for(var i=0, len=y.length; i<len; i++){
result = padLeft(lagrange(at, x, y[i]).toString(2)) + result;
}
if(at===0){// reconstructing the secret
var idx = result.indexOf('1'); //find the first 1
return bin2hex(result.slice(idx+1));
}else{// generating a new share
return bin2hex(result);
}
} | [
"function",
"combine",
"(",
"at",
",",
"shares",
")",
"{",
"var",
"setBits",
",",
"share",
",",
"x",
"=",
"[",
"]",
",",
"y",
"=",
"[",
"]",
",",
"result",
"=",
"''",
",",
"idx",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"len",
"=",
"shares",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"share",
"=",
"processShare",
"(",
"shares",
"[",
"i",
"]",
")",
";",
"if",
"(",
"typeof",
"setBits",
"===",
"'undefined'",
")",
"{",
"setBits",
"=",
"share",
"[",
"'bits'",
"]",
";",
"}",
"else",
"if",
"(",
"share",
"[",
"'bits'",
"]",
"!==",
"setBits",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Mismatched shares: Different bit settings.'",
")",
"}",
"if",
"(",
"config",
".",
"bits",
"!==",
"setBits",
")",
"{",
"init",
"(",
"setBits",
")",
";",
"}",
"if",
"(",
"inArray",
"(",
"x",
",",
"share",
"[",
"'id'",
"]",
")",
")",
"{",
"continue",
";",
"}",
"idx",
"=",
"x",
".",
"push",
"(",
"share",
"[",
"'id'",
"]",
")",
"-",
"1",
";",
"share",
"=",
"split",
"(",
"hex2bin",
"(",
"share",
"[",
"'value'",
"]",
")",
")",
";",
"for",
"(",
"var",
"j",
"=",
"0",
",",
"len2",
"=",
"share",
".",
"length",
";",
"j",
"<",
"len2",
";",
"j",
"++",
")",
"{",
"y",
"[",
"j",
"]",
"=",
"y",
"[",
"j",
"]",
"||",
"[",
"]",
";",
"y",
"[",
"j",
"]",
"[",
"idx",
"]",
"=",
"share",
"[",
"j",
"]",
";",
"}",
"}",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"len",
"=",
"y",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"result",
"=",
"padLeft",
"(",
"lagrange",
"(",
"at",
",",
"x",
",",
"y",
"[",
"i",
"]",
")",
".",
"toString",
"(",
"2",
")",
")",
"+",
"result",
";",
"}",
"if",
"(",
"at",
"===",
"0",
")",
"{",
"var",
"idx",
"=",
"result",
".",
"indexOf",
"(",
"'1'",
")",
";",
"return",
"bin2hex",
"(",
"result",
".",
"slice",
"(",
"idx",
"+",
"1",
")",
")",
";",
"}",
"else",
"{",
"return",
"bin2hex",
"(",
"result",
")",
";",
"}",
"}"
] | Protected method that evaluates the Lagrange interpolation polynomial at x=`at` for individual config.bits-length segments of each share in the `shares` Array. Each share is expressed in base `inputRadix`. The output is expressed in base `outputRadix' | [
"Protected",
"method",
"that",
"evaluates",
"the",
"Lagrange",
"interpolation",
"polynomial",
"at",
"x",
"=",
"at",
"for",
"individual",
"config",
".",
"bits",
"-",
"length",
"segments",
"of",
"each",
"share",
"in",
"the",
"shares",
"Array",
".",
"Each",
"share",
"is",
"expressed",
"in",
"base",
"inputRadix",
".",
"The",
"output",
"is",
"expressed",
"in",
"base",
"outputRadix"
] | 3c03b3f708b257d5717e754b777c14b06c13d53a | https://github.com/amper5and/secrets.js/blob/3c03b3f708b257d5717e754b777c14b06c13d53a/secrets.js#L334-L371 | train |
amper5and/secrets.js | secrets.js | lagrange | function lagrange(at, x, y){
var sum = 0,
product,
i, j;
for(var i=0, len = x.length; i<len; i++){
if(!y[i]){
continue;
}
product = config.logs[y[i]];
for(var j=0; j<len; j++){
if(i === j){ continue; }
if(at === x[j]){ // happens when computing a share that is in the list of shares used to compute it
product = -1; // fix for a zero product term, after which the sum should be sum^0 = sum, not sum^1
break;
}
product = ( product + config.logs[at ^ x[j]] - config.logs[x[i] ^ x[j]] + config.max/* to make sure it's not negative */ ) % config.max;
}
sum = product === -1 ? sum : sum ^ config.exps[product]; // though exps[-1]= undefined and undefined ^ anything = anything in chrome, this behavior may not hold everywhere, so do the check
}
return sum;
} | javascript | function lagrange(at, x, y){
var sum = 0,
product,
i, j;
for(var i=0, len = x.length; i<len; i++){
if(!y[i]){
continue;
}
product = config.logs[y[i]];
for(var j=0; j<len; j++){
if(i === j){ continue; }
if(at === x[j]){ // happens when computing a share that is in the list of shares used to compute it
product = -1; // fix for a zero product term, after which the sum should be sum^0 = sum, not sum^1
break;
}
product = ( product + config.logs[at ^ x[j]] - config.logs[x[i] ^ x[j]] + config.max/* to make sure it's not negative */ ) % config.max;
}
sum = product === -1 ? sum : sum ^ config.exps[product]; // though exps[-1]= undefined and undefined ^ anything = anything in chrome, this behavior may not hold everywhere, so do the check
}
return sum;
} | [
"function",
"lagrange",
"(",
"at",
",",
"x",
",",
"y",
")",
"{",
"var",
"sum",
"=",
"0",
",",
"product",
",",
"i",
",",
"j",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"len",
"=",
"x",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"if",
"(",
"!",
"y",
"[",
"i",
"]",
")",
"{",
"continue",
";",
"}",
"product",
"=",
"config",
".",
"logs",
"[",
"y",
"[",
"i",
"]",
"]",
";",
"for",
"(",
"var",
"j",
"=",
"0",
";",
"j",
"<",
"len",
";",
"j",
"++",
")",
"{",
"if",
"(",
"i",
"===",
"j",
")",
"{",
"continue",
";",
"}",
"if",
"(",
"at",
"===",
"x",
"[",
"j",
"]",
")",
"{",
"product",
"=",
"-",
"1",
";",
"break",
";",
"}",
"product",
"=",
"(",
"product",
"+",
"config",
".",
"logs",
"[",
"at",
"^",
"x",
"[",
"j",
"]",
"]",
"-",
"config",
".",
"logs",
"[",
"x",
"[",
"i",
"]",
"^",
"x",
"[",
"j",
"]",
"]",
"+",
"config",
".",
"max",
")",
"%",
"config",
".",
"max",
";",
"}",
"sum",
"=",
"product",
"===",
"-",
"1",
"?",
"sum",
":",
"sum",
"^",
"config",
".",
"exps",
"[",
"product",
"]",
";",
"}",
"return",
"sum",
";",
"}"
] | Evaluate the Lagrange interpolation polynomial at x = `at` using x and y Arrays that are of the same length, with corresponding elements constituting points on the polynomial. | [
"Evaluate",
"the",
"Lagrange",
"interpolation",
"polynomial",
"at",
"x",
"=",
"at",
"using",
"x",
"and",
"y",
"Arrays",
"that",
"are",
"of",
"the",
"same",
"length",
"with",
"corresponding",
"elements",
"constituting",
"points",
"on",
"the",
"polynomial",
"."
] | 3c03b3f708b257d5717e754b777c14b06c13d53a | https://github.com/amper5and/secrets.js/blob/3c03b3f708b257d5717e754b777c14b06c13d53a/secrets.js#L401-L424 | train |
amper5and/secrets.js | secrets.js | padLeft | function padLeft(str, bits){
bits = bits || config.bits
var missing = str.length % bits;
return (missing ? new Array(bits - missing + 1).join('0') : '') + str;
} | javascript | function padLeft(str, bits){
bits = bits || config.bits
var missing = str.length % bits;
return (missing ? new Array(bits - missing + 1).join('0') : '') + str;
} | [
"function",
"padLeft",
"(",
"str",
",",
"bits",
")",
"{",
"bits",
"=",
"bits",
"||",
"config",
".",
"bits",
"var",
"missing",
"=",
"str",
".",
"length",
"%",
"bits",
";",
"return",
"(",
"missing",
"?",
"new",
"Array",
"(",
"bits",
"-",
"missing",
"+",
"1",
")",
".",
"join",
"(",
"'0'",
")",
":",
"''",
")",
"+",
"str",
";",
"}"
] | Pads a string `str` with zeros on the left so that its length is a multiple of `bits` | [
"Pads",
"a",
"string",
"str",
"with",
"zeros",
"on",
"the",
"left",
"so",
"that",
"its",
"length",
"is",
"a",
"multiple",
"of",
"bits"
] | 3c03b3f708b257d5717e754b777c14b06c13d53a | https://github.com/amper5and/secrets.js/blob/3c03b3f708b257d5717e754b777c14b06c13d53a/secrets.js#L447-L451 | train |
enudler/kafka-consumer-manager | src/healthCheckers/consumerOffsetOutOfSyncChecker.js | getNotIncrementedTopicPayloads | function getNotIncrementedTopicPayloads(previousConsumerReadOffset, consumer) {
let notIncrementedTopicPayloads = consumer.topicPayloads.filter((topicPayload) => {
let {topic, partition, offset: currentOffset} = topicPayload;
let previousTopicPayloadForPartition = _.find(previousConsumerReadOffset, {topic, partition});
return previousTopicPayloadForPartition && currentOffset === previousTopicPayloadForPartition.offset;
});
return notIncrementedTopicPayloads;
} | javascript | function getNotIncrementedTopicPayloads(previousConsumerReadOffset, consumer) {
let notIncrementedTopicPayloads = consumer.topicPayloads.filter((topicPayload) => {
let {topic, partition, offset: currentOffset} = topicPayload;
let previousTopicPayloadForPartition = _.find(previousConsumerReadOffset, {topic, partition});
return previousTopicPayloadForPartition && currentOffset === previousTopicPayloadForPartition.offset;
});
return notIncrementedTopicPayloads;
} | [
"function",
"getNotIncrementedTopicPayloads",
"(",
"previousConsumerReadOffset",
",",
"consumer",
")",
"{",
"let",
"notIncrementedTopicPayloads",
"=",
"consumer",
".",
"topicPayloads",
".",
"filter",
"(",
"(",
"topicPayload",
")",
"=>",
"{",
"let",
"{",
"topic",
",",
"partition",
",",
"offset",
":",
"currentOffset",
"}",
"=",
"topicPayload",
";",
"let",
"previousTopicPayloadForPartition",
"=",
"_",
".",
"find",
"(",
"previousConsumerReadOffset",
",",
"{",
"topic",
",",
"partition",
"}",
")",
";",
"return",
"previousTopicPayloadForPartition",
"&&",
"currentOffset",
"===",
"previousTopicPayloadForPartition",
".",
"offset",
";",
"}",
")",
";",
"return",
"notIncrementedTopicPayloads",
";",
"}"
] | Compares the current consumer offsets vs the its previous state Returns topic payload that wasn't incremented from last check | [
"Compares",
"the",
"current",
"consumer",
"offsets",
"vs",
"the",
"its",
"previous",
"state",
"Returns",
"topic",
"payload",
"that",
"wasn",
"t",
"incremented",
"from",
"last",
"check"
] | b390d9580b233527576ab24cc9f5aaa30c5f865e | https://github.com/enudler/kafka-consumer-manager/blob/b390d9580b233527576ab24cc9f5aaa30c5f865e/src/healthCheckers/consumerOffsetOutOfSyncChecker.js#L90-L98 | train |
enudler/kafka-consumer-manager | src/healthCheckers/consumerOffsetOutOfSyncChecker.js | isOffsetsInSync | function isOffsetsInSync(notIncrementedTopicPayloads, zookeeperOffsets, kafkaOffsetDiffThreshold, logger) {
logger.trace('Monitor Offset: Topics offsets', zookeeperOffsets);
let lastErrorToHealthCheck;
notIncrementedTopicPayloads.forEach(function (topicPayload) {
let {topic, partition, offset} = topicPayload;
if (zookeeperOffsets && zookeeperOffsets[topic] && zookeeperOffsets[topic][partition]) {
let zkLatestOffset = zookeeperOffsets[topic][partition][0];
let unhandledMessages = zkLatestOffset - offset;
if (unhandledMessages > kafkaOffsetDiffThreshold) {
let state = {
topic: topic,
partition: partition,
partitionLatestOffset: zkLatestOffset,
partitionReadOffset: offset,
unhandledMessages: unhandledMessages
};
logger.error('Monitor Offset: Kafka consumer offsets found to be out of sync', state);
lastErrorToHealthCheck = new Error('Monitor Offset: Kafka consumer offsets found to be out of sync:' + JSON.stringify(state));
}
} else {
logger.error('Monitor Offset: Kafka consumer topics/partitions found to be out of sync in topic: ' + topic + ' and in partition:' + partition);
lastErrorToHealthCheck = new Error('Monitor Offset: Kafka consumer topics/partitions found to be out of sync in topic: ' + topic + ' and in partition:' + partition);
}
});
return lastErrorToHealthCheck;
} | javascript | function isOffsetsInSync(notIncrementedTopicPayloads, zookeeperOffsets, kafkaOffsetDiffThreshold, logger) {
logger.trace('Monitor Offset: Topics offsets', zookeeperOffsets);
let lastErrorToHealthCheck;
notIncrementedTopicPayloads.forEach(function (topicPayload) {
let {topic, partition, offset} = topicPayload;
if (zookeeperOffsets && zookeeperOffsets[topic] && zookeeperOffsets[topic][partition]) {
let zkLatestOffset = zookeeperOffsets[topic][partition][0];
let unhandledMessages = zkLatestOffset - offset;
if (unhandledMessages > kafkaOffsetDiffThreshold) {
let state = {
topic: topic,
partition: partition,
partitionLatestOffset: zkLatestOffset,
partitionReadOffset: offset,
unhandledMessages: unhandledMessages
};
logger.error('Monitor Offset: Kafka consumer offsets found to be out of sync', state);
lastErrorToHealthCheck = new Error('Monitor Offset: Kafka consumer offsets found to be out of sync:' + JSON.stringify(state));
}
} else {
logger.error('Monitor Offset: Kafka consumer topics/partitions found to be out of sync in topic: ' + topic + ' and in partition:' + partition);
lastErrorToHealthCheck = new Error('Monitor Offset: Kafka consumer topics/partitions found to be out of sync in topic: ' + topic + ' and in partition:' + partition);
}
});
return lastErrorToHealthCheck;
} | [
"function",
"isOffsetsInSync",
"(",
"notIncrementedTopicPayloads",
",",
"zookeeperOffsets",
",",
"kafkaOffsetDiffThreshold",
",",
"logger",
")",
"{",
"logger",
".",
"trace",
"(",
"'Monitor Offset: Topics offsets'",
",",
"zookeeperOffsets",
")",
";",
"let",
"lastErrorToHealthCheck",
";",
"notIncrementedTopicPayloads",
".",
"forEach",
"(",
"function",
"(",
"topicPayload",
")",
"{",
"let",
"{",
"topic",
",",
"partition",
",",
"offset",
"}",
"=",
"topicPayload",
";",
"if",
"(",
"zookeeperOffsets",
"&&",
"zookeeperOffsets",
"[",
"topic",
"]",
"&&",
"zookeeperOffsets",
"[",
"topic",
"]",
"[",
"partition",
"]",
")",
"{",
"let",
"zkLatestOffset",
"=",
"zookeeperOffsets",
"[",
"topic",
"]",
"[",
"partition",
"]",
"[",
"0",
"]",
";",
"let",
"unhandledMessages",
"=",
"zkLatestOffset",
"-",
"offset",
";",
"if",
"(",
"unhandledMessages",
">",
"kafkaOffsetDiffThreshold",
")",
"{",
"let",
"state",
"=",
"{",
"topic",
":",
"topic",
",",
"partition",
":",
"partition",
",",
"partitionLatestOffset",
":",
"zkLatestOffset",
",",
"partitionReadOffset",
":",
"offset",
",",
"unhandledMessages",
":",
"unhandledMessages",
"}",
";",
"logger",
".",
"error",
"(",
"'Monitor Offset: Kafka consumer offsets found to be out of sync'",
",",
"state",
")",
";",
"lastErrorToHealthCheck",
"=",
"new",
"Error",
"(",
"'Monitor Offset: Kafka consumer offsets found to be out of sync:'",
"+",
"JSON",
".",
"stringify",
"(",
"state",
")",
")",
";",
"}",
"}",
"else",
"{",
"logger",
".",
"error",
"(",
"'Monitor Offset: Kafka consumer topics/partitions found to be out of sync in topic: '",
"+",
"topic",
"+",
"' and in partition:'",
"+",
"partition",
")",
";",
"lastErrorToHealthCheck",
"=",
"new",
"Error",
"(",
"'Monitor Offset: Kafka consumer topics/partitions found to be out of sync in topic: '",
"+",
"topic",
"+",
"' and in partition:'",
"+",
"partition",
")",
";",
"}",
"}",
")",
";",
"return",
"lastErrorToHealthCheck",
";",
"}"
] | Compares the consumer offsets vs ZooKeeper's offset Will return false if founds a diff | [
"Compares",
"the",
"consumer",
"offsets",
"vs",
"ZooKeeper",
"s",
"offset",
"Will",
"return",
"false",
"if",
"founds",
"a",
"diff"
] | b390d9580b233527576ab24cc9f5aaa30c5f865e | https://github.com/enudler/kafka-consumer-manager/blob/b390d9580b233527576ab24cc9f5aaa30c5f865e/src/healthCheckers/consumerOffsetOutOfSyncChecker.js#L102-L129 | train |
jsreport/jsreport-version-control | lib/versionControl.js | applyPatches | function applyPatches (versions) {
versions = sortVersions(versions, 'ASC')
let state = []
// iterate patches to the final one => get previous commit state
versions.forEach((v) => {
v.changes.forEach((c) => {
if (c.operation === 'insert') {
return state.push({
entityId: c.entityId,
entitySet: c.entitySet,
entity: parse(c.serializedDoc),
path: c.path
})
}
if (c.operation === 'remove') {
state = state.filter((e) => e.entityId !== c.entityId)
return
}
const entityState = state.find((e) => e.entityId === c.entityId)
applyPatch(entityState.entity, parse(c.serializedPatch), c.entitySet, documentModel)
})
})
return state
} | javascript | function applyPatches (versions) {
versions = sortVersions(versions, 'ASC')
let state = []
// iterate patches to the final one => get previous commit state
versions.forEach((v) => {
v.changes.forEach((c) => {
if (c.operation === 'insert') {
return state.push({
entityId: c.entityId,
entitySet: c.entitySet,
entity: parse(c.serializedDoc),
path: c.path
})
}
if (c.operation === 'remove') {
state = state.filter((e) => e.entityId !== c.entityId)
return
}
const entityState = state.find((e) => e.entityId === c.entityId)
applyPatch(entityState.entity, parse(c.serializedPatch), c.entitySet, documentModel)
})
})
return state
} | [
"function",
"applyPatches",
"(",
"versions",
")",
"{",
"versions",
"=",
"sortVersions",
"(",
"versions",
",",
"'ASC'",
")",
"let",
"state",
"=",
"[",
"]",
"versions",
".",
"forEach",
"(",
"(",
"v",
")",
"=>",
"{",
"v",
".",
"changes",
".",
"forEach",
"(",
"(",
"c",
")",
"=>",
"{",
"if",
"(",
"c",
".",
"operation",
"===",
"'insert'",
")",
"{",
"return",
"state",
".",
"push",
"(",
"{",
"entityId",
":",
"c",
".",
"entityId",
",",
"entitySet",
":",
"c",
".",
"entitySet",
",",
"entity",
":",
"parse",
"(",
"c",
".",
"serializedDoc",
")",
",",
"path",
":",
"c",
".",
"path",
"}",
")",
"}",
"if",
"(",
"c",
".",
"operation",
"===",
"'remove'",
")",
"{",
"state",
"=",
"state",
".",
"filter",
"(",
"(",
"e",
")",
"=>",
"e",
".",
"entityId",
"!==",
"c",
".",
"entityId",
")",
"return",
"}",
"const",
"entityState",
"=",
"state",
".",
"find",
"(",
"(",
"e",
")",
"=>",
"e",
".",
"entityId",
"===",
"c",
".",
"entityId",
")",
"applyPatch",
"(",
"entityState",
".",
"entity",
",",
"parse",
"(",
"c",
".",
"serializedPatch",
")",
",",
"c",
".",
"entitySet",
",",
"documentModel",
")",
"}",
")",
"}",
")",
"return",
"state",
"}"
] | apply all patches in collection and return final state of entities | [
"apply",
"all",
"patches",
"in",
"collection",
"and",
"return",
"final",
"state",
"of",
"entities"
] | d10eca45b1cf0db4638998570bc1c16906743ec1 | https://github.com/jsreport/jsreport-version-control/blob/d10eca45b1cf0db4638998570bc1c16906743ec1/lib/versionControl.js#L75-L101 | train |
psiphi75/web-remote-control | src/MySmaz.js | generateCodebook | function generateCodebook() {
var codebook = {};
reverse_codebook.forEach(function (value, i) {
codebook[value] = i;
});
return codebook;
} | javascript | function generateCodebook() {
var codebook = {};
reverse_codebook.forEach(function (value, i) {
codebook[value] = i;
});
return codebook;
} | [
"function",
"generateCodebook",
"(",
")",
"{",
"var",
"codebook",
"=",
"{",
"}",
";",
"reverse_codebook",
".",
"forEach",
"(",
"function",
"(",
"value",
",",
"i",
")",
"{",
"codebook",
"[",
"value",
"]",
"=",
"i",
";",
"}",
")",
";",
"return",
"codebook",
";",
"}"
] | Generate the codebook from the reverse_codebook.
@return {[string]} The codebook | [
"Generate",
"the",
"codebook",
"from",
"the",
"reverse_codebook",
"."
] | 3c88953a657dcbecd6d4da54fbc85aabb642c7d2 | https://github.com/psiphi75/web-remote-control/blob/3c88953a657dcbecd6d4da54fbc85aabb642c7d2/src/MySmaz.js#L100-L108 | train |
ove/ove | packages/ove-lib-utils/src/index.js | function (logLevel) {
return chalk.bgHex(logLevel.label.bgColor).hex(logLevel.label.color).bold;
} | javascript | function (logLevel) {
return chalk.bgHex(logLevel.label.bgColor).hex(logLevel.label.color).bold;
} | [
"function",
"(",
"logLevel",
")",
"{",
"return",
"chalk",
".",
"bgHex",
"(",
"logLevel",
".",
"label",
".",
"bgColor",
")",
".",
"hex",
"(",
"logLevel",
".",
"label",
".",
"color",
")",
".",
"bold",
";",
"}"
] | Internal Utility function to get log labels | [
"Internal",
"Utility",
"function",
"to",
"get",
"log",
"labels"
] | 28a167910bda3ca56d94aadaa90bfefca35eaa52 | https://github.com/ove/ove/blob/28a167910bda3ca56d94aadaa90bfefca35eaa52/packages/ove-lib-utils/src/index.js#L58-L60 | train |
|
ove/ove | packages/ove-lib-utils/src/index.js | function (logLevel, args) {
const time = dateFormat(new Date(), 'dd/mm/yyyy, h:MM:ss.l tt');
// Each logger can have its own name. If this is
// not provided, it will default to Unknown.
const loggerName = __private.name || Constants.LOG_UNKNOWN_APP_ID;
return [ (logLevel.name.length === 4 ? ' ' : '') +
getLogLabel(logLevel)('[' + logLevel.name + ']'), time, '-',
loggerName.padEnd(Constants.LOG_APP_ID_WIDTH), ':'].concat(Object.values(args));
} | javascript | function (logLevel, args) {
const time = dateFormat(new Date(), 'dd/mm/yyyy, h:MM:ss.l tt');
// Each logger can have its own name. If this is
// not provided, it will default to Unknown.
const loggerName = __private.name || Constants.LOG_UNKNOWN_APP_ID;
return [ (logLevel.name.length === 4 ? ' ' : '') +
getLogLabel(logLevel)('[' + logLevel.name + ']'), time, '-',
loggerName.padEnd(Constants.LOG_APP_ID_WIDTH), ':'].concat(Object.values(args));
} | [
"function",
"(",
"logLevel",
",",
"args",
")",
"{",
"const",
"time",
"=",
"dateFormat",
"(",
"new",
"Date",
"(",
")",
",",
"'dd/mm/yyyy, h:MM:ss.l tt'",
")",
";",
"const",
"loggerName",
"=",
"__private",
".",
"name",
"||",
"Constants",
".",
"LOG_UNKNOWN_APP_ID",
";",
"return",
"[",
"(",
"logLevel",
".",
"name",
".",
"length",
"===",
"4",
"?",
"' '",
":",
"''",
")",
"+",
"getLogLabel",
"(",
"logLevel",
")",
"(",
"'['",
"+",
"logLevel",
".",
"name",
"+",
"']'",
")",
",",
"time",
",",
"'-'",
",",
"loggerName",
".",
"padEnd",
"(",
"Constants",
".",
"LOG_APP_ID_WIDTH",
")",
",",
"':'",
"]",
".",
"concat",
"(",
"Object",
".",
"values",
"(",
"args",
")",
")",
";",
"}"
] | Internal Utility function to build log messages. | [
"Internal",
"Utility",
"function",
"to",
"build",
"log",
"messages",
"."
] | 28a167910bda3ca56d94aadaa90bfefca35eaa52 | https://github.com/ove/ove/blob/28a167910bda3ca56d94aadaa90bfefca35eaa52/packages/ove-lib-utils/src/index.js#L63-L71 | train |
|
ove/ove | packages/ove-lib-appbase/src/index.js | function (name, state) {
if (!module.exports.operations.validateState || module.exports.operations.validateState(state)) {
module.exports.config.states[name] = state;
} else {
log.error('Unable to update invalid state:', state, 'with name:', name);
}
} | javascript | function (name, state) {
if (!module.exports.operations.validateState || module.exports.operations.validateState(state)) {
module.exports.config.states[name] = state;
} else {
log.error('Unable to update invalid state:', state, 'with name:', name);
}
} | [
"function",
"(",
"name",
",",
"state",
")",
"{",
"if",
"(",
"!",
"module",
".",
"exports",
".",
"operations",
".",
"validateState",
"||",
"module",
".",
"exports",
".",
"operations",
".",
"validateState",
"(",
"state",
")",
")",
"{",
"module",
".",
"exports",
".",
"config",
".",
"states",
"[",
"name",
"]",
"=",
"state",
";",
"}",
"else",
"{",
"log",
".",
"error",
"(",
"'Unable to update invalid state:'",
",",
"state",
",",
"'with name:'",
",",
"name",
")",
";",
"}",
"}"
] | Utility method to update named state | [
"Utility",
"method",
"to",
"update",
"named",
"state"
] | 28a167910bda3ca56d94aadaa90bfefca35eaa52 | https://github.com/ove/ove/blob/28a167910bda3ca56d94aadaa90bfefca35eaa52/packages/ove-lib-appbase/src/index.js#L95-L101 | train |
|
ove/ove | packages/ove-lib-appbase/src/index.js | function (sectionId, state) {
if (!module.exports.operations.validateState || module.exports.operations.validateState(state)) {
appState.set('state[' + sectionId + ']', state);
} else {
log.error('Unable to update invalid state:', state, 'in section:', sectionId);
}
} | javascript | function (sectionId, state) {
if (!module.exports.operations.validateState || module.exports.operations.validateState(state)) {
appState.set('state[' + sectionId + ']', state);
} else {
log.error('Unable to update invalid state:', state, 'in section:', sectionId);
}
} | [
"function",
"(",
"sectionId",
",",
"state",
")",
"{",
"if",
"(",
"!",
"module",
".",
"exports",
".",
"operations",
".",
"validateState",
"||",
"module",
".",
"exports",
".",
"operations",
".",
"validateState",
"(",
"state",
")",
")",
"{",
"appState",
".",
"set",
"(",
"'state['",
"+",
"sectionId",
"+",
"']'",
",",
"state",
")",
";",
"}",
"else",
"{",
"log",
".",
"error",
"(",
"'Unable to update invalid state:'",
",",
"state",
",",
"'in section:'",
",",
"sectionId",
")",
";",
"}",
"}"
] | Utility method to update state of section | [
"Utility",
"method",
"to",
"update",
"state",
"of",
"section"
] | 28a167910bda3ca56d94aadaa90bfefca35eaa52 | https://github.com/ove/ove/blob/28a167910bda3ca56d94aadaa90bfefca35eaa52/packages/ove-lib-appbase/src/index.js#L104-L110 | train |
|
ove/ove | packages/ove-lib-appbase/src/index.js | function (state, transformation, res) {
if (!module.exports.operations.canTransform || !module.exports.operations.transform) {
log.warn('Transform State operation not implemented by application');
Utils.sendMessage(res, HttpStatus.NOT_IMPLEMENTED, JSON.stringify({ error: 'operation not implemented' }));
return state;
} else if (Utils.isNullOrEmpty(transformation)) {
log.error('Transformation not provided');
Utils.sendMessage(res, HttpStatus.BAD_REQUEST, JSON.stringify({ error: 'invalid transformation' }));
return state;
} else if (!module.exports.operations.canTransform(state, transformation)) {
log.error('Unable to apply transformation:', transformation);
Utils.sendMessage(res, HttpStatus.BAD_REQUEST, JSON.stringify({ error: 'invalid transformation' }));
return state;
}
const result = module.exports.operations.transform(state, transformation);
log.info('Successfully transformed state');
log.debug('Transformed state from:', state, 'into:', result, 'using transformation:', transformation);
Utils.sendMessage(res, HttpStatus.OK, JSON.stringify(result));
return result;
} | javascript | function (state, transformation, res) {
if (!module.exports.operations.canTransform || !module.exports.operations.transform) {
log.warn('Transform State operation not implemented by application');
Utils.sendMessage(res, HttpStatus.NOT_IMPLEMENTED, JSON.stringify({ error: 'operation not implemented' }));
return state;
} else if (Utils.isNullOrEmpty(transformation)) {
log.error('Transformation not provided');
Utils.sendMessage(res, HttpStatus.BAD_REQUEST, JSON.stringify({ error: 'invalid transformation' }));
return state;
} else if (!module.exports.operations.canTransform(state, transformation)) {
log.error('Unable to apply transformation:', transformation);
Utils.sendMessage(res, HttpStatus.BAD_REQUEST, JSON.stringify({ error: 'invalid transformation' }));
return state;
}
const result = module.exports.operations.transform(state, transformation);
log.info('Successfully transformed state');
log.debug('Transformed state from:', state, 'into:', result, 'using transformation:', transformation);
Utils.sendMessage(res, HttpStatus.OK, JSON.stringify(result));
return result;
} | [
"function",
"(",
"state",
",",
"transformation",
",",
"res",
")",
"{",
"if",
"(",
"!",
"module",
".",
"exports",
".",
"operations",
".",
"canTransform",
"||",
"!",
"module",
".",
"exports",
".",
"operations",
".",
"transform",
")",
"{",
"log",
".",
"warn",
"(",
"'Transform State operation not implemented by application'",
")",
";",
"Utils",
".",
"sendMessage",
"(",
"res",
",",
"HttpStatus",
".",
"NOT_IMPLEMENTED",
",",
"JSON",
".",
"stringify",
"(",
"{",
"error",
":",
"'operation not implemented'",
"}",
")",
")",
";",
"return",
"state",
";",
"}",
"else",
"if",
"(",
"Utils",
".",
"isNullOrEmpty",
"(",
"transformation",
")",
")",
"{",
"log",
".",
"error",
"(",
"'Transformation not provided'",
")",
";",
"Utils",
".",
"sendMessage",
"(",
"res",
",",
"HttpStatus",
".",
"BAD_REQUEST",
",",
"JSON",
".",
"stringify",
"(",
"{",
"error",
":",
"'invalid transformation'",
"}",
")",
")",
";",
"return",
"state",
";",
"}",
"else",
"if",
"(",
"!",
"module",
".",
"exports",
".",
"operations",
".",
"canTransform",
"(",
"state",
",",
"transformation",
")",
")",
"{",
"log",
".",
"error",
"(",
"'Unable to apply transformation:'",
",",
"transformation",
")",
";",
"Utils",
".",
"sendMessage",
"(",
"res",
",",
"HttpStatus",
".",
"BAD_REQUEST",
",",
"JSON",
".",
"stringify",
"(",
"{",
"error",
":",
"'invalid transformation'",
"}",
")",
")",
";",
"return",
"state",
";",
"}",
"const",
"result",
"=",
"module",
".",
"exports",
".",
"operations",
".",
"transform",
"(",
"state",
",",
"transformation",
")",
";",
"log",
".",
"info",
"(",
"'Successfully transformed state'",
")",
";",
"log",
".",
"debug",
"(",
"'Transformed state from:'",
",",
"state",
",",
"'into:'",
",",
"result",
",",
"'using transformation:'",
",",
"transformation",
")",
";",
"Utils",
".",
"sendMessage",
"(",
"res",
",",
"HttpStatus",
".",
"OK",
",",
"JSON",
".",
"stringify",
"(",
"result",
")",
")",
";",
"return",
"result",
";",
"}"
] | Internal utility function to transform a state | [
"Internal",
"utility",
"function",
"to",
"transform",
"a",
"state"
] | 28a167910bda3ca56d94aadaa90bfefca35eaa52 | https://github.com/ove/ove/blob/28a167910bda3ca56d94aadaa90bfefca35eaa52/packages/ove-lib-appbase/src/index.js#L167-L186 | train |
|
ove/ove | packages/ove-lib-appbase/src/index.js | function (source, target, res) {
if (!module.exports.operations.canDiff || !module.exports.operations.diff) {
log.warn('Difference operation not implemented by application');
Utils.sendMessage(res, HttpStatus.NOT_IMPLEMENTED, JSON.stringify({ error: 'operation not implemented' }));
} else if (Utils.isNullOrEmpty(target)) {
log.error('Target state not provided');
Utils.sendMessage(res, HttpStatus.BAD_REQUEST, JSON.stringify({ error: 'invalid states' }));
} else if (!module.exports.operations.canDiff(source, target)) {
log.error('Unable to get difference from source:', source, 'to target:', target);
Utils.sendMessage(res, HttpStatus.BAD_REQUEST, JSON.stringify({ error: 'invalid states' }));
} else {
const result = module.exports.operations.diff(source, target);
log.debug('Successfully computed difference', result, 'from source:', source, 'to target:', target);
Utils.sendMessage(res, HttpStatus.OK, JSON.stringify(result));
}
} | javascript | function (source, target, res) {
if (!module.exports.operations.canDiff || !module.exports.operations.diff) {
log.warn('Difference operation not implemented by application');
Utils.sendMessage(res, HttpStatus.NOT_IMPLEMENTED, JSON.stringify({ error: 'operation not implemented' }));
} else if (Utils.isNullOrEmpty(target)) {
log.error('Target state not provided');
Utils.sendMessage(res, HttpStatus.BAD_REQUEST, JSON.stringify({ error: 'invalid states' }));
} else if (!module.exports.operations.canDiff(source, target)) {
log.error('Unable to get difference from source:', source, 'to target:', target);
Utils.sendMessage(res, HttpStatus.BAD_REQUEST, JSON.stringify({ error: 'invalid states' }));
} else {
const result = module.exports.operations.diff(source, target);
log.debug('Successfully computed difference', result, 'from source:', source, 'to target:', target);
Utils.sendMessage(res, HttpStatus.OK, JSON.stringify(result));
}
} | [
"function",
"(",
"source",
",",
"target",
",",
"res",
")",
"{",
"if",
"(",
"!",
"module",
".",
"exports",
".",
"operations",
".",
"canDiff",
"||",
"!",
"module",
".",
"exports",
".",
"operations",
".",
"diff",
")",
"{",
"log",
".",
"warn",
"(",
"'Difference operation not implemented by application'",
")",
";",
"Utils",
".",
"sendMessage",
"(",
"res",
",",
"HttpStatus",
".",
"NOT_IMPLEMENTED",
",",
"JSON",
".",
"stringify",
"(",
"{",
"error",
":",
"'operation not implemented'",
"}",
")",
")",
";",
"}",
"else",
"if",
"(",
"Utils",
".",
"isNullOrEmpty",
"(",
"target",
")",
")",
"{",
"log",
".",
"error",
"(",
"'Target state not provided'",
")",
";",
"Utils",
".",
"sendMessage",
"(",
"res",
",",
"HttpStatus",
".",
"BAD_REQUEST",
",",
"JSON",
".",
"stringify",
"(",
"{",
"error",
":",
"'invalid states'",
"}",
")",
")",
";",
"}",
"else",
"if",
"(",
"!",
"module",
".",
"exports",
".",
"operations",
".",
"canDiff",
"(",
"source",
",",
"target",
")",
")",
"{",
"log",
".",
"error",
"(",
"'Unable to get difference from source:'",
",",
"source",
",",
"'to target:'",
",",
"target",
")",
";",
"Utils",
".",
"sendMessage",
"(",
"res",
",",
"HttpStatus",
".",
"BAD_REQUEST",
",",
"JSON",
".",
"stringify",
"(",
"{",
"error",
":",
"'invalid states'",
"}",
")",
")",
";",
"}",
"else",
"{",
"const",
"result",
"=",
"module",
".",
"exports",
".",
"operations",
".",
"diff",
"(",
"source",
",",
"target",
")",
";",
"log",
".",
"debug",
"(",
"'Successfully computed difference'",
",",
"result",
",",
"'from source:'",
",",
"source",
",",
"'to target:'",
",",
"target",
")",
";",
"Utils",
".",
"sendMessage",
"(",
"res",
",",
"HttpStatus",
".",
"OK",
",",
"JSON",
".",
"stringify",
"(",
"result",
")",
")",
";",
"}",
"}"
] | Internal utility function to calculate difference between two states | [
"Internal",
"utility",
"function",
"to",
"calculate",
"difference",
"between",
"two",
"states"
] | 28a167910bda3ca56d94aadaa90bfefca35eaa52 | https://github.com/ove/ove/blob/28a167910bda3ca56d94aadaa90bfefca35eaa52/packages/ove-lib-appbase/src/index.js#L209-L224 | train |
|
carrot/sprout | lib/template.js | runPrompts | function runPrompts (opts) {
if (opts.questionnaire && this.init.configure) {
this.sprout.emit('msg', 'running questionnaire function')
const unansweredConfig = lodash.filter(this.init.configure, (q) => {
return !lodash.includes(lodash.keys(this.config), q.name)
})
return opts.questionnaire(unansweredConfig)
.then((answers) => { return lodash.assign(this.config, answers) })
}
} | javascript | function runPrompts (opts) {
if (opts.questionnaire && this.init.configure) {
this.sprout.emit('msg', 'running questionnaire function')
const unansweredConfig = lodash.filter(this.init.configure, (q) => {
return !lodash.includes(lodash.keys(this.config), q.name)
})
return opts.questionnaire(unansweredConfig)
.then((answers) => { return lodash.assign(this.config, answers) })
}
} | [
"function",
"runPrompts",
"(",
"opts",
")",
"{",
"if",
"(",
"opts",
".",
"questionnaire",
"&&",
"this",
".",
"init",
".",
"configure",
")",
"{",
"this",
".",
"sprout",
".",
"emit",
"(",
"'msg'",
",",
"'running questionnaire function'",
")",
"const",
"unansweredConfig",
"=",
"lodash",
".",
"filter",
"(",
"this",
".",
"init",
".",
"configure",
",",
"(",
"q",
")",
"=>",
"{",
"return",
"!",
"lodash",
".",
"includes",
"(",
"lodash",
".",
"keys",
"(",
"this",
".",
"config",
")",
",",
"q",
".",
"name",
")",
"}",
")",
"return",
"opts",
".",
"questionnaire",
"(",
"unansweredConfig",
")",
".",
"then",
"(",
"(",
"answers",
")",
"=>",
"{",
"return",
"lodash",
".",
"assign",
"(",
"this",
".",
"config",
",",
"answers",
")",
"}",
")",
"}",
"}"
] | If questionnaire function exists, run it to get answers. Omitting keys already set in config return answers merged with config values. | [
"If",
"questionnaire",
"function",
"exists",
"run",
"it",
"to",
"get",
"answers",
".",
"Omitting",
"keys",
"already",
"set",
"in",
"config",
"return",
"answers",
"merged",
"with",
"config",
"values",
"."
] | 4fd4eecd56a78a9539afec109e23e947e7ae6928 | https://github.com/carrot/sprout/blob/4fd4eecd56a78a9539afec109e23e947e7ae6928/lib/template.js#L348-L357 | train |
skatejs/named-slots | src/util/each.js | reverse | function reverse (arr) {
const reversedArray = [];
for (let i = arr.length - 1; i >= 0; i--) {
reversedArray.push(arr[i]);
}
return reversedArray;
} | javascript | function reverse (arr) {
const reversedArray = [];
for (let i = arr.length - 1; i >= 0; i--) {
reversedArray.push(arr[i]);
}
return reversedArray;
} | [
"function",
"reverse",
"(",
"arr",
")",
"{",
"const",
"reversedArray",
"=",
"[",
"]",
";",
"for",
"(",
"let",
"i",
"=",
"arr",
".",
"length",
"-",
"1",
";",
"i",
">=",
"0",
";",
"i",
"--",
")",
"{",
"reversedArray",
".",
"push",
"(",
"arr",
"[",
"i",
"]",
")",
";",
"}",
"return",
"reversedArray",
";",
"}"
] | Re-implemented to avoid Array.prototype.slice.call for performance reasons | [
"Re",
"-",
"implemented",
"to",
"avoid",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"for",
"performance",
"reasons"
] | 53aa799e23435867189e7cbc63d6f3a8eec62cb8 | https://github.com/skatejs/named-slots/blob/53aa799e23435867189e7cbc63d6f3a8eec62cb8/src/util/each.js#L19-L25 | train |
jabney/render-template-loader | index.js | renderTemplateLoader | function renderTemplateLoader(source) {
// Get the loader options object.
var options = getOptions(this)
// Get the template locals.
var locals = getLocals.call(this, options)
// Create info object of the filename of the resource being loaded.
var info = { filename: this.resourcePath }
// Get the engine options to be passed to the engine.
var engineOptions = getEngineOptions.call(this, options.engineOptions, info)
// Get the template renderer
var renderer = getRenderer.call(this, options.engine)
// Call options.init.
init.call(this, renderer.engine, info, options)
// Render the template
var result = render(renderer, source, locals, engineOptions)
// Assign the tempate to module.exports.
return 'module.exports = ' + JSON.stringify(result)
} | javascript | function renderTemplateLoader(source) {
// Get the loader options object.
var options = getOptions(this)
// Get the template locals.
var locals = getLocals.call(this, options)
// Create info object of the filename of the resource being loaded.
var info = { filename: this.resourcePath }
// Get the engine options to be passed to the engine.
var engineOptions = getEngineOptions.call(this, options.engineOptions, info)
// Get the template renderer
var renderer = getRenderer.call(this, options.engine)
// Call options.init.
init.call(this, renderer.engine, info, options)
// Render the template
var result = render(renderer, source, locals, engineOptions)
// Assign the tempate to module.exports.
return 'module.exports = ' + JSON.stringify(result)
} | [
"function",
"renderTemplateLoader",
"(",
"source",
")",
"{",
"var",
"options",
"=",
"getOptions",
"(",
"this",
")",
"var",
"locals",
"=",
"getLocals",
".",
"call",
"(",
"this",
",",
"options",
")",
"var",
"info",
"=",
"{",
"filename",
":",
"this",
".",
"resourcePath",
"}",
"var",
"engineOptions",
"=",
"getEngineOptions",
".",
"call",
"(",
"this",
",",
"options",
".",
"engineOptions",
",",
"info",
")",
"var",
"renderer",
"=",
"getRenderer",
".",
"call",
"(",
"this",
",",
"options",
".",
"engine",
")",
"init",
".",
"call",
"(",
"this",
",",
"renderer",
".",
"engine",
",",
"info",
",",
"options",
")",
"var",
"result",
"=",
"render",
"(",
"renderer",
",",
"source",
",",
"locals",
",",
"engineOptions",
")",
"return",
"'module.exports = '",
"+",
"JSON",
".",
"stringify",
"(",
"result",
")",
"}"
] | The Render Template Loader
Render via supported template engines or a custom template renderer.
@this {webpack.loader.LoaderContext}
@param {string} source
@returns {string} | [
"The",
"Render",
"Template",
"Loader"
] | 039c7fae2803fca3a9186973b103cd9bf9e76b05 | https://github.com/jabney/render-template-loader/blob/039c7fae2803fca3a9186973b103cd9bf9e76b05/index.js#L45-L62 | train |