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 |
---|---|---|---|---|---|---|---|---|---|---|---|
jabney/render-template-loader | index.js | customRenderFn | function customRenderFn(renderFn) {
// The loader context.
var _this = this
return function (engine, template, locals, options) {
return renderFn.call(_this, template, locals, options)
}
} | javascript | function customRenderFn(renderFn) {
// The loader context.
var _this = this
return function (engine, template, locals, options) {
return renderFn.call(_this, template, locals, options)
}
} | [
"function",
"customRenderFn",
"(",
"renderFn",
")",
"{",
"var",
"_this",
"=",
"this",
"return",
"function",
"(",
"engine",
",",
"template",
",",
"locals",
",",
"options",
")",
"{",
"return",
"renderFn",
".",
"call",
"(",
"_this",
",",
"template",
",",
"locals",
",",
"options",
")",
"}",
"}"
] | Create a custom renderer from a custom render function.
@this {webpack.loader.LoaderContext}
@param {(s: string, l: any, o: any) => string} renderFn
@returns {(e: any, t: string, l: any, o: any) => string} | [
"Create",
"a",
"custom",
"renderer",
"from",
"a",
"custom",
"render",
"function",
"."
] | 039c7fae2803fca3a9186973b103cd9bf9e76b05 | https://github.com/jabney/render-template-loader/blob/039c7fae2803fca3a9186973b103cd9bf9e76b05/index.js#L147-L154 | train |
jabney/render-template-loader | index.js | render | function render(engine, str, locals, engineOptions) {
try {
var output = engine.render(engine.engine, str, locals, engineOptions)
} catch(e) {
throw new Error(
NAME + ': there was a problem rendering the template:\n' + e)
}
return output
} | javascript | function render(engine, str, locals, engineOptions) {
try {
var output = engine.render(engine.engine, str, locals, engineOptions)
} catch(e) {
throw new Error(
NAME + ': there was a problem rendering the template:\n' + e)
}
return output
} | [
"function",
"render",
"(",
"engine",
",",
"str",
",",
"locals",
",",
"engineOptions",
")",
"{",
"try",
"{",
"var",
"output",
"=",
"engine",
".",
"render",
"(",
"engine",
".",
"engine",
",",
"str",
",",
"locals",
",",
"engineOptions",
")",
"}",
"catch",
"(",
"e",
")",
"{",
"throw",
"new",
"Error",
"(",
"NAME",
"+",
"': there was a problem rendering the template:\\n'",
"+",
"\\n",
")",
"}",
"e",
"}"
] | Render a string using a template engine
@param {any} engine
@param {string} str
@param {Object} locals
@returns {string} | [
"Render",
"a",
"string",
"using",
"a",
"template",
"engine"
] | 039c7fae2803fca3a9186973b103cd9bf9e76b05 | https://github.com/jabney/render-template-loader/blob/039c7fae2803fca3a9186973b103cd9bf9e76b05/index.js#L164-L172 | train |
psiphi75/web-remote-control | index.js | init | function init(type) {
return function(params) {
if (!params) {
params = {};
}
var settings = {
proxyUrl: params.proxyUrl || defaults.proxyUrl,
channel: params.channel || defaults.channel,
keepalive: parseFalsey(params.keepalive, defaults.keepalive),
port: params.port || defaults.port,
log: params.log || defaults.log,
tcp: parseFalsey(params.tcp, defaults.tcp),
udp4: parseFalsey(params.udp4, defaults.udp4),
socketio: parseFalsey(params.socketio, defaults.socketio),
onlyOneControllerPerChannel: parseFalsey(params.onlyOneControllerPerChannel, defaults.onlyOneControllerPerChannel),
onlyOneToyPerChannel: parseFalsey(params.onlyOneToyPerChannel, defaults.onlyOneToyPerChannel),
allowObservers: parseFalsey(params.allowObservers, defaults.allowObservers),
deviceType: type
};
if (typeof params.log !== 'function') {
params.log = defaults.log;
}
switch (type) {
case 'proxy':
if (isBrowser()) {
console.error('Cannot create proxy in browser');
}
var Proxy = require('./src/Proxy');
return new Proxy(settings);
case 'toy':
case 'controller':
case 'observer':
var connectionModule;
if (isBrowser()) {
connectionModule = require('./src/WebClientConnection');
settings.udp4 = false;
settings.tcp = false;
settings.socketio = true;
} else {
connectionModule = require('./src/ClientConnection');
settings.socketio = false;
}
var Device = require('./src/Device');
return new Device(settings, connectionModule);
default:
throw new Error('Could not determine server type.');
}
};
} | javascript | function init(type) {
return function(params) {
if (!params) {
params = {};
}
var settings = {
proxyUrl: params.proxyUrl || defaults.proxyUrl,
channel: params.channel || defaults.channel,
keepalive: parseFalsey(params.keepalive, defaults.keepalive),
port: params.port || defaults.port,
log: params.log || defaults.log,
tcp: parseFalsey(params.tcp, defaults.tcp),
udp4: parseFalsey(params.udp4, defaults.udp4),
socketio: parseFalsey(params.socketio, defaults.socketio),
onlyOneControllerPerChannel: parseFalsey(params.onlyOneControllerPerChannel, defaults.onlyOneControllerPerChannel),
onlyOneToyPerChannel: parseFalsey(params.onlyOneToyPerChannel, defaults.onlyOneToyPerChannel),
allowObservers: parseFalsey(params.allowObservers, defaults.allowObservers),
deviceType: type
};
if (typeof params.log !== 'function') {
params.log = defaults.log;
}
switch (type) {
case 'proxy':
if (isBrowser()) {
console.error('Cannot create proxy in browser');
}
var Proxy = require('./src/Proxy');
return new Proxy(settings);
case 'toy':
case 'controller':
case 'observer':
var connectionModule;
if (isBrowser()) {
connectionModule = require('./src/WebClientConnection');
settings.udp4 = false;
settings.tcp = false;
settings.socketio = true;
} else {
connectionModule = require('./src/ClientConnection');
settings.socketio = false;
}
var Device = require('./src/Device');
return new Device(settings, connectionModule);
default:
throw new Error('Could not determine server type.');
}
};
} | [
"function",
"init",
"(",
"type",
")",
"{",
"return",
"function",
"(",
"params",
")",
"{",
"if",
"(",
"!",
"params",
")",
"{",
"params",
"=",
"{",
"}",
";",
"}",
"var",
"settings",
"=",
"{",
"proxyUrl",
":",
"params",
".",
"proxyUrl",
"||",
"defaults",
".",
"proxyUrl",
",",
"channel",
":",
"params",
".",
"channel",
"||",
"defaults",
".",
"channel",
",",
"keepalive",
":",
"parseFalsey",
"(",
"params",
".",
"keepalive",
",",
"defaults",
".",
"keepalive",
")",
",",
"port",
":",
"params",
".",
"port",
"||",
"defaults",
".",
"port",
",",
"log",
":",
"params",
".",
"log",
"||",
"defaults",
".",
"log",
",",
"tcp",
":",
"parseFalsey",
"(",
"params",
".",
"tcp",
",",
"defaults",
".",
"tcp",
")",
",",
"udp4",
":",
"parseFalsey",
"(",
"params",
".",
"udp4",
",",
"defaults",
".",
"udp4",
")",
",",
"socketio",
":",
"parseFalsey",
"(",
"params",
".",
"socketio",
",",
"defaults",
".",
"socketio",
")",
",",
"onlyOneControllerPerChannel",
":",
"parseFalsey",
"(",
"params",
".",
"onlyOneControllerPerChannel",
",",
"defaults",
".",
"onlyOneControllerPerChannel",
")",
",",
"onlyOneToyPerChannel",
":",
"parseFalsey",
"(",
"params",
".",
"onlyOneToyPerChannel",
",",
"defaults",
".",
"onlyOneToyPerChannel",
")",
",",
"allowObservers",
":",
"parseFalsey",
"(",
"params",
".",
"allowObservers",
",",
"defaults",
".",
"allowObservers",
")",
",",
"deviceType",
":",
"type",
"}",
";",
"if",
"(",
"typeof",
"params",
".",
"log",
"!==",
"'function'",
")",
"{",
"params",
".",
"log",
"=",
"defaults",
".",
"log",
";",
"}",
"switch",
"(",
"type",
")",
"{",
"case",
"'proxy'",
":",
"if",
"(",
"isBrowser",
"(",
")",
")",
"{",
"console",
".",
"error",
"(",
"'Cannot create proxy in browser'",
")",
";",
"}",
"var",
"Proxy",
"=",
"require",
"(",
"'./src/Proxy'",
")",
";",
"return",
"new",
"Proxy",
"(",
"settings",
")",
";",
"case",
"'toy'",
":",
"case",
"'controller'",
":",
"case",
"'observer'",
":",
"var",
"connectionModule",
";",
"if",
"(",
"isBrowser",
"(",
")",
")",
"{",
"connectionModule",
"=",
"require",
"(",
"'./src/WebClientConnection'",
")",
";",
"settings",
".",
"udp4",
"=",
"false",
";",
"settings",
".",
"tcp",
"=",
"false",
";",
"settings",
".",
"socketio",
"=",
"true",
";",
"}",
"else",
"{",
"connectionModule",
"=",
"require",
"(",
"'./src/ClientConnection'",
")",
";",
"settings",
".",
"socketio",
"=",
"false",
";",
"}",
"var",
"Device",
"=",
"require",
"(",
"'./src/Device'",
")",
";",
"return",
"new",
"Device",
"(",
"settings",
",",
"connectionModule",
")",
";",
"default",
":",
"throw",
"new",
"Error",
"(",
"'Could not determine server type.'",
")",
";",
"}",
"}",
";",
"}"
] | Helper function to create an initialised device or proxy server.
@param {string} type 'proxy', 'toy', or 'controller'.
@return {function} The initialisation function that can be called later. | [
"Helper",
"function",
"to",
"create",
"an",
"initialised",
"device",
"or",
"proxy",
"server",
"."
] | 3c88953a657dcbecd6d4da54fbc85aabb642c7d2 | https://github.com/psiphi75/web-remote-control/blob/3c88953a657dcbecd6d4da54fbc85aabb642c7d2/index.js#L82-L138 | train |
DispatchMe/mgp | packages.js | function (path, errorMessage) {
if (!shell.test('-e', path)) {
shell.echo('Error: ' + errorMessage);
shell.exit(1);
}
} | javascript | function (path, errorMessage) {
if (!shell.test('-e', path)) {
shell.echo('Error: ' + errorMessage);
shell.exit(1);
}
} | [
"function",
"(",
"path",
",",
"errorMessage",
")",
"{",
"if",
"(",
"!",
"shell",
".",
"test",
"(",
"'-e'",
",",
"path",
")",
")",
"{",
"shell",
".",
"echo",
"(",
"'Error: '",
"+",
"errorMessage",
")",
";",
"shell",
".",
"exit",
"(",
"1",
")",
";",
"}",
"}"
] | Test if path exists and fail with error if it is not exists | [
"Test",
"if",
"path",
"exists",
"and",
"fail",
"with",
"error",
"if",
"it",
"is",
"not",
"exists"
] | 15463d71b6ab04d3deaec8548a387a95a1b7ddb8 | https://github.com/DispatchMe/mgp/blob/15463d71b6ab04d3deaec8548a387a95a1b7ddb8/packages.js#L81-L86 | train |
|
jabney/render-template-loader | lib/merge.js | merge | function merge(dest) {
if (dest) {
Array.prototype.slice.call(arguments, 1).forEach(function(arg) {
Object.keys(arg).forEach(function(key) {
dest[key] = arg[key]
})
})
}
return dest
} | javascript | function merge(dest) {
if (dest) {
Array.prototype.slice.call(arguments, 1).forEach(function(arg) {
Object.keys(arg).forEach(function(key) {
dest[key] = arg[key]
})
})
}
return dest
} | [
"function",
"merge",
"(",
"dest",
")",
"{",
"if",
"(",
"dest",
")",
"{",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"arguments",
",",
"1",
")",
".",
"forEach",
"(",
"function",
"(",
"arg",
")",
"{",
"Object",
".",
"keys",
"(",
"arg",
")",
".",
"forEach",
"(",
"function",
"(",
"key",
")",
"{",
"dest",
"[",
"key",
"]",
"=",
"arg",
"[",
"key",
"]",
"}",
")",
"}",
")",
"}",
"return",
"dest",
"}"
] | Merge any number of objects with the 'dest' object.
@param {Object} dest
@param {...args}
@returns {Object} | [
"Merge",
"any",
"number",
"of",
"objects",
"with",
"the",
"dest",
"object",
"."
] | 039c7fae2803fca3a9186973b103cd9bf9e76b05 | https://github.com/jabney/render-template-loader/blob/039c7fae2803fca3a9186973b103cd9bf9e76b05/lib/merge.js#L9-L19 | train |
jsdom/w3c-hr-time | lib/calculate-clock-offset.js | calculateClockOffset | function calculateClockOffset() {
const start = Date.now();
let cur = start;
// Limit the iterations, just in case we're running in an environment where Date.now() has been mocked and is
// constant.
for (let i = 0; i < 1e6 && cur === start; i++) {
cur = Date.now();
}
// At this point |cur| "just" became equal to the next millisecond -- the unseen digits after |cur| are approximately
// all 0, and |cur| is the closest to the actual value of the UNIX time. Now, get the current global monotonic clock
// value and do the remaining calculations.
return cur - getGlobalMonotonicClockMS();
} | javascript | function calculateClockOffset() {
const start = Date.now();
let cur = start;
// Limit the iterations, just in case we're running in an environment where Date.now() has been mocked and is
// constant.
for (let i = 0; i < 1e6 && cur === start; i++) {
cur = Date.now();
}
// At this point |cur| "just" became equal to the next millisecond -- the unseen digits after |cur| are approximately
// all 0, and |cur| is the closest to the actual value of the UNIX time. Now, get the current global monotonic clock
// value and do the remaining calculations.
return cur - getGlobalMonotonicClockMS();
} | [
"function",
"calculateClockOffset",
"(",
")",
"{",
"const",
"start",
"=",
"Date",
".",
"now",
"(",
")",
";",
"let",
"cur",
"=",
"start",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"1e6",
"&&",
"cur",
"===",
"start",
";",
"i",
"++",
")",
"{",
"cur",
"=",
"Date",
".",
"now",
"(",
")",
";",
"}",
"return",
"cur",
"-",
"getGlobalMonotonicClockMS",
"(",
")",
";",
"}"
] | This function assumes the clock is accurate. | [
"This",
"function",
"assumes",
"the",
"clock",
"is",
"accurate",
"."
] | bfa8eb258553f28b64eb9ec24371ec4bb65f3253 | https://github.com/jsdom/w3c-hr-time/blob/bfa8eb258553f28b64eb9ec24371ec4bb65f3253/lib/calculate-clock-offset.js#L14-L28 | train |
asciidisco/grunt-patternprimer | tasks/patternprimer.js | function (cb) {
// check if we have a custom index file set
if (settings.index) {
// generate the real index file path
var indexFile = process.cwd() + '/' + settings.index;
// check if the file exists, throw an error otherwise
if (!grunt.file.exists(indexFile)) {
grunt.log.error('Index file: "' + indexFile + '" not found');
cb('Index file: "' + indexFile + '" not found');
return;
}
// load the file contents
sourceFile = grunt.file.read(indexFile);
}
// modify the sourcefile css according to the settings
var css = settings.css.map(function (file) {
if (settings.snapshot && file.search('http://') !== -1) {
return '<link rel="stylesheet" type="text/css" href="' + path.basename(file) + '"/>';
} else {
return '<link rel="stylesheet" type="text/css" href="' + file + '"/>';
}
});
sourceFile = sourceFile.replace('{{css}}', css.join(''));
// spit out the default sourcefile
cb(sourceFile);
} | javascript | function (cb) {
// check if we have a custom index file set
if (settings.index) {
// generate the real index file path
var indexFile = process.cwd() + '/' + settings.index;
// check if the file exists, throw an error otherwise
if (!grunt.file.exists(indexFile)) {
grunt.log.error('Index file: "' + indexFile + '" not found');
cb('Index file: "' + indexFile + '" not found');
return;
}
// load the file contents
sourceFile = grunt.file.read(indexFile);
}
// modify the sourcefile css according to the settings
var css = settings.css.map(function (file) {
if (settings.snapshot && file.search('http://') !== -1) {
return '<link rel="stylesheet" type="text/css" href="' + path.basename(file) + '"/>';
} else {
return '<link rel="stylesheet" type="text/css" href="' + file + '"/>';
}
});
sourceFile = sourceFile.replace('{{css}}', css.join(''));
// spit out the default sourcefile
cb(sourceFile);
} | [
"function",
"(",
"cb",
")",
"{",
"if",
"(",
"settings",
".",
"index",
")",
"{",
"var",
"indexFile",
"=",
"process",
".",
"cwd",
"(",
")",
"+",
"'/'",
"+",
"settings",
".",
"index",
";",
"if",
"(",
"!",
"grunt",
".",
"file",
".",
"exists",
"(",
"indexFile",
")",
")",
"{",
"grunt",
".",
"log",
".",
"error",
"(",
"'Index file: \"'",
"+",
"indexFile",
"+",
"'\" not found'",
")",
";",
"cb",
"(",
"'Index file: \"'",
"+",
"indexFile",
"+",
"'\" not found'",
")",
";",
"return",
";",
"}",
"sourceFile",
"=",
"grunt",
".",
"file",
".",
"read",
"(",
"indexFile",
")",
";",
"}",
"var",
"css",
"=",
"settings",
".",
"css",
".",
"map",
"(",
"function",
"(",
"file",
")",
"{",
"if",
"(",
"settings",
".",
"snapshot",
"&&",
"file",
".",
"search",
"(",
"'http://'",
")",
"!==",
"-",
"1",
")",
"{",
"return",
"'<link rel=\"stylesheet\" type=\"text/css\" href=\"'",
"+",
"path",
".",
"basename",
"(",
"file",
")",
"+",
"'\"/>'",
";",
"}",
"else",
"{",
"return",
"'<link rel=\"stylesheet\" type=\"text/css\" href=\"'",
"+",
"file",
"+",
"'\"/>'",
";",
"}",
"}",
")",
";",
"sourceFile",
"=",
"sourceFile",
".",
"replace",
"(",
"'{{css}}'",
",",
"css",
".",
"join",
"(",
"''",
")",
")",
";",
"cb",
"(",
"sourceFile",
")",
";",
"}"
] | gets the user defined source file, or uses the default one | [
"gets",
"the",
"user",
"defined",
"source",
"file",
"or",
"uses",
"the",
"default",
"one"
] | ea0f58f10cde3d65428db7a70417f97016ba6977 | https://github.com/asciidisco/grunt-patternprimer/blob/ea0f58f10cde3d65428db7a70417f97016ba6977/tasks/patternprimer.js#L45-L74 | train |
|
asciidisco/grunt-patternprimer | tasks/patternprimer.js | function (patternFolder, patterns, cb) {
getSourceFile(function generatePatterns(content) {
patterns.forEach(function (file) {
content += '<hr/>';
content += '<div class="pattern"><div class="display">';
content += file.content;
content += '</div><div class="source"><textarea rows="6" cols="30">';
content += simpleEscaper(file.content);
content += '</textarea>';
content += '<p><a href="/'+ patternFolder + '/' + file.filename +'">' + file.filename + '</a></p>';
content += '</div></div>';
});
content += '</body></html>';
cb(content);
});
} | javascript | function (patternFolder, patterns, cb) {
getSourceFile(function generatePatterns(content) {
patterns.forEach(function (file) {
content += '<hr/>';
content += '<div class="pattern"><div class="display">';
content += file.content;
content += '</div><div class="source"><textarea rows="6" cols="30">';
content += simpleEscaper(file.content);
content += '</textarea>';
content += '<p><a href="/'+ patternFolder + '/' + file.filename +'">' + file.filename + '</a></p>';
content += '</div></div>';
});
content += '</body></html>';
cb(content);
});
} | [
"function",
"(",
"patternFolder",
",",
"patterns",
",",
"cb",
")",
"{",
"getSourceFile",
"(",
"function",
"generatePatterns",
"(",
"content",
")",
"{",
"patterns",
".",
"forEach",
"(",
"function",
"(",
"file",
")",
"{",
"content",
"+=",
"'<hr/>'",
";",
"content",
"+=",
"'<div class=\"pattern\"><div class=\"display\">'",
";",
"content",
"+=",
"file",
".",
"content",
";",
"content",
"+=",
"'</div><div class=\"source\"><textarea rows=\"6\" cols=\"30\">'",
";",
"content",
"+=",
"simpleEscaper",
"(",
"file",
".",
"content",
")",
";",
"content",
"+=",
"'</textarea>'",
";",
"content",
"+=",
"'<p><a href=\"/'",
"+",
"patternFolder",
"+",
"'/'",
"+",
"file",
".",
"filename",
"+",
"'\">'",
"+",
"file",
".",
"filename",
"+",
"'</a></p>'",
";",
"content",
"+=",
"'</div></div>'",
";",
"}",
")",
";",
"content",
"+=",
"'</body></html>'",
";",
"cb",
"(",
"content",
")",
";",
"}",
")",
";",
"}"
] | generates the html output for the patterns | [
"generates",
"the",
"html",
"output",
"for",
"the",
"patterns"
] | ea0f58f10cde3d65428db7a70417f97016ba6977 | https://github.com/asciidisco/grunt-patternprimer/blob/ea0f58f10cde3d65428db7a70417f97016ba6977/tasks/patternprimer.js#L77-L92 | train |
|
asciidisco/grunt-patternprimer | tasks/patternprimer.js | function (patternFolder, files, cb) {
var file, patterns = [];
files.forEach(function readPattern(pattern) {
file = {filename: pattern};
file.content = grunt.file.read(patternFolder + '/' + file.filename);
patterns.push(file);
});
// call the outputPatterns function that generates
// the html for every pattern
outputPatterns(patternFolder, patterns, cb);
} | javascript | function (patternFolder, files, cb) {
var file, patterns = [];
files.forEach(function readPattern(pattern) {
file = {filename: pattern};
file.content = grunt.file.read(patternFolder + '/' + file.filename);
patterns.push(file);
});
// call the outputPatterns function that generates
// the html for every pattern
outputPatterns(patternFolder, patterns, cb);
} | [
"function",
"(",
"patternFolder",
",",
"files",
",",
"cb",
")",
"{",
"var",
"file",
",",
"patterns",
"=",
"[",
"]",
";",
"files",
".",
"forEach",
"(",
"function",
"readPattern",
"(",
"pattern",
")",
"{",
"file",
"=",
"{",
"filename",
":",
"pattern",
"}",
";",
"file",
".",
"content",
"=",
"grunt",
".",
"file",
".",
"read",
"(",
"patternFolder",
"+",
"'/'",
"+",
"file",
".",
"filename",
")",
";",
"patterns",
".",
"push",
"(",
"file",
")",
";",
"}",
")",
";",
"outputPatterns",
"(",
"patternFolder",
",",
"patterns",
",",
"cb",
")",
";",
"}"
] | walks through the pattern folder reads all the contents of the pattern files | [
"walks",
"through",
"the",
"pattern",
"folder",
"reads",
"all",
"the",
"contents",
"of",
"the",
"pattern",
"files"
] | ea0f58f10cde3d65428db7a70417f97016ba6977 | https://github.com/asciidisco/grunt-patternprimer/blob/ea0f58f10cde3d65428db7a70417f97016ba6977/tasks/patternprimer.js#L96-L107 | train |
|
asciidisco/grunt-patternprimer | tasks/patternprimer.js | function (patternFolder, cb) {
// read pattern folder
fs.readdir(patternFolder, function (err, contents) {
// check for errors
if (err !== null && err.code === 'ENOENT') {
grunt.log.error('Cannot find patterns folder:', patternFolder);
cb('Cannot find patterns folder: ' + patternFolder);
return;
}
// list all pattern files (that end with .html)
var files = [];
contents.forEach(function (content) {
if (content.substr(-5) === '.html') {
files.push(content);
}
});
// handle all the found pattern files
handleFiles(patternFolder, files, cb);
});
} | javascript | function (patternFolder, cb) {
// read pattern folder
fs.readdir(patternFolder, function (err, contents) {
// check for errors
if (err !== null && err.code === 'ENOENT') {
grunt.log.error('Cannot find patterns folder:', patternFolder);
cb('Cannot find patterns folder: ' + patternFolder);
return;
}
// list all pattern files (that end with .html)
var files = [];
contents.forEach(function (content) {
if (content.substr(-5) === '.html') {
files.push(content);
}
});
// handle all the found pattern files
handleFiles(patternFolder, files, cb);
});
} | [
"function",
"(",
"patternFolder",
",",
"cb",
")",
"{",
"fs",
".",
"readdir",
"(",
"patternFolder",
",",
"function",
"(",
"err",
",",
"contents",
")",
"{",
"if",
"(",
"err",
"!==",
"null",
"&&",
"err",
".",
"code",
"===",
"'ENOENT'",
")",
"{",
"grunt",
".",
"log",
".",
"error",
"(",
"'Cannot find patterns folder:'",
",",
"patternFolder",
")",
";",
"cb",
"(",
"'Cannot find patterns folder: '",
"+",
"patternFolder",
")",
";",
"return",
";",
"}",
"var",
"files",
"=",
"[",
"]",
";",
"contents",
".",
"forEach",
"(",
"function",
"(",
"content",
")",
"{",
"if",
"(",
"content",
".",
"substr",
"(",
"-",
"5",
")",
"===",
"'.html'",
")",
"{",
"files",
".",
"push",
"(",
"content",
")",
";",
"}",
"}",
")",
";",
"handleFiles",
"(",
"patternFolder",
",",
"files",
",",
"cb",
")",
";",
"}",
")",
";",
"}"
] | reads all the patterns from the folder | [
"reads",
"all",
"the",
"patterns",
"from",
"the",
"folder"
] | ea0f58f10cde3d65428db7a70417f97016ba6977 | https://github.com/asciidisco/grunt-patternprimer/blob/ea0f58f10cde3d65428db7a70417f97016ba6977/tasks/patternprimer.js#L115-L135 | train |
|
ove/ove | packages/ove-lib-utils/src/persistence.js | function (item) {
let x;
switch (item.type) {
case Type.STRING:
case Type.NUMBER:
case Type.BOOLEAN:
case Type.UNDEFINED:
return item.value;
case Type.ARRAY:
x = [];
item.value.forEach(function (e) {
let key = e.key.substring(e.key.lastIndexOf('[') + 1, e.key.lastIndexOf(']'));
x[parseInt(key, 10)] = _fromPersistable(e);
});
return x;
case Type.OBJECT:
x = {};
item.value.forEach(function (e) {
let key = e.key.substring(e.key.lastIndexOf('[') + 1, e.key.lastIndexOf(']'));
x[key] = _fromPersistable(e);
});
return x;
default:
_logUnknownType(item.type);
}
} | javascript | function (item) {
let x;
switch (item.type) {
case Type.STRING:
case Type.NUMBER:
case Type.BOOLEAN:
case Type.UNDEFINED:
return item.value;
case Type.ARRAY:
x = [];
item.value.forEach(function (e) {
let key = e.key.substring(e.key.lastIndexOf('[') + 1, e.key.lastIndexOf(']'));
x[parseInt(key, 10)] = _fromPersistable(e);
});
return x;
case Type.OBJECT:
x = {};
item.value.forEach(function (e) {
let key = e.key.substring(e.key.lastIndexOf('[') + 1, e.key.lastIndexOf(']'));
x[key] = _fromPersistable(e);
});
return x;
default:
_logUnknownType(item.type);
}
} | [
"function",
"(",
"item",
")",
"{",
"let",
"x",
";",
"switch",
"(",
"item",
".",
"type",
")",
"{",
"case",
"Type",
".",
"STRING",
":",
"case",
"Type",
".",
"NUMBER",
":",
"case",
"Type",
".",
"BOOLEAN",
":",
"case",
"Type",
".",
"UNDEFINED",
":",
"return",
"item",
".",
"value",
";",
"case",
"Type",
".",
"ARRAY",
":",
"x",
"=",
"[",
"]",
";",
"item",
".",
"value",
".",
"forEach",
"(",
"function",
"(",
"e",
")",
"{",
"let",
"key",
"=",
"e",
".",
"key",
".",
"substring",
"(",
"e",
".",
"key",
".",
"lastIndexOf",
"(",
"'['",
")",
"+",
"1",
",",
"e",
".",
"key",
".",
"lastIndexOf",
"(",
"']'",
")",
")",
";",
"x",
"[",
"parseInt",
"(",
"key",
",",
"10",
")",
"]",
"=",
"_fromPersistable",
"(",
"e",
")",
";",
"}",
")",
";",
"return",
"x",
";",
"case",
"Type",
".",
"OBJECT",
":",
"x",
"=",
"{",
"}",
";",
"item",
".",
"value",
".",
"forEach",
"(",
"function",
"(",
"e",
")",
"{",
"let",
"key",
"=",
"e",
".",
"key",
".",
"substring",
"(",
"e",
".",
"key",
".",
"lastIndexOf",
"(",
"'['",
")",
"+",
"1",
",",
"e",
".",
"key",
".",
"lastIndexOf",
"(",
"']'",
")",
")",
";",
"x",
"[",
"key",
"]",
"=",
"_fromPersistable",
"(",
"e",
")",
";",
"}",
")",
";",
"return",
"x",
";",
"default",
":",
"_logUnknownType",
"(",
"item",
".",
"type",
")",
";",
"}",
"}"
] | A utility method to extract the original value in its original type. | [
"A",
"utility",
"method",
"to",
"extract",
"the",
"original",
"value",
"in",
"its",
"original",
"type",
"."
] | 28a167910bda3ca56d94aadaa90bfefca35eaa52 | https://github.com/ove/ove/blob/28a167910bda3ca56d94aadaa90bfefca35eaa52/packages/ove-lib-utils/src/persistence.js#L24-L49 | train |
|
ove/ove | packages/ove-lib-utils/src/persistence.js | Persistable | function Persistable (key, value) {
const __self = this;
__self.key = key;
// Set value and type of object.
if (value === undefined || value === null) {
__self.value = undefined;
__self.type = typeof undefined;
} else if (value instanceof Array) {
__self.value = [];
value.forEach(function (e, i) {
__self.value.push(new Persistable(key + '[' + i + ']', e));
});
__self.type = Type.ARRAY;
} else {
switch (typeof value) {
case Type.STRING:
case Type.NUMBER:
case Type.BOOLEAN:
__self.value = value;
__self.type = typeof value;
break;
case Type.OBJECT:
__self.value = [];
Object.keys(value).forEach(function (e) {
__self.value.push(new Persistable(key + '[' + e + ']', value[e]));
});
__self.type = typeof value;
break;
default:
_logUnknownType(typeof value);
}
}
__self.timestamp = Date.now();
__self.toOriginal = function () {
return _fromPersistable(__self);
};
} | javascript | function Persistable (key, value) {
const __self = this;
__self.key = key;
// Set value and type of object.
if (value === undefined || value === null) {
__self.value = undefined;
__self.type = typeof undefined;
} else if (value instanceof Array) {
__self.value = [];
value.forEach(function (e, i) {
__self.value.push(new Persistable(key + '[' + i + ']', e));
});
__self.type = Type.ARRAY;
} else {
switch (typeof value) {
case Type.STRING:
case Type.NUMBER:
case Type.BOOLEAN:
__self.value = value;
__self.type = typeof value;
break;
case Type.OBJECT:
__self.value = [];
Object.keys(value).forEach(function (e) {
__self.value.push(new Persistable(key + '[' + e + ']', value[e]));
});
__self.type = typeof value;
break;
default:
_logUnknownType(typeof value);
}
}
__self.timestamp = Date.now();
__self.toOriginal = function () {
return _fromPersistable(__self);
};
} | [
"function",
"Persistable",
"(",
"key",
",",
"value",
")",
"{",
"const",
"__self",
"=",
"this",
";",
"__self",
".",
"key",
"=",
"key",
";",
"if",
"(",
"value",
"===",
"undefined",
"||",
"value",
"===",
"null",
")",
"{",
"__self",
".",
"value",
"=",
"undefined",
";",
"__self",
".",
"type",
"=",
"typeof",
"undefined",
";",
"}",
"else",
"if",
"(",
"value",
"instanceof",
"Array",
")",
"{",
"__self",
".",
"value",
"=",
"[",
"]",
";",
"value",
".",
"forEach",
"(",
"function",
"(",
"e",
",",
"i",
")",
"{",
"__self",
".",
"value",
".",
"push",
"(",
"new",
"Persistable",
"(",
"key",
"+",
"'['",
"+",
"i",
"+",
"']'",
",",
"e",
")",
")",
";",
"}",
")",
";",
"__self",
".",
"type",
"=",
"Type",
".",
"ARRAY",
";",
"}",
"else",
"{",
"switch",
"(",
"typeof",
"value",
")",
"{",
"case",
"Type",
".",
"STRING",
":",
"case",
"Type",
".",
"NUMBER",
":",
"case",
"Type",
".",
"BOOLEAN",
":",
"__self",
".",
"value",
"=",
"value",
";",
"__self",
".",
"type",
"=",
"typeof",
"value",
";",
"break",
";",
"case",
"Type",
".",
"OBJECT",
":",
"__self",
".",
"value",
"=",
"[",
"]",
";",
"Object",
".",
"keys",
"(",
"value",
")",
".",
"forEach",
"(",
"function",
"(",
"e",
")",
"{",
"__self",
".",
"value",
".",
"push",
"(",
"new",
"Persistable",
"(",
"key",
"+",
"'['",
"+",
"e",
"+",
"']'",
",",
"value",
"[",
"e",
"]",
")",
")",
";",
"}",
")",
";",
"__self",
".",
"type",
"=",
"typeof",
"value",
";",
"break",
";",
"default",
":",
"_logUnknownType",
"(",
"typeof",
"value",
")",
";",
"}",
"}",
"__self",
".",
"timestamp",
"=",
"Date",
".",
"now",
"(",
")",
";",
"__self",
".",
"toOriginal",
"=",
"function",
"(",
")",
"{",
"return",
"_fromPersistable",
"(",
"__self",
")",
";",
"}",
";",
"}"
] | The persistable object. | [
"The",
"persistable",
"object",
"."
] | 28a167910bda3ca56d94aadaa90bfefca35eaa52 | https://github.com/ove/ove/blob/28a167910bda3ca56d94aadaa90bfefca35eaa52/packages/ove-lib-utils/src/persistence.js#L52-L91 | train |
ove/ove | packages/ove-lib-utils/src/persistence.js | function (item) {
item.value.sort(function (a, b) {
if (a.key < b.key) {
return -1;
}
/* istanbul ignore next */
// Below line exists only for the sake of completeness. Generally the array will
// always be sorted, and therefore it is impossible to get to this state in a test.
return a.key > b.key ? 1 : 0;
});
return item;
} | javascript | function (item) {
item.value.sort(function (a, b) {
if (a.key < b.key) {
return -1;
}
/* istanbul ignore next */
// Below line exists only for the sake of completeness. Generally the array will
// always be sorted, and therefore it is impossible to get to this state in a test.
return a.key > b.key ? 1 : 0;
});
return item;
} | [
"function",
"(",
"item",
")",
"{",
"item",
".",
"value",
".",
"sort",
"(",
"function",
"(",
"a",
",",
"b",
")",
"{",
"if",
"(",
"a",
".",
"key",
"<",
"b",
".",
"key",
")",
"{",
"return",
"-",
"1",
";",
"}",
"return",
"a",
".",
"key",
">",
"b",
".",
"key",
"?",
"1",
":",
"0",
";",
"}",
")",
";",
"return",
"item",
";",
"}"
] | A utility method to sort values of a persistable object or array, which is used when comparing current values with future values. | [
"A",
"utility",
"method",
"to",
"sort",
"values",
"of",
"a",
"persistable",
"object",
"or",
"array",
"which",
"is",
"used",
"when",
"comparing",
"current",
"values",
"with",
"future",
"values",
"."
] | 28a167910bda3ca56d94aadaa90bfefca35eaa52 | https://github.com/ove/ove/blob/28a167910bda3ca56d94aadaa90bfefca35eaa52/packages/ove-lib-utils/src/persistence.js#L182-L193 | train |
|
apollographql/graphql-tracer | src/Tracer.js | addTracingToResolvers | function addTracingToResolvers(schema) {
// XXX this is a hacky way of making sure that the schema only gets decorated
// with tracer once.
if (schema._apolloTracerApplied) {
// console.log('Tracing already added to resolve functions. Not adding again.');
return;
}
// eslint-disable-next-line no-param-reassign
schema._apolloTracerApplied = true;
forEachField(schema, (field, typeName, fieldName) => {
const functionName = `${typeName}.${fieldName}`;
if (field.resolve) {
// eslint-disable-next-line no-param-reassign
field.resolve = decorateWithTracer(
field.resolve,
{ type: 'resolve', functionName },
);
}
});
} | javascript | function addTracingToResolvers(schema) {
// XXX this is a hacky way of making sure that the schema only gets decorated
// with tracer once.
if (schema._apolloTracerApplied) {
// console.log('Tracing already added to resolve functions. Not adding again.');
return;
}
// eslint-disable-next-line no-param-reassign
schema._apolloTracerApplied = true;
forEachField(schema, (field, typeName, fieldName) => {
const functionName = `${typeName}.${fieldName}`;
if (field.resolve) {
// eslint-disable-next-line no-param-reassign
field.resolve = decorateWithTracer(
field.resolve,
{ type: 'resolve', functionName },
);
}
});
} | [
"function",
"addTracingToResolvers",
"(",
"schema",
")",
"{",
"if",
"(",
"schema",
".",
"_apolloTracerApplied",
")",
"{",
"return",
";",
"}",
"schema",
".",
"_apolloTracerApplied",
"=",
"true",
";",
"forEachField",
"(",
"schema",
",",
"(",
"field",
",",
"typeName",
",",
"fieldName",
")",
"=>",
"{",
"const",
"functionName",
"=",
"`",
"${",
"typeName",
"}",
"${",
"fieldName",
"}",
"`",
";",
"if",
"(",
"field",
".",
"resolve",
")",
"{",
"field",
".",
"resolve",
"=",
"decorateWithTracer",
"(",
"field",
".",
"resolve",
",",
"{",
"type",
":",
"'resolve'",
",",
"functionName",
"}",
",",
")",
";",
"}",
"}",
")",
";",
"}"
] | This function modifies the schema in place to add tracing around all resolve functions | [
"This",
"function",
"modifies",
"the",
"schema",
"in",
"place",
"to",
"add",
"tracing",
"around",
"all",
"resolve",
"functions"
] | b39577978b5222857b87e33332262e794f0f838f | https://github.com/apollographql/graphql-tracer/blob/b39577978b5222857b87e33332262e794f0f838f/src/Tracer.js#L193-L213 | train |
apollographql/graphql-tracer | src/Tracer.js | instrumentSchemaForExpressGraphQL | function instrumentSchemaForExpressGraphQL(schema) {
addTracingToResolvers(schema);
addSchemaLevelResolveFunction(schema, (root, args, ctx, info) => {
const operation = print(info.operation);
const fragments = Object.keys(info.fragments).map(k => print(info.fragments[k])).join('\n');
ctx.tracer.log('request.query', `${operation}\n${fragments}`);
ctx.tracer.log('request.variables', info.variableValues);
ctx.tracer.log('request.operationName', info.operation.name);
return root;
});
} | javascript | function instrumentSchemaForExpressGraphQL(schema) {
addTracingToResolvers(schema);
addSchemaLevelResolveFunction(schema, (root, args, ctx, info) => {
const operation = print(info.operation);
const fragments = Object.keys(info.fragments).map(k => print(info.fragments[k])).join('\n');
ctx.tracer.log('request.query', `${operation}\n${fragments}`);
ctx.tracer.log('request.variables', info.variableValues);
ctx.tracer.log('request.operationName', info.operation.name);
return root;
});
} | [
"function",
"instrumentSchemaForExpressGraphQL",
"(",
"schema",
")",
"{",
"addTracingToResolvers",
"(",
"schema",
")",
";",
"addSchemaLevelResolveFunction",
"(",
"schema",
",",
"(",
"root",
",",
"args",
",",
"ctx",
",",
"info",
")",
"=>",
"{",
"const",
"operation",
"=",
"print",
"(",
"info",
".",
"operation",
")",
";",
"const",
"fragments",
"=",
"Object",
".",
"keys",
"(",
"info",
".",
"fragments",
")",
".",
"map",
"(",
"k",
"=>",
"print",
"(",
"info",
".",
"fragments",
"[",
"k",
"]",
")",
")",
".",
"join",
"(",
"'\\n'",
")",
";",
"\\n",
"ctx",
".",
"tracer",
".",
"log",
"(",
"'request.query'",
",",
"`",
"${",
"operation",
"}",
"\\n",
"${",
"fragments",
"}",
"`",
")",
";",
"ctx",
".",
"tracer",
".",
"log",
"(",
"'request.variables'",
",",
"info",
".",
"variableValues",
")",
";",
"ctx",
".",
"tracer",
".",
"log",
"(",
"'request.operationName'",
",",
"info",
".",
"operation",
".",
"name",
")",
";",
"}",
")",
";",
"}"
] | This instruments a GraphQL.js schema when using tracer with express-graphql | [
"This",
"instruments",
"a",
"GraphQL",
".",
"js",
"schema",
"when",
"using",
"tracer",
"with",
"express",
"-",
"graphql"
] | b39577978b5222857b87e33332262e794f0f838f | https://github.com/apollographql/graphql-tracer/blob/b39577978b5222857b87e33332262e794f0f838f/src/Tracer.js#L216-L227 | train |
skatejs/named-slots | src/v1/index.js | indexOfNode | function indexOfNode (host, node) {
const chs = host.childNodes;
const chsLen = chs.length;
for (let a = 0; a < chsLen; a++) {
if (chs[a] === node) {
return a;
}
}
return -1;
} | javascript | function indexOfNode (host, node) {
const chs = host.childNodes;
const chsLen = chs.length;
for (let a = 0; a < chsLen; a++) {
if (chs[a] === node) {
return a;
}
}
return -1;
} | [
"function",
"indexOfNode",
"(",
"host",
",",
"node",
")",
"{",
"const",
"chs",
"=",
"host",
".",
"childNodes",
";",
"const",
"chsLen",
"=",
"chs",
".",
"length",
";",
"for",
"(",
"let",
"a",
"=",
"0",
";",
"a",
"<",
"chsLen",
";",
"a",
"++",
")",
"{",
"if",
"(",
"chs",
"[",
"a",
"]",
"===",
"node",
")",
"{",
"return",
"a",
";",
"}",
"}",
"return",
"-",
"1",
";",
"}"
] | Returns the index of the node in the host's childNodes. | [
"Returns",
"the",
"index",
"of",
"the",
"node",
"in",
"the",
"host",
"s",
"childNodes",
"."
] | 53aa799e23435867189e7cbc63d6f3a8eec62cb8 | https://github.com/skatejs/named-slots/blob/53aa799e23435867189e7cbc63d6f3a8eec62cb8/src/v1/index.js#L209-L218 | train |
skatejs/named-slots | src/v1/index.js | registerNode | function registerNode (host, node, insertBefore, func) {
const index = indexOfNode(host, insertBefore);
eachNodeOrFragmentNodes(node, (eachNode, eachIndex) => {
func(eachNode, eachIndex);
if (canPatchNativeAccessors) {
nodeToParentNodeMap.set(eachNode, host);
} else {
staticProp(eachNode, 'parentNode', host);
}
// When childNodes is artificial, do manual house keeping.
if (Array.isArray(host.childNodes)) {
if (index > -1) {
arrProto.splice.call(host.childNodes, index + eachIndex, 0, eachNode);
} else {
arrProto.push.call(host.childNodes, eachNode);
}
}
});
} | javascript | function registerNode (host, node, insertBefore, func) {
const index = indexOfNode(host, insertBefore);
eachNodeOrFragmentNodes(node, (eachNode, eachIndex) => {
func(eachNode, eachIndex);
if (canPatchNativeAccessors) {
nodeToParentNodeMap.set(eachNode, host);
} else {
staticProp(eachNode, 'parentNode', host);
}
// When childNodes is artificial, do manual house keeping.
if (Array.isArray(host.childNodes)) {
if (index > -1) {
arrProto.splice.call(host.childNodes, index + eachIndex, 0, eachNode);
} else {
arrProto.push.call(host.childNodes, eachNode);
}
}
});
} | [
"function",
"registerNode",
"(",
"host",
",",
"node",
",",
"insertBefore",
",",
"func",
")",
"{",
"const",
"index",
"=",
"indexOfNode",
"(",
"host",
",",
"insertBefore",
")",
";",
"eachNodeOrFragmentNodes",
"(",
"node",
",",
"(",
"eachNode",
",",
"eachIndex",
")",
"=>",
"{",
"func",
"(",
"eachNode",
",",
"eachIndex",
")",
";",
"if",
"(",
"canPatchNativeAccessors",
")",
"{",
"nodeToParentNodeMap",
".",
"set",
"(",
"eachNode",
",",
"host",
")",
";",
"}",
"else",
"{",
"staticProp",
"(",
"eachNode",
",",
"'parentNode'",
",",
"host",
")",
";",
"}",
"if",
"(",
"Array",
".",
"isArray",
"(",
"host",
".",
"childNodes",
")",
")",
"{",
"if",
"(",
"index",
">",
"-",
"1",
")",
"{",
"arrProto",
".",
"splice",
".",
"call",
"(",
"host",
".",
"childNodes",
",",
"index",
"+",
"eachIndex",
",",
"0",
",",
"eachNode",
")",
";",
"}",
"else",
"{",
"arrProto",
".",
"push",
".",
"call",
"(",
"host",
".",
"childNodes",
",",
"eachNode",
")",
";",
"}",
"}",
"}",
")",
";",
"}"
] | Adds the node to the list of childNodes on the host and fakes any necessary information such as parentNode. | [
"Adds",
"the",
"node",
"to",
"the",
"list",
"of",
"childNodes",
"on",
"the",
"host",
"and",
"fakes",
"any",
"necessary",
"information",
"such",
"as",
"parentNode",
"."
] | 53aa799e23435867189e7cbc63d6f3a8eec62cb8 | https://github.com/skatejs/named-slots/blob/53aa799e23435867189e7cbc63d6f3a8eec62cb8/src/v1/index.js#L222-L242 | train |
skatejs/named-slots | src/v1/index.js | addNodeToSlot | function addNodeToSlot (slot, node, insertBefore) {
const isInDefaultMode = slot.assignedNodes().length === 0;
registerNode(slot, node, insertBefore, eachNode => {
if (isInDefaultMode) {
slot.__insertBefore(eachNode, insertBefore !== undefined ? insertBefore : null);
}
});
} | javascript | function addNodeToSlot (slot, node, insertBefore) {
const isInDefaultMode = slot.assignedNodes().length === 0;
registerNode(slot, node, insertBefore, eachNode => {
if (isInDefaultMode) {
slot.__insertBefore(eachNode, insertBefore !== undefined ? insertBefore : null);
}
});
} | [
"function",
"addNodeToSlot",
"(",
"slot",
",",
"node",
",",
"insertBefore",
")",
"{",
"const",
"isInDefaultMode",
"=",
"slot",
".",
"assignedNodes",
"(",
")",
".",
"length",
"===",
"0",
";",
"registerNode",
"(",
"slot",
",",
"node",
",",
"insertBefore",
",",
"eachNode",
"=>",
"{",
"if",
"(",
"isInDefaultMode",
")",
"{",
"slot",
".",
"__insertBefore",
"(",
"eachNode",
",",
"insertBefore",
"!==",
"undefined",
"?",
"insertBefore",
":",
"null",
")",
";",
"}",
"}",
")",
";",
"}"
] | Adds a node to a slot. In other words, adds default content to a slot. It ensures that if the slot doesn't have any assigned nodes yet, that the node is actually displayed, otherwise it's just registered as child content. | [
"Adds",
"a",
"node",
"to",
"a",
"slot",
".",
"In",
"other",
"words",
"adds",
"default",
"content",
"to",
"a",
"slot",
".",
"It",
"ensures",
"that",
"if",
"the",
"slot",
"doesn",
"t",
"have",
"any",
"assigned",
"nodes",
"yet",
"that",
"the",
"node",
"is",
"actually",
"displayed",
"otherwise",
"it",
"s",
"just",
"registered",
"as",
"child",
"content",
"."
] | 53aa799e23435867189e7cbc63d6f3a8eec62cb8 | https://github.com/skatejs/named-slots/blob/53aa799e23435867189e7cbc63d6f3a8eec62cb8/src/v1/index.js#L320-L327 | train |
ove/ove | packages/ove-core/src/client/view/core.js | function () {
if (!window.ove.context.isInitialized) {
log.debug('Requesting an update of state configuration from server');
window.ove.socket.send({ action: Constants.Action.READ });
}
} | javascript | function () {
if (!window.ove.context.isInitialized) {
log.debug('Requesting an update of state configuration from server');
window.ove.socket.send({ action: Constants.Action.READ });
}
} | [
"function",
"(",
")",
"{",
"if",
"(",
"!",
"window",
".",
"ove",
".",
"context",
".",
"isInitialized",
")",
"{",
"log",
".",
"debug",
"(",
"'Requesting an update of state configuration from server'",
")",
";",
"window",
".",
"ove",
".",
"socket",
".",
"send",
"(",
"{",
"action",
":",
"Constants",
".",
"Action",
".",
"READ",
"}",
")",
";",
"}",
"}"
] | We will attempt to load content by restoring the existing state either after a period of time or when the browser is resized. | [
"We",
"will",
"attempt",
"to",
"load",
"content",
"by",
"restoring",
"the",
"existing",
"state",
"either",
"after",
"a",
"period",
"of",
"time",
"or",
"when",
"the",
"browser",
"is",
"resized",
"."
] | 28a167910bda3ca56d94aadaa90bfefca35eaa52 | https://github.com/ove/ove/blob/28a167910bda3ca56d94aadaa90bfefca35eaa52/packages/ove-core/src/client/view/core.js#L17-L22 | train |
|
ove/ove | packages/ove-core/src/server/api.js | function (req, res) {
let sectionId = req.query.oveSectionId;
if (sectionId === undefined) {
log.debug('Returning parsed result of ' + Constants.SPACES_JSON_FILENAME);
Utils.sendMessage(res, HttpStatus.OK, JSON.stringify(server.spaces));
} else if (!server.state.get('sections[' + sectionId + ']')) {
log.debug('Unable to produce list of spaces for section id:', sectionId);
Utils.sendEmptySuccess(res);
} else {
log.debug('Returning parsed result of ' + Constants.SPACES_JSON_FILENAME + ' for section id:', sectionId);
Utils.sendMessage(res, HttpStatus.OK, JSON.stringify(server.state.get('sections[' + sectionId + '][spaces]')));
}
} | javascript | function (req, res) {
let sectionId = req.query.oveSectionId;
if (sectionId === undefined) {
log.debug('Returning parsed result of ' + Constants.SPACES_JSON_FILENAME);
Utils.sendMessage(res, HttpStatus.OK, JSON.stringify(server.spaces));
} else if (!server.state.get('sections[' + sectionId + ']')) {
log.debug('Unable to produce list of spaces for section id:', sectionId);
Utils.sendEmptySuccess(res);
} else {
log.debug('Returning parsed result of ' + Constants.SPACES_JSON_FILENAME + ' for section id:', sectionId);
Utils.sendMessage(res, HttpStatus.OK, JSON.stringify(server.state.get('sections[' + sectionId + '][spaces]')));
}
} | [
"function",
"(",
"req",
",",
"res",
")",
"{",
"let",
"sectionId",
"=",
"req",
".",
"query",
".",
"oveSectionId",
";",
"if",
"(",
"sectionId",
"===",
"undefined",
")",
"{",
"log",
".",
"debug",
"(",
"'Returning parsed result of '",
"+",
"Constants",
".",
"SPACES_JSON_FILENAME",
")",
";",
"Utils",
".",
"sendMessage",
"(",
"res",
",",
"HttpStatus",
".",
"OK",
",",
"JSON",
".",
"stringify",
"(",
"server",
".",
"spaces",
")",
")",
";",
"}",
"else",
"if",
"(",
"!",
"server",
".",
"state",
".",
"get",
"(",
"'sections['",
"+",
"sectionId",
"+",
"']'",
")",
")",
"{",
"log",
".",
"debug",
"(",
"'Unable to produce list of spaces for section id:'",
",",
"sectionId",
")",
";",
"Utils",
".",
"sendEmptySuccess",
"(",
"res",
")",
";",
"}",
"else",
"{",
"log",
".",
"debug",
"(",
"'Returning parsed result of '",
"+",
"Constants",
".",
"SPACES_JSON_FILENAME",
"+",
"' for section id:'",
",",
"sectionId",
")",
";",
"Utils",
".",
"sendMessage",
"(",
"res",
",",
"HttpStatus",
".",
"OK",
",",
"JSON",
".",
"stringify",
"(",
"server",
".",
"state",
".",
"get",
"(",
"'sections['",
"+",
"sectionId",
"+",
"'][spaces]'",
")",
")",
")",
";",
"}",
"}"
] | Lists details of all spaces, and accepts filters as a part of its query string. | [
"Lists",
"details",
"of",
"all",
"spaces",
"and",
"accepts",
"filters",
"as",
"a",
"part",
"of",
"its",
"query",
"string",
"."
] | 28a167910bda3ca56d94aadaa90bfefca35eaa52 | https://github.com/ove/ove/blob/28a167910bda3ca56d94aadaa90bfefca35eaa52/packages/ove-core/src/server/api.js#L10-L22 | train |
|
ove/ove | packages/ove-core/src/server/api.js | function () {
if (Utils.isNullOrEmpty(server.spaceGeometries) && !Utils.isNullOrEmpty(server.spaces)) {
Object.keys(server.spaces).forEach(function (s) {
const geometry = { w: Number.MIN_VALUE, h: Number.MIN_VALUE };
server.spaces[s].forEach(function (e) {
geometry.w = Math.max(e.x + e.w, geometry.w);
geometry.h = Math.max(e.y + e.h, geometry.h);
});
log.debug('Successfully computed geometry for space:', s);
server.spaceGeometries[s] = geometry;
});
}
return server.spaceGeometries;
} | javascript | function () {
if (Utils.isNullOrEmpty(server.spaceGeometries) && !Utils.isNullOrEmpty(server.spaces)) {
Object.keys(server.spaces).forEach(function (s) {
const geometry = { w: Number.MIN_VALUE, h: Number.MIN_VALUE };
server.spaces[s].forEach(function (e) {
geometry.w = Math.max(e.x + e.w, geometry.w);
geometry.h = Math.max(e.y + e.h, geometry.h);
});
log.debug('Successfully computed geometry for space:', s);
server.spaceGeometries[s] = geometry;
});
}
return server.spaceGeometries;
} | [
"function",
"(",
")",
"{",
"if",
"(",
"Utils",
".",
"isNullOrEmpty",
"(",
"server",
".",
"spaceGeometries",
")",
"&&",
"!",
"Utils",
".",
"isNullOrEmpty",
"(",
"server",
".",
"spaces",
")",
")",
"{",
"Object",
".",
"keys",
"(",
"server",
".",
"spaces",
")",
".",
"forEach",
"(",
"function",
"(",
"s",
")",
"{",
"const",
"geometry",
"=",
"{",
"w",
":",
"Number",
".",
"MIN_VALUE",
",",
"h",
":",
"Number",
".",
"MIN_VALUE",
"}",
";",
"server",
".",
"spaces",
"[",
"s",
"]",
".",
"forEach",
"(",
"function",
"(",
"e",
")",
"{",
"geometry",
".",
"w",
"=",
"Math",
".",
"max",
"(",
"e",
".",
"x",
"+",
"e",
".",
"w",
",",
"geometry",
".",
"w",
")",
";",
"geometry",
".",
"h",
"=",
"Math",
".",
"max",
"(",
"e",
".",
"y",
"+",
"e",
".",
"h",
",",
"geometry",
".",
"h",
")",
";",
"}",
")",
";",
"log",
".",
"debug",
"(",
"'Successfully computed geometry for space:'",
",",
"s",
")",
";",
"server",
".",
"spaceGeometries",
"[",
"s",
"]",
"=",
"geometry",
";",
"}",
")",
";",
"}",
"return",
"server",
".",
"spaceGeometries",
";",
"}"
] | Internal utility function to calculate space geometries. | [
"Internal",
"utility",
"function",
"to",
"calculate",
"space",
"geometries",
"."
] | 28a167910bda3ca56d94aadaa90bfefca35eaa52 | https://github.com/ove/ove/blob/28a167910bda3ca56d94aadaa90bfefca35eaa52/packages/ove-core/src/server/api.js#L25-L38 | train |
|
ove/ove | packages/ove-core/src/server/api.js | function (req, res) {
const spaceName = req.params.name;
const geometry = _getSpaceGeometries()[spaceName];
if (Utils.isNullOrEmpty(geometry)) {
log.error('Invalid Space', 'name:', spaceName);
Utils.sendMessage(res, HttpStatus.BAD_REQUEST, JSON.stringify({ error: 'invalid space' }));
} else {
log.debug('Returning geometry for space:', spaceName);
Utils.sendMessage(res, HttpStatus.OK, JSON.stringify(geometry));
}
} | javascript | function (req, res) {
const spaceName = req.params.name;
const geometry = _getSpaceGeometries()[spaceName];
if (Utils.isNullOrEmpty(geometry)) {
log.error('Invalid Space', 'name:', spaceName);
Utils.sendMessage(res, HttpStatus.BAD_REQUEST, JSON.stringify({ error: 'invalid space' }));
} else {
log.debug('Returning geometry for space:', spaceName);
Utils.sendMessage(res, HttpStatus.OK, JSON.stringify(geometry));
}
} | [
"function",
"(",
"req",
",",
"res",
")",
"{",
"const",
"spaceName",
"=",
"req",
".",
"params",
".",
"name",
";",
"const",
"geometry",
"=",
"_getSpaceGeometries",
"(",
")",
"[",
"spaceName",
"]",
";",
"if",
"(",
"Utils",
".",
"isNullOrEmpty",
"(",
"geometry",
")",
")",
"{",
"log",
".",
"error",
"(",
"'Invalid Space'",
",",
"'name:'",
",",
"spaceName",
")",
";",
"Utils",
".",
"sendMessage",
"(",
"res",
",",
"HttpStatus",
".",
"BAD_REQUEST",
",",
"JSON",
".",
"stringify",
"(",
"{",
"error",
":",
"'invalid space'",
"}",
")",
")",
";",
"}",
"else",
"{",
"log",
".",
"debug",
"(",
"'Returning geometry for space:'",
",",
"spaceName",
")",
";",
"Utils",
".",
"sendMessage",
"(",
"res",
",",
"HttpStatus",
".",
"OK",
",",
"JSON",
".",
"stringify",
"(",
"geometry",
")",
")",
";",
"}",
"}"
] | Gets geometry of a named space. | [
"Gets",
"geometry",
"of",
"a",
"named",
"space",
"."
] | 28a167910bda3ca56d94aadaa90bfefca35eaa52 | https://github.com/ove/ove/blob/28a167910bda3ca56d94aadaa90bfefca35eaa52/packages/ove-core/src/server/api.js#L41-L51 | train |
|
ove/ove | packages/ove-core/src/server/api.js | function (sectionId) {
let section = server.state.get('sections[' + sectionId + ']');
if (section.app && section.app.url) {
log.debug('Flushing application at URL:', section.app.url);
request.post(section.app.url + '/instances/' + sectionId + '/flush', _handleRequestError);
}
server.state.get('groups').forEach(function (e, groupId) {
if (e.includes(parseInt(sectionId, 10))) {
// The outcome of this operation is logged within the internal utility method
if (e.length === 1) {
_deleteGroupById(groupId);
} else {
e.splice(e.indexOf(parseInt(sectionId, 10)), 1);
server.state.set('groups[' + groupId + ']', e);
}
}
});
server.state.set('sections[' + sectionId + ']', {});
server.wss.clients.forEach(function (c) {
if (c.readyState === Constants.WEBSOCKET_READY) {
c.safeSend(JSON.stringify({ appId: Constants.APP_NAME, message: { action: Constants.Action.DELETE, id: parseInt(sectionId, 10) } }));
}
});
} | javascript | function (sectionId) {
let section = server.state.get('sections[' + sectionId + ']');
if (section.app && section.app.url) {
log.debug('Flushing application at URL:', section.app.url);
request.post(section.app.url + '/instances/' + sectionId + '/flush', _handleRequestError);
}
server.state.get('groups').forEach(function (e, groupId) {
if (e.includes(parseInt(sectionId, 10))) {
// The outcome of this operation is logged within the internal utility method
if (e.length === 1) {
_deleteGroupById(groupId);
} else {
e.splice(e.indexOf(parseInt(sectionId, 10)), 1);
server.state.set('groups[' + groupId + ']', e);
}
}
});
server.state.set('sections[' + sectionId + ']', {});
server.wss.clients.forEach(function (c) {
if (c.readyState === Constants.WEBSOCKET_READY) {
c.safeSend(JSON.stringify({ appId: Constants.APP_NAME, message: { action: Constants.Action.DELETE, id: parseInt(sectionId, 10) } }));
}
});
} | [
"function",
"(",
"sectionId",
")",
"{",
"let",
"section",
"=",
"server",
".",
"state",
".",
"get",
"(",
"'sections['",
"+",
"sectionId",
"+",
"']'",
")",
";",
"if",
"(",
"section",
".",
"app",
"&&",
"section",
".",
"app",
".",
"url",
")",
"{",
"log",
".",
"debug",
"(",
"'Flushing application at URL:'",
",",
"section",
".",
"app",
".",
"url",
")",
";",
"request",
".",
"post",
"(",
"section",
".",
"app",
".",
"url",
"+",
"'/instances/'",
"+",
"sectionId",
"+",
"'/flush'",
",",
"_handleRequestError",
")",
";",
"}",
"server",
".",
"state",
".",
"get",
"(",
"'groups'",
")",
".",
"forEach",
"(",
"function",
"(",
"e",
",",
"groupId",
")",
"{",
"if",
"(",
"e",
".",
"includes",
"(",
"parseInt",
"(",
"sectionId",
",",
"10",
")",
")",
")",
"{",
"if",
"(",
"e",
".",
"length",
"===",
"1",
")",
"{",
"_deleteGroupById",
"(",
"groupId",
")",
";",
"}",
"else",
"{",
"e",
".",
"splice",
"(",
"e",
".",
"indexOf",
"(",
"parseInt",
"(",
"sectionId",
",",
"10",
")",
")",
",",
"1",
")",
";",
"server",
".",
"state",
".",
"set",
"(",
"'groups['",
"+",
"groupId",
"+",
"']'",
",",
"e",
")",
";",
"}",
"}",
"}",
")",
";",
"server",
".",
"state",
".",
"set",
"(",
"'sections['",
"+",
"sectionId",
"+",
"']'",
",",
"{",
"}",
")",
";",
"server",
".",
"wss",
".",
"clients",
".",
"forEach",
"(",
"function",
"(",
"c",
")",
"{",
"if",
"(",
"c",
".",
"readyState",
"===",
"Constants",
".",
"WEBSOCKET_READY",
")",
"{",
"c",
".",
"safeSend",
"(",
"JSON",
".",
"stringify",
"(",
"{",
"appId",
":",
"Constants",
".",
"APP_NAME",
",",
"message",
":",
"{",
"action",
":",
"Constants",
".",
"Action",
".",
"DELETE",
",",
"id",
":",
"parseInt",
"(",
"sectionId",
",",
"10",
")",
"}",
"}",
")",
")",
";",
"}",
"}",
")",
";",
"}"
] | Internal utility function to delete section by a given id. This function is used either to delete all sections belonging to a given space, or to delete a specific section by its id. | [
"Internal",
"utility",
"function",
"to",
"delete",
"section",
"by",
"a",
"given",
"id",
".",
"This",
"function",
"is",
"used",
"either",
"to",
"delete",
"all",
"sections",
"belonging",
"to",
"a",
"given",
"space",
"or",
"to",
"delete",
"a",
"specific",
"section",
"by",
"its",
"id",
"."
] | 28a167910bda3ca56d94aadaa90bfefca35eaa52 | https://github.com/ove/ove/blob/28a167910bda3ca56d94aadaa90bfefca35eaa52/packages/ove-core/src/server/api.js#L212-L236 | train |
|
ove/ove | packages/ove-core/src/server/api.js | function (req, res) {
_updateSections({ moveTo: req.body }, req.query.space, req.query.groupId, res);
} | javascript | function (req, res) {
_updateSections({ moveTo: req.body }, req.query.space, req.query.groupId, res);
} | [
"function",
"(",
"req",
",",
"res",
")",
"{",
"_updateSections",
"(",
"{",
"moveTo",
":",
"req",
".",
"body",
"}",
",",
"req",
".",
"query",
".",
"space",
",",
"req",
".",
"query",
".",
"groupId",
",",
"res",
")",
";",
"}"
] | Moves sections to another space | [
"Moves",
"sections",
"to",
"another",
"space"
] | 28a167910bda3ca56d94aadaa90bfefca35eaa52 | https://github.com/ove/ove/blob/28a167910bda3ca56d94aadaa90bfefca35eaa52/packages/ove-core/src/server/api.js#L604-L606 | train |
|
ove/ove | packages/ove-core/src/server/api.js | function (req, res) {
let sectionId = req.params.id;
let s = server.state.get('sections[' + sectionId + ']');
if (Utils.isNullOrEmpty(s)) {
log.debug('Unable to read configuration for section id:', sectionId);
Utils.sendEmptySuccess(res);
return;
}
let section = {
id: parseInt(sectionId, 10), x: s.x, y: s.y, w: s.w, h: s.h, space: Object.keys(s.spaces)[0]
};
const app = s.app;
if (app) {
section.app = { url: app.url, state: app.state, opacity: app.opacity };
}
log.debug('Successfully read configuration for section id:', sectionId);
Utils.sendMessage(res, HttpStatus.OK, JSON.stringify(section));
} | javascript | function (req, res) {
let sectionId = req.params.id;
let s = server.state.get('sections[' + sectionId + ']');
if (Utils.isNullOrEmpty(s)) {
log.debug('Unable to read configuration for section id:', sectionId);
Utils.sendEmptySuccess(res);
return;
}
let section = {
id: parseInt(sectionId, 10), x: s.x, y: s.y, w: s.w, h: s.h, space: Object.keys(s.spaces)[0]
};
const app = s.app;
if (app) {
section.app = { url: app.url, state: app.state, opacity: app.opacity };
}
log.debug('Successfully read configuration for section id:', sectionId);
Utils.sendMessage(res, HttpStatus.OK, JSON.stringify(section));
} | [
"function",
"(",
"req",
",",
"res",
")",
"{",
"let",
"sectionId",
"=",
"req",
".",
"params",
".",
"id",
";",
"let",
"s",
"=",
"server",
".",
"state",
".",
"get",
"(",
"'sections['",
"+",
"sectionId",
"+",
"']'",
")",
";",
"if",
"(",
"Utils",
".",
"isNullOrEmpty",
"(",
"s",
")",
")",
"{",
"log",
".",
"debug",
"(",
"'Unable to read configuration for section id:'",
",",
"sectionId",
")",
";",
"Utils",
".",
"sendEmptySuccess",
"(",
"res",
")",
";",
"return",
";",
"}",
"let",
"section",
"=",
"{",
"id",
":",
"parseInt",
"(",
"sectionId",
",",
"10",
")",
",",
"x",
":",
"s",
".",
"x",
",",
"y",
":",
"s",
".",
"y",
",",
"w",
":",
"s",
".",
"w",
",",
"h",
":",
"s",
".",
"h",
",",
"space",
":",
"Object",
".",
"keys",
"(",
"s",
".",
"spaces",
")",
"[",
"0",
"]",
"}",
";",
"const",
"app",
"=",
"s",
".",
"app",
";",
"if",
"(",
"app",
")",
"{",
"section",
".",
"app",
"=",
"{",
"url",
":",
"app",
".",
"url",
",",
"state",
":",
"app",
".",
"state",
",",
"opacity",
":",
"app",
".",
"opacity",
"}",
";",
"}",
"log",
".",
"debug",
"(",
"'Successfully read configuration for section id:'",
",",
"sectionId",
")",
";",
"Utils",
".",
"sendMessage",
"(",
"res",
",",
"HttpStatus",
".",
"OK",
",",
"JSON",
".",
"stringify",
"(",
"section",
")",
")",
";",
"}"
] | Fetches details of an individual section | [
"Fetches",
"details",
"of",
"an",
"individual",
"section"
] | 28a167910bda3ca56d94aadaa90bfefca35eaa52 | https://github.com/ove/ove/blob/28a167910bda3ca56d94aadaa90bfefca35eaa52/packages/ove-core/src/server/api.js#L609-L627 | train |
|
ove/ove | packages/ove-core/src/server/api.js | function (req, res) {
let sectionId = req.params.id;
if (Utils.isNullOrEmpty(server.state.get('sections[' + sectionId + ']'))) {
log.error('Invalid Section Id:', sectionId);
Utils.sendMessage(res, HttpStatus.BAD_REQUEST, JSON.stringify({ error: 'invalid section id' }));
} else {
_deleteSectionById(sectionId);
log.info('Successfully deleted section:', sectionId);
Utils.sendMessage(res, HttpStatus.OK, JSON.stringify({ ids: [ parseInt(sectionId, 10) ] }));
}
} | javascript | function (req, res) {
let sectionId = req.params.id;
if (Utils.isNullOrEmpty(server.state.get('sections[' + sectionId + ']'))) {
log.error('Invalid Section Id:', sectionId);
Utils.sendMessage(res, HttpStatus.BAD_REQUEST, JSON.stringify({ error: 'invalid section id' }));
} else {
_deleteSectionById(sectionId);
log.info('Successfully deleted section:', sectionId);
Utils.sendMessage(res, HttpStatus.OK, JSON.stringify({ ids: [ parseInt(sectionId, 10) ] }));
}
} | [
"function",
"(",
"req",
",",
"res",
")",
"{",
"let",
"sectionId",
"=",
"req",
".",
"params",
".",
"id",
";",
"if",
"(",
"Utils",
".",
"isNullOrEmpty",
"(",
"server",
".",
"state",
".",
"get",
"(",
"'sections['",
"+",
"sectionId",
"+",
"']'",
")",
")",
")",
"{",
"log",
".",
"error",
"(",
"'Invalid Section Id:'",
",",
"sectionId",
")",
";",
"Utils",
".",
"sendMessage",
"(",
"res",
",",
"HttpStatus",
".",
"BAD_REQUEST",
",",
"JSON",
".",
"stringify",
"(",
"{",
"error",
":",
"'invalid section id'",
"}",
")",
")",
";",
"}",
"else",
"{",
"_deleteSectionById",
"(",
"sectionId",
")",
";",
"log",
".",
"info",
"(",
"'Successfully deleted section:'",
",",
"sectionId",
")",
";",
"Utils",
".",
"sendMessage",
"(",
"res",
",",
"HttpStatus",
".",
"OK",
",",
"JSON",
".",
"stringify",
"(",
"{",
"ids",
":",
"[",
"parseInt",
"(",
"sectionId",
",",
"10",
")",
"]",
"}",
")",
")",
";",
"}",
"}"
] | Deletes an individual section | [
"Deletes",
"an",
"individual",
"section"
] | 28a167910bda3ca56d94aadaa90bfefca35eaa52 | https://github.com/ove/ove/blob/28a167910bda3ca56d94aadaa90bfefca35eaa52/packages/ove-core/src/server/api.js#L663-L673 | train |
|
ove/ove | packages/ove-core/src/server/api.js | function (groupId, operation, req, res) {
const validateSections = function (group) {
let valid = true;
const sections = server.state.get('sections');
group.forEach(function (e) {
if (Utils.isNullOrEmpty(sections[e])) {
valid = false;
}
});
return valid;
};
if (!req.body || !req.body.length || !validateSections(req.body)) {
log.error('Invalid Group', 'request:', JSON.stringify(req.body));
Utils.sendMessage(res, HttpStatus.BAD_REQUEST, JSON.stringify({ error: 'invalid group' }));
} else {
server.state.set('groups[' + groupId + ']', req.body.slice());
log.info('Successfully ' + operation + 'd group:', groupId);
Utils.sendMessage(res, HttpStatus.OK, JSON.stringify({ id: parseInt(groupId, 10) }));
}
} | javascript | function (groupId, operation, req, res) {
const validateSections = function (group) {
let valid = true;
const sections = server.state.get('sections');
group.forEach(function (e) {
if (Utils.isNullOrEmpty(sections[e])) {
valid = false;
}
});
return valid;
};
if (!req.body || !req.body.length || !validateSections(req.body)) {
log.error('Invalid Group', 'request:', JSON.stringify(req.body));
Utils.sendMessage(res, HttpStatus.BAD_REQUEST, JSON.stringify({ error: 'invalid group' }));
} else {
server.state.set('groups[' + groupId + ']', req.body.slice());
log.info('Successfully ' + operation + 'd group:', groupId);
Utils.sendMessage(res, HttpStatus.OK, JSON.stringify({ id: parseInt(groupId, 10) }));
}
} | [
"function",
"(",
"groupId",
",",
"operation",
",",
"req",
",",
"res",
")",
"{",
"const",
"validateSections",
"=",
"function",
"(",
"group",
")",
"{",
"let",
"valid",
"=",
"true",
";",
"const",
"sections",
"=",
"server",
".",
"state",
".",
"get",
"(",
"'sections'",
")",
";",
"group",
".",
"forEach",
"(",
"function",
"(",
"e",
")",
"{",
"if",
"(",
"Utils",
".",
"isNullOrEmpty",
"(",
"sections",
"[",
"e",
"]",
")",
")",
"{",
"valid",
"=",
"false",
";",
"}",
"}",
")",
";",
"return",
"valid",
";",
"}",
";",
"if",
"(",
"!",
"req",
".",
"body",
"||",
"!",
"req",
".",
"body",
".",
"length",
"||",
"!",
"validateSections",
"(",
"req",
".",
"body",
")",
")",
"{",
"log",
".",
"error",
"(",
"'Invalid Group'",
",",
"'request:'",
",",
"JSON",
".",
"stringify",
"(",
"req",
".",
"body",
")",
")",
";",
"Utils",
".",
"sendMessage",
"(",
"res",
",",
"HttpStatus",
".",
"BAD_REQUEST",
",",
"JSON",
".",
"stringify",
"(",
"{",
"error",
":",
"'invalid group'",
"}",
")",
")",
";",
"}",
"else",
"{",
"server",
".",
"state",
".",
"set",
"(",
"'groups['",
"+",
"groupId",
"+",
"']'",
",",
"req",
".",
"body",
".",
"slice",
"(",
")",
")",
";",
"log",
".",
"info",
"(",
"'Successfully '",
"+",
"operation",
"+",
"'d group:'",
",",
"groupId",
")",
";",
"Utils",
".",
"sendMessage",
"(",
"res",
",",
"HttpStatus",
".",
"OK",
",",
"JSON",
".",
"stringify",
"(",
"{",
"id",
":",
"parseInt",
"(",
"groupId",
",",
"10",
")",
"}",
")",
")",
";",
"}",
"}"
] | Internal utility function to create or update a group | [
"Internal",
"utility",
"function",
"to",
"create",
"or",
"update",
"a",
"group"
] | 28a167910bda3ca56d94aadaa90bfefca35eaa52 | https://github.com/ove/ove/blob/28a167910bda3ca56d94aadaa90bfefca35eaa52/packages/ove-core/src/server/api.js#L687-L706 | train |
|
ove/ove | packages/ove-core/src/server/api.js | function (req, res) {
let groupId = req.params.id;
if (Utils.isNullOrEmpty(server.state.get('groups[' + groupId + ']'))) {
log.error('Invalid Group Id:', groupId);
Utils.sendMessage(res, HttpStatus.BAD_REQUEST, JSON.stringify({ error: 'invalid group id' }));
} else {
log.debug('Successfully read configuration for group id:', groupId);
Utils.sendMessage(res, HttpStatus.OK, JSON.stringify(server.state.get('groups[' + groupId + ']')));
}
} | javascript | function (req, res) {
let groupId = req.params.id;
if (Utils.isNullOrEmpty(server.state.get('groups[' + groupId + ']'))) {
log.error('Invalid Group Id:', groupId);
Utils.sendMessage(res, HttpStatus.BAD_REQUEST, JSON.stringify({ error: 'invalid group id' }));
} else {
log.debug('Successfully read configuration for group id:', groupId);
Utils.sendMessage(res, HttpStatus.OK, JSON.stringify(server.state.get('groups[' + groupId + ']')));
}
} | [
"function",
"(",
"req",
",",
"res",
")",
"{",
"let",
"groupId",
"=",
"req",
".",
"params",
".",
"id",
";",
"if",
"(",
"Utils",
".",
"isNullOrEmpty",
"(",
"server",
".",
"state",
".",
"get",
"(",
"'groups['",
"+",
"groupId",
"+",
"']'",
")",
")",
")",
"{",
"log",
".",
"error",
"(",
"'Invalid Group Id:'",
",",
"groupId",
")",
";",
"Utils",
".",
"sendMessage",
"(",
"res",
",",
"HttpStatus",
".",
"BAD_REQUEST",
",",
"JSON",
".",
"stringify",
"(",
"{",
"error",
":",
"'invalid group id'",
"}",
")",
")",
";",
"}",
"else",
"{",
"log",
".",
"debug",
"(",
"'Successfully read configuration for group id:'",
",",
"groupId",
")",
";",
"Utils",
".",
"sendMessage",
"(",
"res",
",",
"HttpStatus",
".",
"OK",
",",
"JSON",
".",
"stringify",
"(",
"server",
".",
"state",
".",
"get",
"(",
"'groups['",
"+",
"groupId",
"+",
"']'",
")",
")",
")",
";",
"}",
"}"
] | Fetches details of an individual group | [
"Fetches",
"details",
"of",
"an",
"individual",
"group"
] | 28a167910bda3ca56d94aadaa90bfefca35eaa52 | https://github.com/ove/ove/blob/28a167910bda3ca56d94aadaa90bfefca35eaa52/packages/ove-core/src/server/api.js#L714-L723 | train |
|
ove/ove | packages/ove-core/src/server/api.js | function (groupId) {
server.state.set('groups[' + groupId + ']', []);
let hasNonEmptyGroups = false;
server.state.get('groups').forEach(function (e) {
if (!Utils.isNullOrEmpty(e)) {
hasNonEmptyGroups = true;
}
});
if (hasNonEmptyGroups) {
log.info('Successfully deleted group:', groupId);
} else {
server.state.set('groups', []);
log.info('Successfully deleted all groups');
}
} | javascript | function (groupId) {
server.state.set('groups[' + groupId + ']', []);
let hasNonEmptyGroups = false;
server.state.get('groups').forEach(function (e) {
if (!Utils.isNullOrEmpty(e)) {
hasNonEmptyGroups = true;
}
});
if (hasNonEmptyGroups) {
log.info('Successfully deleted group:', groupId);
} else {
server.state.set('groups', []);
log.info('Successfully deleted all groups');
}
} | [
"function",
"(",
"groupId",
")",
"{",
"server",
".",
"state",
".",
"set",
"(",
"'groups['",
"+",
"groupId",
"+",
"']'",
",",
"[",
"]",
")",
";",
"let",
"hasNonEmptyGroups",
"=",
"false",
";",
"server",
".",
"state",
".",
"get",
"(",
"'groups'",
")",
".",
"forEach",
"(",
"function",
"(",
"e",
")",
"{",
"if",
"(",
"!",
"Utils",
".",
"isNullOrEmpty",
"(",
"e",
")",
")",
"{",
"hasNonEmptyGroups",
"=",
"true",
";",
"}",
"}",
")",
";",
"if",
"(",
"hasNonEmptyGroups",
")",
"{",
"log",
".",
"info",
"(",
"'Successfully deleted group:'",
",",
"groupId",
")",
";",
"}",
"else",
"{",
"server",
".",
"state",
".",
"set",
"(",
"'groups'",
",",
"[",
"]",
")",
";",
"log",
".",
"info",
"(",
"'Successfully deleted all groups'",
")",
";",
"}",
"}"
] | Internal utility function to delete a group by the given id | [
"Internal",
"utility",
"function",
"to",
"delete",
"a",
"group",
"by",
"the",
"given",
"id"
] | 28a167910bda3ca56d94aadaa90bfefca35eaa52 | https://github.com/ove/ove/blob/28a167910bda3ca56d94aadaa90bfefca35eaa52/packages/ove-core/src/server/api.js#L731-L745 | train |
|
ove/ove | packages/ove-core/src/server/messaging.js | function (peerURL) {
let host = peerURL;
/* istanbul ignore else */
// The host should never be null, empty or undefined based on how this method is used.
// This check is an additional precaution.
if (host) {
if (host.indexOf('//') >= 0) {
host = host.substring(host.indexOf('//') + 2);
}
if (host.indexOf('/') >= 0) {
host = host.substring(0, host.indexOf('/'));
}
}
return host;
} | javascript | function (peerURL) {
let host = peerURL;
/* istanbul ignore else */
// The host should never be null, empty or undefined based on how this method is used.
// This check is an additional precaution.
if (host) {
if (host.indexOf('//') >= 0) {
host = host.substring(host.indexOf('//') + 2);
}
if (host.indexOf('/') >= 0) {
host = host.substring(0, host.indexOf('/'));
}
}
return host;
} | [
"function",
"(",
"peerURL",
")",
"{",
"let",
"host",
"=",
"peerURL",
";",
"if",
"(",
"host",
")",
"{",
"if",
"(",
"host",
".",
"indexOf",
"(",
"'//'",
")",
">=",
"0",
")",
"{",
"host",
"=",
"host",
".",
"substring",
"(",
"host",
".",
"indexOf",
"(",
"'//'",
")",
"+",
"2",
")",
";",
"}",
"if",
"(",
"host",
".",
"indexOf",
"(",
"'/'",
")",
">=",
"0",
")",
"{",
"host",
"=",
"host",
".",
"substring",
"(",
"0",
",",
"host",
".",
"indexOf",
"(",
"'/'",
")",
")",
";",
"}",
"}",
"return",
"host",
";",
"}"
] | Utility function to get peer socket URL | [
"Utility",
"function",
"to",
"get",
"peer",
"socket",
"URL"
] | 28a167910bda3ca56d94aadaa90bfefca35eaa52 | https://github.com/ove/ove/blob/28a167910bda3ca56d94aadaa90bfefca35eaa52/packages/ove-core/src/server/messaging.js#L32-L46 | train |
|
GitbookIO/slate-trailing-block | lib/focusAtEnd.js | focusAtEnd | function focusAtEnd(change) {
const { value } = change;
const document = value.document;
return change.collapseToEndOf(document);
} | javascript | function focusAtEnd(change) {
const { value } = change;
const document = value.document;
return change.collapseToEndOf(document);
} | [
"function",
"focusAtEnd",
"(",
"change",
")",
"{",
"const",
"{",
"value",
"}",
"=",
"change",
";",
"const",
"document",
"=",
"value",
".",
"document",
";",
"return",
"change",
".",
"collapseToEndOf",
"(",
"document",
")",
";",
"}"
] | Focus at the end of the document
@param {Slate.Change} change
@return {Slate.Change} | [
"Focus",
"at",
"the",
"end",
"of",
"the",
"document"
] | d6d5dfb5f1ed9d6daac154bf949112d10a7657c0 | https://github.com/GitbookIO/slate-trailing-block/blob/d6d5dfb5f1ed9d6daac154bf949112d10a7657c0/lib/focusAtEnd.js#L7-L11 | train |
moneybutton/yours-core | lib/contentauth.js | ContentAuth | function ContentAuth (pubkey, sig, blockhashbuf, blockheightnum, parenthashbuf, date, address, contentbuf) {
if (!(this instanceof ContentAuth)) {
return new ContentAuth(pubkey, sig, blockhashbuf, blockheightnum, parenthashbuf, date, address, contentbuf)
}
this.initialize()
this.fromObject({pubkey, sig, blockhashbuf, blockheightnum, parenthashbuf, date, address, contentbuf})
} | javascript | function ContentAuth (pubkey, sig, blockhashbuf, blockheightnum, parenthashbuf, date, address, contentbuf) {
if (!(this instanceof ContentAuth)) {
return new ContentAuth(pubkey, sig, blockhashbuf, blockheightnum, parenthashbuf, date, address, contentbuf)
}
this.initialize()
this.fromObject({pubkey, sig, blockhashbuf, blockheightnum, parenthashbuf, date, address, contentbuf})
} | [
"function",
"ContentAuth",
"(",
"pubkey",
",",
"sig",
",",
"blockhashbuf",
",",
"blockheightnum",
",",
"parenthashbuf",
",",
"date",
",",
"address",
",",
"contentbuf",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"ContentAuth",
")",
")",
"{",
"return",
"new",
"ContentAuth",
"(",
"pubkey",
",",
"sig",
",",
"blockhashbuf",
",",
"blockheightnum",
",",
"parenthashbuf",
",",
"date",
",",
"address",
",",
"contentbuf",
")",
"}",
"this",
".",
"initialize",
"(",
")",
"this",
".",
"fromObject",
"(",
"{",
"pubkey",
",",
"sig",
",",
"blockhashbuf",
",",
"blockheightnum",
",",
"parenthashbuf",
",",
"date",
",",
"address",
",",
"contentbuf",
"}",
")",
"}"
] | Note that the signature must be compact, meaning it has a recovery factor
and compressed factor. date is a javascript date object. | [
"Note",
"that",
"the",
"signature",
"must",
"be",
"compact",
"meaning",
"it",
"has",
"a",
"recovery",
"factor",
"and",
"compressed",
"factor",
".",
"date",
"is",
"a",
"javascript",
"date",
"object",
"."
] | e7e044c1603609e48337841d88a17fc10111a282 | https://github.com/moneybutton/yours-core/blob/e7e044c1603609e48337841d88a17fc10111a282/lib/contentauth.js#L34-L40 | train |
AndreasMadsen/stack-chain | stack-chain.js | stackChain | function stackChain() {
this.extend = new TraceModifier();
this.filter = new TraceModifier();
this.format = new StackFormater();
this.version = require('./package.json').version;
} | javascript | function stackChain() {
this.extend = new TraceModifier();
this.filter = new TraceModifier();
this.format = new StackFormater();
this.version = require('./package.json').version;
} | [
"function",
"stackChain",
"(",
")",
"{",
"this",
".",
"extend",
"=",
"new",
"TraceModifier",
"(",
")",
";",
"this",
".",
"filter",
"=",
"new",
"TraceModifier",
"(",
")",
";",
"this",
".",
"format",
"=",
"new",
"StackFormater",
"(",
")",
";",
"this",
".",
"version",
"=",
"require",
"(",
"'./package.json'",
")",
".",
"version",
";",
"}"
] | public define API | [
"public",
"define",
"API"
] | 001f69e35ecd070c68209d13c4325fe5d23fc136 | https://github.com/AndreasMadsen/stack-chain/blob/001f69e35ecd070c68209d13c4325fe5d23fc136/stack-chain.js#L8-L13 | train |
richardschneider/pbn | lib/bri-to-pbn.js | BriToPbn | function BriToPbn(opts) {
if (!(this instanceof BriToPbn)) return new BriToPbn(opts);
opts = opts || {};
this.needDirectives = true;
this.boardNumber = opts.boardNumber || 1;
stream.Transform.call(this, opts);
} | javascript | function BriToPbn(opts) {
if (!(this instanceof BriToPbn)) return new BriToPbn(opts);
opts = opts || {};
this.needDirectives = true;
this.boardNumber = opts.boardNumber || 1;
stream.Transform.call(this, opts);
} | [
"function",
"BriToPbn",
"(",
"opts",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"BriToPbn",
")",
")",
"return",
"new",
"BriToPbn",
"(",
"opts",
")",
";",
"opts",
"=",
"opts",
"||",
"{",
"}",
";",
"this",
".",
"needDirectives",
"=",
"true",
";",
"this",
".",
"boardNumber",
"=",
"opts",
".",
"boardNumber",
"||",
"1",
";",
"stream",
".",
"Transform",
".",
"call",
"(",
"this",
",",
"opts",
")",
";",
"}"
] | Converts a BRI stream into PBN | [
"Converts",
"a",
"BRI",
"stream",
"into",
"PBN"
] | cc2928f3c3e2915e46c6b57779880e134766eb9a | https://github.com/richardschneider/pbn/blob/cc2928f3c3e2915e46c6b57779880e134766eb9a/lib/bri-to-pbn.js#L80-L88 | train |
richardschneider/pbn | lib/dge-to-pbn.js | DgeToPbn | function DgeToPbn(opts) {
if (!(this instanceof DgeToPbn)) return new DgeToPbn(opts);
opts = opts || {};
this.needDirectives = true;
this.boardNumber = opts.boardNumber || 1;
stream.Transform.call(this, opts);
} | javascript | function DgeToPbn(opts) {
if (!(this instanceof DgeToPbn)) return new DgeToPbn(opts);
opts = opts || {};
this.needDirectives = true;
this.boardNumber = opts.boardNumber || 1;
stream.Transform.call(this, opts);
} | [
"function",
"DgeToPbn",
"(",
"opts",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"DgeToPbn",
")",
")",
"return",
"new",
"DgeToPbn",
"(",
"opts",
")",
";",
"opts",
"=",
"opts",
"||",
"{",
"}",
";",
"this",
".",
"needDirectives",
"=",
"true",
";",
"this",
".",
"boardNumber",
"=",
"opts",
".",
"boardNumber",
"||",
"1",
";",
"stream",
".",
"Transform",
".",
"call",
"(",
"this",
",",
"opts",
")",
";",
"}"
] | Converts a DGE stream into PBN | [
"Converts",
"a",
"DGE",
"stream",
"into",
"PBN"
] | cc2928f3c3e2915e46c6b57779880e134766eb9a | https://github.com/richardschneider/pbn/blob/cc2928f3c3e2915e46c6b57779880e134766eb9a/lib/dge-to-pbn.js#L27-L35 | train |
neftaly/grunt-sri | tasks/sri.js | function (manifest, file, callback) {
generate(file.src, options, function (err, sriData) {
// Make relative if a cwd is specified
if (file.orig && file.orig.cwd) {
file.id = file.id.replace(file.orig.cwd, "");
sriData.path = sriData.path.replace(file.orig.cwd, "");
}
// Attach a property to the WIP manifest object
manifest[file.id] = sriData;
callback(err, manifest);
});
} | javascript | function (manifest, file, callback) {
generate(file.src, options, function (err, sriData) {
// Make relative if a cwd is specified
if (file.orig && file.orig.cwd) {
file.id = file.id.replace(file.orig.cwd, "");
sriData.path = sriData.path.replace(file.orig.cwd, "");
}
// Attach a property to the WIP manifest object
manifest[file.id] = sriData;
callback(err, manifest);
});
} | [
"function",
"(",
"manifest",
",",
"file",
",",
"callback",
")",
"{",
"generate",
"(",
"file",
".",
"src",
",",
"options",
",",
"function",
"(",
"err",
",",
"sriData",
")",
"{",
"if",
"(",
"file",
".",
"orig",
"&&",
"file",
".",
"orig",
".",
"cwd",
")",
"{",
"file",
".",
"id",
"=",
"file",
".",
"id",
".",
"replace",
"(",
"file",
".",
"orig",
".",
"cwd",
",",
"\"\"",
")",
";",
"sriData",
".",
"path",
"=",
"sriData",
".",
"path",
".",
"replace",
"(",
"file",
".",
"orig",
".",
"cwd",
",",
"\"\"",
")",
";",
"}",
"manifest",
"[",
"file",
".",
"id",
"]",
"=",
"sriData",
";",
"callback",
"(",
"err",
",",
"manifest",
")",
";",
"}",
")",
";",
"}"
] | Build manifest using the "reduce to object" pattern | [
"Build",
"manifest",
"using",
"the",
"reduce",
"to",
"object",
"pattern"
] | cc772056dca8b703b84777ede4531a7d24c2a377 | https://github.com/neftaly/grunt-sri/blob/cc772056dca8b703b84777ede4531a7d24c2a377/tasks/sri.js#L137-L148 | train |
|
neftaly/grunt-sri | tasks/sri.js | function (err, manifest) {
if (err) {
// Error generating SRI hashes
grunt.log.error("Error loading resource: " + err);
return done(false);
}
return saveJson(
options,
manifest,
writeLog(fileCount, done)
);
} | javascript | function (err, manifest) {
if (err) {
// Error generating SRI hashes
grunt.log.error("Error loading resource: " + err);
return done(false);
}
return saveJson(
options,
manifest,
writeLog(fileCount, done)
);
} | [
"function",
"(",
"err",
",",
"manifest",
")",
"{",
"if",
"(",
"err",
")",
"{",
"grunt",
".",
"log",
".",
"error",
"(",
"\"Error loading resource: \"",
"+",
"err",
")",
";",
"return",
"done",
"(",
"false",
")",
";",
"}",
"return",
"saveJson",
"(",
"options",
",",
"manifest",
",",
"writeLog",
"(",
"fileCount",
",",
"done",
")",
")",
";",
"}"
] | Process completed manifest and finish up | [
"Process",
"completed",
"manifest",
"and",
"finish",
"up"
] | cc772056dca8b703b84777ede4531a7d24c2a377 | https://github.com/neftaly/grunt-sri/blob/cc772056dca8b703b84777ede4531a7d24c2a377/tasks/sri.js#L151-L163 | train |
|
richardschneider/pbn | lib/dup-to-pbn.js | DupToPbn | function DupToPbn(opts) {
if (!(this instanceof DupToPbn)) return new DupToPbn(opts);
opts = opts || {};
this.needDirectives = true;
this.boardNumber = opts.boardNumber || 1;
stream.Transform.call(this, opts);
} | javascript | function DupToPbn(opts) {
if (!(this instanceof DupToPbn)) return new DupToPbn(opts);
opts = opts || {};
this.needDirectives = true;
this.boardNumber = opts.boardNumber || 1;
stream.Transform.call(this, opts);
} | [
"function",
"DupToPbn",
"(",
"opts",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"DupToPbn",
")",
")",
"return",
"new",
"DupToPbn",
"(",
"opts",
")",
";",
"opts",
"=",
"opts",
"||",
"{",
"}",
";",
"this",
".",
"needDirectives",
"=",
"true",
";",
"this",
".",
"boardNumber",
"=",
"opts",
".",
"boardNumber",
"||",
"1",
";",
"stream",
".",
"Transform",
".",
"call",
"(",
"this",
",",
"opts",
")",
";",
"}"
] | Converts a DUP stream into PBN | [
"Converts",
"a",
"DUP",
"stream",
"into",
"PBN"
] | cc2928f3c3e2915e46c6b57779880e134766eb9a | https://github.com/richardschneider/pbn/blob/cc2928f3c3e2915e46c6b57779880e134766eb9a/lib/dup-to-pbn.js#L19-L27 | train |
GitbookIO/slate-trailing-block | lib/index.js | TrailingBlock | function TrailingBlock(opts) {
opts = opts || {};
opts.type = opts.type || 'paragraph';
opts.match = opts.match || (node => node.type === opts.type);
return {
validateNode: (node) => {
if (node.object !== 'document') {
return undefined;
}
const lastNode = node.nodes.last();
if (lastNode && opts.match(lastNode)) {
return undefined;
}
const lastIndex = node.nodes.count();
const block = Slate.Block.create({
type: opts.type,
nodes: [Slate.Text.create()]
});
return (change) => change.insertNodeByKey(node.key, lastIndex, block);
},
changes: {
focusAtEnd
}
};
} | javascript | function TrailingBlock(opts) {
opts = opts || {};
opts.type = opts.type || 'paragraph';
opts.match = opts.match || (node => node.type === opts.type);
return {
validateNode: (node) => {
if (node.object !== 'document') {
return undefined;
}
const lastNode = node.nodes.last();
if (lastNode && opts.match(lastNode)) {
return undefined;
}
const lastIndex = node.nodes.count();
const block = Slate.Block.create({
type: opts.type,
nodes: [Slate.Text.create()]
});
return (change) => change.insertNodeByKey(node.key, lastIndex, block);
},
changes: {
focusAtEnd
}
};
} | [
"function",
"TrailingBlock",
"(",
"opts",
")",
"{",
"opts",
"=",
"opts",
"||",
"{",
"}",
";",
"opts",
".",
"type",
"=",
"opts",
".",
"type",
"||",
"'paragraph'",
";",
"opts",
".",
"match",
"=",
"opts",
".",
"match",
"||",
"(",
"node",
"=>",
"node",
".",
"type",
"===",
"opts",
".",
"type",
")",
";",
"return",
"{",
"validateNode",
":",
"(",
"node",
")",
"=>",
"{",
"if",
"(",
"node",
".",
"object",
"!==",
"'document'",
")",
"{",
"return",
"undefined",
";",
"}",
"const",
"lastNode",
"=",
"node",
".",
"nodes",
".",
"last",
"(",
")",
";",
"if",
"(",
"lastNode",
"&&",
"opts",
".",
"match",
"(",
"lastNode",
")",
")",
"{",
"return",
"undefined",
";",
"}",
"const",
"lastIndex",
"=",
"node",
".",
"nodes",
".",
"count",
"(",
")",
";",
"const",
"block",
"=",
"Slate",
".",
"Block",
".",
"create",
"(",
"{",
"type",
":",
"opts",
".",
"type",
",",
"nodes",
":",
"[",
"Slate",
".",
"Text",
".",
"create",
"(",
")",
"]",
"}",
")",
";",
"return",
"(",
"change",
")",
"=>",
"change",
".",
"insertNodeByKey",
"(",
"node",
".",
"key",
",",
"lastIndex",
",",
"block",
")",
";",
"}",
",",
"changes",
":",
"{",
"focusAtEnd",
"}",
"}",
";",
"}"
] | Slate plugin to ensure a trailing block.
@param {Object} [opts] Options for the plugin
@param {String|Function} [opts.match='paragraph'] Match last block
@param {String} [opts.type] The type of the trailing block to insert
@return {Object} | [
"Slate",
"plugin",
"to",
"ensure",
"a",
"trailing",
"block",
"."
] | d6d5dfb5f1ed9d6daac154bf949112d10a7657c0 | https://github.com/GitbookIO/slate-trailing-block/blob/d6d5dfb5f1ed9d6daac154bf949112d10a7657c0/lib/index.js#L12-L41 | train |
jonschlinkert/relative | index.js | relative | function relative(a, b, stat) {
if (typeof a !== 'string') {
throw new TypeError('relative expects a string.');
}
if (a == '' && !b) return a;
var len = arguments.length;
if (len === 1) {
b = a; a = process.cwd(); stat = null;
}
if (len === 2 && typeof b === 'boolean') {
b = a; a = process.cwd(); stat = true;
}
if (len === 2 && typeof b === 'object') {
stat = b; b = a; a = process.cwd();
}
var origB = b;
// see if a slash exists before normalizing
var slashA = endsWith(a, '/');
var slashB = endsWith(b, '/');
a = unixify(a);
b = unixify(b);
// if `a` had a slash, add it back
if (slashA) { a = a + '/'; }
if (isFile(a, stat)) {
a = path.dirname(a);
}
var res = path.relative(a, b);
if (res === '') {
return '.';
}
// if `b` originally had a slash, and the path ends
// with `b` missing a slash, then re-add the slash.
var noslash = trimEnd(origB, '/');
if (slashB && (res === noslash || endsWith(res, noslash))) {
res = res + '/';
}
return res;
} | javascript | function relative(a, b, stat) {
if (typeof a !== 'string') {
throw new TypeError('relative expects a string.');
}
if (a == '' && !b) return a;
var len = arguments.length;
if (len === 1) {
b = a; a = process.cwd(); stat = null;
}
if (len === 2 && typeof b === 'boolean') {
b = a; a = process.cwd(); stat = true;
}
if (len === 2 && typeof b === 'object') {
stat = b; b = a; a = process.cwd();
}
var origB = b;
// see if a slash exists before normalizing
var slashA = endsWith(a, '/');
var slashB = endsWith(b, '/');
a = unixify(a);
b = unixify(b);
// if `a` had a slash, add it back
if (slashA) { a = a + '/'; }
if (isFile(a, stat)) {
a = path.dirname(a);
}
var res = path.relative(a, b);
if (res === '') {
return '.';
}
// if `b` originally had a slash, and the path ends
// with `b` missing a slash, then re-add the slash.
var noslash = trimEnd(origB, '/');
if (slashB && (res === noslash || endsWith(res, noslash))) {
res = res + '/';
}
return res;
} | [
"function",
"relative",
"(",
"a",
",",
"b",
",",
"stat",
")",
"{",
"if",
"(",
"typeof",
"a",
"!==",
"'string'",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'relative expects a string.'",
")",
";",
"}",
"if",
"(",
"a",
"==",
"''",
"&&",
"!",
"b",
")",
"return",
"a",
";",
"var",
"len",
"=",
"arguments",
".",
"length",
";",
"if",
"(",
"len",
"===",
"1",
")",
"{",
"b",
"=",
"a",
";",
"a",
"=",
"process",
".",
"cwd",
"(",
")",
";",
"stat",
"=",
"null",
";",
"}",
"if",
"(",
"len",
"===",
"2",
"&&",
"typeof",
"b",
"===",
"'boolean'",
")",
"{",
"b",
"=",
"a",
";",
"a",
"=",
"process",
".",
"cwd",
"(",
")",
";",
"stat",
"=",
"true",
";",
"}",
"if",
"(",
"len",
"===",
"2",
"&&",
"typeof",
"b",
"===",
"'object'",
")",
"{",
"stat",
"=",
"b",
";",
"b",
"=",
"a",
";",
"a",
"=",
"process",
".",
"cwd",
"(",
")",
";",
"}",
"var",
"origB",
"=",
"b",
";",
"var",
"slashA",
"=",
"endsWith",
"(",
"a",
",",
"'/'",
")",
";",
"var",
"slashB",
"=",
"endsWith",
"(",
"b",
",",
"'/'",
")",
";",
"a",
"=",
"unixify",
"(",
"a",
")",
";",
"b",
"=",
"unixify",
"(",
"b",
")",
";",
"if",
"(",
"slashA",
")",
"{",
"a",
"=",
"a",
"+",
"'/'",
";",
"}",
"if",
"(",
"isFile",
"(",
"a",
",",
"stat",
")",
")",
"{",
"a",
"=",
"path",
".",
"dirname",
"(",
"a",
")",
";",
"}",
"var",
"res",
"=",
"path",
".",
"relative",
"(",
"a",
",",
"b",
")",
";",
"if",
"(",
"res",
"===",
"''",
")",
"{",
"return",
"'.'",
";",
"}",
"var",
"noslash",
"=",
"trimEnd",
"(",
"origB",
",",
"'/'",
")",
";",
"if",
"(",
"slashB",
"&&",
"(",
"res",
"===",
"noslash",
"||",
"endsWith",
"(",
"res",
",",
"noslash",
")",
")",
")",
"{",
"res",
"=",
"res",
"+",
"'/'",
";",
"}",
"return",
"res",
";",
"}"
] | Get the relative path from `a` to `b`. | [
"Get",
"the",
"relative",
"path",
"from",
"a",
"to",
"b",
"."
] | fc8d85af704a4a7c9b24bd5f04dc623df0bf35d9 | https://github.com/jonschlinkert/relative/blob/fc8d85af704a4a7c9b24bd5f04dc623df0bf35d9/index.js#L17-L65 | train |
jonschlinkert/relative | index.js | isDir | function isDir(fp, stat) {
if (endsWith(fp, '/')) {
return true;
}
if (stat === null) {
// try to get the directory info if it hasn't been done yet
// to ensure directories containing dots are well handle
stat = tryStats(fp);
}
if (isObject(stat) && typeof stat.isDirectory === 'function') {
return stat.isDirectory();
}
var segs = fp.split('/');
var last = segs[segs.length - 1];
if (last && last.indexOf('.') !== -1) {
return false;
}
return true;
} | javascript | function isDir(fp, stat) {
if (endsWith(fp, '/')) {
return true;
}
if (stat === null) {
// try to get the directory info if it hasn't been done yet
// to ensure directories containing dots are well handle
stat = tryStats(fp);
}
if (isObject(stat) && typeof stat.isDirectory === 'function') {
return stat.isDirectory();
}
var segs = fp.split('/');
var last = segs[segs.length - 1];
if (last && last.indexOf('.') !== -1) {
return false;
}
return true;
} | [
"function",
"isDir",
"(",
"fp",
",",
"stat",
")",
"{",
"if",
"(",
"endsWith",
"(",
"fp",
",",
"'/'",
")",
")",
"{",
"return",
"true",
";",
"}",
"if",
"(",
"stat",
"===",
"null",
")",
"{",
"stat",
"=",
"tryStats",
"(",
"fp",
")",
";",
"}",
"if",
"(",
"isObject",
"(",
"stat",
")",
"&&",
"typeof",
"stat",
".",
"isDirectory",
"===",
"'function'",
")",
"{",
"return",
"stat",
".",
"isDirectory",
"(",
")",
";",
"}",
"var",
"segs",
"=",
"fp",
".",
"split",
"(",
"'/'",
")",
";",
"var",
"last",
"=",
"segs",
"[",
"segs",
".",
"length",
"-",
"1",
"]",
";",
"if",
"(",
"last",
"&&",
"last",
".",
"indexOf",
"(",
"'.'",
")",
"!==",
"-",
"1",
")",
"{",
"return",
"false",
";",
"}",
"return",
"true",
";",
"}"
] | Returns true if `fp` is a directory. To use a `fs`
stat object to actually check the file system,
either pass `true` as the second arg, or pass your
own stat object as the second arg.
@param {String} `fp`
@param {Boolean|Object} `stat`
@return {Boolean} | [
"Returns",
"true",
"if",
"fp",
"is",
"a",
"directory",
".",
"To",
"use",
"a",
"fs",
"stat",
"object",
"to",
"actually",
"check",
"the",
"file",
"system",
"either",
"pass",
"true",
"as",
"the",
"second",
"arg",
"or",
"pass",
"your",
"own",
"stat",
"object",
"as",
"the",
"second",
"arg",
"."
] | fc8d85af704a4a7c9b24bd5f04dc623df0bf35d9 | https://github.com/jonschlinkert/relative/blob/fc8d85af704a4a7c9b24bd5f04dc623df0bf35d9/index.js#L131-L152 | train |
jonschlinkert/relative | index.js | isFile | function isFile(fp, stat) {
if (stat === true) {
stat = tryStats(fp);
}
return !isDir(fp, stat);
} | javascript | function isFile(fp, stat) {
if (stat === true) {
stat = tryStats(fp);
}
return !isDir(fp, stat);
} | [
"function",
"isFile",
"(",
"fp",
",",
"stat",
")",
"{",
"if",
"(",
"stat",
"===",
"true",
")",
"{",
"stat",
"=",
"tryStats",
"(",
"fp",
")",
";",
"}",
"return",
"!",
"isDir",
"(",
"fp",
",",
"stat",
")",
";",
"}"
] | Return true if `fp` looks like a file, or
actually is a file if fs.stat is used. | [
"Return",
"true",
"if",
"fp",
"looks",
"like",
"a",
"file",
"or",
"actually",
"is",
"a",
"file",
"if",
"fs",
".",
"stat",
"is",
"used",
"."
] | fc8d85af704a4a7c9b24bd5f04dc623df0bf35d9 | https://github.com/jonschlinkert/relative/blob/fc8d85af704a4a7c9b24bd5f04dc623df0bf35d9/index.js#L159-L164 | train |
yahoo/fluxible-action-utils | mixins/PeriodicActions.js | getIntervalRunner | function getIntervalRunner (context, actions) {
return function itervalRunner () {
var i = 0;
var len = actions.length;
var actionData = null;
for (; i < len; i += 1) {
actionData = actions[i];
context.executeAction(actionData.action, actionData.params);
}
};
} | javascript | function getIntervalRunner (context, actions) {
return function itervalRunner () {
var i = 0;
var len = actions.length;
var actionData = null;
for (; i < len; i += 1) {
actionData = actions[i];
context.executeAction(actionData.action, actionData.params);
}
};
} | [
"function",
"getIntervalRunner",
"(",
"context",
",",
"actions",
")",
"{",
"return",
"function",
"itervalRunner",
"(",
")",
"{",
"var",
"i",
"=",
"0",
";",
"var",
"len",
"=",
"actions",
".",
"length",
";",
"var",
"actionData",
"=",
"null",
";",
"for",
"(",
";",
"i",
"<",
"len",
";",
"i",
"+=",
"1",
")",
"{",
"actionData",
"=",
"actions",
"[",
"i",
"]",
";",
"context",
".",
"executeAction",
"(",
"actionData",
".",
"action",
",",
"actionData",
".",
"params",
")",
";",
"}",
"}",
";",
"}"
] | Return a function that can run the array of actions
@method getIntervalRunner
@param {FluxibleActionContext} context The fluxible component context (with executeAction)
@param {Array.<Function>} actions The actions to run
@return {Function} Function to run the actions array | [
"Return",
"a",
"function",
"that",
"can",
"run",
"the",
"array",
"of",
"actions"
] | 37cc25c8a1e3f3ffae0401f9d90030f40da9a5f4 | https://github.com/yahoo/fluxible-action-utils/blob/37cc25c8a1e3f3ffae0401f9d90030f40da9a5f4/mixins/PeriodicActions.js#L23-L34 | train |
yahoo/fluxible-action-utils | mixins/PeriodicActions.js | function (uuid, action, params, interval) {
var actions = null;
if (typeof uuid !== 'string' ||
typeof action !== 'function') {
return false;
}
if (interval === undefined) {
if (typeof params === 'number') {
interval = params;
params = null;
} else {
interval = 100;
}
}
if (uuidMap[uuid]) {
return false;
}
if (!intervalsMap[interval]) {
actions = [];
intervalsMap[interval] = {
id: setInterval(getIntervalRunner(this.context, actions), interval),
interval: interval,
actions: actions
};
}
intervalsMap[interval].actions.push({
uuid: uuid,
action: action,
params: params
});
uuidMap[uuid] = intervalsMap[interval];
if (!this._periodicActionUUIDs) {
this._periodicActionUUIDs = [];
}
this._periodicActionUUIDs.push(uuid);
return true;
} | javascript | function (uuid, action, params, interval) {
var actions = null;
if (typeof uuid !== 'string' ||
typeof action !== 'function') {
return false;
}
if (interval === undefined) {
if (typeof params === 'number') {
interval = params;
params = null;
} else {
interval = 100;
}
}
if (uuidMap[uuid]) {
return false;
}
if (!intervalsMap[interval]) {
actions = [];
intervalsMap[interval] = {
id: setInterval(getIntervalRunner(this.context, actions), interval),
interval: interval,
actions: actions
};
}
intervalsMap[interval].actions.push({
uuid: uuid,
action: action,
params: params
});
uuidMap[uuid] = intervalsMap[interval];
if (!this._periodicActionUUIDs) {
this._periodicActionUUIDs = [];
}
this._periodicActionUUIDs.push(uuid);
return true;
} | [
"function",
"(",
"uuid",
",",
"action",
",",
"params",
",",
"interval",
")",
"{",
"var",
"actions",
"=",
"null",
";",
"if",
"(",
"typeof",
"uuid",
"!==",
"'string'",
"||",
"typeof",
"action",
"!==",
"'function'",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"interval",
"===",
"undefined",
")",
"{",
"if",
"(",
"typeof",
"params",
"===",
"'number'",
")",
"{",
"interval",
"=",
"params",
";",
"params",
"=",
"null",
";",
"}",
"else",
"{",
"interval",
"=",
"100",
";",
"}",
"}",
"if",
"(",
"uuidMap",
"[",
"uuid",
"]",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"!",
"intervalsMap",
"[",
"interval",
"]",
")",
"{",
"actions",
"=",
"[",
"]",
";",
"intervalsMap",
"[",
"interval",
"]",
"=",
"{",
"id",
":",
"setInterval",
"(",
"getIntervalRunner",
"(",
"this",
".",
"context",
",",
"actions",
")",
",",
"interval",
")",
",",
"interval",
":",
"interval",
",",
"actions",
":",
"actions",
"}",
";",
"}",
"intervalsMap",
"[",
"interval",
"]",
".",
"actions",
".",
"push",
"(",
"{",
"uuid",
":",
"uuid",
",",
"action",
":",
"action",
",",
"params",
":",
"params",
"}",
")",
";",
"uuidMap",
"[",
"uuid",
"]",
"=",
"intervalsMap",
"[",
"interval",
"]",
";",
"if",
"(",
"!",
"this",
".",
"_periodicActionUUIDs",
")",
"{",
"this",
".",
"_periodicActionUUIDs",
"=",
"[",
"]",
";",
"}",
"this",
".",
"_periodicActionUUIDs",
".",
"push",
"(",
"uuid",
")",
";",
"return",
"true",
";",
"}"
] | Start running an action periodically
@method startPeriodicAction
@param {string} uuid A globally unique identifier
@param {Function} action The action to run
@param {(Object|Array|string|number|boolean)} [params=undefined] The parameters to pass to the action
@param {number} [interval=100] The amount of time to wait between action executions
@return {boolean} True if adding the periodic action succeeded, false otherwise | [
"Start",
"running",
"an",
"action",
"periodically"
] | 37cc25c8a1e3f3ffae0401f9d90030f40da9a5f4 | https://github.com/yahoo/fluxible-action-utils/blob/37cc25c8a1e3f3ffae0401f9d90030f40da9a5f4/mixins/PeriodicActions.js#L59-L102 | train |
|
yahoo/fluxible-action-utils | mixins/PeriodicActions.js | function () {
var i = 0;
var len = 0;
var actionData = null;
if (!(this.constructor.periodicActions instanceof Array)) {
return;
}
len = this.constructor.periodicActions.length;
for (; i < len; i += 1) {
actionData = this.constructor.periodicActions[i];
this.startPeriodicAction(actionData.uuid, actionData.action, actionData.params, actionData.interval);
}
} | javascript | function () {
var i = 0;
var len = 0;
var actionData = null;
if (!(this.constructor.periodicActions instanceof Array)) {
return;
}
len = this.constructor.periodicActions.length;
for (; i < len; i += 1) {
actionData = this.constructor.periodicActions[i];
this.startPeriodicAction(actionData.uuid, actionData.action, actionData.params, actionData.interval);
}
} | [
"function",
"(",
")",
"{",
"var",
"i",
"=",
"0",
";",
"var",
"len",
"=",
"0",
";",
"var",
"actionData",
"=",
"null",
";",
"if",
"(",
"!",
"(",
"this",
".",
"constructor",
".",
"periodicActions",
"instanceof",
"Array",
")",
")",
"{",
"return",
";",
"}",
"len",
"=",
"this",
".",
"constructor",
".",
"periodicActions",
".",
"length",
";",
"for",
"(",
";",
"i",
"<",
"len",
";",
"i",
"+=",
"1",
")",
"{",
"actionData",
"=",
"this",
".",
"constructor",
".",
"periodicActions",
"[",
"i",
"]",
";",
"this",
".",
"startPeriodicAction",
"(",
"actionData",
".",
"uuid",
",",
"actionData",
".",
"action",
",",
"actionData",
".",
"params",
",",
"actionData",
".",
"interval",
")",
";",
"}",
"}"
] | Check statics for periodic actions, if found add them all
@method startPeriodicActions
@return {void} | [
"Check",
"statics",
"for",
"periodic",
"actions",
"if",
"found",
"add",
"them",
"all"
] | 37cc25c8a1e3f3ffae0401f9d90030f40da9a5f4 | https://github.com/yahoo/fluxible-action-utils/blob/37cc25c8a1e3f3ffae0401f9d90030f40da9a5f4/mixins/PeriodicActions.js#L110-L125 | train |
|
yahoo/fluxible-action-utils | mixins/PeriodicActions.js | function (uuid) {
var intervalData = null;
var i = 0;
var len = 0;
var actionData = null;
if (typeof uuid !== 'string') {
return false;
}
intervalData = uuidMap[uuid];
if (!intervalData) {
return false;
}
uuidMap[uuid] = null;
len = intervalData.actions.length;
for (; i < len; i += 1) {
actionData = intervalData.actions[i];
if (actionData.uuid === uuid) {
intervalData.actions.splice(i, 1);
break;
}
}
if (intervalData.actions.length === 0) {
clearInterval(intervalData.id);
intervalsMap[intervalData.interval] = null;
}
return true;
} | javascript | function (uuid) {
var intervalData = null;
var i = 0;
var len = 0;
var actionData = null;
if (typeof uuid !== 'string') {
return false;
}
intervalData = uuidMap[uuid];
if (!intervalData) {
return false;
}
uuidMap[uuid] = null;
len = intervalData.actions.length;
for (; i < len; i += 1) {
actionData = intervalData.actions[i];
if (actionData.uuid === uuid) {
intervalData.actions.splice(i, 1);
break;
}
}
if (intervalData.actions.length === 0) {
clearInterval(intervalData.id);
intervalsMap[intervalData.interval] = null;
}
return true;
} | [
"function",
"(",
"uuid",
")",
"{",
"var",
"intervalData",
"=",
"null",
";",
"var",
"i",
"=",
"0",
";",
"var",
"len",
"=",
"0",
";",
"var",
"actionData",
"=",
"null",
";",
"if",
"(",
"typeof",
"uuid",
"!==",
"'string'",
")",
"{",
"return",
"false",
";",
"}",
"intervalData",
"=",
"uuidMap",
"[",
"uuid",
"]",
";",
"if",
"(",
"!",
"intervalData",
")",
"{",
"return",
"false",
";",
"}",
"uuidMap",
"[",
"uuid",
"]",
"=",
"null",
";",
"len",
"=",
"intervalData",
".",
"actions",
".",
"length",
";",
"for",
"(",
";",
"i",
"<",
"len",
";",
"i",
"+=",
"1",
")",
"{",
"actionData",
"=",
"intervalData",
".",
"actions",
"[",
"i",
"]",
";",
"if",
"(",
"actionData",
".",
"uuid",
"===",
"uuid",
")",
"{",
"intervalData",
".",
"actions",
".",
"splice",
"(",
"i",
",",
"1",
")",
";",
"break",
";",
"}",
"}",
"if",
"(",
"intervalData",
".",
"actions",
".",
"length",
"===",
"0",
")",
"{",
"clearInterval",
"(",
"intervalData",
".",
"id",
")",
";",
"intervalsMap",
"[",
"intervalData",
".",
"interval",
"]",
"=",
"null",
";",
"}",
"return",
"true",
";",
"}"
] | Stop running an action periodically
@method stopPeriodicAction
@param {string} uuid A globally unique identifier
@return {boolean} True if stopping the periodic action succeeded, false otherwise | [
"Stop",
"running",
"an",
"action",
"periodically"
] | 37cc25c8a1e3f3ffae0401f9d90030f40da9a5f4 | https://github.com/yahoo/fluxible-action-utils/blob/37cc25c8a1e3f3ffae0401f9d90030f40da9a5f4/mixins/PeriodicActions.js#L135-L169 | train |
|
yahoo/fluxible-action-utils | mixins/PeriodicActions.js | function () {
var i = 0;
var len = 0;
var uuid = '';
if (!this._periodicActionUUIDs) {
return;
}
len = this._periodicActionUUIDs.length;
for (; i < len; i += 1) {
uuid = this._periodicActionUUIDs[i];
this.stopPeriodicAction(uuid);
}
} | javascript | function () {
var i = 0;
var len = 0;
var uuid = '';
if (!this._periodicActionUUIDs) {
return;
}
len = this._periodicActionUUIDs.length;
for (; i < len; i += 1) {
uuid = this._periodicActionUUIDs[i];
this.stopPeriodicAction(uuid);
}
} | [
"function",
"(",
")",
"{",
"var",
"i",
"=",
"0",
";",
"var",
"len",
"=",
"0",
";",
"var",
"uuid",
"=",
"''",
";",
"if",
"(",
"!",
"this",
".",
"_periodicActionUUIDs",
")",
"{",
"return",
";",
"}",
"len",
"=",
"this",
".",
"_periodicActionUUIDs",
".",
"length",
";",
"for",
"(",
";",
"i",
"<",
"len",
";",
"i",
"+=",
"1",
")",
"{",
"uuid",
"=",
"this",
".",
"_periodicActionUUIDs",
"[",
"i",
"]",
";",
"this",
".",
"stopPeriodicAction",
"(",
"uuid",
")",
";",
"}",
"}"
] | Stop all periodic actions registered on this component
@method stopPeriodicActions
@return {void} | [
"Stop",
"all",
"periodic",
"actions",
"registered",
"on",
"this",
"component"
] | 37cc25c8a1e3f3ffae0401f9d90030f40da9a5f4 | https://github.com/yahoo/fluxible-action-utils/blob/37cc25c8a1e3f3ffae0401f9d90030f40da9a5f4/mixins/PeriodicActions.js#L177-L192 | train |
|
bitnami/nami-utils | lib/file/xml/set.js | _xmlFileSet | function _xmlFileSet(file, element, attributeMapping, options) {
const doc = loadXmlFile(file, options);
const node = getXmlNode(doc, element);
const result = [];
if (_.isReallyObject(attributeMapping)) {
_.each(attributeMapping, (value, attributeName) => {
if (_.isFunction(value)) {
result.push(value(node.getAttributeNode(attributeName)));
} else {
if (_.isNull(value)) {
node.removeAttribute(attributeName);
} else {
node.setAttribute(attributeName, value);
}
}
});
} else {
// still being able to provide the node to pass the node to a given function
if (_.isFunction(attributeMapping)) {
result.push(attributeMapping(node, doc));
} else {
if (node.hasChildNodes()) {
let i = 0;
const nNodes = node.childNodes.length;
while (i < nNodes) {
node.removeChild(i);
i++;
}
}
// if attribute and value == null, delete the node
if (_.isNull(attributeMapping)) {
node.parentNode.removeChild(node);
} else {
node.appendChild(doc.createTextNode(attributeMapping));
}
}
}
write(file, new XMLSerializer().serializeToString(doc), options);
if (!_.isEmpty(result)) {
return (result.length > 1) ? result : result[0];
}
} | javascript | function _xmlFileSet(file, element, attributeMapping, options) {
const doc = loadXmlFile(file, options);
const node = getXmlNode(doc, element);
const result = [];
if (_.isReallyObject(attributeMapping)) {
_.each(attributeMapping, (value, attributeName) => {
if (_.isFunction(value)) {
result.push(value(node.getAttributeNode(attributeName)));
} else {
if (_.isNull(value)) {
node.removeAttribute(attributeName);
} else {
node.setAttribute(attributeName, value);
}
}
});
} else {
// still being able to provide the node to pass the node to a given function
if (_.isFunction(attributeMapping)) {
result.push(attributeMapping(node, doc));
} else {
if (node.hasChildNodes()) {
let i = 0;
const nNodes = node.childNodes.length;
while (i < nNodes) {
node.removeChild(i);
i++;
}
}
// if attribute and value == null, delete the node
if (_.isNull(attributeMapping)) {
node.parentNode.removeChild(node);
} else {
node.appendChild(doc.createTextNode(attributeMapping));
}
}
}
write(file, new XMLSerializer().serializeToString(doc), options);
if (!_.isEmpty(result)) {
return (result.length > 1) ? result : result[0];
}
} | [
"function",
"_xmlFileSet",
"(",
"file",
",",
"element",
",",
"attributeMapping",
",",
"options",
")",
"{",
"const",
"doc",
"=",
"loadXmlFile",
"(",
"file",
",",
"options",
")",
";",
"const",
"node",
"=",
"getXmlNode",
"(",
"doc",
",",
"element",
")",
";",
"const",
"result",
"=",
"[",
"]",
";",
"if",
"(",
"_",
".",
"isReallyObject",
"(",
"attributeMapping",
")",
")",
"{",
"_",
".",
"each",
"(",
"attributeMapping",
",",
"(",
"value",
",",
"attributeName",
")",
"=>",
"{",
"if",
"(",
"_",
".",
"isFunction",
"(",
"value",
")",
")",
"{",
"result",
".",
"push",
"(",
"value",
"(",
"node",
".",
"getAttributeNode",
"(",
"attributeName",
")",
")",
")",
";",
"}",
"else",
"{",
"if",
"(",
"_",
".",
"isNull",
"(",
"value",
")",
")",
"{",
"node",
".",
"removeAttribute",
"(",
"attributeName",
")",
";",
"}",
"else",
"{",
"node",
".",
"setAttribute",
"(",
"attributeName",
",",
"value",
")",
";",
"}",
"}",
"}",
")",
";",
"}",
"else",
"{",
"if",
"(",
"_",
".",
"isFunction",
"(",
"attributeMapping",
")",
")",
"{",
"result",
".",
"push",
"(",
"attributeMapping",
"(",
"node",
",",
"doc",
")",
")",
";",
"}",
"else",
"{",
"if",
"(",
"node",
".",
"hasChildNodes",
"(",
")",
")",
"{",
"let",
"i",
"=",
"0",
";",
"const",
"nNodes",
"=",
"node",
".",
"childNodes",
".",
"length",
";",
"while",
"(",
"i",
"<",
"nNodes",
")",
"{",
"node",
".",
"removeChild",
"(",
"i",
")",
";",
"i",
"++",
";",
"}",
"}",
"if",
"(",
"_",
".",
"isNull",
"(",
"attributeMapping",
")",
")",
"{",
"node",
".",
"parentNode",
".",
"removeChild",
"(",
"node",
")",
";",
"}",
"else",
"{",
"node",
".",
"appendChild",
"(",
"doc",
".",
"createTextNode",
"(",
"attributeMapping",
")",
")",
";",
"}",
"}",
"}",
"write",
"(",
"file",
",",
"new",
"XMLSerializer",
"(",
")",
".",
"serializeToString",
"(",
"doc",
")",
",",
"options",
")",
";",
"if",
"(",
"!",
"_",
".",
"isEmpty",
"(",
"result",
")",
")",
"{",
"return",
"(",
"result",
".",
"length",
">",
"1",
")",
"?",
"result",
":",
"result",
"[",
"0",
"]",
";",
"}",
"}"
] | Set value in XML file
@function $file~xml/set
@param {string} file - XML File to write the value to
@param {string} element - XPath expression to the node element to be modified
@param {string} attribute - Attribute to be set (null will delete the node in the provided path
and create a text node in its place)
@param {string} value - New value for the node or attribute (null will delete it). Providing a function this
will be passed the node and document objects
@param {Object} [options]
@param {string} [options.encoding=utf-8] - Encoding used to read the file
@param {boolean} [options.retryOnENOENT=true] - Retry if writing files because of the parent directory
does not exists
@throws Will throw an error if the path is not a file
@throws Will throw an error if the XPath is not valid
@throws Will throw an error if the XPath is not found
@example
// Set a single attribute 'charset' in the node '//html/head/meta' section to 'UTF-8'
$file.xml.set('index.html', '//html/head/meta, 'charset', 'UTF-8');
@example
// Delete a single attribute 'charset' in the node '//html/head/meta' section
$file.xml.set('index.html', '//html/head/meta, 'charset', null);
Set value in XML file
@function $file~xml/set²
@param {string} file - XML File to write the value to
@param {string} element - XPath expression to the node element to be modified
@param {Object} attributeMapping - attribute-value map to set in the file
@param {Object} [options]
@param {string} [options.encoding=utf-8] - Encoding used to read the file
@param {boolean} [options.retryOnENOENT=true] - Retry if writing files because of the parent directory
does not exists
@throws Will throw an error if the path is not a file
@throws Will throw an error if the XPath is not valid
@throws Will throw an error if the XPath is not found
@example
// Set several attributes in a XML node
$file.xml.set('index.html', '//html/head/meta, {name: 'myname', version: '1.0'});
@example
// Create text nodes
$file.xml.set('index.html', '//html/head/title, 'My Page');
@example
// Use functions to operate with the XML node objects
$file.xml.set('index.html', '//html/head/title, 'My Page'); | [
"Set",
"value",
"in",
"XML",
"file"
] | 1b34424b6cb93593db7ba2c238dbfe301ab9defc | https://github.com/bitnami/nami-utils/blob/1b34424b6cb93593db7ba2c238dbfe301ab9defc/lib/file/xml/set.js#L57-L99 | train |
bitnami/nami-utils | lib/file/delete-if-empty.js | deleteIfEmpty | function deleteIfEmpty(file, options) {
options = _.opts(options, {deleteDirs: true});
return fileDelete(file, _.extend(_.opts(options), {onlyEmptyDirs: true}));
} | javascript | function deleteIfEmpty(file, options) {
options = _.opts(options, {deleteDirs: true});
return fileDelete(file, _.extend(_.opts(options), {onlyEmptyDirs: true}));
} | [
"function",
"deleteIfEmpty",
"(",
"file",
",",
"options",
")",
"{",
"options",
"=",
"_",
".",
"opts",
"(",
"options",
",",
"{",
"deleteDirs",
":",
"true",
"}",
")",
";",
"return",
"fileDelete",
"(",
"file",
",",
"_",
".",
"extend",
"(",
"_",
".",
"opts",
"(",
"options",
")",
",",
"{",
"onlyEmptyDirs",
":",
"true",
"}",
")",
")",
";",
"}"
] | Delete file or empty directory
@function $file~deleteIfEmpty
@param {string} file
@param {Object} [options]
@param {string} [options.deleteDirs=true] - Also delete directories
@returns {boolean} Returns true if the path was deleted or false if not
@example
// Delete $app.installdir if it is empty
$file.deleteIfEmpty($app.installdir);
// => true | [
"Delete",
"file",
"or",
"empty",
"directory"
] | 1b34424b6cb93593db7ba2c238dbfe301ab9defc | https://github.com/bitnami/nami-utils/blob/1b34424b6cb93593db7ba2c238dbfe301ab9defc/lib/file/delete-if-empty.js#L19-L22 | train |
ui-kit/ui-kit | utils/keybinding.js | attachKeybindings | function attachKeybindings (binding, method) {
if (!binding) return console.warn('attachKeybinding requires character or object for binding');
if (typeof binding === 'string' && !method) console.warn('attachKeybindings requries method as second arg');
if (hasKeybinding(binding, method)) return console.warn(`attachKeybinding: already attached ${binding} to method`, method);
if (typeof binding === 'string') addMethod(binding, method);
else Object.keys(binding).forEach((key) => addMethod(key, binding[key]))
} | javascript | function attachKeybindings (binding, method) {
if (!binding) return console.warn('attachKeybinding requires character or object for binding');
if (typeof binding === 'string' && !method) console.warn('attachKeybindings requries method as second arg');
if (hasKeybinding(binding, method)) return console.warn(`attachKeybinding: already attached ${binding} to method`, method);
if (typeof binding === 'string') addMethod(binding, method);
else Object.keys(binding).forEach((key) => addMethod(key, binding[key]))
} | [
"function",
"attachKeybindings",
"(",
"binding",
",",
"method",
")",
"{",
"if",
"(",
"!",
"binding",
")",
"return",
"console",
".",
"warn",
"(",
"'attachKeybinding requires character or object for binding'",
")",
";",
"if",
"(",
"typeof",
"binding",
"===",
"'string'",
"&&",
"!",
"method",
")",
"console",
".",
"warn",
"(",
"'attachKeybindings requries method as second arg'",
")",
";",
"if",
"(",
"hasKeybinding",
"(",
"binding",
",",
"method",
")",
")",
"return",
"console",
".",
"warn",
"(",
"`",
"${",
"binding",
"}",
"`",
",",
"method",
")",
";",
"if",
"(",
"typeof",
"binding",
"===",
"'string'",
")",
"addMethod",
"(",
"binding",
",",
"method",
")",
";",
"else",
"Object",
".",
"keys",
"(",
"binding",
")",
".",
"forEach",
"(",
"(",
"key",
")",
"=>",
"addMethod",
"(",
"key",
",",
"binding",
"[",
"key",
"]",
")",
")",
"}"
] | - Function to call when adding keybindings - @arg {String} bindings - the character key to be bound - || {Object} bindings - the character to listen for as the key, method as the value {[character]: method} - @arg {Function} method - the callback handler to call when string is passed to bindings | [
"-",
"Function",
"to",
"call",
"when",
"adding",
"keybindings",
"-"
] | ea879779f46b5974019a82442547420514a29707 | https://github.com/ui-kit/ui-kit/blob/ea879779f46b5974019a82442547420514a29707/utils/keybinding.js#L22-L29 | train |
ui-kit/ui-kit | utils/keybinding.js | removeKeybindings | function removeKeybindings (bindings, method) {
if (!bindings) return;
if (typeof bindings === 'string' && !method) console.warn('removeKeybindings requries method as second arg');
if (typeof bindings === 'string') return removeMethod(bindings, method);
Object.keys(bindings).forEach((key) => removeMethod(key, bindings[key]));
} | javascript | function removeKeybindings (bindings, method) {
if (!bindings) return;
if (typeof bindings === 'string' && !method) console.warn('removeKeybindings requries method as second arg');
if (typeof bindings === 'string') return removeMethod(bindings, method);
Object.keys(bindings).forEach((key) => removeMethod(key, bindings[key]));
} | [
"function",
"removeKeybindings",
"(",
"bindings",
",",
"method",
")",
"{",
"if",
"(",
"!",
"bindings",
")",
"return",
";",
"if",
"(",
"typeof",
"bindings",
"===",
"'string'",
"&&",
"!",
"method",
")",
"console",
".",
"warn",
"(",
"'removeKeybindings requries method as second arg'",
")",
";",
"if",
"(",
"typeof",
"bindings",
"===",
"'string'",
")",
"return",
"removeMethod",
"(",
"bindings",
",",
"method",
")",
";",
"Object",
".",
"keys",
"(",
"bindings",
")",
".",
"forEach",
"(",
"(",
"key",
")",
"=>",
"removeMethod",
"(",
"key",
",",
"bindings",
"[",
"key",
"]",
")",
")",
";",
"}"
] | - Function to call to remove keybindings - @arg {String} bindings - the character key to be removed || {Object} bindings - the character to remove, with method as the value {[character]: method} - @arg {Function} method - the callback handler to call when string is passed to bindingsr | [
"-",
"Function",
"to",
"call",
"to",
"remove",
"keybindings",
"-"
] | ea879779f46b5974019a82442547420514a29707 | https://github.com/ui-kit/ui-kit/blob/ea879779f46b5974019a82442547420514a29707/utils/keybinding.js#L35-L40 | train |
ui-kit/ui-kit | utils/keybinding.js | addMethod | function addMethod (char, method) {
var keyIsBound = hasKeybinding(char);
var listener = keyupHandler.bind(null, char, method);
bindings[char] = bindings[char] || {methods: [], listeners: []};
if (keyIsBound) window.removeEventListener('keyup', bindings[char].listeners[0]);
bindings[char].methods.unshift(method);
bindings[char].listeners.unshift(listener);
window.addEventListener('keyup', listener);
} | javascript | function addMethod (char, method) {
var keyIsBound = hasKeybinding(char);
var listener = keyupHandler.bind(null, char, method);
bindings[char] = bindings[char] || {methods: [], listeners: []};
if (keyIsBound) window.removeEventListener('keyup', bindings[char].listeners[0]);
bindings[char].methods.unshift(method);
bindings[char].listeners.unshift(listener);
window.addEventListener('keyup', listener);
} | [
"function",
"addMethod",
"(",
"char",
",",
"method",
")",
"{",
"var",
"keyIsBound",
"=",
"hasKeybinding",
"(",
"char",
")",
";",
"var",
"listener",
"=",
"keyupHandler",
".",
"bind",
"(",
"null",
",",
"char",
",",
"method",
")",
";",
"bindings",
"[",
"char",
"]",
"=",
"bindings",
"[",
"char",
"]",
"||",
"{",
"methods",
":",
"[",
"]",
",",
"listeners",
":",
"[",
"]",
"}",
";",
"if",
"(",
"keyIsBound",
")",
"window",
".",
"removeEventListener",
"(",
"'keyup'",
",",
"bindings",
"[",
"char",
"]",
".",
"listeners",
"[",
"0",
"]",
")",
";",
"bindings",
"[",
"char",
"]",
".",
"methods",
".",
"unshift",
"(",
"method",
")",
";",
"bindings",
"[",
"char",
"]",
".",
"listeners",
".",
"unshift",
"(",
"listener",
")",
";",
"window",
".",
"addEventListener",
"(",
"'keyup'",
",",
"listener",
")",
";",
"}"
] | - Adds the event to window and the methods to bindings - @arg {String} char - the character key to be bound - @arg {Function} method - the callback handler to call | [
"-",
"Adds",
"the",
"event",
"to",
"window",
"and",
"the",
"methods",
"to",
"bindings",
"-"
] | ea879779f46b5974019a82442547420514a29707 | https://github.com/ui-kit/ui-kit/blob/ea879779f46b5974019a82442547420514a29707/utils/keybinding.js#L45-L56 | train |
ui-kit/ui-kit | utils/keybinding.js | removeMethod | function removeMethod (char, method) {
if (!hasKeybinding(char, method)) return;
var fnIndex = bindings[char].methods.indexOf(method);
window.removeEventListener('keyup', bindings[char].listeners[fnIndex]);
bindings[char].methods.splice(fnIndex, 1);
bindings[char].listeners.splice(fnIndex, 1);
if (!bindings[char].methods.length) {
delete bindings[char];
} else if (fnIndex === 0) {
window.addEventListener('keyup', bindings[char].listeners[0]);
}
} | javascript | function removeMethod (char, method) {
if (!hasKeybinding(char, method)) return;
var fnIndex = bindings[char].methods.indexOf(method);
window.removeEventListener('keyup', bindings[char].listeners[fnIndex]);
bindings[char].methods.splice(fnIndex, 1);
bindings[char].listeners.splice(fnIndex, 1);
if (!bindings[char].methods.length) {
delete bindings[char];
} else if (fnIndex === 0) {
window.addEventListener('keyup', bindings[char].listeners[0]);
}
} | [
"function",
"removeMethod",
"(",
"char",
",",
"method",
")",
"{",
"if",
"(",
"!",
"hasKeybinding",
"(",
"char",
",",
"method",
")",
")",
"return",
";",
"var",
"fnIndex",
"=",
"bindings",
"[",
"char",
"]",
".",
"methods",
".",
"indexOf",
"(",
"method",
")",
";",
"window",
".",
"removeEventListener",
"(",
"'keyup'",
",",
"bindings",
"[",
"char",
"]",
".",
"listeners",
"[",
"fnIndex",
"]",
")",
";",
"bindings",
"[",
"char",
"]",
".",
"methods",
".",
"splice",
"(",
"fnIndex",
",",
"1",
")",
";",
"bindings",
"[",
"char",
"]",
".",
"listeners",
".",
"splice",
"(",
"fnIndex",
",",
"1",
")",
";",
"if",
"(",
"!",
"bindings",
"[",
"char",
"]",
".",
"methods",
".",
"length",
")",
"{",
"delete",
"bindings",
"[",
"char",
"]",
";",
"}",
"else",
"if",
"(",
"fnIndex",
"===",
"0",
")",
"{",
"window",
".",
"addEventListener",
"(",
"'keyup'",
",",
"bindings",
"[",
"char",
"]",
".",
"listeners",
"[",
"0",
"]",
")",
";",
"}",
"}"
] | - Removes the event from window and the methods from bindings - @arg {String} char - the character key to be removed - @arg {Function} method - the callback handler to remove | [
"-",
"Removes",
"the",
"event",
"from",
"window",
"and",
"the",
"methods",
"from",
"bindings",
"-"
] | ea879779f46b5974019a82442547420514a29707 | https://github.com/ui-kit/ui-kit/blob/ea879779f46b5974019a82442547420514a29707/utils/keybinding.js#L61-L73 | train |
ui-kit/ui-kit | utils/keybinding.js | hasKeybinding | function hasKeybinding (key, method) {
if (!bindings[key]) return false;
return method ? !!~bindings[key].methods.indexOf(method) : true;
} | javascript | function hasKeybinding (key, method) {
if (!bindings[key]) return false;
return method ? !!~bindings[key].methods.indexOf(method) : true;
} | [
"function",
"hasKeybinding",
"(",
"key",
",",
"method",
")",
"{",
"if",
"(",
"!",
"bindings",
"[",
"key",
"]",
")",
"return",
"false",
";",
"return",
"method",
"?",
"!",
"!",
"~",
"bindings",
"[",
"key",
"]",
".",
"methods",
".",
"indexOf",
"(",
"method",
")",
":",
"true",
";",
"}"
] | - Returns Boolean if key is bound to a method, or if any bindings exist for that character - @arg {String} key - character in question - @arg {Function} method - used when you want to know if a key has been bound to a method. | [
"-",
"Returns",
"Boolean",
"if",
"key",
"is",
"bound",
"to",
"a",
"method",
"or",
"if",
"any",
"bindings",
"exist",
"for",
"that",
"character",
"-"
] | ea879779f46b5974019a82442547420514a29707 | https://github.com/ui-kit/ui-kit/blob/ea879779f46b5974019a82442547420514a29707/utils/keybinding.js#L78-L81 | train |
ui-kit/ui-kit | utils/keybinding.js | keyupHandler | function keyupHandler (matchChar, method, evt) {
// except for esc, we don't want to fire events when somebody is typing in an input
if ((evt.target.tagName !== 'INPUT' && evt.target.tagName !== 'TEXTAREA' && !evt.target.hasAttribute('contenteditable')) || keysMatch(evt, 'esc')) {
if (keysMatch(evt, matchChar)) method(evt);
}
} | javascript | function keyupHandler (matchChar, method, evt) {
// except for esc, we don't want to fire events when somebody is typing in an input
if ((evt.target.tagName !== 'INPUT' && evt.target.tagName !== 'TEXTAREA' && !evt.target.hasAttribute('contenteditable')) || keysMatch(evt, 'esc')) {
if (keysMatch(evt, matchChar)) method(evt);
}
} | [
"function",
"keyupHandler",
"(",
"matchChar",
",",
"method",
",",
"evt",
")",
"{",
"if",
"(",
"(",
"evt",
".",
"target",
".",
"tagName",
"!==",
"'INPUT'",
"&&",
"evt",
".",
"target",
".",
"tagName",
"!==",
"'TEXTAREA'",
"&&",
"!",
"evt",
".",
"target",
".",
"hasAttribute",
"(",
"'contenteditable'",
")",
")",
"||",
"keysMatch",
"(",
"evt",
",",
"'esc'",
")",
")",
"{",
"if",
"(",
"keysMatch",
"(",
"evt",
",",
"matchChar",
")",
")",
"method",
"(",
"evt",
")",
";",
"}",
"}"
] | The method we call to parse the event for the key pressed - @arg {String} matchChar - the character to match - @arg {Function} method - function to call when the key specified is pressed - @arg {Object} evt - default browser keyup event | [
"The",
"method",
"we",
"call",
"to",
"parse",
"the",
"event",
"for",
"the",
"key",
"pressed",
"-"
] | ea879779f46b5974019a82442547420514a29707 | https://github.com/ui-kit/ui-kit/blob/ea879779f46b5974019a82442547420514a29707/utils/keybinding.js#L87-L92 | train |
cdapio/ui-schema-parser | lib/index.js | parse | function parse(schema, opts) {
var attrs = files.load(schema);
return attrs.protocol ?
protocols.createProtocol(attrs, opts) :
types.createType(attrs, opts);
} | javascript | function parse(schema, opts) {
var attrs = files.load(schema);
return attrs.protocol ?
protocols.createProtocol(attrs, opts) :
types.createType(attrs, opts);
} | [
"function",
"parse",
"(",
"schema",
",",
"opts",
")",
"{",
"var",
"attrs",
"=",
"files",
".",
"load",
"(",
"schema",
")",
";",
"return",
"attrs",
".",
"protocol",
"?",
"protocols",
".",
"createProtocol",
"(",
"attrs",
",",
"opts",
")",
":",
"types",
".",
"createType",
"(",
"attrs",
",",
"opts",
")",
";",
"}"
] | Parse a schema and return the corresponding type or protocol. | [
"Parse",
"a",
"schema",
"and",
"return",
"the",
"corresponding",
"type",
"or",
"protocol",
"."
] | 7fa333e0fe1208de6adc17e597ec847f5ae84124 | https://github.com/cdapio/ui-schema-parser/blob/7fa333e0fe1208de6adc17e597ec847f5ae84124/lib/index.js#L27-L32 | train |
cdapio/ui-schema-parser | lib/index.js | extractFileHeader | function extractFileHeader(path, opts) {
opts = opts || {};
var decode = opts.decode === undefined ? true : !!opts.decode;
var size = Math.max(opts.size || 4096, 4);
var fd = fs.openSync(path, 'r');
var buf = new Buffer(size);
var pos = 0;
var tap = new utils.Tap(buf);
var header = null;
while (pos < 4) {
// Make sure we have enough to check the magic bytes.
pos += fs.readSync(fd, buf, pos, size - pos);
}
if (containers.MAGIC_BYTES.equals(buf.slice(0, 4))) {
do {
header = containers.HEADER_TYPE._read(tap);
} while (!isValid());
if (decode !== false) {
var meta = header.meta;
meta['avro.schema'] = JSON.parse(meta['avro.schema'].toString());
if (meta['avro.codec'] !== undefined) {
meta['avro.codec'] = meta['avro.codec'].toString();
}
}
}
fs.closeSync(fd);
return header;
function isValid() {
if (tap.isValid()) {
return true;
}
var len = 2 * tap.buf.length;
var buf = new Buffer(len);
len = fs.readSync(fd, buf, 0, len);
tap.buf = Buffer.concat([tap.buf, buf]);
tap.pos = 0;
return false;
}
} | javascript | function extractFileHeader(path, opts) {
opts = opts || {};
var decode = opts.decode === undefined ? true : !!opts.decode;
var size = Math.max(opts.size || 4096, 4);
var fd = fs.openSync(path, 'r');
var buf = new Buffer(size);
var pos = 0;
var tap = new utils.Tap(buf);
var header = null;
while (pos < 4) {
// Make sure we have enough to check the magic bytes.
pos += fs.readSync(fd, buf, pos, size - pos);
}
if (containers.MAGIC_BYTES.equals(buf.slice(0, 4))) {
do {
header = containers.HEADER_TYPE._read(tap);
} while (!isValid());
if (decode !== false) {
var meta = header.meta;
meta['avro.schema'] = JSON.parse(meta['avro.schema'].toString());
if (meta['avro.codec'] !== undefined) {
meta['avro.codec'] = meta['avro.codec'].toString();
}
}
}
fs.closeSync(fd);
return header;
function isValid() {
if (tap.isValid()) {
return true;
}
var len = 2 * tap.buf.length;
var buf = new Buffer(len);
len = fs.readSync(fd, buf, 0, len);
tap.buf = Buffer.concat([tap.buf, buf]);
tap.pos = 0;
return false;
}
} | [
"function",
"extractFileHeader",
"(",
"path",
",",
"opts",
")",
"{",
"opts",
"=",
"opts",
"||",
"{",
"}",
";",
"var",
"decode",
"=",
"opts",
".",
"decode",
"===",
"undefined",
"?",
"true",
":",
"!",
"!",
"opts",
".",
"decode",
";",
"var",
"size",
"=",
"Math",
".",
"max",
"(",
"opts",
".",
"size",
"||",
"4096",
",",
"4",
")",
";",
"var",
"fd",
"=",
"fs",
".",
"openSync",
"(",
"path",
",",
"'r'",
")",
";",
"var",
"buf",
"=",
"new",
"Buffer",
"(",
"size",
")",
";",
"var",
"pos",
"=",
"0",
";",
"var",
"tap",
"=",
"new",
"utils",
".",
"Tap",
"(",
"buf",
")",
";",
"var",
"header",
"=",
"null",
";",
"while",
"(",
"pos",
"<",
"4",
")",
"{",
"pos",
"+=",
"fs",
".",
"readSync",
"(",
"fd",
",",
"buf",
",",
"pos",
",",
"size",
"-",
"pos",
")",
";",
"}",
"if",
"(",
"containers",
".",
"MAGIC_BYTES",
".",
"equals",
"(",
"buf",
".",
"slice",
"(",
"0",
",",
"4",
")",
")",
")",
"{",
"do",
"{",
"header",
"=",
"containers",
".",
"HEADER_TYPE",
".",
"_read",
"(",
"tap",
")",
";",
"}",
"while",
"(",
"!",
"isValid",
"(",
")",
")",
";",
"if",
"(",
"decode",
"!==",
"false",
")",
"{",
"var",
"meta",
"=",
"header",
".",
"meta",
";",
"meta",
"[",
"'avro.schema'",
"]",
"=",
"JSON",
".",
"parse",
"(",
"meta",
"[",
"'avro.schema'",
"]",
".",
"toString",
"(",
")",
")",
";",
"if",
"(",
"meta",
"[",
"'avro.codec'",
"]",
"!==",
"undefined",
")",
"{",
"meta",
"[",
"'avro.codec'",
"]",
"=",
"meta",
"[",
"'avro.codec'",
"]",
".",
"toString",
"(",
")",
";",
"}",
"}",
"}",
"fs",
".",
"closeSync",
"(",
"fd",
")",
";",
"return",
"header",
";",
"function",
"isValid",
"(",
")",
"{",
"if",
"(",
"tap",
".",
"isValid",
"(",
")",
")",
"{",
"return",
"true",
";",
"}",
"var",
"len",
"=",
"2",
"*",
"tap",
".",
"buf",
".",
"length",
";",
"var",
"buf",
"=",
"new",
"Buffer",
"(",
"len",
")",
";",
"len",
"=",
"fs",
".",
"readSync",
"(",
"fd",
",",
"buf",
",",
"0",
",",
"len",
")",
";",
"tap",
".",
"buf",
"=",
"Buffer",
".",
"concat",
"(",
"[",
"tap",
".",
"buf",
",",
"buf",
"]",
")",
";",
"tap",
".",
"pos",
"=",
"0",
";",
"return",
"false",
";",
"}",
"}"
] | Extract a container file's header synchronously. | [
"Extract",
"a",
"container",
"file",
"s",
"header",
"synchronously",
"."
] | 7fa333e0fe1208de6adc17e597ec847f5ae84124 | https://github.com/cdapio/ui-schema-parser/blob/7fa333e0fe1208de6adc17e597ec847f5ae84124/lib/index.js#L38-L79 | train |
ui-kit/ui-kit | utils/root.js | evaluate | function evaluate(conf, parent) {
if (!conf || conf.constructor.name !== 'Object') return conf;
var val;
for (var key in conf) {
val = conf[key];
if (typeof val === 'function') val = reduceVal(parent, val);
conf[key] = evaluate(val, parent);
}
return conf;
} | javascript | function evaluate(conf, parent) {
if (!conf || conf.constructor.name !== 'Object') return conf;
var val;
for (var key in conf) {
val = conf[key];
if (typeof val === 'function') val = reduceVal(parent, val);
conf[key] = evaluate(val, parent);
}
return conf;
} | [
"function",
"evaluate",
"(",
"conf",
",",
"parent",
")",
"{",
"if",
"(",
"!",
"conf",
"||",
"conf",
".",
"constructor",
".",
"name",
"!==",
"'Object'",
")",
"return",
"conf",
";",
"var",
"val",
";",
"for",
"(",
"var",
"key",
"in",
"conf",
")",
"{",
"val",
"=",
"conf",
"[",
"key",
"]",
";",
"if",
"(",
"typeof",
"val",
"===",
"'function'",
")",
"val",
"=",
"reduceVal",
"(",
"parent",
",",
"val",
")",
";",
"conf",
"[",
"key",
"]",
"=",
"evaluate",
"(",
"val",
",",
"parent",
")",
";",
"}",
"return",
"conf",
";",
"}"
] | Recursively evaluate lazy values
@param {Object} conf
@param {Object} parent | [
"Recursively",
"evaluate",
"lazy",
"values"
] | ea879779f46b5974019a82442547420514a29707 | https://github.com/ui-kit/ui-kit/blob/ea879779f46b5974019a82442547420514a29707/utils/root.js#L62-L71 | train |
ui-kit/ui-kit | utils/root.js | reduceVal | function reduceVal(conf, val) {
val = val.call(conf);
return typeof val === 'function' ? reduceVal(conf, val) : val;
} | javascript | function reduceVal(conf, val) {
val = val.call(conf);
return typeof val === 'function' ? reduceVal(conf, val) : val;
} | [
"function",
"reduceVal",
"(",
"conf",
",",
"val",
")",
"{",
"val",
"=",
"val",
".",
"call",
"(",
"conf",
")",
";",
"return",
"typeof",
"val",
"===",
"'function'",
"?",
"reduceVal",
"(",
"conf",
",",
"val",
")",
":",
"val",
";",
"}"
] | Call function `val` in context of `conf`
@param {Object} conf
@param {Function} val | [
"Call",
"function",
"val",
"in",
"context",
"of",
"conf"
] | ea879779f46b5974019a82442547420514a29707 | https://github.com/ui-kit/ui-kit/blob/ea879779f46b5974019a82442547420514a29707/utils/root.js#L79-L82 | train |
ui-kit/ui-kit | utils/root.js | generateColors | function generateColors(conf) {
for (var key in conf.color) {
if (typeof conf.color[key] !== 'string') continue;
conf.color[key] = new Color(conf.color[key]);
}
return conf;
} | javascript | function generateColors(conf) {
for (var key in conf.color) {
if (typeof conf.color[key] !== 'string') continue;
conf.color[key] = new Color(conf.color[key]);
}
return conf;
} | [
"function",
"generateColors",
"(",
"conf",
")",
"{",
"for",
"(",
"var",
"key",
"in",
"conf",
".",
"color",
")",
"{",
"if",
"(",
"typeof",
"conf",
".",
"color",
"[",
"key",
"]",
"!==",
"'string'",
")",
"continue",
";",
"conf",
".",
"color",
"[",
"key",
"]",
"=",
"new",
"Color",
"(",
"conf",
".",
"color",
"[",
"key",
"]",
")",
";",
"}",
"return",
"conf",
";",
"}"
] | Iterate over given colors in `conf` with `Color` class
@param {Object} conf | [
"Iterate",
"over",
"given",
"colors",
"in",
"conf",
"with",
"Color",
"class"
] | ea879779f46b5974019a82442547420514a29707 | https://github.com/ui-kit/ui-kit/blob/ea879779f46b5974019a82442547420514a29707/utils/root.js#L103-L109 | train |
bitnami/nami-utils | lib/os/user-management/get-user-groups.js | getUserGroups | function getUserGroups(user) {
try {
const output = runProgram('groups', [user]).trim();
const groupsText = isBusyboxCommand('groups') ? output : output.split(':')[1].trim();
return groupsText.split(/\s+/);
} catch (e) {
throw new Error(`Cannot resolve user ${user}`);
}
} | javascript | function getUserGroups(user) {
try {
const output = runProgram('groups', [user]).trim();
const groupsText = isBusyboxCommand('groups') ? output : output.split(':')[1].trim();
return groupsText.split(/\s+/);
} catch (e) {
throw new Error(`Cannot resolve user ${user}`);
}
} | [
"function",
"getUserGroups",
"(",
"user",
")",
"{",
"try",
"{",
"const",
"output",
"=",
"runProgram",
"(",
"'groups'",
",",
"[",
"user",
"]",
")",
".",
"trim",
"(",
")",
";",
"const",
"groupsText",
"=",
"isBusyboxCommand",
"(",
"'groups'",
")",
"?",
"output",
":",
"output",
".",
"split",
"(",
"':'",
")",
"[",
"1",
"]",
".",
"trim",
"(",
")",
";",
"return",
"groupsText",
".",
"split",
"(",
"/",
"\\s+",
"/",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"throw",
"new",
"Error",
"(",
"`",
"${",
"user",
"}",
"`",
")",
";",
"}",
"}"
] | Get User Groups
@function $os~getUserGroups
@param {string|number} user - Username or user id
@returns {string[]} - User groups
@example
// Get group names of user 'mysql'
$os.getUserGroups('mysql');
// => ['mysql', 'system'] | [
"Get",
"User",
"Groups"
] | 1b34424b6cb93593db7ba2c238dbfe301ab9defc | https://github.com/bitnami/nami-utils/blob/1b34424b6cb93593db7ba2c238dbfe301ab9defc/lib/os/user-management/get-user-groups.js#L16-L24 | train |
bitnami/nami-utils | lib/file/delete.js | fileDelete | function fileDelete(src, options) {
options = _.sanitize(options, {exclude: [], deleteDirs: true, onlyEmptyDirs: false});
let result = true;
const files = _matchingFilesArray(src, options);
_.each(files, (f) => {
const fileWasDeleted = _fileDelete(f, options);
result = result && fileWasDeleted;
});
return result;
} | javascript | function fileDelete(src, options) {
options = _.sanitize(options, {exclude: [], deleteDirs: true, onlyEmptyDirs: false});
let result = true;
const files = _matchingFilesArray(src, options);
_.each(files, (f) => {
const fileWasDeleted = _fileDelete(f, options);
result = result && fileWasDeleted;
});
return result;
} | [
"function",
"fileDelete",
"(",
"src",
",",
"options",
")",
"{",
"options",
"=",
"_",
".",
"sanitize",
"(",
"options",
",",
"{",
"exclude",
":",
"[",
"]",
",",
"deleteDirs",
":",
"true",
",",
"onlyEmptyDirs",
":",
"false",
"}",
")",
";",
"let",
"result",
"=",
"true",
";",
"const",
"files",
"=",
"_matchingFilesArray",
"(",
"src",
",",
"options",
")",
";",
"_",
".",
"each",
"(",
"files",
",",
"(",
"f",
")",
"=>",
"{",
"const",
"fileWasDeleted",
"=",
"_fileDelete",
"(",
"f",
",",
"options",
")",
";",
"result",
"=",
"result",
"&&",
"fileWasDeleted",
";",
"}",
")",
";",
"return",
"result",
";",
"}"
] | Delete file or directory
@function $file~delete
@param {string|string[]} source - File or array of files to copy. It also supports wildcards.
@param {Object} [options]
@param {string[]} [options.exclude=[]] - List of patterns used to exclude files when deleting
@param {string} [options.deleteDirs=true] - Also delete directories
@param {string} [options.onlyEmptyDirs=false] - Only delete directories if they are empty
@returns {boolean} Returns true if the path was deleted or false if not
@example
// Delete /foo/bar/sample file
$file.delete('/tmp/bar/sample');
=> true
@example
// Delete /tmp/ files avoiding directories
$file.delete('/tmp/*', {deleteDirs: false});
=> false | [
"Delete",
"file",
"or",
"directory"
] | 1b34424b6cb93593db7ba2c238dbfe301ab9defc | https://github.com/bitnami/nami-utils/blob/1b34424b6cb93593db7ba2c238dbfe301ab9defc/lib/file/delete.js#L48-L57 | train |
bitnami/nami-utils | lib/crypto/index.js | rand | function rand(options) {
options = _.opts(options, {size: 32, ascii: false, alphanumeric: false, numeric: false});
const size = options.size;
let data = '';
while (data.length < size) {
// ASCII is in range of 0 to 127
let randBytes = crypto.pseudoRandomBytes(Math.max(size, 32)).toString();
/* eslint-disable no-control-regex */
if (options.ascii) randBytes = randBytes.replace(/[^\s\x00-\x7F]/g, '');
/* eslint-enable no-control-regex */
if (options.alphanumeric) randBytes = randBytes.replace(/[^a-zA-Z0-9]/g, '');
if (options.numeric) randBytes = randBytes.replace(/[^0-9]/g, '');
data += randBytes;
}
data = data.slice(0, size);
return data;
} | javascript | function rand(options) {
options = _.opts(options, {size: 32, ascii: false, alphanumeric: false, numeric: false});
const size = options.size;
let data = '';
while (data.length < size) {
// ASCII is in range of 0 to 127
let randBytes = crypto.pseudoRandomBytes(Math.max(size, 32)).toString();
/* eslint-disable no-control-regex */
if (options.ascii) randBytes = randBytes.replace(/[^\s\x00-\x7F]/g, '');
/* eslint-enable no-control-regex */
if (options.alphanumeric) randBytes = randBytes.replace(/[^a-zA-Z0-9]/g, '');
if (options.numeric) randBytes = randBytes.replace(/[^0-9]/g, '');
data += randBytes;
}
data = data.slice(0, size);
return data;
} | [
"function",
"rand",
"(",
"options",
")",
"{",
"options",
"=",
"_",
".",
"opts",
"(",
"options",
",",
"{",
"size",
":",
"32",
",",
"ascii",
":",
"false",
",",
"alphanumeric",
":",
"false",
",",
"numeric",
":",
"false",
"}",
")",
";",
"const",
"size",
"=",
"options",
".",
"size",
";",
"let",
"data",
"=",
"''",
";",
"while",
"(",
"data",
".",
"length",
"<",
"size",
")",
"{",
"let",
"randBytes",
"=",
"crypto",
".",
"pseudoRandomBytes",
"(",
"Math",
".",
"max",
"(",
"size",
",",
"32",
")",
")",
".",
"toString",
"(",
")",
";",
"if",
"(",
"options",
".",
"ascii",
")",
"randBytes",
"=",
"randBytes",
".",
"replace",
"(",
"/",
"[^\\s\\x00-\\x7F]",
"/",
"g",
",",
"''",
")",
";",
"if",
"(",
"options",
".",
"alphanumeric",
")",
"randBytes",
"=",
"randBytes",
".",
"replace",
"(",
"/",
"[^a-zA-Z0-9]",
"/",
"g",
",",
"''",
")",
";",
"if",
"(",
"options",
".",
"numeric",
")",
"randBytes",
"=",
"randBytes",
".",
"replace",
"(",
"/",
"[^0-9]",
"/",
"g",
",",
"''",
")",
";",
"data",
"+=",
"randBytes",
";",
"}",
"data",
"=",
"data",
".",
"slice",
"(",
"0",
",",
"size",
")",
";",
"return",
"data",
";",
"}"
] | Generate pseudo random value
@function $crypt~rand
@param {object} [options]
@param {number} [options.size=32] - Number of bytes to return
@param {boolean} [options.ascii=false] - Return ascii values
@param {boolean} [options.alphanumeric=false] - Return alphanumeric value
@param {boolean} [options.numeric=false] - Return numeric-only value
@returns {string} - Random bytes string
@example
// Generate an alphanumeric 10 chars string
$crypt.rand({'size': 10, 'alphanumeric': true});
// => 'hT8sePMvVM' | [
"Generate",
"pseudo",
"random",
"value"
] | 1b34424b6cb93593db7ba2c238dbfe301ab9defc | https://github.com/bitnami/nami-utils/blob/1b34424b6cb93593db7ba2c238dbfe301ab9defc/lib/crypto/index.js#L159-L175 | train |
bitnami/nami-utils | lib/crypto/index.js | base64 | function base64(text, operation) {
operation = operation || 'encode';
if (operation === 'decode') {
return (new Buffer(text, 'base64')).toString();
} else {
return (new Buffer(text)).toString('base64');
}
} | javascript | function base64(text, operation) {
operation = operation || 'encode';
if (operation === 'decode') {
return (new Buffer(text, 'base64')).toString();
} else {
return (new Buffer(text)).toString('base64');
}
} | [
"function",
"base64",
"(",
"text",
",",
"operation",
")",
"{",
"operation",
"=",
"operation",
"||",
"'encode'",
";",
"if",
"(",
"operation",
"===",
"'decode'",
")",
"{",
"return",
"(",
"new",
"Buffer",
"(",
"text",
",",
"'base64'",
")",
")",
".",
"toString",
"(",
")",
";",
"}",
"else",
"{",
"return",
"(",
"new",
"Buffer",
"(",
"text",
")",
")",
".",
"toString",
"(",
"'base64'",
")",
";",
"}",
"}"
] | Base64 encode and decode
@function $crypt~base64
@param {string} string - String to encode or decode
@param {string} [operation=encode] - Operation to perform. Allowed values: 'encode', 'decode'
@returns {string} - Base64 encoded or decoded value
@example
// Encode binary text
$crypt.base64('hello');
// => 'aGVsbG8='
@example
// Decode base64 encoded text
$crypt.base64('aGVsbG8=', 'decode');
// => 'hello' | [
"Base64",
"encode",
"and",
"decode"
] | 1b34424b6cb93593db7ba2c238dbfe301ab9defc | https://github.com/bitnami/nami-utils/blob/1b34424b6cb93593db7ba2c238dbfe301ab9defc/lib/crypto/index.js#L192-L199 | train |
bitnami/nami-utils | lib/os/temporary-files.js | createTempFile | function createTempFile(options) {
options = _.opts(options, {cleanup: true});
return _createTemporaryPath((f) => fs.writeFileSync(f, ''), options.cleanup);
} | javascript | function createTempFile(options) {
options = _.opts(options, {cleanup: true});
return _createTemporaryPath((f) => fs.writeFileSync(f, ''), options.cleanup);
} | [
"function",
"createTempFile",
"(",
"options",
")",
"{",
"options",
"=",
"_",
".",
"opts",
"(",
"options",
",",
"{",
"cleanup",
":",
"true",
"}",
")",
";",
"return",
"_createTemporaryPath",
"(",
"(",
"f",
")",
"=>",
"fs",
".",
"writeFileSync",
"(",
"f",
",",
"''",
")",
",",
"options",
".",
"cleanup",
")",
";",
"}"
] | Create temporary file
@function $os~createTempFile
@param {Object} [options]
@param {boolean} [options.cleanup=true] - Mark the file to be cleaned up on exit
@returns {string} - Temporary file created
@example
// Create a temporary file that will be deleted at exit
$os.createTempFile();
// => '/tmp/1453824062535.702'
@example
// Create a temporary file but do not automatically clean it up at exit
$os.createTempFile({cleanup: false});
// => '/tmp/1453461306625.4946' | [
"Create",
"temporary",
"file"
] | 1b34424b6cb93593db7ba2c238dbfe301ab9defc | https://github.com/bitnami/nami-utils/blob/1b34424b6cb93593db7ba2c238dbfe301ab9defc/lib/os/temporary-files.js#L71-L74 | train |
bitnami/nami-utils | lib/os/temporary-files.js | createTempDir | function createTempDir(options) {
options = _.opts(options, {cleanup: true});
return _createTemporaryPath(fs.mkdirSync, options.cleanup);
} | javascript | function createTempDir(options) {
options = _.opts(options, {cleanup: true});
return _createTemporaryPath(fs.mkdirSync, options.cleanup);
} | [
"function",
"createTempDir",
"(",
"options",
")",
"{",
"options",
"=",
"_",
".",
"opts",
"(",
"options",
",",
"{",
"cleanup",
":",
"true",
"}",
")",
";",
"return",
"_createTemporaryPath",
"(",
"fs",
".",
"mkdirSync",
",",
"options",
".",
"cleanup",
")",
";",
"}"
] | Create temporary directory
@function $os~createTempDir
@param {Object} [options]
@param {boolean} [options.cleanup=true] - Mark the directory to be cleaned up on exit
@returns {string} - Temporary directory created
@example
// Create a temporary directory that will be deleted at exit
$os.createTempDir();
// => '/tmp/1453474785995.4712'
@example
// Create a temporary directory but do not automatically clean it up at exit
$os.createTempDir({cleanup: false});
// => '/tmp/1453824141131.3015' | [
"Create",
"temporary",
"directory"
] | 1b34424b6cb93593db7ba2c238dbfe301ab9defc | https://github.com/bitnami/nami-utils/blob/1b34424b6cb93593db7ba2c238dbfe301ab9defc/lib/os/temporary-files.js#L91-L94 | train |
baby-loris/bla | lib/validators/normalize.js | parseJson | function parseJson(name, type, value) {
try {
return typeof value === 'string' ?
JSON.parse(value) :
value;
} catch (e) {
throwError(name, type, value);
}
} | javascript | function parseJson(name, type, value) {
try {
return typeof value === 'string' ?
JSON.parse(value) :
value;
} catch (e) {
throwError(name, type, value);
}
} | [
"function",
"parseJson",
"(",
"name",
",",
"type",
",",
"value",
")",
"{",
"try",
"{",
"return",
"typeof",
"value",
"===",
"'string'",
"?",
"JSON",
".",
"parse",
"(",
"value",
")",
":",
"value",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"throwError",
"(",
"name",
",",
"type",
",",
"value",
")",
";",
"}",
"}"
] | Parses a string as a JSON.
@param {String} name Parameter value.
@param {String} type Parameter type.
@param {String|Object} value Parameter value.
@returns {Object} | [
"Parses",
"a",
"string",
"as",
"a",
"JSON",
"."
] | d40bdfc4991ce4758345989df18d44543e064509 | https://github.com/baby-loris/bla/blob/d40bdfc4991ce4758345989df18d44543e064509/lib/validators/normalize.js#L11-L19 | train |
bitnami/nami-utils | lib/templates.js | renderTemplateText | function renderTemplateText(template, data, options) {
data = _.opts(data, {});
options = _.opts(options, {noEscape: true, compact: false});
// TODO: We should support recursively resolving, as in IB
return hb.compile(template, options)(_.defaults(data, globalSettings), {helpers: globalHelpers});
} | javascript | function renderTemplateText(template, data, options) {
data = _.opts(data, {});
options = _.opts(options, {noEscape: true, compact: false});
// TODO: We should support recursively resolving, as in IB
return hb.compile(template, options)(_.defaults(data, globalSettings), {helpers: globalHelpers});
} | [
"function",
"renderTemplateText",
"(",
"template",
",",
"data",
",",
"options",
")",
"{",
"data",
"=",
"_",
".",
"opts",
"(",
"data",
",",
"{",
"}",
")",
";",
"options",
"=",
"_",
".",
"opts",
"(",
"options",
",",
"{",
"noEscape",
":",
"true",
",",
"compact",
":",
"false",
"}",
")",
";",
"return",
"hb",
".",
"compile",
"(",
"template",
",",
"options",
")",
"(",
"_",
".",
"defaults",
"(",
"data",
",",
"globalSettings",
")",
",",
"{",
"helpers",
":",
"globalHelpers",
"}",
")",
";",
"}"
] | Render text replacing handlebar references
@function $hb~renderText
@param {string} template - Template text
@param {Object} [data] - Object containing substitutions to perform on the template. By default, it will
render the text using $app properties.
@param {Object} [options] - Handlebars options
@param {string} [options.noEscape=true] - Set to false to HTML escape any content
@param {string} [options.compact=false] - Set to true to enable recursive field lookup
@returns {string} - The rendered text
@example
// Returns rendered text
$hb.renderText(`
[mysqld]
port={{port}}
basedir={{basedir}}
`, {port: 3306, basedir: '/opt/bitnami/mysql'});
// => [mysqld]
basedir=/opt/bitnami/mysql
port=3306 | [
"Render",
"text",
"replacing",
"handlebar",
"references"
] | 1b34424b6cb93593db7ba2c238dbfe301ab9defc | https://github.com/bitnami/nami-utils/blob/1b34424b6cb93593db7ba2c238dbfe301ab9defc/lib/templates.js#L49-L54 | train |
bitnami/nami-utils | lib/templates.js | renderTemplate | function renderTemplate(templateFile, data, options) {
return renderTemplateText(read(normalizeTemplate(templateFile)), data, options);
} | javascript | function renderTemplate(templateFile, data, options) {
return renderTemplateText(read(normalizeTemplate(templateFile)), data, options);
} | [
"function",
"renderTemplate",
"(",
"templateFile",
",",
"data",
",",
"options",
")",
"{",
"return",
"renderTemplateText",
"(",
"read",
"(",
"normalizeTemplate",
"(",
"templateFile",
")",
")",
",",
"data",
",",
"options",
")",
";",
"}"
] | Render template file
@function $hb~render
@param {string} template - Template file
@param {Object} [data] - Object containing substitutions to perform on the template
@param {Object} [options] - Handlebars options
@param {string} [options.noEscape=true] - Set to false to HTML escape any content
@param {string} [options.compact=false] - Set to true to enable recursive field lookup
@returns {string} - The rendered text | [
"Render",
"template",
"file"
] | 1b34424b6cb93593db7ba2c238dbfe301ab9defc | https://github.com/bitnami/nami-utils/blob/1b34424b6cb93593db7ba2c238dbfe301ab9defc/lib/templates.js#L66-L68 | train |
bitnami/nami-utils | lib/templates.js | renderTemplateToFile | function renderTemplateToFile(templateFile, destFile, data, options) {
renderTemplateTextToFile(read(templateFile), normalizeFile(destFile), data, options);
} | javascript | function renderTemplateToFile(templateFile, destFile, data, options) {
renderTemplateTextToFile(read(templateFile), normalizeFile(destFile), data, options);
} | [
"function",
"renderTemplateToFile",
"(",
"templateFile",
",",
"destFile",
",",
"data",
",",
"options",
")",
"{",
"renderTemplateTextToFile",
"(",
"read",
"(",
"templateFile",
")",
",",
"normalizeFile",
"(",
"destFile",
")",
",",
"data",
",",
"options",
")",
";",
"}"
] | Render template to file
@function $hb~renderToFile
@param {string} template - Template file
@param {string} destination - Destination file
@param {Object} [data] - Object containing substitutions to perform on the template. By default, it will
render the text using $app properties
@example
// Writes a rendered file 'my.cnf'
$hb.renderToFile('my.cnf.tpl', 'conf/my.cnf'); | [
"Render",
"template",
"to",
"file"
] | 1b34424b6cb93593db7ba2c238dbfe301ab9defc | https://github.com/bitnami/nami-utils/blob/1b34424b6cb93593db7ba2c238dbfe301ab9defc/lib/templates.js#L85-L87 | train |
bitnami/nami-utils | lib/file/strip-path-prefix.js | stripPathPrefix | function stripPathPrefix(p, prefix, options) {
if (!prefix) return p;
options = _.sanitize(options, {force: false});
p = _fileCleanPath(p);
prefix = _fileCleanPath(prefix);
if (options.force) {
return path.relative(prefix, p);
} else {
const pathSplit = split(p);
const prefixSplit = split(prefix);
if (prefixSplit.length > pathSplit.length) return p;
let i = 0;
for (i = 0; i < prefixSplit.length; i++) {
if (pathSplit[i] !== prefixSplit[i]) return p;
}
return pathSplit.slice(i).join('/');
}
} | javascript | function stripPathPrefix(p, prefix, options) {
if (!prefix) return p;
options = _.sanitize(options, {force: false});
p = _fileCleanPath(p);
prefix = _fileCleanPath(prefix);
if (options.force) {
return path.relative(prefix, p);
} else {
const pathSplit = split(p);
const prefixSplit = split(prefix);
if (prefixSplit.length > pathSplit.length) return p;
let i = 0;
for (i = 0; i < prefixSplit.length; i++) {
if (pathSplit[i] !== prefixSplit[i]) return p;
}
return pathSplit.slice(i).join('/');
}
} | [
"function",
"stripPathPrefix",
"(",
"p",
",",
"prefix",
",",
"options",
")",
"{",
"if",
"(",
"!",
"prefix",
")",
"return",
"p",
";",
"options",
"=",
"_",
".",
"sanitize",
"(",
"options",
",",
"{",
"force",
":",
"false",
"}",
")",
";",
"p",
"=",
"_fileCleanPath",
"(",
"p",
")",
";",
"prefix",
"=",
"_fileCleanPath",
"(",
"prefix",
")",
";",
"if",
"(",
"options",
".",
"force",
")",
"{",
"return",
"path",
".",
"relative",
"(",
"prefix",
",",
"p",
")",
";",
"}",
"else",
"{",
"const",
"pathSplit",
"=",
"split",
"(",
"p",
")",
";",
"const",
"prefixSplit",
"=",
"split",
"(",
"prefix",
")",
";",
"if",
"(",
"prefixSplit",
".",
"length",
">",
"pathSplit",
".",
"length",
")",
"return",
"p",
";",
"let",
"i",
"=",
"0",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"prefixSplit",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"pathSplit",
"[",
"i",
"]",
"!==",
"prefixSplit",
"[",
"i",
"]",
")",
"return",
"p",
";",
"}",
"return",
"pathSplit",
".",
"slice",
"(",
"i",
")",
".",
"join",
"(",
"'/'",
")",
";",
"}",
"}"
] | Take a path and a prefix and return a relativized version
@function $file~relativize
@param {string} path - File path to relativize
@param {string} prefix - Prefix to remove
@param {Object} [options]
@param {boolean} [options.force=false] - Relativize even if the path is not under the prefix
@returns {string} - The relativized path
@example
// Get relative path of 'test' from the '/foo' directory
$file.relativize('/foo/bar/test', '/foo');
// => 'bar/test' | [
"Take",
"a",
"path",
"and",
"a",
"prefix",
"and",
"return",
"a",
"relativized",
"version"
] | 1b34424b6cb93593db7ba2c238dbfe301ab9defc | https://github.com/bitnami/nami-utils/blob/1b34424b6cb93593db7ba2c238dbfe301ab9defc/lib/file/strip-path-prefix.js#L25-L42 | train |
bitnami/nami-utils | lib/file/is-empty-dir.js | isEmptyDir | function isEmptyDir(dir) {
try {
return !(fs.readdirSync(dir).length > 0);
} catch (e) {
if (e.code === 'ENOENT') {
// We consider non-existent as empty
return true;
}
throw e;
}
} | javascript | function isEmptyDir(dir) {
try {
return !(fs.readdirSync(dir).length > 0);
} catch (e) {
if (e.code === 'ENOENT') {
// We consider non-existent as empty
return true;
}
throw e;
}
} | [
"function",
"isEmptyDir",
"(",
"dir",
")",
"{",
"try",
"{",
"return",
"!",
"(",
"fs",
".",
"readdirSync",
"(",
"dir",
")",
".",
"length",
">",
"0",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"if",
"(",
"e",
".",
"code",
"===",
"'ENOENT'",
")",
"{",
"return",
"true",
";",
"}",
"throw",
"e",
";",
"}",
"}"
] | Check if the given directory is empty
@function $file~isEmptyDir
@param {string} dir
@returns {boolean} Returns true if the directory is empty or does not exists
@example
// Check if '/tmp' directory is empty
$file.isEmptyDir('/tmp');
// => false | [
"Check",
"if",
"the",
"given",
"directory",
"is",
"empty"
] | 1b34424b6cb93593db7ba2c238dbfe301ab9defc | https://github.com/bitnami/nami-utils/blob/1b34424b6cb93593db7ba2c238dbfe301ab9defc/lib/file/is-empty-dir.js#L15-L25 | train |
bitnami/nami-utils | lib/file/size.js | size | function size(file) {
if (!exists(file) || !isFile(file)) {
return -1;
} else {
try {
return _fileStats(file).size;
} catch (e) {
return -1;
}
}
} | javascript | function size(file) {
if (!exists(file) || !isFile(file)) {
return -1;
} else {
try {
return _fileStats(file).size;
} catch (e) {
return -1;
}
}
} | [
"function",
"size",
"(",
"file",
")",
"{",
"if",
"(",
"!",
"exists",
"(",
"file",
")",
"||",
"!",
"isFile",
"(",
"file",
")",
")",
"{",
"return",
"-",
"1",
";",
"}",
"else",
"{",
"try",
"{",
"return",
"_fileStats",
"(",
"file",
")",
".",
"size",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"return",
"-",
"1",
";",
"}",
"}",
"}"
] | Returns the size of a given path. Returns -1 if the path is a directory or does not exists.
@function $file~size
@param {string} file
@returns {number}
@example
// Get file size of '/bin/ls'
$file.size('/bin/ls');
// => 110080 | [
"Returns",
"the",
"size",
"of",
"a",
"given",
"path",
".",
"Returns",
"-",
"1",
"if",
"the",
"path",
"is",
"a",
"directory",
"or",
"does",
"not",
"exists",
"."
] | 1b34424b6cb93593db7ba2c238dbfe301ab9defc | https://github.com/bitnami/nami-utils/blob/1b34424b6cb93593db7ba2c238dbfe301ab9defc/lib/file/size.js#L18-L28 | train |
bitnami/nami-utils | lib/file/chmod.js | chmod | function chmod(file, permissions, options) {
if (!isPlatform('unix')) return;
if (!exists(file)) throw new Error(`Path '${file}' does not exists`);
const isDir = isDirectory(file);
options = _.sanitize(options, {recursive: false});
let filePermissions = null;
let dirPermissions = null;
if (_.isReallyObject(permissions)) {
filePermissions = permissions.file || null;
dirPermissions = permissions.directory || null;
} else {
filePermissions = permissions;
dirPermissions = permissions;
}
if (isDir && options.recursive) {
_.each(listDirContents(file, {compact: false, includeTopDir: true}), function(data) {
_chmod(data.file, data.type === 'directory' ? dirPermissions : filePermissions);
});
} else {
_chmod(file, isDir ? dirPermissions : filePermissions);
}
} | javascript | function chmod(file, permissions, options) {
if (!isPlatform('unix')) return;
if (!exists(file)) throw new Error(`Path '${file}' does not exists`);
const isDir = isDirectory(file);
options = _.sanitize(options, {recursive: false});
let filePermissions = null;
let dirPermissions = null;
if (_.isReallyObject(permissions)) {
filePermissions = permissions.file || null;
dirPermissions = permissions.directory || null;
} else {
filePermissions = permissions;
dirPermissions = permissions;
}
if (isDir && options.recursive) {
_.each(listDirContents(file, {compact: false, includeTopDir: true}), function(data) {
_chmod(data.file, data.type === 'directory' ? dirPermissions : filePermissions);
});
} else {
_chmod(file, isDir ? dirPermissions : filePermissions);
}
} | [
"function",
"chmod",
"(",
"file",
",",
"permissions",
",",
"options",
")",
"{",
"if",
"(",
"!",
"isPlatform",
"(",
"'unix'",
")",
")",
"return",
";",
"if",
"(",
"!",
"exists",
"(",
"file",
")",
")",
"throw",
"new",
"Error",
"(",
"`",
"${",
"file",
"}",
"`",
")",
";",
"const",
"isDir",
"=",
"isDirectory",
"(",
"file",
")",
";",
"options",
"=",
"_",
".",
"sanitize",
"(",
"options",
",",
"{",
"recursive",
":",
"false",
"}",
")",
";",
"let",
"filePermissions",
"=",
"null",
";",
"let",
"dirPermissions",
"=",
"null",
";",
"if",
"(",
"_",
".",
"isReallyObject",
"(",
"permissions",
")",
")",
"{",
"filePermissions",
"=",
"permissions",
".",
"file",
"||",
"null",
";",
"dirPermissions",
"=",
"permissions",
".",
"directory",
"||",
"null",
";",
"}",
"else",
"{",
"filePermissions",
"=",
"permissions",
";",
"dirPermissions",
"=",
"permissions",
";",
"}",
"if",
"(",
"isDir",
"&&",
"options",
".",
"recursive",
")",
"{",
"_",
".",
"each",
"(",
"listDirContents",
"(",
"file",
",",
"{",
"compact",
":",
"false",
",",
"includeTopDir",
":",
"true",
"}",
")",
",",
"function",
"(",
"data",
")",
"{",
"_chmod",
"(",
"data",
".",
"file",
",",
"data",
".",
"type",
"===",
"'directory'",
"?",
"dirPermissions",
":",
"filePermissions",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"_chmod",
"(",
"file",
",",
"isDir",
"?",
"dirPermissions",
":",
"filePermissions",
")",
";",
"}",
"}"
] | Change file permissions
@function $file~chmod
@param {string} file - File which permissions will be modified
@param {string|Object} permissions - String describing the new permissions or object defining different set of
permissions for 'file' and 'directory' types.
@param {string} [permissions.file] - File permissions
@param {string} [permissions.directory] - Directory permissions
@param {Object} [options]
@param {boolean} [options.recursive=false] - Change directory permissions recursively
@example
// Set permissions of '/foo/bar' to '664'
$file.chmod('/foo/bar', '664');
@example
// Recursively change all permissions in plugins directory
$file.chmod('plugins', {file: '664', directory: '775'}, {recursive: true}); | [
"Change",
"file",
"permissions"
] | 1b34424b6cb93593db7ba2c238dbfe301ab9defc | https://github.com/bitnami/nami-utils/blob/1b34424b6cb93593db7ba2c238dbfe301ab9defc/lib/file/chmod.js#L33-L56 | train |
cdapio/ui-schema-parser | lib/values.js | infer | function infer(val, opts) {
opts = opts || {};
// Optional custom inference hook.
if (opts.valueHook) {
var type = opts.valueHook(val, opts);
if (type !== undefined) {
if (!types.Type.isType(type)) {
throw new Error(f('invalid value hook return value: %j', type));
}
return type;
}
}
// Default inference logic.
switch (typeof val) {
case 'string':
return createType('string', opts);
case 'boolean':
return createType('boolean', opts);
case 'number':
if ((val | 0) === val) {
return createType('int', opts);
} else if (Math.abs(val) < 9007199254740991) {
return createType('float', opts);
}
return createType('double', opts);
case 'object':
if (val === null) {
return createType('null', opts);
} else if (Array.isArray(val)) {
if (!val.length) {
return EMPTY_ARRAY_TYPE;
}
return createType({
type: 'array',
items: combine(val.map(function (v) { return infer(v, opts); }))
}, opts);
} else if (Buffer.isBuffer(val)) {
return createType('bytes', opts);
}
var fieldNames = Object.keys(val);
if (fieldNames.some(function (s) { return !types.isValidName(s); })) {
// We have to fall back to a map.
return createType({
type: 'map',
values: combine(fieldNames.map(function (s) {
return infer(val[s], opts);
}), opts)
}, opts);
}
return createType({
type: 'record',
fields: fieldNames.map(function (s) {
return {name: s, type: infer(val[s], opts)};
})
}, opts);
default:
throw new Error(f('cannot infer type from: %j', val));
}
} | javascript | function infer(val, opts) {
opts = opts || {};
// Optional custom inference hook.
if (opts.valueHook) {
var type = opts.valueHook(val, opts);
if (type !== undefined) {
if (!types.Type.isType(type)) {
throw new Error(f('invalid value hook return value: %j', type));
}
return type;
}
}
// Default inference logic.
switch (typeof val) {
case 'string':
return createType('string', opts);
case 'boolean':
return createType('boolean', opts);
case 'number':
if ((val | 0) === val) {
return createType('int', opts);
} else if (Math.abs(val) < 9007199254740991) {
return createType('float', opts);
}
return createType('double', opts);
case 'object':
if (val === null) {
return createType('null', opts);
} else if (Array.isArray(val)) {
if (!val.length) {
return EMPTY_ARRAY_TYPE;
}
return createType({
type: 'array',
items: combine(val.map(function (v) { return infer(v, opts); }))
}, opts);
} else if (Buffer.isBuffer(val)) {
return createType('bytes', opts);
}
var fieldNames = Object.keys(val);
if (fieldNames.some(function (s) { return !types.isValidName(s); })) {
// We have to fall back to a map.
return createType({
type: 'map',
values: combine(fieldNames.map(function (s) {
return infer(val[s], opts);
}), opts)
}, opts);
}
return createType({
type: 'record',
fields: fieldNames.map(function (s) {
return {name: s, type: infer(val[s], opts)};
})
}, opts);
default:
throw new Error(f('cannot infer type from: %j', val));
}
} | [
"function",
"infer",
"(",
"val",
",",
"opts",
")",
"{",
"opts",
"=",
"opts",
"||",
"{",
"}",
";",
"if",
"(",
"opts",
".",
"valueHook",
")",
"{",
"var",
"type",
"=",
"opts",
".",
"valueHook",
"(",
"val",
",",
"opts",
")",
";",
"if",
"(",
"type",
"!==",
"undefined",
")",
"{",
"if",
"(",
"!",
"types",
".",
"Type",
".",
"isType",
"(",
"type",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"f",
"(",
"'invalid value hook return value: %j'",
",",
"type",
")",
")",
";",
"}",
"return",
"type",
";",
"}",
"}",
"switch",
"(",
"typeof",
"val",
")",
"{",
"case",
"'string'",
":",
"return",
"createType",
"(",
"'string'",
",",
"opts",
")",
";",
"case",
"'boolean'",
":",
"return",
"createType",
"(",
"'boolean'",
",",
"opts",
")",
";",
"case",
"'number'",
":",
"if",
"(",
"(",
"val",
"|",
"0",
")",
"===",
"val",
")",
"{",
"return",
"createType",
"(",
"'int'",
",",
"opts",
")",
";",
"}",
"else",
"if",
"(",
"Math",
".",
"abs",
"(",
"val",
")",
"<",
"9007199254740991",
")",
"{",
"return",
"createType",
"(",
"'float'",
",",
"opts",
")",
";",
"}",
"return",
"createType",
"(",
"'double'",
",",
"opts",
")",
";",
"case",
"'object'",
":",
"if",
"(",
"val",
"===",
"null",
")",
"{",
"return",
"createType",
"(",
"'null'",
",",
"opts",
")",
";",
"}",
"else",
"if",
"(",
"Array",
".",
"isArray",
"(",
"val",
")",
")",
"{",
"if",
"(",
"!",
"val",
".",
"length",
")",
"{",
"return",
"EMPTY_ARRAY_TYPE",
";",
"}",
"return",
"createType",
"(",
"{",
"type",
":",
"'array'",
",",
"items",
":",
"combine",
"(",
"val",
".",
"map",
"(",
"function",
"(",
"v",
")",
"{",
"return",
"infer",
"(",
"v",
",",
"opts",
")",
";",
"}",
")",
")",
"}",
",",
"opts",
")",
";",
"}",
"else",
"if",
"(",
"Buffer",
".",
"isBuffer",
"(",
"val",
")",
")",
"{",
"return",
"createType",
"(",
"'bytes'",
",",
"opts",
")",
";",
"}",
"var",
"fieldNames",
"=",
"Object",
".",
"keys",
"(",
"val",
")",
";",
"if",
"(",
"fieldNames",
".",
"some",
"(",
"function",
"(",
"s",
")",
"{",
"return",
"!",
"types",
".",
"isValidName",
"(",
"s",
")",
";",
"}",
")",
")",
"{",
"return",
"createType",
"(",
"{",
"type",
":",
"'map'",
",",
"values",
":",
"combine",
"(",
"fieldNames",
".",
"map",
"(",
"function",
"(",
"s",
")",
"{",
"return",
"infer",
"(",
"val",
"[",
"s",
"]",
",",
"opts",
")",
";",
"}",
")",
",",
"opts",
")",
"}",
",",
"opts",
")",
";",
"}",
"return",
"createType",
"(",
"{",
"type",
":",
"'record'",
",",
"fields",
":",
"fieldNames",
".",
"map",
"(",
"function",
"(",
"s",
")",
"{",
"return",
"{",
"name",
":",
"s",
",",
"type",
":",
"infer",
"(",
"val",
"[",
"s",
"]",
",",
"opts",
")",
"}",
";",
"}",
")",
"}",
",",
"opts",
")",
";",
"default",
":",
"throw",
"new",
"Error",
"(",
"f",
"(",
"'cannot infer type from: %j'",
",",
"val",
")",
")",
";",
"}",
"}"
] | Infer a type from a value. | [
"Infer",
"a",
"type",
"from",
"a",
"value",
"."
] | 7fa333e0fe1208de6adc17e597ec847f5ae84124 | https://github.com/cdapio/ui-schema-parser/blob/7fa333e0fe1208de6adc17e597ec847f5ae84124/lib/values.js#L30-L90 | train |
cdapio/ui-schema-parser | lib/types.js | createType | function createType(attrs, opts) {
if (attrs === null) {
// Let's be helpful for this common error.
throw new Error('invalid type: null (did you mean "null"?)');
}
if (Type.isType(attrs)) {
return attrs;
}
opts = opts || {};
opts.registry = opts.registry || {};
var type;
if (opts.typeHook && (type = opts.typeHook(attrs, opts))) {
if (!Type.isType(type)) {
throw new Error(f('invalid typehook return value: %j', type));
}
return type;
}
if (typeof attrs == 'string') { // Type reference.
attrs = qualify(attrs, opts.namespace);
type = opts.registry[attrs];
if (type) {
// Type was already defined, return it.
return type;
}
if (isPrimitive(attrs)) {
// Reference to a primitive type. These are also defined names by default
// so we create the appropriate type and it to the registry for future
// reference.
return opts.registry[attrs] = createType({type: attrs}, opts);
}
throw new Error(f('undefined type name: %s', attrs));
}
if (attrs.logicalType && opts.logicalTypes && !LOGICAL_TYPE) {
var DerivedType = opts.logicalTypes[attrs.logicalType];
if (DerivedType) {
var namespace = opts.namespace;
var registry = {};
Object.keys(opts.registry).forEach(function (key) {
registry[key] = opts.registry[key];
});
try {
return new DerivedType(attrs, opts);
} catch (err) {
if (opts.assertLogicalTypes) {
// The spec mandates that we fall through to the underlying type if
// the logical type is invalid. We provide this option to ease
// debugging.
throw err;
}
LOGICAL_TYPE = null;
opts.namespace = namespace;
opts.registry = registry;
}
}
}
if (Array.isArray(attrs)) { // Union.
var UnionType = opts.wrapUnions ? WrappedUnionType : UnwrappedUnionType;
type = new UnionType(attrs, opts);
} else { // New type definition.
type = (function (typeName) {
var Type = TYPES[typeName];
if (Type === undefined) {
throw new Error(f('unknown type: %j', typeName));
}
return new Type(attrs, opts);
})(attrs.type);
}
return type;
} | javascript | function createType(attrs, opts) {
if (attrs === null) {
// Let's be helpful for this common error.
throw new Error('invalid type: null (did you mean "null"?)');
}
if (Type.isType(attrs)) {
return attrs;
}
opts = opts || {};
opts.registry = opts.registry || {};
var type;
if (opts.typeHook && (type = opts.typeHook(attrs, opts))) {
if (!Type.isType(type)) {
throw new Error(f('invalid typehook return value: %j', type));
}
return type;
}
if (typeof attrs == 'string') { // Type reference.
attrs = qualify(attrs, opts.namespace);
type = opts.registry[attrs];
if (type) {
// Type was already defined, return it.
return type;
}
if (isPrimitive(attrs)) {
// Reference to a primitive type. These are also defined names by default
// so we create the appropriate type and it to the registry for future
// reference.
return opts.registry[attrs] = createType({type: attrs}, opts);
}
throw new Error(f('undefined type name: %s', attrs));
}
if (attrs.logicalType && opts.logicalTypes && !LOGICAL_TYPE) {
var DerivedType = opts.logicalTypes[attrs.logicalType];
if (DerivedType) {
var namespace = opts.namespace;
var registry = {};
Object.keys(opts.registry).forEach(function (key) {
registry[key] = opts.registry[key];
});
try {
return new DerivedType(attrs, opts);
} catch (err) {
if (opts.assertLogicalTypes) {
// The spec mandates that we fall through to the underlying type if
// the logical type is invalid. We provide this option to ease
// debugging.
throw err;
}
LOGICAL_TYPE = null;
opts.namespace = namespace;
opts.registry = registry;
}
}
}
if (Array.isArray(attrs)) { // Union.
var UnionType = opts.wrapUnions ? WrappedUnionType : UnwrappedUnionType;
type = new UnionType(attrs, opts);
} else { // New type definition.
type = (function (typeName) {
var Type = TYPES[typeName];
if (Type === undefined) {
throw new Error(f('unknown type: %j', typeName));
}
return new Type(attrs, opts);
})(attrs.type);
}
return type;
} | [
"function",
"createType",
"(",
"attrs",
",",
"opts",
")",
"{",
"if",
"(",
"attrs",
"===",
"null",
")",
"{",
"throw",
"new",
"Error",
"(",
"'invalid type: null (did you mean \"null\"?)'",
")",
";",
"}",
"if",
"(",
"Type",
".",
"isType",
"(",
"attrs",
")",
")",
"{",
"return",
"attrs",
";",
"}",
"opts",
"=",
"opts",
"||",
"{",
"}",
";",
"opts",
".",
"registry",
"=",
"opts",
".",
"registry",
"||",
"{",
"}",
";",
"var",
"type",
";",
"if",
"(",
"opts",
".",
"typeHook",
"&&",
"(",
"type",
"=",
"opts",
".",
"typeHook",
"(",
"attrs",
",",
"opts",
")",
")",
")",
"{",
"if",
"(",
"!",
"Type",
".",
"isType",
"(",
"type",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"f",
"(",
"'invalid typehook return value: %j'",
",",
"type",
")",
")",
";",
"}",
"return",
"type",
";",
"}",
"if",
"(",
"typeof",
"attrs",
"==",
"'string'",
")",
"{",
"attrs",
"=",
"qualify",
"(",
"attrs",
",",
"opts",
".",
"namespace",
")",
";",
"type",
"=",
"opts",
".",
"registry",
"[",
"attrs",
"]",
";",
"if",
"(",
"type",
")",
"{",
"return",
"type",
";",
"}",
"if",
"(",
"isPrimitive",
"(",
"attrs",
")",
")",
"{",
"return",
"opts",
".",
"registry",
"[",
"attrs",
"]",
"=",
"createType",
"(",
"{",
"type",
":",
"attrs",
"}",
",",
"opts",
")",
";",
"}",
"throw",
"new",
"Error",
"(",
"f",
"(",
"'undefined type name: %s'",
",",
"attrs",
")",
")",
";",
"}",
"if",
"(",
"attrs",
".",
"logicalType",
"&&",
"opts",
".",
"logicalTypes",
"&&",
"!",
"LOGICAL_TYPE",
")",
"{",
"var",
"DerivedType",
"=",
"opts",
".",
"logicalTypes",
"[",
"attrs",
".",
"logicalType",
"]",
";",
"if",
"(",
"DerivedType",
")",
"{",
"var",
"namespace",
"=",
"opts",
".",
"namespace",
";",
"var",
"registry",
"=",
"{",
"}",
";",
"Object",
".",
"keys",
"(",
"opts",
".",
"registry",
")",
".",
"forEach",
"(",
"function",
"(",
"key",
")",
"{",
"registry",
"[",
"key",
"]",
"=",
"opts",
".",
"registry",
"[",
"key",
"]",
";",
"}",
")",
";",
"try",
"{",
"return",
"new",
"DerivedType",
"(",
"attrs",
",",
"opts",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"if",
"(",
"opts",
".",
"assertLogicalTypes",
")",
"{",
"throw",
"err",
";",
"}",
"LOGICAL_TYPE",
"=",
"null",
";",
"opts",
".",
"namespace",
"=",
"namespace",
";",
"opts",
".",
"registry",
"=",
"registry",
";",
"}",
"}",
"}",
"if",
"(",
"Array",
".",
"isArray",
"(",
"attrs",
")",
")",
"{",
"var",
"UnionType",
"=",
"opts",
".",
"wrapUnions",
"?",
"WrappedUnionType",
":",
"UnwrappedUnionType",
";",
"type",
"=",
"new",
"UnionType",
"(",
"attrs",
",",
"opts",
")",
";",
"}",
"else",
"{",
"type",
"=",
"(",
"function",
"(",
"typeName",
")",
"{",
"var",
"Type",
"=",
"TYPES",
"[",
"typeName",
"]",
";",
"if",
"(",
"Type",
"===",
"undefined",
")",
"{",
"throw",
"new",
"Error",
"(",
"f",
"(",
"'unknown type: %j'",
",",
"typeName",
")",
")",
";",
"}",
"return",
"new",
"Type",
"(",
"attrs",
",",
"opts",
")",
";",
"}",
")",
"(",
"attrs",
".",
"type",
")",
";",
"}",
"return",
"type",
";",
"}"
] | Schema parsing entry point.
It isn't exposed directly but called from `parse` inside `index.js` (node)
or `avsc.js` (browserify) which each add convenience functionality. | [
"Schema",
"parsing",
"entry",
"point",
"."
] | 7fa333e0fe1208de6adc17e597ec847f5ae84124 | https://github.com/cdapio/ui-schema-parser/blob/7fa333e0fe1208de6adc17e597ec847f5ae84124/lib/types.js#L68-L141 | train |
cdapio/ui-schema-parser | lib/types.js | WrappedUnionType | function WrappedUnionType(attrs, opts) {
UnionType.call(this, attrs, opts);
this._constructors = this._types.map(function (type) {
// jshint -W054
var name = type.getName(true);
if (name === 'null') {
return null;
}
function ConstructorFunction(name) {
return function Branch$(val) {
this[`${name}`] = val;
}
}
var constructor = ConstructorFunction(name);
constructor.getBranchType = function() { return type; };
return constructor;
});
} | javascript | function WrappedUnionType(attrs, opts) {
UnionType.call(this, attrs, opts);
this._constructors = this._types.map(function (type) {
// jshint -W054
var name = type.getName(true);
if (name === 'null') {
return null;
}
function ConstructorFunction(name) {
return function Branch$(val) {
this[`${name}`] = val;
}
}
var constructor = ConstructorFunction(name);
constructor.getBranchType = function() { return type; };
return constructor;
});
} | [
"function",
"WrappedUnionType",
"(",
"attrs",
",",
"opts",
")",
"{",
"UnionType",
".",
"call",
"(",
"this",
",",
"attrs",
",",
"opts",
")",
";",
"this",
".",
"_constructors",
"=",
"this",
".",
"_types",
".",
"map",
"(",
"function",
"(",
"type",
")",
"{",
"var",
"name",
"=",
"type",
".",
"getName",
"(",
"true",
")",
";",
"if",
"(",
"name",
"===",
"'null'",
")",
"{",
"return",
"null",
";",
"}",
"function",
"ConstructorFunction",
"(",
"name",
")",
"{",
"return",
"function",
"Branch$",
"(",
"val",
")",
"{",
"this",
"[",
"`",
"${",
"name",
"}",
"`",
"]",
"=",
"val",
";",
"}",
"}",
"var",
"constructor",
"=",
"ConstructorFunction",
"(",
"name",
")",
";",
"constructor",
".",
"getBranchType",
"=",
"function",
"(",
")",
"{",
"return",
"type",
";",
"}",
";",
"return",
"constructor",
";",
"}",
")",
";",
"}"
] | Compatible union type.
Values of this type are represented in memory similarly to their JSON
representation (i.e. inside an object with single key the name of the
contained type).
This is not ideal, but is the most efficient way to unambiguously support
all unions. Here are a few reasons why the wrapping object is necessary:
+ Unions with multiple number types would have undefined behavior, unless
numbers are wrapped (either everywhere, leading to large performance and
convenience costs; or only when necessary inside unions, making it hard to
understand when numbers are wrapped or not).
+ Fixed types would have to be wrapped to be distinguished from bytes.
+ Using record's constructor names would work (after a slight change to use
the fully qualified name), but would mean that generic objects could no
longer be valid records (making it inconvenient to do simple things like
creating new records). | [
"Compatible",
"union",
"type",
"."
] | 7fa333e0fe1208de6adc17e597ec847f5ae84124 | https://github.com/cdapio/ui-schema-parser/blob/7fa333e0fe1208de6adc17e597ec847f5ae84124/lib/types.js#L1102-L1121 | train |
cdapio/ui-schema-parser | lib/types.js | FixedType | function FixedType(attrs, opts) {
Type.call(this, attrs, opts);
if (attrs.size !== (attrs.size | 0) || attrs.size < 1) {
throw new Error(f('invalid %s fixed size', this.getName(true)));
}
this._size = attrs.size | 0;
} | javascript | function FixedType(attrs, opts) {
Type.call(this, attrs, opts);
if (attrs.size !== (attrs.size | 0) || attrs.size < 1) {
throw new Error(f('invalid %s fixed size', this.getName(true)));
}
this._size = attrs.size | 0;
} | [
"function",
"FixedType",
"(",
"attrs",
",",
"opts",
")",
"{",
"Type",
".",
"call",
"(",
"this",
",",
"attrs",
",",
"opts",
")",
";",
"if",
"(",
"attrs",
".",
"size",
"!==",
"(",
"attrs",
".",
"size",
"|",
"0",
")",
"||",
"attrs",
".",
"size",
"<",
"1",
")",
"{",
"throw",
"new",
"Error",
"(",
"f",
"(",
"'invalid %s fixed size'",
",",
"this",
".",
"getName",
"(",
"true",
")",
")",
")",
";",
"}",
"this",
".",
"_size",
"=",
"attrs",
".",
"size",
"|",
"0",
";",
"}"
] | Avro fixed type.
Represented simply as a `Buffer`. | [
"Avro",
"fixed",
"type",
"."
] | 7fa333e0fe1208de6adc17e597ec847f5ae84124 | https://github.com/cdapio/ui-schema-parser/blob/7fa333e0fe1208de6adc17e597ec847f5ae84124/lib/types.js#L1403-L1410 | train |
cdapio/ui-schema-parser | lib/types.js | MapType | function MapType(attrs, opts) {
Type.call(this);
if (!attrs.values) {
throw new Error(f('missing map values: %j', attrs));
}
this._values = createType(attrs.values, opts);
// Addition by Edwin Elia
var keys = attrs.keys;
if (!keys) {
keys = 'string';
}
this._keys = createType(keys, opts);
} | javascript | function MapType(attrs, opts) {
Type.call(this);
if (!attrs.values) {
throw new Error(f('missing map values: %j', attrs));
}
this._values = createType(attrs.values, opts);
// Addition by Edwin Elia
var keys = attrs.keys;
if (!keys) {
keys = 'string';
}
this._keys = createType(keys, opts);
} | [
"function",
"MapType",
"(",
"attrs",
",",
"opts",
")",
"{",
"Type",
".",
"call",
"(",
"this",
")",
";",
"if",
"(",
"!",
"attrs",
".",
"values",
")",
"{",
"throw",
"new",
"Error",
"(",
"f",
"(",
"'missing map values: %j'",
",",
"attrs",
")",
")",
";",
"}",
"this",
".",
"_values",
"=",
"createType",
"(",
"attrs",
".",
"values",
",",
"opts",
")",
";",
"var",
"keys",
"=",
"attrs",
".",
"keys",
";",
"if",
"(",
"!",
"keys",
")",
"{",
"keys",
"=",
"'string'",
";",
"}",
"this",
".",
"_keys",
"=",
"createType",
"(",
"keys",
",",
"opts",
")",
";",
"}"
] | Avro map.
Represented as vanilla objects. | [
"Avro",
"map",
"."
] | 7fa333e0fe1208de6adc17e597ec847f5ae84124 | https://github.com/cdapio/ui-schema-parser/blob/7fa333e0fe1208de6adc17e597ec847f5ae84124/lib/types.js#L1480-L1494 | train |
cdapio/ui-schema-parser | lib/types.js | ArrayType | function ArrayType(attrs, opts) {
Type.call(this);
if (!attrs.items) {
throw new Error(f('missing array items: %j', attrs));
}
this._items = createType(attrs.items, opts);
} | javascript | function ArrayType(attrs, opts) {
Type.call(this);
if (!attrs.items) {
throw new Error(f('missing array items: %j', attrs));
}
this._items = createType(attrs.items, opts);
} | [
"function",
"ArrayType",
"(",
"attrs",
",",
"opts",
")",
"{",
"Type",
".",
"call",
"(",
"this",
")",
";",
"if",
"(",
"!",
"attrs",
".",
"items",
")",
"{",
"throw",
"new",
"Error",
"(",
"f",
"(",
"'missing array items: %j'",
",",
"attrs",
")",
")",
";",
"}",
"this",
".",
"_items",
"=",
"createType",
"(",
"attrs",
".",
"items",
",",
"opts",
")",
";",
"}"
] | Avro array.
Represented as vanilla arrays. | [
"Avro",
"array",
"."
] | 7fa333e0fe1208de6adc17e597ec847f5ae84124 | https://github.com/cdapio/ui-schema-parser/blob/7fa333e0fe1208de6adc17e597ec847f5ae84124/lib/types.js#L1632-L1639 | train |
cdapio/ui-schema-parser | lib/types.js | stringify | function stringify(obj, opts) {
EXPORT_ATTRS = opts && opts.exportAttrs;
var noDeref = opts && opts.noDeref;
// Since JS objects are unordered, this implementation (unfortunately)
// relies on engines returning properties in the same order that they are
// inserted in. This is not in the JS spec, but can be "somewhat" safely
// assumed (more here: http://stackoverflow.com/q/5525795/1062617).
return (function (registry) {
return JSON.stringify(obj, function (key, value) {
if (value) {
if (
typeof value == 'object' &&
value.hasOwnProperty('default') &&
!value.hasOwnProperty('logicalType')
) {
// This is a field.
if (EXPORT_ATTRS) {
return {
name: value.name,
type: value.type,
'default': value['default'],
order: value.order !== 'ascending' ? value.order : undefined,
aliases: value.aliases.length ? value.aliases : undefined
};
} else {
return {name: value.name, type: value.type};
}
} else if (value.aliases) {
// This is a named type (enum, fixed, record, error).
var name = value.name;
if (name) {
// If the type is anonymous, we always dereference it.
if (noDeref || registry[name]) {
return name;
}
registry[name] = true;
}
if (!EXPORT_ATTRS || !value.aliases.length) {
value.aliases = undefined;
}
}
}
return value;
});
})({});
} | javascript | function stringify(obj, opts) {
EXPORT_ATTRS = opts && opts.exportAttrs;
var noDeref = opts && opts.noDeref;
// Since JS objects are unordered, this implementation (unfortunately)
// relies on engines returning properties in the same order that they are
// inserted in. This is not in the JS spec, but can be "somewhat" safely
// assumed (more here: http://stackoverflow.com/q/5525795/1062617).
return (function (registry) {
return JSON.stringify(obj, function (key, value) {
if (value) {
if (
typeof value == 'object' &&
value.hasOwnProperty('default') &&
!value.hasOwnProperty('logicalType')
) {
// This is a field.
if (EXPORT_ATTRS) {
return {
name: value.name,
type: value.type,
'default': value['default'],
order: value.order !== 'ascending' ? value.order : undefined,
aliases: value.aliases.length ? value.aliases : undefined
};
} else {
return {name: value.name, type: value.type};
}
} else if (value.aliases) {
// This is a named type (enum, fixed, record, error).
var name = value.name;
if (name) {
// If the type is anonymous, we always dereference it.
if (noDeref || registry[name]) {
return name;
}
registry[name] = true;
}
if (!EXPORT_ATTRS || !value.aliases.length) {
value.aliases = undefined;
}
}
}
return value;
});
})({});
} | [
"function",
"stringify",
"(",
"obj",
",",
"opts",
")",
"{",
"EXPORT_ATTRS",
"=",
"opts",
"&&",
"opts",
".",
"exportAttrs",
";",
"var",
"noDeref",
"=",
"opts",
"&&",
"opts",
".",
"noDeref",
";",
"return",
"(",
"function",
"(",
"registry",
")",
"{",
"return",
"JSON",
".",
"stringify",
"(",
"obj",
",",
"function",
"(",
"key",
",",
"value",
")",
"{",
"if",
"(",
"value",
")",
"{",
"if",
"(",
"typeof",
"value",
"==",
"'object'",
"&&",
"value",
".",
"hasOwnProperty",
"(",
"'default'",
")",
"&&",
"!",
"value",
".",
"hasOwnProperty",
"(",
"'logicalType'",
")",
")",
"{",
"if",
"(",
"EXPORT_ATTRS",
")",
"{",
"return",
"{",
"name",
":",
"value",
".",
"name",
",",
"type",
":",
"value",
".",
"type",
",",
"'default'",
":",
"value",
"[",
"'default'",
"]",
",",
"order",
":",
"value",
".",
"order",
"!==",
"'ascending'",
"?",
"value",
".",
"order",
":",
"undefined",
",",
"aliases",
":",
"value",
".",
"aliases",
".",
"length",
"?",
"value",
".",
"aliases",
":",
"undefined",
"}",
";",
"}",
"else",
"{",
"return",
"{",
"name",
":",
"value",
".",
"name",
",",
"type",
":",
"value",
".",
"type",
"}",
";",
"}",
"}",
"else",
"if",
"(",
"value",
".",
"aliases",
")",
"{",
"var",
"name",
"=",
"value",
".",
"name",
";",
"if",
"(",
"name",
")",
"{",
"if",
"(",
"noDeref",
"||",
"registry",
"[",
"name",
"]",
")",
"{",
"return",
"name",
";",
"}",
"registry",
"[",
"name",
"]",
"=",
"true",
";",
"}",
"if",
"(",
"!",
"EXPORT_ATTRS",
"||",
"!",
"value",
".",
"aliases",
".",
"length",
")",
"{",
"value",
".",
"aliases",
"=",
"undefined",
";",
"}",
"}",
"}",
"return",
"value",
";",
"}",
")",
";",
"}",
")",
"(",
"{",
"}",
")",
";",
"}"
] | Correctly stringify an object which contains types.
@param obj {Object} The object to stringify. Typically, a type itself or an
object containing types. Any types inside will be expanded only once then
referenced by name.
@param opts {Object} Options:
+ `exportAttrs` {Boolean} Include field and logical type attributes.
+ `noDeref` {Boolean} Always reference types by name when possible,
rather than expand it the first time it is encountered. | [
"Correctly",
"stringify",
"an",
"object",
"which",
"contains",
"types",
"."
] | 7fa333e0fe1208de6adc17e597ec847f5ae84124 | https://github.com/cdapio/ui-schema-parser/blob/7fa333e0fe1208de6adc17e597ec847f5ae84124/lib/types.js#L2628-L2674 | train |
bitnami/nami-utils | lib/file/matches.js | matches | function matches(file, patternList, excludePatterList, options) {
options = _.sanitize(options, {minimatch: false});
let shouldInclude = false;
let shouldExclude = false;
const matcher = options.minimatch ? (f, pattern) => minimatch(f, pattern, {dot: true, matchBase: true}) : globMatch;
if (!_.isEmpty(patternList)) {
shouldInclude = _.some(_ensureArray(patternList), pattern => matcher(file, pattern));
}
if (!_.isEmpty(excludePatterList)) {
shouldExclude = _.some(_ensureArray(excludePatterList), pattern => matcher(file, pattern));
}
return shouldInclude && !shouldExclude;
} | javascript | function matches(file, patternList, excludePatterList, options) {
options = _.sanitize(options, {minimatch: false});
let shouldInclude = false;
let shouldExclude = false;
const matcher = options.minimatch ? (f, pattern) => minimatch(f, pattern, {dot: true, matchBase: true}) : globMatch;
if (!_.isEmpty(patternList)) {
shouldInclude = _.some(_ensureArray(patternList), pattern => matcher(file, pattern));
}
if (!_.isEmpty(excludePatterList)) {
shouldExclude = _.some(_ensureArray(excludePatterList), pattern => matcher(file, pattern));
}
return shouldInclude && !shouldExclude;
} | [
"function",
"matches",
"(",
"file",
",",
"patternList",
",",
"excludePatterList",
",",
"options",
")",
"{",
"options",
"=",
"_",
".",
"sanitize",
"(",
"options",
",",
"{",
"minimatch",
":",
"false",
"}",
")",
";",
"let",
"shouldInclude",
"=",
"false",
";",
"let",
"shouldExclude",
"=",
"false",
";",
"const",
"matcher",
"=",
"options",
".",
"minimatch",
"?",
"(",
"f",
",",
"pattern",
")",
"=>",
"minimatch",
"(",
"f",
",",
"pattern",
",",
"{",
"dot",
":",
"true",
",",
"matchBase",
":",
"true",
"}",
")",
":",
"globMatch",
";",
"if",
"(",
"!",
"_",
".",
"isEmpty",
"(",
"patternList",
")",
")",
"{",
"shouldInclude",
"=",
"_",
".",
"some",
"(",
"_ensureArray",
"(",
"patternList",
")",
",",
"pattern",
"=>",
"matcher",
"(",
"file",
",",
"pattern",
")",
")",
";",
"}",
"if",
"(",
"!",
"_",
".",
"isEmpty",
"(",
"excludePatterList",
")",
")",
"{",
"shouldExclude",
"=",
"_",
".",
"some",
"(",
"_ensureArray",
"(",
"excludePatterList",
")",
",",
"pattern",
"=>",
"matcher",
"(",
"file",
",",
"pattern",
")",
")",
";",
"}",
"return",
"shouldInclude",
"&&",
"!",
"shouldExclude",
";",
"}"
] | Check if file path matches a set of patterns
@function $file~matches
@param {string} file
@param {string[]} [patternList] - Patterns that the path must match to be accepted
@param {string[]} [excludePatterList] - Patterns that the path must NOT match to be accepted
@returns {boolean} - true if the file path matches any of the patternList tags and none of the excludePatterList,
false otherwise
@example
// Check if file 'my.cnf' matches with 'my*' and doesn't match with '*tpl'
$file.matches('my.cnf', ['my*'], ['*tpl']);
// => true | [
"Check",
"if",
"file",
"path",
"matches",
"a",
"set",
"of",
"patterns"
] | 1b34424b6cb93593db7ba2c238dbfe301ab9defc | https://github.com/bitnami/nami-utils/blob/1b34424b6cb93593db7ba2c238dbfe301ab9defc/lib/file/matches.js#L24-L37 | train |
bitnami/nami-utils | lib/os/user-management/user-exists.js | userExists | function userExists(user) {
if (_.isEmpty(findUser(user, {refresh: true, throwIfNotFound: false}))) {
return false;
} else {
return true;
}
} | javascript | function userExists(user) {
if (_.isEmpty(findUser(user, {refresh: true, throwIfNotFound: false}))) {
return false;
} else {
return true;
}
} | [
"function",
"userExists",
"(",
"user",
")",
"{",
"if",
"(",
"_",
".",
"isEmpty",
"(",
"findUser",
"(",
"user",
",",
"{",
"refresh",
":",
"true",
",",
"throwIfNotFound",
":",
"false",
"}",
")",
")",
")",
"{",
"return",
"false",
";",
"}",
"else",
"{",
"return",
"true",
";",
"}",
"}"
] | Check for user existence
@function $os~userExists
@param {string|number} user - Username or user id
@returns {boolean} - Whether the user exists or not
@example
// Check if user 'mysql' exists
$os.userExists('mysql');
// => true | [
"Check",
"for",
"user",
"existence"
] | 1b34424b6cb93593db7ba2c238dbfe301ab9defc | https://github.com/bitnami/nami-utils/blob/1b34424b6cb93593db7ba2c238dbfe301ab9defc/lib/os/user-management/user-exists.js#L16-L22 | train |
LaunchPadLab/lp-requests | src/http/middleware/add-query-to-url.js | addQueryToUrl | function addQueryToUrl ({ query, decamelizeQuery=true, url }) {
if (!query) return
const transformedQuery = decamelizeQuery ? decamelizeKeys(query) : query
return {
url: url + '?' + stringify(transformedQuery)
}
} | javascript | function addQueryToUrl ({ query, decamelizeQuery=true, url }) {
if (!query) return
const transformedQuery = decamelizeQuery ? decamelizeKeys(query) : query
return {
url: url + '?' + stringify(transformedQuery)
}
} | [
"function",
"addQueryToUrl",
"(",
"{",
"query",
",",
"decamelizeQuery",
"=",
"true",
",",
"url",
"}",
")",
"{",
"if",
"(",
"!",
"query",
")",
"return",
"const",
"transformedQuery",
"=",
"decamelizeQuery",
"?",
"decamelizeKeys",
"(",
"query",
")",
":",
"query",
"return",
"{",
"url",
":",
"url",
"+",
"'?'",
"+",
"stringify",
"(",
"transformedQuery",
")",
"}",
"}"
] | Adds a query string to the url if a 'query' option is provided | [
"Adds",
"a",
"query",
"string",
"to",
"the",
"url",
"if",
"a",
"query",
"option",
"is",
"provided"
] | 139294b1594b2d62ba8403c9ac6e97d5e84961f3 | https://github.com/LaunchPadLab/lp-requests/blob/139294b1594b2d62ba8403c9ac6e97d5e84961f3/src/http/middleware/add-query-to-url.js#L6-L12 | train |
cdapio/ui-schema-parser | etc/browser/lib/files.js | load | function load(schema) {
var obj;
if (typeof schema == 'string' && schema !== 'null') {
try {
obj = JSON.parse(schema);
} catch (err) {
// No file loading here.
}
}
if (obj === undefined) {
obj = schema;
}
return obj;
} | javascript | function load(schema) {
var obj;
if (typeof schema == 'string' && schema !== 'null') {
try {
obj = JSON.parse(schema);
} catch (err) {
// No file loading here.
}
}
if (obj === undefined) {
obj = schema;
}
return obj;
} | [
"function",
"load",
"(",
"schema",
")",
"{",
"var",
"obj",
";",
"if",
"(",
"typeof",
"schema",
"==",
"'string'",
"&&",
"schema",
"!==",
"'null'",
")",
"{",
"try",
"{",
"obj",
"=",
"JSON",
".",
"parse",
"(",
"schema",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"}",
"}",
"if",
"(",
"obj",
"===",
"undefined",
")",
"{",
"obj",
"=",
"schema",
";",
"}",
"return",
"obj",
";",
"}"
] | Schema loader, without file-system access. | [
"Schema",
"loader",
"without",
"file",
"-",
"system",
"access",
"."
] | 7fa333e0fe1208de6adc17e597ec847f5ae84124 | https://github.com/cdapio/ui-schema-parser/blob/7fa333e0fe1208de6adc17e597ec847f5ae84124/etc/browser/lib/files.js#L55-L68 | train |
cdapio/ui-schema-parser | lib/containers.js | copyBuffer | function copyBuffer(buf, pos, len) {
var copy = new Buffer(len);
buf.copy(copy, 0, pos, pos + len);
return copy;
} | javascript | function copyBuffer(buf, pos, len) {
var copy = new Buffer(len);
buf.copy(copy, 0, pos, pos + len);
return copy;
} | [
"function",
"copyBuffer",
"(",
"buf",
",",
"pos",
",",
"len",
")",
"{",
"var",
"copy",
"=",
"new",
"Buffer",
"(",
"len",
")",
";",
"buf",
".",
"copy",
"(",
"copy",
",",
"0",
",",
"pos",
",",
"pos",
"+",
"len",
")",
";",
"return",
"copy",
";",
"}"
] | Copy a buffer.
This avoids having to create a slice of the original buffer. | [
"Copy",
"a",
"buffer",
"."
] | 7fa333e0fe1208de6adc17e597ec847f5ae84124 | https://github.com/cdapio/ui-schema-parser/blob/7fa333e0fe1208de6adc17e597ec847f5ae84124/lib/containers.js#L572-L576 | train |
bitnami/nami-utils | lib/os/user-management/delete-group.js | deleteGroup | function deleteGroup(group) {
if (!runningAsRoot()) return;
if (!group) throw new Error('You must provide a group to delete');
if (!groupExists(group)) {
return;
}
const groupdelBin = _safeLocateBinary('groupdel');
const delgroupBin = _safeLocateBinary('delgroup');
if (isPlatform('linux')) {
if (groupdelBin !== null) { // most modern systems
runProgram(groupdelBin, [group]);
} else {
if (_isBusyboxBinary(delgroupBin)) { // busybox-based systems
runProgram(delgroupBin, [group]);
} else {
throw new Error(`Don't know how to delete group ${group} on this strange linux`);
}
}
} else if (isPlatform('osx')) {
runProgram('dscl', ['.', '-delete', `/Groups/${group}`]);
} else if (isPlatform('windows')) {
throw new Error(`Don't know how to delete group ${group} on Windows`);
} else {
throw new Error(`Don't know how to delete group ${group} on the current platformp`);
}
} | javascript | function deleteGroup(group) {
if (!runningAsRoot()) return;
if (!group) throw new Error('You must provide a group to delete');
if (!groupExists(group)) {
return;
}
const groupdelBin = _safeLocateBinary('groupdel');
const delgroupBin = _safeLocateBinary('delgroup');
if (isPlatform('linux')) {
if (groupdelBin !== null) { // most modern systems
runProgram(groupdelBin, [group]);
} else {
if (_isBusyboxBinary(delgroupBin)) { // busybox-based systems
runProgram(delgroupBin, [group]);
} else {
throw new Error(`Don't know how to delete group ${group} on this strange linux`);
}
}
} else if (isPlatform('osx')) {
runProgram('dscl', ['.', '-delete', `/Groups/${group}`]);
} else if (isPlatform('windows')) {
throw new Error(`Don't know how to delete group ${group} on Windows`);
} else {
throw new Error(`Don't know how to delete group ${group} on the current platformp`);
}
} | [
"function",
"deleteGroup",
"(",
"group",
")",
"{",
"if",
"(",
"!",
"runningAsRoot",
"(",
")",
")",
"return",
";",
"if",
"(",
"!",
"group",
")",
"throw",
"new",
"Error",
"(",
"'You must provide a group to delete'",
")",
";",
"if",
"(",
"!",
"groupExists",
"(",
"group",
")",
")",
"{",
"return",
";",
"}",
"const",
"groupdelBin",
"=",
"_safeLocateBinary",
"(",
"'groupdel'",
")",
";",
"const",
"delgroupBin",
"=",
"_safeLocateBinary",
"(",
"'delgroup'",
")",
";",
"if",
"(",
"isPlatform",
"(",
"'linux'",
")",
")",
"{",
"if",
"(",
"groupdelBin",
"!==",
"null",
")",
"{",
"runProgram",
"(",
"groupdelBin",
",",
"[",
"group",
"]",
")",
";",
"}",
"else",
"{",
"if",
"(",
"_isBusyboxBinary",
"(",
"delgroupBin",
")",
")",
"{",
"runProgram",
"(",
"delgroupBin",
",",
"[",
"group",
"]",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"`",
"${",
"group",
"}",
"`",
")",
";",
"}",
"}",
"}",
"else",
"if",
"(",
"isPlatform",
"(",
"'osx'",
")",
")",
"{",
"runProgram",
"(",
"'dscl'",
",",
"[",
"'.'",
",",
"'-delete'",
",",
"`",
"${",
"group",
"}",
"`",
"]",
")",
";",
"}",
"else",
"if",
"(",
"isPlatform",
"(",
"'windows'",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"`",
"${",
"group",
"}",
"`",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"`",
"${",
"group",
"}",
"`",
")",
";",
"}",
"}"
] | Delete system group
@function $os~deleteGroup
@param {string|number} group - Groupname or group id
@example
// Delete mysql group
$os.deleteGroup('mysql'); | [
"Delete",
"system",
"group"
] | 1b34424b6cb93593db7ba2c238dbfe301ab9defc | https://github.com/bitnami/nami-utils/blob/1b34424b6cb93593db7ba2c238dbfe301ab9defc/lib/os/user-management/delete-group.js#L18-L44 | train |
bitnami/nami-utils | lib/os/kill.js | kill | function kill(pid, signal) {
signal = _.isUndefined(signal) ? 'SIGINT' : signal;
// process.kill does not recognize many of the well known numeric signals,
// only by name
if (_.isFinite(signal) && _.has(signalsMap, signal)) {
signal = signalsMap[signal];
}
if (!_.isFinite(pid)) return false;
try {
process.kill(pid, signal);
} catch (e) {
return false;
}
return true;
} | javascript | function kill(pid, signal) {
signal = _.isUndefined(signal) ? 'SIGINT' : signal;
// process.kill does not recognize many of the well known numeric signals,
// only by name
if (_.isFinite(signal) && _.has(signalsMap, signal)) {
signal = signalsMap[signal];
}
if (!_.isFinite(pid)) return false;
try {
process.kill(pid, signal);
} catch (e) {
return false;
}
return true;
} | [
"function",
"kill",
"(",
"pid",
",",
"signal",
")",
"{",
"signal",
"=",
"_",
".",
"isUndefined",
"(",
"signal",
")",
"?",
"'SIGINT'",
":",
"signal",
";",
"if",
"(",
"_",
".",
"isFinite",
"(",
"signal",
")",
"&&",
"_",
".",
"has",
"(",
"signalsMap",
",",
"signal",
")",
")",
"{",
"signal",
"=",
"signalsMap",
"[",
"signal",
"]",
";",
"}",
"if",
"(",
"!",
"_",
".",
"isFinite",
"(",
"pid",
")",
")",
"return",
"false",
";",
"try",
"{",
"process",
".",
"kill",
"(",
"pid",
",",
"signal",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"return",
"false",
";",
"}",
"return",
"true",
";",
"}"
] | Send signal to process
@function $os~kill
@param {number} pid - Process ID
@param {number|string} [signal=SIGINT] - Signal number or name
@returns {boolean} - True if it successed to kill the process
@example
// Send 'SIGKILL' signal to process 123213
$os.kill(123213, 'SIGKILL')
// => true | [
"Send",
"signal",
"to",
"process"
] | 1b34424b6cb93593db7ba2c238dbfe301ab9defc | https://github.com/bitnami/nami-utils/blob/1b34424b6cb93593db7ba2c238dbfe301ab9defc/lib/os/kill.js#L17-L32 | train |
bitnami/nami-utils | lib/file/contains.js | contains | function contains(file, pattern, options) {
options = _.sanitize(options, {encoding: 'utf-8'});
if (!exists(file)) return false;
const text = read(file, options);
if (_.isRegExp(pattern)) {
return !!text.match(pattern);
} else {
return (text.search(_escapeRegExp(pattern)) !== -1);
}
} | javascript | function contains(file, pattern, options) {
options = _.sanitize(options, {encoding: 'utf-8'});
if (!exists(file)) return false;
const text = read(file, options);
if (_.isRegExp(pattern)) {
return !!text.match(pattern);
} else {
return (text.search(_escapeRegExp(pattern)) !== -1);
}
} | [
"function",
"contains",
"(",
"file",
",",
"pattern",
",",
"options",
")",
"{",
"options",
"=",
"_",
".",
"sanitize",
"(",
"options",
",",
"{",
"encoding",
":",
"'utf-8'",
"}",
")",
";",
"if",
"(",
"!",
"exists",
"(",
"file",
")",
")",
"return",
"false",
";",
"const",
"text",
"=",
"read",
"(",
"file",
",",
"options",
")",
";",
"if",
"(",
"_",
".",
"isRegExp",
"(",
"pattern",
")",
")",
"{",
"return",
"!",
"!",
"text",
".",
"match",
"(",
"pattern",
")",
";",
"}",
"else",
"{",
"return",
"(",
"text",
".",
"search",
"(",
"_escapeRegExp",
"(",
"pattern",
")",
")",
"!==",
"-",
"1",
")",
";",
"}",
"}"
] | Check if file contents contains a given pattern
@function $file~contains
@param {string} file - File path to check its contents
@param {string|RegExp} pattern - Glob like pattern or regexp to match
@param {Object} [options]
@param {string} [options.encoding=utf-8] - Encoding used to read the file
@returns {boolean} - Whether the contents of the file match or not the pattern
@example
// Check if service has started successfully
$file.contains('logs/service.log', /.*service.*started\s*successfully/);
// => true | [
"Check",
"if",
"file",
"contents",
"contains",
"a",
"given",
"pattern"
] | 1b34424b6cb93593db7ba2c238dbfe301ab9defc | https://github.com/bitnami/nami-utils/blob/1b34424b6cb93593db7ba2c238dbfe301ab9defc/lib/file/contains.js#L21-L30 | train |
LaunchPadLab/lp-requests | src/http/middleware/serialize-body.js | serializeBody | function serializeBody ({ decamelizeBody=true, headers, body }) {
if (!body || !isJSONRequest(headers)) return
const transformedBody = decamelizeBody ? decamelizeKeys(body) : body
return {
body: JSON.stringify(transformedBody)
}
} | javascript | function serializeBody ({ decamelizeBody=true, headers, body }) {
if (!body || !isJSONRequest(headers)) return
const transformedBody = decamelizeBody ? decamelizeKeys(body) : body
return {
body: JSON.stringify(transformedBody)
}
} | [
"function",
"serializeBody",
"(",
"{",
"decamelizeBody",
"=",
"true",
",",
"headers",
",",
"body",
"}",
")",
"{",
"if",
"(",
"!",
"body",
"||",
"!",
"isJSONRequest",
"(",
"headers",
")",
")",
"return",
"const",
"transformedBody",
"=",
"decamelizeBody",
"?",
"decamelizeKeys",
"(",
"body",
")",
":",
"body",
"return",
"{",
"body",
":",
"JSON",
".",
"stringify",
"(",
"transformedBody",
")",
"}",
"}"
] | Serializes the request body if necessary | [
"Serializes",
"the",
"request",
"body",
"if",
"necessary"
] | 139294b1594b2d62ba8403c9ac6e97d5e84961f3 | https://github.com/LaunchPadLab/lp-requests/blob/139294b1594b2d62ba8403c9ac6e97d5e84961f3/src/http/middleware/serialize-body.js#L9-L15 | train |
cdapio/ui-schema-parser | lib/protocols.js | createProtocol | function createProtocol(attrs, opts) {
opts = opts || {};
var name = attrs.protocol;
if (!name) {
throw new Error('missing protocol name');
}
if (attrs.namespace !== undefined) {
opts.namespace = attrs.namespace;
} else {
var match = /^(.*)\.[^.]+$/.exec(name);
if (match) {
opts.namespace = match[1];
}
}
name = types.qualify(name, opts.namespace);
if (attrs.types) {
attrs.types.forEach(function (obj) { types.createType(obj, opts); });
}
var messages = {};
if (attrs.messages) {
Object.keys(attrs.messages).forEach(function (key) {
messages[key] = new Message(key, attrs.messages[key], opts);
});
}
return new Protocol(name, messages, opts.registry || {});
} | javascript | function createProtocol(attrs, opts) {
opts = opts || {};
var name = attrs.protocol;
if (!name) {
throw new Error('missing protocol name');
}
if (attrs.namespace !== undefined) {
opts.namespace = attrs.namespace;
} else {
var match = /^(.*)\.[^.]+$/.exec(name);
if (match) {
opts.namespace = match[1];
}
}
name = types.qualify(name, opts.namespace);
if (attrs.types) {
attrs.types.forEach(function (obj) { types.createType(obj, opts); });
}
var messages = {};
if (attrs.messages) {
Object.keys(attrs.messages).forEach(function (key) {
messages[key] = new Message(key, attrs.messages[key], opts);
});
}
return new Protocol(name, messages, opts.registry || {});
} | [
"function",
"createProtocol",
"(",
"attrs",
",",
"opts",
")",
"{",
"opts",
"=",
"opts",
"||",
"{",
"}",
";",
"var",
"name",
"=",
"attrs",
".",
"protocol",
";",
"if",
"(",
"!",
"name",
")",
"{",
"throw",
"new",
"Error",
"(",
"'missing protocol name'",
")",
";",
"}",
"if",
"(",
"attrs",
".",
"namespace",
"!==",
"undefined",
")",
"{",
"opts",
".",
"namespace",
"=",
"attrs",
".",
"namespace",
";",
"}",
"else",
"{",
"var",
"match",
"=",
"/",
"^(.*)\\.[^.]+$",
"/",
".",
"exec",
"(",
"name",
")",
";",
"if",
"(",
"match",
")",
"{",
"opts",
".",
"namespace",
"=",
"match",
"[",
"1",
"]",
";",
"}",
"}",
"name",
"=",
"types",
".",
"qualify",
"(",
"name",
",",
"opts",
".",
"namespace",
")",
";",
"if",
"(",
"attrs",
".",
"types",
")",
"{",
"attrs",
".",
"types",
".",
"forEach",
"(",
"function",
"(",
"obj",
")",
"{",
"types",
".",
"createType",
"(",
"obj",
",",
"opts",
")",
";",
"}",
")",
";",
"}",
"var",
"messages",
"=",
"{",
"}",
";",
"if",
"(",
"attrs",
".",
"messages",
")",
"{",
"Object",
".",
"keys",
"(",
"attrs",
".",
"messages",
")",
".",
"forEach",
"(",
"function",
"(",
"key",
")",
"{",
"messages",
"[",
"key",
"]",
"=",
"new",
"Message",
"(",
"key",
",",
"attrs",
".",
"messages",
"[",
"key",
"]",
",",
"opts",
")",
";",
"}",
")",
";",
"}",
"return",
"new",
"Protocol",
"(",
"name",
",",
"messages",
",",
"opts",
".",
"registry",
"||",
"{",
"}",
")",
";",
"}"
] | Protocol generation function.
This should be used instead of the protocol constructor. The protocol's
constructor performs no logic to better support efficient protocol copy. | [
"Protocol",
"generation",
"function",
"."
] | 7fa333e0fe1208de6adc17e597ec847f5ae84124 | https://github.com/cdapio/ui-schema-parser/blob/7fa333e0fe1208de6adc17e597ec847f5ae84124/lib/protocols.js#L80-L108 | train |
cdapio/ui-schema-parser | lib/protocols.js | Protocol | function Protocol(name, messages, types, handlers) {
if (types === undefined) {
// Let's be helpful in case this class is instantiated directly.
return createProtocol(name, messages);
}
this._name = name;
this._messages = messages;
this._types = types;
// Shared with subprotocols (via the prototype chain, overwriting is safe).
this._handlers = handlers || {};
// We cache a string rather than a buffer to not retain an entire slab. This
// also lets us use hashes as keys inside maps (e.g. for resolvers).
this._hs = utils.getHash(this.getSchema()).toString('binary');
} | javascript | function Protocol(name, messages, types, handlers) {
if (types === undefined) {
// Let's be helpful in case this class is instantiated directly.
return createProtocol(name, messages);
}
this._name = name;
this._messages = messages;
this._types = types;
// Shared with subprotocols (via the prototype chain, overwriting is safe).
this._handlers = handlers || {};
// We cache a string rather than a buffer to not retain an entire slab. This
// also lets us use hashes as keys inside maps (e.g. for resolvers).
this._hs = utils.getHash(this.getSchema()).toString('binary');
} | [
"function",
"Protocol",
"(",
"name",
",",
"messages",
",",
"types",
",",
"handlers",
")",
"{",
"if",
"(",
"types",
"===",
"undefined",
")",
"{",
"return",
"createProtocol",
"(",
"name",
",",
"messages",
")",
";",
"}",
"this",
".",
"_name",
"=",
"name",
";",
"this",
".",
"_messages",
"=",
"messages",
";",
"this",
".",
"_types",
"=",
"types",
";",
"this",
".",
"_handlers",
"=",
"handlers",
"||",
"{",
"}",
";",
"this",
".",
"_hs",
"=",
"utils",
".",
"getHash",
"(",
"this",
".",
"getSchema",
"(",
")",
")",
".",
"toString",
"(",
"'binary'",
")",
";",
"}"
] | An Avro protocol. | [
"An",
"Avro",
"protocol",
"."
] | 7fa333e0fe1208de6adc17e597ec847f5ae84124 | https://github.com/cdapio/ui-schema-parser/blob/7fa333e0fe1208de6adc17e597ec847f5ae84124/lib/protocols.js#L114-L128 | train |
cdapio/ui-schema-parser | lib/protocols.js | MessageEmitter | function MessageEmitter(ptcl, opts) {
opts = opts || {};
events.EventEmitter.call(this);
this._ptcl = ptcl;
this._strict = !!opts.strictErrors;
this._endWritable = !!utils.getOption(opts, 'endWritable', true);
this._timeout = utils.getOption(opts, 'timeout', 10000);
this._prefix = normalizedPrefix(opts.scope);
this._cache = opts.cache || {};
var fgpt = opts.serverFingerprint;
var adapter;
if (fgpt) {
adapter = this._cache[fgpt];
}
if (!adapter) {
// This might happen even if the server fingerprint option was set, in
// cases where the cache doesn't contain the corresponding adapter.
fgpt = ptcl.getFingerprint();
adapter = this._cache[fgpt] = new Adapter(ptcl, ptcl, fgpt);
}
this._adapter = adapter;
this._registry = new Registry(this, PREFIX_LENGTH);
this._destroyed = false;
this._interrupted = false;
this.once('_eot', function (pending) { this.emit('eot', pending); });
} | javascript | function MessageEmitter(ptcl, opts) {
opts = opts || {};
events.EventEmitter.call(this);
this._ptcl = ptcl;
this._strict = !!opts.strictErrors;
this._endWritable = !!utils.getOption(opts, 'endWritable', true);
this._timeout = utils.getOption(opts, 'timeout', 10000);
this._prefix = normalizedPrefix(opts.scope);
this._cache = opts.cache || {};
var fgpt = opts.serverFingerprint;
var adapter;
if (fgpt) {
adapter = this._cache[fgpt];
}
if (!adapter) {
// This might happen even if the server fingerprint option was set, in
// cases where the cache doesn't contain the corresponding adapter.
fgpt = ptcl.getFingerprint();
adapter = this._cache[fgpt] = new Adapter(ptcl, ptcl, fgpt);
}
this._adapter = adapter;
this._registry = new Registry(this, PREFIX_LENGTH);
this._destroyed = false;
this._interrupted = false;
this.once('_eot', function (pending) { this.emit('eot', pending); });
} | [
"function",
"MessageEmitter",
"(",
"ptcl",
",",
"opts",
")",
"{",
"opts",
"=",
"opts",
"||",
"{",
"}",
";",
"events",
".",
"EventEmitter",
".",
"call",
"(",
"this",
")",
";",
"this",
".",
"_ptcl",
"=",
"ptcl",
";",
"this",
".",
"_strict",
"=",
"!",
"!",
"opts",
".",
"strictErrors",
";",
"this",
".",
"_endWritable",
"=",
"!",
"!",
"utils",
".",
"getOption",
"(",
"opts",
",",
"'endWritable'",
",",
"true",
")",
";",
"this",
".",
"_timeout",
"=",
"utils",
".",
"getOption",
"(",
"opts",
",",
"'timeout'",
",",
"10000",
")",
";",
"this",
".",
"_prefix",
"=",
"normalizedPrefix",
"(",
"opts",
".",
"scope",
")",
";",
"this",
".",
"_cache",
"=",
"opts",
".",
"cache",
"||",
"{",
"}",
";",
"var",
"fgpt",
"=",
"opts",
".",
"serverFingerprint",
";",
"var",
"adapter",
";",
"if",
"(",
"fgpt",
")",
"{",
"adapter",
"=",
"this",
".",
"_cache",
"[",
"fgpt",
"]",
";",
"}",
"if",
"(",
"!",
"adapter",
")",
"{",
"fgpt",
"=",
"ptcl",
".",
"getFingerprint",
"(",
")",
";",
"adapter",
"=",
"this",
".",
"_cache",
"[",
"fgpt",
"]",
"=",
"new",
"Adapter",
"(",
"ptcl",
",",
"ptcl",
",",
"fgpt",
")",
";",
"}",
"this",
".",
"_adapter",
"=",
"adapter",
";",
"this",
".",
"_registry",
"=",
"new",
"Registry",
"(",
"this",
",",
"PREFIX_LENGTH",
")",
";",
"this",
".",
"_destroyed",
"=",
"false",
";",
"this",
".",
"_interrupted",
"=",
"false",
";",
"this",
".",
"once",
"(",
"'_eot'",
",",
"function",
"(",
"pending",
")",
"{",
"this",
".",
"emit",
"(",
"'eot'",
",",
"pending",
")",
";",
"}",
")",
";",
"}"
] | Base message emitter class.
See below for the two available variants. | [
"Base",
"message",
"emitter",
"class",
"."
] | 7fa333e0fe1208de6adc17e597ec847f5ae84124 | https://github.com/cdapio/ui-schema-parser/blob/7fa333e0fe1208de6adc17e597ec847f5ae84124/lib/protocols.js#L364-L392 | train |
cdapio/ui-schema-parser | lib/protocols.js | StatelessEmitter | function StatelessEmitter(ptcl, writableFactory, opts) {
MessageEmitter.call(this, ptcl, opts);
this._writableFactory = writableFactory;
if (!opts || !opts.noPing) {
// Ping the server to check whether the remote protocol is compatible.
this.emitMessage('', {}, function (err) {
if (err) {
this.emit('error', err);
}
});
}
} | javascript | function StatelessEmitter(ptcl, writableFactory, opts) {
MessageEmitter.call(this, ptcl, opts);
this._writableFactory = writableFactory;
if (!opts || !opts.noPing) {
// Ping the server to check whether the remote protocol is compatible.
this.emitMessage('', {}, function (err) {
if (err) {
this.emit('error', err);
}
});
}
} | [
"function",
"StatelessEmitter",
"(",
"ptcl",
",",
"writableFactory",
",",
"opts",
")",
"{",
"MessageEmitter",
".",
"call",
"(",
"this",
",",
"ptcl",
",",
"opts",
")",
";",
"this",
".",
"_writableFactory",
"=",
"writableFactory",
";",
"if",
"(",
"!",
"opts",
"||",
"!",
"opts",
".",
"noPing",
")",
"{",
"this",
".",
"emitMessage",
"(",
"''",
",",
"{",
"}",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"this",
".",
"emit",
"(",
"'error'",
",",
"err",
")",
";",
"}",
"}",
")",
";",
"}",
"}"
] | Factory-based emitter.
This emitter doesn't keep a persistent connection to the server and requires
prepending a handshake to each message emitted. Usage examples include
talking to an HTTP server (where the factory returns an HTTP request).
Since each message will use its own writable/readable stream pair, the
advantage of this emitter is that it is able to keep track of which response
corresponds to each request without relying on transport ordering. In
particular, this means these emitters are compatible with any server
implementation. | [
"Factory",
"-",
"based",
"emitter",
"."
] | 7fa333e0fe1208de6adc17e597ec847f5ae84124 | https://github.com/cdapio/ui-schema-parser/blob/7fa333e0fe1208de6adc17e597ec847f5ae84124/lib/protocols.js#L541-L553 | train |
cdapio/ui-schema-parser | lib/protocols.js | emit | function emit(retry) {
if (self._interrupted) {
// The request's callback will already have been called.
return;
}
var hreq = self._createHandshakeRequest(adapter, !retry);
var writable = self._writableFactory.call(self, function (err, readable) {
if (err) {
cb(err);
return;
}
readable.on('data', function (obj) {
debug('received response %s', obj.id);
// We don't check that the prefix matches since the ID likely hasn't
// been propagated to the response (see default stateless codec).
var buf = Buffer.concat(obj.payload);
try {
var parts = readHead(HANDSHAKE_RESPONSE_TYPE, buf);
var hres = parts.head;
if (hres.serverHash) {
adapter = self._getAdapter(hres);
}
} catch (err) {
cb(err);
return;
}
self.emit('handshake', hreq, hres);
if (hres.match === 'NONE') {
process.nextTick(function() { emit(true); });
return;
}
// Change the default adapter.
self._adapter = adapter;
cb(null, parts.tail, adapter);
});
});
writable.write({
id: id,
payload: [HANDSHAKE_REQUEST_TYPE.toBuffer(hreq), reqBuf]
});
if (self._endWritable) {
writable.end();
}
} | javascript | function emit(retry) {
if (self._interrupted) {
// The request's callback will already have been called.
return;
}
var hreq = self._createHandshakeRequest(adapter, !retry);
var writable = self._writableFactory.call(self, function (err, readable) {
if (err) {
cb(err);
return;
}
readable.on('data', function (obj) {
debug('received response %s', obj.id);
// We don't check that the prefix matches since the ID likely hasn't
// been propagated to the response (see default stateless codec).
var buf = Buffer.concat(obj.payload);
try {
var parts = readHead(HANDSHAKE_RESPONSE_TYPE, buf);
var hres = parts.head;
if (hres.serverHash) {
adapter = self._getAdapter(hres);
}
} catch (err) {
cb(err);
return;
}
self.emit('handshake', hreq, hres);
if (hres.match === 'NONE') {
process.nextTick(function() { emit(true); });
return;
}
// Change the default adapter.
self._adapter = adapter;
cb(null, parts.tail, adapter);
});
});
writable.write({
id: id,
payload: [HANDSHAKE_REQUEST_TYPE.toBuffer(hreq), reqBuf]
});
if (self._endWritable) {
writable.end();
}
} | [
"function",
"emit",
"(",
"retry",
")",
"{",
"if",
"(",
"self",
".",
"_interrupted",
")",
"{",
"return",
";",
"}",
"var",
"hreq",
"=",
"self",
".",
"_createHandshakeRequest",
"(",
"adapter",
",",
"!",
"retry",
")",
";",
"var",
"writable",
"=",
"self",
".",
"_writableFactory",
".",
"call",
"(",
"self",
",",
"function",
"(",
"err",
",",
"readable",
")",
"{",
"if",
"(",
"err",
")",
"{",
"cb",
"(",
"err",
")",
";",
"return",
";",
"}",
"readable",
".",
"on",
"(",
"'data'",
",",
"function",
"(",
"obj",
")",
"{",
"debug",
"(",
"'received response %s'",
",",
"obj",
".",
"id",
")",
";",
"var",
"buf",
"=",
"Buffer",
".",
"concat",
"(",
"obj",
".",
"payload",
")",
";",
"try",
"{",
"var",
"parts",
"=",
"readHead",
"(",
"HANDSHAKE_RESPONSE_TYPE",
",",
"buf",
")",
";",
"var",
"hres",
"=",
"parts",
".",
"head",
";",
"if",
"(",
"hres",
".",
"serverHash",
")",
"{",
"adapter",
"=",
"self",
".",
"_getAdapter",
"(",
"hres",
")",
";",
"}",
"}",
"catch",
"(",
"err",
")",
"{",
"cb",
"(",
"err",
")",
";",
"return",
";",
"}",
"self",
".",
"emit",
"(",
"'handshake'",
",",
"hreq",
",",
"hres",
")",
";",
"if",
"(",
"hres",
".",
"match",
"===",
"'NONE'",
")",
"{",
"process",
".",
"nextTick",
"(",
"function",
"(",
")",
"{",
"emit",
"(",
"true",
")",
";",
"}",
")",
";",
"return",
";",
"}",
"self",
".",
"_adapter",
"=",
"adapter",
";",
"cb",
"(",
"null",
",",
"parts",
".",
"tail",
",",
"adapter",
")",
";",
"}",
")",
";",
"}",
")",
";",
"writable",
".",
"write",
"(",
"{",
"id",
":",
"id",
",",
"payload",
":",
"[",
"HANDSHAKE_REQUEST_TYPE",
".",
"toBuffer",
"(",
"hreq",
")",
",",
"reqBuf",
"]",
"}",
")",
";",
"if",
"(",
"self",
".",
"_endWritable",
")",
"{",
"writable",
".",
"end",
"(",
")",
";",
"}",
"}"
] | Each writable is only used once, no risk of buffering. | [
"Each",
"writable",
"is",
"only",
"used",
"once",
"no",
"risk",
"of",
"buffering",
"."
] | 7fa333e0fe1208de6adc17e597ec847f5ae84124 | https://github.com/cdapio/ui-schema-parser/blob/7fa333e0fe1208de6adc17e597ec847f5ae84124/lib/protocols.js#L563-L609 | train |
cdapio/ui-schema-parser | lib/protocols.js | StatelessListener | function StatelessListener(ptcl, readableFactory, opts) {
MessageListener.call(this, ptcl, opts);
var self = this;
var readable;
process.nextTick(function () {
// Delay listening to allow handlers to be attached even if the factory is
// purely synchronous.
readable = readableFactory.call(this, function (err, writable) {
if (err) {
self.emit('error', err);
// Since stateless listeners are only used once, it is safe to destroy.
onFinish();
return;
}
self._writable = writable.on('finish', onFinish);
self.emit('_writable');
}).on('data', onRequest)
.on('end', onEnd);
});
function onRequest(obj) {
var id = obj.id;
var buf = Buffer.concat(obj.payload);
var err = null;
try {
var parts = readHead(HANDSHAKE_REQUEST_TYPE, buf);
var hreq = parts.head;
var adapter = self._getAdapter(hreq);
} catch (cause) {
err = wrapError('invalid handshake request', cause);
}
if (err) {
done(encodeError(err));
} else {
self._receive(parts.tail, adapter, done);
}
function done(resBuf) {
if (!self._writable) {
self.once('_writable', function () { done(resBuf); });
return;
}
var hres = self._createHandshakeResponse(err, hreq);
self.emit('handshake', hreq, hres);
var payload = [
HANDSHAKE_RESPONSE_TYPE.toBuffer(hres),
resBuf
];
self._writable.write({id: id, payload: payload});
if (self._endWritable) {
self._writable.end();
}
}
}
function onEnd() { self.destroy(); }
function onFinish() {
if (readable) {
readable
.removeListener('data', onRequest)
.removeListener('end', onEnd);
}
self.destroy(true);
}
} | javascript | function StatelessListener(ptcl, readableFactory, opts) {
MessageListener.call(this, ptcl, opts);
var self = this;
var readable;
process.nextTick(function () {
// Delay listening to allow handlers to be attached even if the factory is
// purely synchronous.
readable = readableFactory.call(this, function (err, writable) {
if (err) {
self.emit('error', err);
// Since stateless listeners are only used once, it is safe to destroy.
onFinish();
return;
}
self._writable = writable.on('finish', onFinish);
self.emit('_writable');
}).on('data', onRequest)
.on('end', onEnd);
});
function onRequest(obj) {
var id = obj.id;
var buf = Buffer.concat(obj.payload);
var err = null;
try {
var parts = readHead(HANDSHAKE_REQUEST_TYPE, buf);
var hreq = parts.head;
var adapter = self._getAdapter(hreq);
} catch (cause) {
err = wrapError('invalid handshake request', cause);
}
if (err) {
done(encodeError(err));
} else {
self._receive(parts.tail, adapter, done);
}
function done(resBuf) {
if (!self._writable) {
self.once('_writable', function () { done(resBuf); });
return;
}
var hres = self._createHandshakeResponse(err, hreq);
self.emit('handshake', hreq, hres);
var payload = [
HANDSHAKE_RESPONSE_TYPE.toBuffer(hres),
resBuf
];
self._writable.write({id: id, payload: payload});
if (self._endWritable) {
self._writable.end();
}
}
}
function onEnd() { self.destroy(); }
function onFinish() {
if (readable) {
readable
.removeListener('data', onRequest)
.removeListener('end', onEnd);
}
self.destroy(true);
}
} | [
"function",
"StatelessListener",
"(",
"ptcl",
",",
"readableFactory",
",",
"opts",
")",
"{",
"MessageListener",
".",
"call",
"(",
"this",
",",
"ptcl",
",",
"opts",
")",
";",
"var",
"self",
"=",
"this",
";",
"var",
"readable",
";",
"process",
".",
"nextTick",
"(",
"function",
"(",
")",
"{",
"readable",
"=",
"readableFactory",
".",
"call",
"(",
"this",
",",
"function",
"(",
"err",
",",
"writable",
")",
"{",
"if",
"(",
"err",
")",
"{",
"self",
".",
"emit",
"(",
"'error'",
",",
"err",
")",
";",
"onFinish",
"(",
")",
";",
"return",
";",
"}",
"self",
".",
"_writable",
"=",
"writable",
".",
"on",
"(",
"'finish'",
",",
"onFinish",
")",
";",
"self",
".",
"emit",
"(",
"'_writable'",
")",
";",
"}",
")",
".",
"on",
"(",
"'data'",
",",
"onRequest",
")",
".",
"on",
"(",
"'end'",
",",
"onEnd",
")",
";",
"}",
")",
";",
"function",
"onRequest",
"(",
"obj",
")",
"{",
"var",
"id",
"=",
"obj",
".",
"id",
";",
"var",
"buf",
"=",
"Buffer",
".",
"concat",
"(",
"obj",
".",
"payload",
")",
";",
"var",
"err",
"=",
"null",
";",
"try",
"{",
"var",
"parts",
"=",
"readHead",
"(",
"HANDSHAKE_REQUEST_TYPE",
",",
"buf",
")",
";",
"var",
"hreq",
"=",
"parts",
".",
"head",
";",
"var",
"adapter",
"=",
"self",
".",
"_getAdapter",
"(",
"hreq",
")",
";",
"}",
"catch",
"(",
"cause",
")",
"{",
"err",
"=",
"wrapError",
"(",
"'invalid handshake request'",
",",
"cause",
")",
";",
"}",
"if",
"(",
"err",
")",
"{",
"done",
"(",
"encodeError",
"(",
"err",
")",
")",
";",
"}",
"else",
"{",
"self",
".",
"_receive",
"(",
"parts",
".",
"tail",
",",
"adapter",
",",
"done",
")",
";",
"}",
"function",
"done",
"(",
"resBuf",
")",
"{",
"if",
"(",
"!",
"self",
".",
"_writable",
")",
"{",
"self",
".",
"once",
"(",
"'_writable'",
",",
"function",
"(",
")",
"{",
"done",
"(",
"resBuf",
")",
";",
"}",
")",
";",
"return",
";",
"}",
"var",
"hres",
"=",
"self",
".",
"_createHandshakeResponse",
"(",
"err",
",",
"hreq",
")",
";",
"self",
".",
"emit",
"(",
"'handshake'",
",",
"hreq",
",",
"hres",
")",
";",
"var",
"payload",
"=",
"[",
"HANDSHAKE_RESPONSE_TYPE",
".",
"toBuffer",
"(",
"hres",
")",
",",
"resBuf",
"]",
";",
"self",
".",
"_writable",
".",
"write",
"(",
"{",
"id",
":",
"id",
",",
"payload",
":",
"payload",
"}",
")",
";",
"if",
"(",
"self",
".",
"_endWritable",
")",
"{",
"self",
".",
"_writable",
".",
"end",
"(",
")",
";",
"}",
"}",
"}",
"function",
"onEnd",
"(",
")",
"{",
"self",
".",
"destroy",
"(",
")",
";",
"}",
"function",
"onFinish",
"(",
")",
"{",
"if",
"(",
"readable",
")",
"{",
"readable",
".",
"removeListener",
"(",
"'data'",
",",
"onRequest",
")",
".",
"removeListener",
"(",
"'end'",
",",
"onEnd",
")",
";",
"}",
"self",
".",
"destroy",
"(",
"true",
")",
";",
"}",
"}"
] | MessageListener for stateless transport.
This listener expect a handshake to precede each message. | [
"MessageListener",
"for",
"stateless",
"transport",
"."
] | 7fa333e0fe1208de6adc17e597ec847f5ae84124 | https://github.com/cdapio/ui-schema-parser/blob/7fa333e0fe1208de6adc17e597ec847f5ae84124/lib/protocols.js#L923-L990 | train |
cdapio/ui-schema-parser | lib/protocols.js | Message | function Message(name, attrs, opts) {
opts = opts || {};
if (!types.isValidName(name)) {
throw new Error(f('invalid message name: %s', name));
}
this._name = name;
var recordName = f('org.apache.avro.ipc.%sRequest', name);
this._requestType = types.createType({
name: recordName,
type: 'record',
namespace: opts.namespace || '', // Don't leak request namespace.
fields: attrs.request
}, opts);
// We remove the record from the registry to prevent it from being exported
// in the protocol's schema.
delete opts.registry[recordName];
if (!attrs.response) {
throw new Error('missing response');
}
this._responseType = types.createType(attrs.response, opts);
var errors = attrs.errors || [];
errors.unshift('string');
this._errorType = types.createType(errors, opts);
this._oneWay = !!attrs['one-way'];
if (this._oneWay) {
if (this._responseType.getTypeName() !== 'null' || errors.length > 1) {
throw new Error('unapplicable one-way parameter');
}
}
} | javascript | function Message(name, attrs, opts) {
opts = opts || {};
if (!types.isValidName(name)) {
throw new Error(f('invalid message name: %s', name));
}
this._name = name;
var recordName = f('org.apache.avro.ipc.%sRequest', name);
this._requestType = types.createType({
name: recordName,
type: 'record',
namespace: opts.namespace || '', // Don't leak request namespace.
fields: attrs.request
}, opts);
// We remove the record from the registry to prevent it from being exported
// in the protocol's schema.
delete opts.registry[recordName];
if (!attrs.response) {
throw new Error('missing response');
}
this._responseType = types.createType(attrs.response, opts);
var errors = attrs.errors || [];
errors.unshift('string');
this._errorType = types.createType(errors, opts);
this._oneWay = !!attrs['one-way'];
if (this._oneWay) {
if (this._responseType.getTypeName() !== 'null' || errors.length > 1) {
throw new Error('unapplicable one-way parameter');
}
}
} | [
"function",
"Message",
"(",
"name",
",",
"attrs",
",",
"opts",
")",
"{",
"opts",
"=",
"opts",
"||",
"{",
"}",
";",
"if",
"(",
"!",
"types",
".",
"isValidName",
"(",
"name",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"f",
"(",
"'invalid message name: %s'",
",",
"name",
")",
")",
";",
"}",
"this",
".",
"_name",
"=",
"name",
";",
"var",
"recordName",
"=",
"f",
"(",
"'org.apache.avro.ipc.%sRequest'",
",",
"name",
")",
";",
"this",
".",
"_requestType",
"=",
"types",
".",
"createType",
"(",
"{",
"name",
":",
"recordName",
",",
"type",
":",
"'record'",
",",
"namespace",
":",
"opts",
".",
"namespace",
"||",
"''",
",",
"fields",
":",
"attrs",
".",
"request",
"}",
",",
"opts",
")",
";",
"delete",
"opts",
".",
"registry",
"[",
"recordName",
"]",
";",
"if",
"(",
"!",
"attrs",
".",
"response",
")",
"{",
"throw",
"new",
"Error",
"(",
"'missing response'",
")",
";",
"}",
"this",
".",
"_responseType",
"=",
"types",
".",
"createType",
"(",
"attrs",
".",
"response",
",",
"opts",
")",
";",
"var",
"errors",
"=",
"attrs",
".",
"errors",
"||",
"[",
"]",
";",
"errors",
".",
"unshift",
"(",
"'string'",
")",
";",
"this",
".",
"_errorType",
"=",
"types",
".",
"createType",
"(",
"errors",
",",
"opts",
")",
";",
"this",
".",
"_oneWay",
"=",
"!",
"!",
"attrs",
"[",
"'one-way'",
"]",
";",
"if",
"(",
"this",
".",
"_oneWay",
")",
"{",
"if",
"(",
"this",
".",
"_responseType",
".",
"getTypeName",
"(",
")",
"!==",
"'null'",
"||",
"errors",
".",
"length",
">",
"1",
")",
"{",
"throw",
"new",
"Error",
"(",
"'unapplicable one-way parameter'",
")",
";",
"}",
"}",
"}"
] | An Avro message.
It contains the various types used to send it (request, error, response). | [
"An",
"Avro",
"message",
"."
] | 7fa333e0fe1208de6adc17e597ec847f5ae84124 | https://github.com/cdapio/ui-schema-parser/blob/7fa333e0fe1208de6adc17e597ec847f5ae84124/lib/protocols.js#L1081-L1115 | train |
cdapio/ui-schema-parser | lib/protocols.js | Adapter | function Adapter(clientPtcl, serverPtcl, fingerprint) {
this._clientPtcl = clientPtcl;
this._serverPtcl = serverPtcl;
this._fingerprint = fingerprint; // Convenience.
this._rsvs = clientPtcl.equals(serverPtcl) ? null : this._createResolvers();
} | javascript | function Adapter(clientPtcl, serverPtcl, fingerprint) {
this._clientPtcl = clientPtcl;
this._serverPtcl = serverPtcl;
this._fingerprint = fingerprint; // Convenience.
this._rsvs = clientPtcl.equals(serverPtcl) ? null : this._createResolvers();
} | [
"function",
"Adapter",
"(",
"clientPtcl",
",",
"serverPtcl",
",",
"fingerprint",
")",
"{",
"this",
".",
"_clientPtcl",
"=",
"clientPtcl",
";",
"this",
".",
"_serverPtcl",
"=",
"serverPtcl",
";",
"this",
".",
"_fingerprint",
"=",
"fingerprint",
";",
"this",
".",
"_rsvs",
"=",
"clientPtcl",
".",
"equals",
"(",
"serverPtcl",
")",
"?",
"null",
":",
"this",
".",
"_createResolvers",
"(",
")",
";",
"}"
] | Protocol resolution helper.
It is used both by emitters and listeners, to respectively decode errors and
responses, or requests. | [
"Protocol",
"resolution",
"helper",
"."
] | 7fa333e0fe1208de6adc17e597ec847f5ae84124 | https://github.com/cdapio/ui-schema-parser/blob/7fa333e0fe1208de6adc17e597ec847f5ae84124/lib/protocols.js#L1204-L1209 | train |
cdapio/ui-schema-parser | lib/protocols.js | wrapError | function wrapError(message, cause) {
var err = new Error(f('%s: %s', message, cause.message));
err.cause = cause;
return err;
} | javascript | function wrapError(message, cause) {
var err = new Error(f('%s: %s', message, cause.message));
err.cause = cause;
return err;
} | [
"function",
"wrapError",
"(",
"message",
",",
"cause",
")",
"{",
"var",
"err",
"=",
"new",
"Error",
"(",
"f",
"(",
"'%s: %s'",
",",
"message",
",",
"cause",
".",
"message",
")",
")",
";",
"err",
".",
"cause",
"=",
"cause",
";",
"return",
"err",
";",
"}"
] | Wrap something in an error.
@param message {String} The new error's message.
@param cause {Error} The cause of the error. It is available as `cause`
field on the outer error.
This is used to keep the argument of emitters' `'error'` event errors. | [
"Wrap",
"something",
"in",
"an",
"error",
"."
] | 7fa333e0fe1208de6adc17e597ec847f5ae84124 | https://github.com/cdapio/ui-schema-parser/blob/7fa333e0fe1208de6adc17e597ec847f5ae84124/lib/protocols.js#L1482-L1486 | train |
cdapio/ui-schema-parser | lib/protocols.js | encodeError | function encodeError(err, header) {
return Buffer.concat([
header || new Buffer([0]), // Recover the header if possible.
new Buffer([1, 0]), // Error flag and first union index.
STRING_TYPE.toBuffer(err.message)
]);
} | javascript | function encodeError(err, header) {
return Buffer.concat([
header || new Buffer([0]), // Recover the header if possible.
new Buffer([1, 0]), // Error flag and first union index.
STRING_TYPE.toBuffer(err.message)
]);
} | [
"function",
"encodeError",
"(",
"err",
",",
"header",
")",
"{",
"return",
"Buffer",
".",
"concat",
"(",
"[",
"header",
"||",
"new",
"Buffer",
"(",
"[",
"0",
"]",
")",
",",
"new",
"Buffer",
"(",
"[",
"1",
",",
"0",
"]",
")",
",",
"STRING_TYPE",
".",
"toBuffer",
"(",
"err",
".",
"message",
")",
"]",
")",
";",
"}"
] | Encode an error and optional header into a valid Avro response.
@param err {Error} Error to encode.
@param header {Object} Optional response header. | [
"Encode",
"an",
"error",
"and",
"optional",
"header",
"into",
"a",
"valid",
"Avro",
"response",
"."
] | 7fa333e0fe1208de6adc17e597ec847f5ae84124 | https://github.com/cdapio/ui-schema-parser/blob/7fa333e0fe1208de6adc17e597ec847f5ae84124/lib/protocols.js#L1506-L1512 | train |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.