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
list | docstring
stringlengths 4
11.8k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 86
226
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
OriR/interpolate-loader-options-webpack-plugin | index.js | interpolatedOptions | function interpolatedOptions(options, context, source, hierarchy = '') {
Object.keys(options).forEach((key) => {
if (typeof options[key] === 'object') {
interpolatedOptions(options[key], context, source, `${hierarchy}.${key}`);
}
else if (typeof options[key] === 'string' && shouldPatchProperty(`${hierarchy}.${key}`)) {
options[key] = utils.interpolateName(context, options[key], { content: source });
}
});
return options;
} | javascript | function interpolatedOptions(options, context, source, hierarchy = '') {
Object.keys(options).forEach((key) => {
if (typeof options[key] === 'object') {
interpolatedOptions(options[key], context, source, `${hierarchy}.${key}`);
}
else if (typeof options[key] === 'string' && shouldPatchProperty(`${hierarchy}.${key}`)) {
options[key] = utils.interpolateName(context, options[key], { content: source });
}
});
return options;
} | [
"function",
"interpolatedOptions",
"(",
"options",
",",
"context",
",",
"source",
",",
"hierarchy",
"=",
"''",
")",
"{",
"Object",
".",
"keys",
"(",
"options",
")",
".",
"forEach",
"(",
"(",
"key",
")",
"=>",
"{",
"if",
"(",
"typeof",
"options",
"[",
"key",
"]",
"===",
"'object'",
")",
"{",
"interpolatedOptions",
"(",
"options",
"[",
"key",
"]",
",",
"context",
",",
"source",
",",
"`",
"${",
"hierarchy",
"}",
"${",
"key",
"}",
"`",
")",
";",
"}",
"else",
"if",
"(",
"typeof",
"options",
"[",
"key",
"]",
"===",
"'string'",
"&&",
"shouldPatchProperty",
"(",
"`",
"${",
"hierarchy",
"}",
"${",
"key",
"}",
"`",
")",
")",
"{",
"options",
"[",
"key",
"]",
"=",
"utils",
".",
"interpolateName",
"(",
"context",
",",
"options",
"[",
"key",
"]",
",",
"{",
"content",
":",
"source",
"}",
")",
";",
"}",
"}",
")",
";",
"return",
"options",
";",
"}"
] | Interpolating all the string values in the options object. | [
"Interpolating",
"all",
"the",
"string",
"values",
"in",
"the",
"options",
"object",
"."
] | 8b8f6e315f7d606a4fbcf4f473e75c4e26d287df | https://github.com/OriR/interpolate-loader-options-webpack-plugin/blob/8b8f6e315f7d606a4fbcf4f473e75c4e26d287df/index.js#L38-L48 | train |
impromptu/impromptu | lib/exec.js | Executable | function Executable(log, command) {
/** @type {string} */
this.command = command
/** @type {Array.<function(Error, Buffer, Buffer)>} */
this.callbacks = []
/** @type {Arguments} */
this.results = null
var startTime = Date.now()
child_process.exec(this.command, function() {
var timeDiff = `${Date.now() - startTime}`
if (timeDiff.length < 3) timeDiff = ` ${timeDiff}`.slice(-3)
log.debug(`Exec | ${timeDiff}ms | ${this.command}`)
this.results = arguments
for (var i = 0; i < this.callbacks.length; i++) {
var callback = this.callbacks[i]
callback.apply(null, arguments)
}
}.bind(this))
} | javascript | function Executable(log, command) {
/** @type {string} */
this.command = command
/** @type {Array.<function(Error, Buffer, Buffer)>} */
this.callbacks = []
/** @type {Arguments} */
this.results = null
var startTime = Date.now()
child_process.exec(this.command, function() {
var timeDiff = `${Date.now() - startTime}`
if (timeDiff.length < 3) timeDiff = ` ${timeDiff}`.slice(-3)
log.debug(`Exec | ${timeDiff}ms | ${this.command}`)
this.results = arguments
for (var i = 0; i < this.callbacks.length; i++) {
var callback = this.callbacks[i]
callback.apply(null, arguments)
}
}.bind(this))
} | [
"function",
"Executable",
"(",
"log",
",",
"command",
")",
"{",
"this",
".",
"command",
"=",
"command",
"this",
".",
"callbacks",
"=",
"[",
"]",
"this",
".",
"results",
"=",
"null",
"var",
"startTime",
"=",
"Date",
".",
"now",
"(",
")",
"child_process",
".",
"exec",
"(",
"this",
".",
"command",
",",
"function",
"(",
")",
"{",
"var",
"timeDiff",
"=",
"`",
"${",
"Date",
".",
"now",
"(",
")",
"-",
"startTime",
"}",
"`",
"if",
"(",
"timeDiff",
".",
"length",
"<",
"3",
")",
"timeDiff",
"=",
"`",
"${",
"timeDiff",
"}",
"`",
".",
"slice",
"(",
"-",
"3",
")",
"log",
".",
"debug",
"(",
"`",
"${",
"timeDiff",
"}",
"${",
"this",
".",
"command",
"}",
"`",
")",
"this",
".",
"results",
"=",
"arguments",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"this",
".",
"callbacks",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"callback",
"=",
"this",
".",
"callbacks",
"[",
"i",
"]",
"callback",
".",
"apply",
"(",
"null",
",",
"arguments",
")",
"}",
"}",
".",
"bind",
"(",
"this",
")",
")",
"}"
] | A memoized executable command. The first time the command is run, the results are stored.
Callbacks are tracked while the command is running to avoid race conditions.
@constructor
@param {Log} log A logging instance.
@param {string} command The command to execute. | [
"A",
"memoized",
"executable",
"command",
".",
"The",
"first",
"time",
"the",
"command",
"is",
"run",
"the",
"results",
"are",
"stored",
".",
"Callbacks",
"are",
"tracked",
"while",
"the",
"command",
"is",
"running",
"to",
"avoid",
"race",
"conditions",
"."
] | 829798eda62771d6a6ed971d87eef7a461932704 | https://github.com/impromptu/impromptu/blob/829798eda62771d6a6ed971d87eef7a461932704/lib/exec.js#L23-L45 | train |
impromptu/impromptu | lib/exec.js | execute | function execute(log, command, opt_callback) {
if (!registry[command]) {
registry[command] = new Executable(log, command)
}
var executable = registry[command]
if (opt_callback) executable.addCallback(opt_callback)
} | javascript | function execute(log, command, opt_callback) {
if (!registry[command]) {
registry[command] = new Executable(log, command)
}
var executable = registry[command]
if (opt_callback) executable.addCallback(opt_callback)
} | [
"function",
"execute",
"(",
"log",
",",
"command",
",",
"opt_callback",
")",
"{",
"if",
"(",
"!",
"registry",
"[",
"command",
"]",
")",
"{",
"registry",
"[",
"command",
"]",
"=",
"new",
"Executable",
"(",
"log",
",",
"command",
")",
"}",
"var",
"executable",
"=",
"registry",
"[",
"command",
"]",
"if",
"(",
"opt_callback",
")",
"executable",
".",
"addCallback",
"(",
"opt_callback",
")",
"}"
] | Executes a memoized command and triggers the callback on a result.
@param {Log} log
@param {string} command
@param {function(Error, Buffer, Buffer)=} opt_callback | [
"Executes",
"a",
"memoized",
"command",
"and",
"triggers",
"the",
"callback",
"on",
"a",
"result",
"."
] | 829798eda62771d6a6ed971d87eef7a461932704 | https://github.com/impromptu/impromptu/blob/829798eda62771d6a6ed971d87eef7a461932704/lib/exec.js#L65-L72 | train |
typhonjs-node-esdoc/esdoc-plugin-enhanced-navigation | template/copy/script/navigation/enhancednav.js | deserializeNavState | function deserializeNavState()
{
var navID = $('.navigation .nav-accordion-menu').data('nav-id');
if (sessionStorage)
{
var checkboxMap = sessionStorage.getItem(navID + '-accordion-state');
// If there is no data in session storage then create an empty map.
if (checkboxMap == null) { checkboxMap = '{}'; }
checkboxMap = JSON.parse(checkboxMap);
$('.navigation .nav-accordion-menu').find('input[type="checkbox"]').each(function()
{
var checkboxValue = checkboxMap[$(this).attr('name')];
if (typeof checkboxValue === 'boolean') { $(this).prop('checked', checkboxValue); }
});
}
// Set navigation menu visible
$('.navigation .nav-accordion-menu').removeClass('hidden');
// Set navigation menu scroll bar from session state.
if (sessionStorage)
{
var navScrollTop = sessionStorage.getItem(navID + '-scrolltop');
if (typeof navScrollTop === 'string') { $('.navigation').prop('scrollTop', navScrollTop); }
}
} | javascript | function deserializeNavState()
{
var navID = $('.navigation .nav-accordion-menu').data('nav-id');
if (sessionStorage)
{
var checkboxMap = sessionStorage.getItem(navID + '-accordion-state');
// If there is no data in session storage then create an empty map.
if (checkboxMap == null) { checkboxMap = '{}'; }
checkboxMap = JSON.parse(checkboxMap);
$('.navigation .nav-accordion-menu').find('input[type="checkbox"]').each(function()
{
var checkboxValue = checkboxMap[$(this).attr('name')];
if (typeof checkboxValue === 'boolean') { $(this).prop('checked', checkboxValue); }
});
}
// Set navigation menu visible
$('.navigation .nav-accordion-menu').removeClass('hidden');
// Set navigation menu scroll bar from session state.
if (sessionStorage)
{
var navScrollTop = sessionStorage.getItem(navID + '-scrolltop');
if (typeof navScrollTop === 'string') { $('.navigation').prop('scrollTop', navScrollTop); }
}
} | [
"function",
"deserializeNavState",
"(",
")",
"{",
"var",
"navID",
"=",
"$",
"(",
"'.navigation .nav-accordion-menu'",
")",
".",
"data",
"(",
"'nav-id'",
")",
";",
"if",
"(",
"sessionStorage",
")",
"{",
"var",
"checkboxMap",
"=",
"sessionStorage",
".",
"getItem",
"(",
"navID",
"+",
"'-accordion-state'",
")",
";",
"if",
"(",
"checkboxMap",
"==",
"null",
")",
"{",
"checkboxMap",
"=",
"'{}'",
";",
"}",
"checkboxMap",
"=",
"JSON",
".",
"parse",
"(",
"checkboxMap",
")",
";",
"$",
"(",
"'.navigation .nav-accordion-menu'",
")",
".",
"find",
"(",
"'input[type=\"checkbox\"]'",
")",
".",
"each",
"(",
"function",
"(",
")",
"{",
"var",
"checkboxValue",
"=",
"checkboxMap",
"[",
"$",
"(",
"this",
")",
".",
"attr",
"(",
"'name'",
")",
"]",
";",
"if",
"(",
"typeof",
"checkboxValue",
"===",
"'boolean'",
")",
"{",
"$",
"(",
"this",
")",
".",
"prop",
"(",
"'checked'",
",",
"checkboxValue",
")",
";",
"}",
"}",
")",
";",
"}",
"$",
"(",
"'.navigation .nav-accordion-menu'",
")",
".",
"removeClass",
"(",
"'hidden'",
")",
";",
"if",
"(",
"sessionStorage",
")",
"{",
"var",
"navScrollTop",
"=",
"sessionStorage",
".",
"getItem",
"(",
"navID",
"+",
"'-scrolltop'",
")",
";",
"if",
"(",
"typeof",
"navScrollTop",
"===",
"'string'",
")",
"{",
"$",
"(",
"'.navigation'",
")",
".",
"prop",
"(",
"'scrollTop'",
",",
"navScrollTop",
")",
";",
"}",
"}",
"}"
] | Deserializes navigation accordion state from session storage. | [
"Deserializes",
"navigation",
"accordion",
"state",
"from",
"session",
"storage",
"."
] | db25fb3e570fbae97bedf06fe4daf4d51e4c788b | https://github.com/typhonjs-node-esdoc/esdoc-plugin-enhanced-navigation/blob/db25fb3e570fbae97bedf06fe4daf4d51e4c788b/template/copy/script/navigation/enhancednav.js#L27-L56 | train |
typhonjs-node-esdoc/esdoc-plugin-enhanced-navigation | template/copy/script/navigation/enhancednav.js | hideNavContextMenu | function hideNavContextMenu(event)
{
var contextMenuButton = $('#context-menu');
var popupmenu = $('#contextpopup .mdl-menu__container');
// If an event is defined then make sure it isn't targeting the context menu.
if (event)
{
// Picked element is not the menu
if (!$(event.target).parents('#contextpopup').length > 0)
{
// Hide menu if currently visible
if (popupmenu.hasClass('is-visible')) { contextMenuButton.click(); }
}
}
else // No event defined so always close context menu and remove node highlighting.
{
// Hide menu if currently visible
if (popupmenu.hasClass('is-visible')) { contextMenuButton.click(); }
}
} | javascript | function hideNavContextMenu(event)
{
var contextMenuButton = $('#context-menu');
var popupmenu = $('#contextpopup .mdl-menu__container');
// If an event is defined then make sure it isn't targeting the context menu.
if (event)
{
// Picked element is not the menu
if (!$(event.target).parents('#contextpopup').length > 0)
{
// Hide menu if currently visible
if (popupmenu.hasClass('is-visible')) { contextMenuButton.click(); }
}
}
else // No event defined so always close context menu and remove node highlighting.
{
// Hide menu if currently visible
if (popupmenu.hasClass('is-visible')) { contextMenuButton.click(); }
}
} | [
"function",
"hideNavContextMenu",
"(",
"event",
")",
"{",
"var",
"contextMenuButton",
"=",
"$",
"(",
"'#context-menu'",
")",
";",
"var",
"popupmenu",
"=",
"$",
"(",
"'#contextpopup .mdl-menu__container'",
")",
";",
"if",
"(",
"event",
")",
"{",
"if",
"(",
"!",
"$",
"(",
"event",
".",
"target",
")",
".",
"parents",
"(",
"'#contextpopup'",
")",
".",
"length",
">",
"0",
")",
"{",
"if",
"(",
"popupmenu",
".",
"hasClass",
"(",
"'is-visible'",
")",
")",
"{",
"contextMenuButton",
".",
"click",
"(",
")",
";",
"}",
"}",
"}",
"else",
"{",
"if",
"(",
"popupmenu",
".",
"hasClass",
"(",
"'is-visible'",
")",
")",
"{",
"contextMenuButton",
".",
"click",
"(",
")",
";",
"}",
"}",
"}"
] | Hides the nav context menu if visible. If an event is supplied it is checked against any existing context menu
and is ignored if the context menu is within the parent hierarchy.
@param {object|undefined} event - Optional event | [
"Hides",
"the",
"nav",
"context",
"menu",
"if",
"visible",
".",
"If",
"an",
"event",
"is",
"supplied",
"it",
"is",
"checked",
"against",
"any",
"existing",
"context",
"menu",
"and",
"is",
"ignored",
"if",
"the",
"context",
"menu",
"is",
"within",
"the",
"parent",
"hierarchy",
"."
] | db25fb3e570fbae97bedf06fe4daf4d51e4c788b | https://github.com/typhonjs-node-esdoc/esdoc-plugin-enhanced-navigation/blob/db25fb3e570fbae97bedf06fe4daf4d51e4c788b/template/copy/script/navigation/enhancednav.js#L64-L84 | train |
typhonjs-node-esdoc/esdoc-plugin-enhanced-navigation | template/copy/script/navigation/enhancednav.js | onNavContextClick | function onNavContextClick(event)
{
// Hides any existing nav context menu.
hideNavContextMenu(event);
var target = $(this);
var packageLink = target.data('package-link');
var packageType = target.data('package-type') || '...';
// Create proper name for package type.
switch (packageType)
{
case 'npm':
packageType = 'NPM';
break;
}
var packageVersion = target.data('package-version');
var scmLink = target.data('scm-link');
var scmType = target.data('scm-type') || '...';
// Create proper name for SCM type.
switch (scmType)
{
case 'github':
scmType = 'Github';
break;
}
var popupmenu = $('#contextpopup .mdl-menu__container');
// Populate data for the context menu.
popupmenu.find('li').each(function(index)
{
var liTarget = $(this);
switch (index)
{
case 0:
if (scmLink)
{
liTarget.text('Open on ' + scmType);
liTarget.data('link', scmLink);
liTarget.removeClass('hidden');
// Add divider if there are additional non-hidden items
if (packageLink || packageVersion) { liTarget.addClass('mdl-menu__item--full-bleed-divider'); }
else { liTarget.removeClass('mdl-menu__item--full-bleed-divider'); }
}
else
{
liTarget.addClass('hidden');
}
break;
case 1:
if (packageLink)
{
liTarget.text('Open on ' + packageType);
liTarget.data('link', packageLink);
liTarget.removeClass('hidden');
// Add divider if there are additional non-hidden items
if (packageVersion) { liTarget.addClass('mdl-menu__item--full-bleed-divider'); }
else { liTarget.removeClass('mdl-menu__item--full-bleed-divider'); }
}
else
{
liTarget.addClass('hidden');
}
break;
case 2:
if (packageVersion)
{
liTarget.text('Version: ' + packageVersion);
liTarget.removeClass('hidden');
}
else
{
liTarget.addClass('hidden');
}
break;
}
});
// Wrapping in a 100ms timeout allows MDL to draw animation when showing a context menu after one has been hidden.
setTimeout(function()
{
// For MDL a programmatic click of the hidden context menu.
var contextMenuButton = $("#context-menu");
contextMenuButton.click();
// Necessary to defer reposition of the context menu.
setTimeout(function()
{
popupmenu.parent().css({ position: 'relative' });
popupmenu.css({ left: event.pageX, top: event.pageY - $('header').outerHeight(), position:'absolute' });
}, 0);
}, 100);
} | javascript | function onNavContextClick(event)
{
// Hides any existing nav context menu.
hideNavContextMenu(event);
var target = $(this);
var packageLink = target.data('package-link');
var packageType = target.data('package-type') || '...';
// Create proper name for package type.
switch (packageType)
{
case 'npm':
packageType = 'NPM';
break;
}
var packageVersion = target.data('package-version');
var scmLink = target.data('scm-link');
var scmType = target.data('scm-type') || '...';
// Create proper name for SCM type.
switch (scmType)
{
case 'github':
scmType = 'Github';
break;
}
var popupmenu = $('#contextpopup .mdl-menu__container');
// Populate data for the context menu.
popupmenu.find('li').each(function(index)
{
var liTarget = $(this);
switch (index)
{
case 0:
if (scmLink)
{
liTarget.text('Open on ' + scmType);
liTarget.data('link', scmLink);
liTarget.removeClass('hidden');
// Add divider if there are additional non-hidden items
if (packageLink || packageVersion) { liTarget.addClass('mdl-menu__item--full-bleed-divider'); }
else { liTarget.removeClass('mdl-menu__item--full-bleed-divider'); }
}
else
{
liTarget.addClass('hidden');
}
break;
case 1:
if (packageLink)
{
liTarget.text('Open on ' + packageType);
liTarget.data('link', packageLink);
liTarget.removeClass('hidden');
// Add divider if there are additional non-hidden items
if (packageVersion) { liTarget.addClass('mdl-menu__item--full-bleed-divider'); }
else { liTarget.removeClass('mdl-menu__item--full-bleed-divider'); }
}
else
{
liTarget.addClass('hidden');
}
break;
case 2:
if (packageVersion)
{
liTarget.text('Version: ' + packageVersion);
liTarget.removeClass('hidden');
}
else
{
liTarget.addClass('hidden');
}
break;
}
});
// Wrapping in a 100ms timeout allows MDL to draw animation when showing a context menu after one has been hidden.
setTimeout(function()
{
// For MDL a programmatic click of the hidden context menu.
var contextMenuButton = $("#context-menu");
contextMenuButton.click();
// Necessary to defer reposition of the context menu.
setTimeout(function()
{
popupmenu.parent().css({ position: 'relative' });
popupmenu.css({ left: event.pageX, top: event.pageY - $('header').outerHeight(), position:'absolute' });
}, 0);
}, 100);
} | [
"function",
"onNavContextClick",
"(",
"event",
")",
"{",
"hideNavContextMenu",
"(",
"event",
")",
";",
"var",
"target",
"=",
"$",
"(",
"this",
")",
";",
"var",
"packageLink",
"=",
"target",
".",
"data",
"(",
"'package-link'",
")",
";",
"var",
"packageType",
"=",
"target",
".",
"data",
"(",
"'package-type'",
")",
"||",
"'...'",
";",
"switch",
"(",
"packageType",
")",
"{",
"case",
"'npm'",
":",
"packageType",
"=",
"'NPM'",
";",
"break",
";",
"}",
"var",
"packageVersion",
"=",
"target",
".",
"data",
"(",
"'package-version'",
")",
";",
"var",
"scmLink",
"=",
"target",
".",
"data",
"(",
"'scm-link'",
")",
";",
"var",
"scmType",
"=",
"target",
".",
"data",
"(",
"'scm-type'",
")",
"||",
"'...'",
";",
"switch",
"(",
"scmType",
")",
"{",
"case",
"'github'",
":",
"scmType",
"=",
"'Github'",
";",
"break",
";",
"}",
"var",
"popupmenu",
"=",
"$",
"(",
"'#contextpopup .mdl-menu__container'",
")",
";",
"popupmenu",
".",
"find",
"(",
"'li'",
")",
".",
"each",
"(",
"function",
"(",
"index",
")",
"{",
"var",
"liTarget",
"=",
"$",
"(",
"this",
")",
";",
"switch",
"(",
"index",
")",
"{",
"case",
"0",
":",
"if",
"(",
"scmLink",
")",
"{",
"liTarget",
".",
"text",
"(",
"'Open on '",
"+",
"scmType",
")",
";",
"liTarget",
".",
"data",
"(",
"'link'",
",",
"scmLink",
")",
";",
"liTarget",
".",
"removeClass",
"(",
"'hidden'",
")",
";",
"if",
"(",
"packageLink",
"||",
"packageVersion",
")",
"{",
"liTarget",
".",
"addClass",
"(",
"'mdl-menu__item--full-bleed-divider'",
")",
";",
"}",
"else",
"{",
"liTarget",
".",
"removeClass",
"(",
"'mdl-menu__item--full-bleed-divider'",
")",
";",
"}",
"}",
"else",
"{",
"liTarget",
".",
"addClass",
"(",
"'hidden'",
")",
";",
"}",
"break",
";",
"case",
"1",
":",
"if",
"(",
"packageLink",
")",
"{",
"liTarget",
".",
"text",
"(",
"'Open on '",
"+",
"packageType",
")",
";",
"liTarget",
".",
"data",
"(",
"'link'",
",",
"packageLink",
")",
";",
"liTarget",
".",
"removeClass",
"(",
"'hidden'",
")",
";",
"if",
"(",
"packageVersion",
")",
"{",
"liTarget",
".",
"addClass",
"(",
"'mdl-menu__item--full-bleed-divider'",
")",
";",
"}",
"else",
"{",
"liTarget",
".",
"removeClass",
"(",
"'mdl-menu__item--full-bleed-divider'",
")",
";",
"}",
"}",
"else",
"{",
"liTarget",
".",
"addClass",
"(",
"'hidden'",
")",
";",
"}",
"break",
";",
"case",
"2",
":",
"if",
"(",
"packageVersion",
")",
"{",
"liTarget",
".",
"text",
"(",
"'Version: '",
"+",
"packageVersion",
")",
";",
"liTarget",
".",
"removeClass",
"(",
"'hidden'",
")",
";",
"}",
"else",
"{",
"liTarget",
".",
"addClass",
"(",
"'hidden'",
")",
";",
"}",
"break",
";",
"}",
"}",
")",
";",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"var",
"contextMenuButton",
"=",
"$",
"(",
"\"#context-menu\"",
")",
";",
"contextMenuButton",
".",
"click",
"(",
")",
";",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"popupmenu",
".",
"parent",
"(",
")",
".",
"css",
"(",
"{",
"position",
":",
"'relative'",
"}",
")",
";",
"popupmenu",
".",
"css",
"(",
"{",
"left",
":",
"event",
".",
"pageX",
",",
"top",
":",
"event",
".",
"pageY",
"-",
"$",
"(",
"'header'",
")",
".",
"outerHeight",
"(",
")",
",",
"position",
":",
"'absolute'",
"}",
")",
";",
"}",
",",
"0",
")",
";",
"}",
",",
"100",
")",
";",
"}"
] | Shows the nav context menu
@param {object} event - jQuery mouse event | [
"Shows",
"the",
"nav",
"context",
"menu"
] | db25fb3e570fbae97bedf06fe4daf4d51e4c788b | https://github.com/typhonjs-node-esdoc/esdoc-plugin-enhanced-navigation/blob/db25fb3e570fbae97bedf06fe4daf4d51e4c788b/template/copy/script/navigation/enhancednav.js#L91-L193 | train |
typhonjs-node-esdoc/esdoc-plugin-enhanced-navigation | template/copy/script/navigation/enhancednav.js | serializeNavState | function serializeNavState()
{
var checkboxMap = {};
$('.navigation .nav-accordion-menu').find('input[type="checkbox"]').each(function()
{
checkboxMap[$(this).attr('name')] = $(this).is(':checked');
});
var navID = $('.navigation .nav-accordion-menu').data('nav-id');
if (sessionStorage) { sessionStorage.setItem(navID + '-accordion-state', JSON.stringify(checkboxMap))}
} | javascript | function serializeNavState()
{
var checkboxMap = {};
$('.navigation .nav-accordion-menu').find('input[type="checkbox"]').each(function()
{
checkboxMap[$(this).attr('name')] = $(this).is(':checked');
});
var navID = $('.navigation .nav-accordion-menu').data('nav-id');
if (sessionStorage) { sessionStorage.setItem(navID + '-accordion-state', JSON.stringify(checkboxMap))}
} | [
"function",
"serializeNavState",
"(",
")",
"{",
"var",
"checkboxMap",
"=",
"{",
"}",
";",
"$",
"(",
"'.navigation .nav-accordion-menu'",
")",
".",
"find",
"(",
"'input[type=\"checkbox\"]'",
")",
".",
"each",
"(",
"function",
"(",
")",
"{",
"checkboxMap",
"[",
"$",
"(",
"this",
")",
".",
"attr",
"(",
"'name'",
")",
"]",
"=",
"$",
"(",
"this",
")",
".",
"is",
"(",
"':checked'",
")",
";",
"}",
")",
";",
"var",
"navID",
"=",
"$",
"(",
"'.navigation .nav-accordion-menu'",
")",
".",
"data",
"(",
"'nav-id'",
")",
";",
"if",
"(",
"sessionStorage",
")",
"{",
"sessionStorage",
".",
"setItem",
"(",
"navID",
"+",
"'-accordion-state'",
",",
"JSON",
".",
"stringify",
"(",
"checkboxMap",
")",
")",
"}",
"}"
] | Serializes to session storage the navigation menu accordion state. | [
"Serializes",
"to",
"session",
"storage",
"the",
"navigation",
"menu",
"accordion",
"state",
"."
] | db25fb3e570fbae97bedf06fe4daf4d51e4c788b | https://github.com/typhonjs-node-esdoc/esdoc-plugin-enhanced-navigation/blob/db25fb3e570fbae97bedf06fe4daf4d51e4c788b/template/copy/script/navigation/enhancednav.js#L219-L231 | train |
mattdesl/webgl-compile-shader | index.js | compile | function compile(gl, vertSource, fragSource, attribs, verbose) {
var log = "";
var vert = loadShader(gl, gl.VERTEX_SHADER, vertSource, verbose);
var frag = loadShader(gl, gl.FRAGMENT_SHADER, fragSource, verbose);
var vertShader = vert.shader;
var fragShader = frag.shader;
log += vert.log + "\n" + frag.log;
var program = gl.createProgram();
gl.attachShader(program, vertShader);
gl.attachShader(program, fragShader);
//TODO: Chrome seems a bit buggy with attribute bindings...
if (attribs) {
for (var key in attribs) {
if (attribs.hasOwnProperty(key)) {
gl.bindAttribLocation(program, Math.floor(attribs[key]), key);
}
}
}
gl.linkProgram(program);
log += gl.getProgramInfoLog(program) || "";
if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
if (verbose) {
console.error("Shader error:\n"+log);
console.error("Problematic shaders:\nVERTEX_SHADER:\n"+addLineNumbers(vertSource)
+"\n\nFRAGMENT_SHADER:\n"+addLineNumbers(fragSource));
}
//delete before throwing error
gl.detachShader(program, vertShader);
gl.detachShader(program, fragShader);
gl.deleteShader(vertShader);
gl.deleteShader(fragShader);
throw new Error("Error linking the shader program:\n" + log);
}
return {
program: program,
vertex: vertShader,
fragment: fragShader,
log: log.trim()
};
} | javascript | function compile(gl, vertSource, fragSource, attribs, verbose) {
var log = "";
var vert = loadShader(gl, gl.VERTEX_SHADER, vertSource, verbose);
var frag = loadShader(gl, gl.FRAGMENT_SHADER, fragSource, verbose);
var vertShader = vert.shader;
var fragShader = frag.shader;
log += vert.log + "\n" + frag.log;
var program = gl.createProgram();
gl.attachShader(program, vertShader);
gl.attachShader(program, fragShader);
//TODO: Chrome seems a bit buggy with attribute bindings...
if (attribs) {
for (var key in attribs) {
if (attribs.hasOwnProperty(key)) {
gl.bindAttribLocation(program, Math.floor(attribs[key]), key);
}
}
}
gl.linkProgram(program);
log += gl.getProgramInfoLog(program) || "";
if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
if (verbose) {
console.error("Shader error:\n"+log);
console.error("Problematic shaders:\nVERTEX_SHADER:\n"+addLineNumbers(vertSource)
+"\n\nFRAGMENT_SHADER:\n"+addLineNumbers(fragSource));
}
//delete before throwing error
gl.detachShader(program, vertShader);
gl.detachShader(program, fragShader);
gl.deleteShader(vertShader);
gl.deleteShader(fragShader);
throw new Error("Error linking the shader program:\n" + log);
}
return {
program: program,
vertex: vertShader,
fragment: fragShader,
log: log.trim()
};
} | [
"function",
"compile",
"(",
"gl",
",",
"vertSource",
",",
"fragSource",
",",
"attribs",
",",
"verbose",
")",
"{",
"var",
"log",
"=",
"\"\"",
";",
"var",
"vert",
"=",
"loadShader",
"(",
"gl",
",",
"gl",
".",
"VERTEX_SHADER",
",",
"vertSource",
",",
"verbose",
")",
";",
"var",
"frag",
"=",
"loadShader",
"(",
"gl",
",",
"gl",
".",
"FRAGMENT_SHADER",
",",
"fragSource",
",",
"verbose",
")",
";",
"var",
"vertShader",
"=",
"vert",
".",
"shader",
";",
"var",
"fragShader",
"=",
"frag",
".",
"shader",
";",
"log",
"+=",
"vert",
".",
"log",
"+",
"\"\\n\"",
"+",
"\\n",
";",
"frag",
".",
"log",
"var",
"program",
"=",
"gl",
".",
"createProgram",
"(",
")",
";",
"gl",
".",
"attachShader",
"(",
"program",
",",
"vertShader",
")",
";",
"gl",
".",
"attachShader",
"(",
"program",
",",
"fragShader",
")",
";",
"if",
"(",
"attribs",
")",
"{",
"for",
"(",
"var",
"key",
"in",
"attribs",
")",
"{",
"if",
"(",
"attribs",
".",
"hasOwnProperty",
"(",
"key",
")",
")",
"{",
"gl",
".",
"bindAttribLocation",
"(",
"program",
",",
"Math",
".",
"floor",
"(",
"attribs",
"[",
"key",
"]",
")",
",",
"key",
")",
";",
"}",
"}",
"}",
"gl",
".",
"linkProgram",
"(",
"program",
")",
";",
"log",
"+=",
"gl",
".",
"getProgramInfoLog",
"(",
"program",
")",
"||",
"\"\"",
";",
"if",
"(",
"!",
"gl",
".",
"getProgramParameter",
"(",
"program",
",",
"gl",
".",
"LINK_STATUS",
")",
")",
"{",
"if",
"(",
"verbose",
")",
"{",
"console",
".",
"error",
"(",
"\"Shader error:\\n\"",
"+",
"\\n",
")",
";",
"log",
"}",
"console",
".",
"error",
"(",
"\"Problematic shaders:\\nVERTEX_SHADER:\\n\"",
"+",
"\\n",
"+",
"\\n",
"+",
"addLineNumbers",
"(",
"vertSource",
")",
")",
";",
"\"\\n\\nFRAGMENT_SHADER:\\n\"",
"\\n",
"\\n",
"\\n",
"}",
"}"
] | Compiles the shaders, throwing an error if the program was invalid. | [
"Compiles",
"the",
"shaders",
"throwing",
"an",
"error",
"if",
"the",
"program",
"was",
"invalid",
"."
] | 0d8f658c19f4e4414504b4304314ca3b8286433e | https://github.com/mattdesl/webgl-compile-shader/blob/0d8f658c19f4e4414504b4304314ca3b8286433e/index.js#L20-L70 | train |
byron-dupreez/aws-core-utils | kms-utils.js | encrypt | function encrypt(kms, params, logger) {
logger = logger || console;
const startMs = Date.now();
return kms.encrypt(params).promise().then(
result => {
if (logger.traceEnabled) logger.trace(`KMS encrypt success took ${Date.now() - startMs} ms`);
return result;
},
err => {
logger.error(`KMS encrypt failure took ${Date.now() - startMs} ms`, err);
throw err;
}
);
} | javascript | function encrypt(kms, params, logger) {
logger = logger || console;
const startMs = Date.now();
return kms.encrypt(params).promise().then(
result => {
if (logger.traceEnabled) logger.trace(`KMS encrypt success took ${Date.now() - startMs} ms`);
return result;
},
err => {
logger.error(`KMS encrypt failure took ${Date.now() - startMs} ms`, err);
throw err;
}
);
} | [
"function",
"encrypt",
"(",
"kms",
",",
"params",
",",
"logger",
")",
"{",
"logger",
"=",
"logger",
"||",
"console",
";",
"const",
"startMs",
"=",
"Date",
".",
"now",
"(",
")",
";",
"return",
"kms",
".",
"encrypt",
"(",
"params",
")",
".",
"promise",
"(",
")",
".",
"then",
"(",
"result",
"=>",
"{",
"if",
"(",
"logger",
".",
"traceEnabled",
")",
"logger",
".",
"trace",
"(",
"`",
"${",
"Date",
".",
"now",
"(",
")",
"-",
"startMs",
"}",
"`",
")",
";",
"return",
"result",
";",
"}",
",",
"err",
"=>",
"{",
"logger",
".",
"error",
"(",
"`",
"${",
"Date",
".",
"now",
"(",
")",
"-",
"startMs",
"}",
"`",
",",
"err",
")",
";",
"throw",
"err",
";",
"}",
")",
";",
"}"
] | Encrypts the plaintext within the given KMS parameters using the given AWS.KMS instance & returns the KMS result.
@param {AWS.KMS} kms - an AWS.KMS instance to use
@param {KMSEncryptParams} params - the KMS encrypt parameters to use
@param {Logger|console|undefined} [logger] - an optional logger to use (defaults to console if omitted)
@returns {Promise.<KMSEncryptResult>} a promise of the KMS encrypt result | [
"Encrypts",
"the",
"plaintext",
"within",
"the",
"given",
"KMS",
"parameters",
"using",
"the",
"given",
"AWS",
".",
"KMS",
"instance",
"&",
"returns",
"the",
"KMS",
"result",
"."
] | 2530155b5afc102f61658b28183a16027ecae86a | https://github.com/byron-dupreez/aws-core-utils/blob/2530155b5afc102f61658b28183a16027ecae86a/kms-utils.js#L22-L35 | train |
byron-dupreez/aws-core-utils | kms-utils.js | encryptKey | function encryptKey(kms, keyId, plaintext, logger) {
const params = {KeyId: keyId, Plaintext: plaintext};
return encrypt(kms, params, logger).then(result => result.CiphertextBlob && result.CiphertextBlob.toString('base64'));
} | javascript | function encryptKey(kms, keyId, plaintext, logger) {
const params = {KeyId: keyId, Plaintext: plaintext};
return encrypt(kms, params, logger).then(result => result.CiphertextBlob && result.CiphertextBlob.toString('base64'));
} | [
"function",
"encryptKey",
"(",
"kms",
",",
"keyId",
",",
"plaintext",
",",
"logger",
")",
"{",
"const",
"params",
"=",
"{",
"KeyId",
":",
"keyId",
",",
"Plaintext",
":",
"plaintext",
"}",
";",
"return",
"encrypt",
"(",
"kms",
",",
"params",
",",
"logger",
")",
".",
"then",
"(",
"result",
"=>",
"result",
".",
"CiphertextBlob",
"&&",
"result",
".",
"CiphertextBlob",
".",
"toString",
"(",
"'base64'",
")",
")",
";",
"}"
] | Encrypts the given plaintext using the given AWS.KMS instance & returns the encrypted ciphertext.
@param {AWS.KMS} kms - an AWS.KMS instance to use
@param {string} keyId - the identifier of the CMK to use for encryption. You can use the key ID or Amazon Resource Name (ARN) of the CMK, or the name or ARN of an alias that refers to the CMK.
@param {string} plaintext - the plaintext to encrypt
@param {Logger|console|undefined} [logger] - an optional logger to use (defaults to console if omitted)
@returns {Promise.<string>} a promise of the encrypted ciphertext | [
"Encrypts",
"the",
"given",
"plaintext",
"using",
"the",
"given",
"AWS",
".",
"KMS",
"instance",
"&",
"returns",
"the",
"encrypted",
"ciphertext",
"."
] | 2530155b5afc102f61658b28183a16027ecae86a | https://github.com/byron-dupreez/aws-core-utils/blob/2530155b5afc102f61658b28183a16027ecae86a/kms-utils.js#L67-L70 | train |
byron-dupreez/aws-core-utils | kms-utils.js | decryptKey | function decryptKey(kms, ciphertextBase64, logger) {
const params = {CiphertextBlob: new Buffer(ciphertextBase64, 'base64')};
return decrypt(kms, params, logger).then(result => result.Plaintext && result.Plaintext.toString('utf8'));
} | javascript | function decryptKey(kms, ciphertextBase64, logger) {
const params = {CiphertextBlob: new Buffer(ciphertextBase64, 'base64')};
return decrypt(kms, params, logger).then(result => result.Plaintext && result.Plaintext.toString('utf8'));
} | [
"function",
"decryptKey",
"(",
"kms",
",",
"ciphertextBase64",
",",
"logger",
")",
"{",
"const",
"params",
"=",
"{",
"CiphertextBlob",
":",
"new",
"Buffer",
"(",
"ciphertextBase64",
",",
"'base64'",
")",
"}",
";",
"return",
"decrypt",
"(",
"kms",
",",
"params",
",",
"logger",
")",
".",
"then",
"(",
"result",
"=>",
"result",
".",
"Plaintext",
"&&",
"result",
".",
"Plaintext",
".",
"toString",
"(",
"'utf8'",
")",
")",
";",
"}"
] | Decrypts the given ciphertext in base 64 using the given AWS.KMS instance & returns the decrypted plaintext.
@param {AWS.KMS} kms - an AWS.KMS instance to use
@param {string} ciphertextBase64 - the encrypted ciphertext in base 64 encoding
@param {Logger|console|undefined} [logger] - an optional logger to use (defaults to console if omitted)
@returns {Promise.<string>} a promise of the decrypted plaintext | [
"Decrypts",
"the",
"given",
"ciphertext",
"in",
"base",
"64",
"using",
"the",
"given",
"AWS",
".",
"KMS",
"instance",
"&",
"returns",
"the",
"decrypted",
"plaintext",
"."
] | 2530155b5afc102f61658b28183a16027ecae86a | https://github.com/byron-dupreez/aws-core-utils/blob/2530155b5afc102f61658b28183a16027ecae86a/kms-utils.js#L79-L82 | train |
zerobias/humint | index.js | genericLog | function genericLog(logger, moduletag, logLevel='info'){
const isDebug = logLevel==='debug'
const level = isDebug
? 'info'
: logLevel
const levelLogger = logger[level]
const active = isDebug
? enabled(moduletag)
: true
/**
* tagged Logger
* @function taggedLog
* @param {...string} tags Optional message tags
*/
function taggedLog(...tags) {
const tag = normalizeDefaults(tags)
/**
* message Logger
* @function messageLog
* @template T
* @param {...T} messages message
* @returns {T}
*/
function messageLog(...messages) {
if (active) {
const protectedMessage = messageArrayProtect(messages)
levelLogger(tag, ...protectedMessage)
}
return messages[0]
}
return messageLog
}
/**
* Array logge Prinst every value on separated line
* @function mapLog
* @param {...string} tags Optional message tags
*/
function mapLog(...tags) {
/**
* Array logge Prinst every value on separated line
* @function printArray
* @param {Array} message Printed list
* @returns {Array}
*/
function printArray(message) {
if (active) {
arrayCheck(message)
const tag = normalizeDefaults(tags)
//count length + 2. Also handles edge case with objects without 'length' field
const spaceLn = P(
length,
defaultTo(0),
add(2) )
const ln = sum( map( spaceLn, tags ) )
const spaces = new Array(ln)
.fill(' ')
.join('')
const getFormatted = num => chalk.green(`<${num}>`)
levelLogger( tag, getFormatted(0), head( message ) )
const printTail = (e, i) => levelLogger(spaces, getFormatted(i+1), e)
P(
tail,
indexedMap(printTail)
)(message)
}
return message
}
return printArray
}
taggedLog.map = mapLog
return taggedLog
} | javascript | function genericLog(logger, moduletag, logLevel='info'){
const isDebug = logLevel==='debug'
const level = isDebug
? 'info'
: logLevel
const levelLogger = logger[level]
const active = isDebug
? enabled(moduletag)
: true
/**
* tagged Logger
* @function taggedLog
* @param {...string} tags Optional message tags
*/
function taggedLog(...tags) {
const tag = normalizeDefaults(tags)
/**
* message Logger
* @function messageLog
* @template T
* @param {...T} messages message
* @returns {T}
*/
function messageLog(...messages) {
if (active) {
const protectedMessage = messageArrayProtect(messages)
levelLogger(tag, ...protectedMessage)
}
return messages[0]
}
return messageLog
}
/**
* Array logge Prinst every value on separated line
* @function mapLog
* @param {...string} tags Optional message tags
*/
function mapLog(...tags) {
/**
* Array logge Prinst every value on separated line
* @function printArray
* @param {Array} message Printed list
* @returns {Array}
*/
function printArray(message) {
if (active) {
arrayCheck(message)
const tag = normalizeDefaults(tags)
//count length + 2. Also handles edge case with objects without 'length' field
const spaceLn = P(
length,
defaultTo(0),
add(2) )
const ln = sum( map( spaceLn, tags ) )
const spaces = new Array(ln)
.fill(' ')
.join('')
const getFormatted = num => chalk.green(`<${num}>`)
levelLogger( tag, getFormatted(0), head( message ) )
const printTail = (e, i) => levelLogger(spaces, getFormatted(i+1), e)
P(
tail,
indexedMap(printTail)
)(message)
}
return message
}
return printArray
}
taggedLog.map = mapLog
return taggedLog
} | [
"function",
"genericLog",
"(",
"logger",
",",
"moduletag",
",",
"logLevel",
"=",
"'info'",
")",
"{",
"const",
"isDebug",
"=",
"logLevel",
"===",
"'debug'",
"const",
"level",
"=",
"isDebug",
"?",
"'info'",
":",
"logLevel",
"const",
"levelLogger",
"=",
"logger",
"[",
"level",
"]",
"const",
"active",
"=",
"isDebug",
"?",
"enabled",
"(",
"moduletag",
")",
":",
"true",
"function",
"taggedLog",
"(",
"...",
"tags",
")",
"{",
"const",
"tag",
"=",
"normalizeDefaults",
"(",
"tags",
")",
"function",
"messageLog",
"(",
"...",
"messages",
")",
"{",
"if",
"(",
"active",
")",
"{",
"const",
"protectedMessage",
"=",
"messageArrayProtect",
"(",
"messages",
")",
"levelLogger",
"(",
"tag",
",",
"...",
"protectedMessage",
")",
"}",
"return",
"messages",
"[",
"0",
"]",
"}",
"return",
"messageLog",
"}",
"function",
"mapLog",
"(",
"...",
"tags",
")",
"{",
"function",
"printArray",
"(",
"message",
")",
"{",
"if",
"(",
"active",
")",
"{",
"arrayCheck",
"(",
"message",
")",
"const",
"tag",
"=",
"normalizeDefaults",
"(",
"tags",
")",
"const",
"spaceLn",
"=",
"P",
"(",
"length",
",",
"defaultTo",
"(",
"0",
")",
",",
"add",
"(",
"2",
")",
")",
"const",
"ln",
"=",
"sum",
"(",
"map",
"(",
"spaceLn",
",",
"tags",
")",
")",
"const",
"spaces",
"=",
"new",
"Array",
"(",
"ln",
")",
".",
"fill",
"(",
"' '",
")",
".",
"join",
"(",
"''",
")",
"const",
"getFormatted",
"=",
"num",
"=>",
"chalk",
".",
"green",
"(",
"`",
"${",
"num",
"}",
"`",
")",
"levelLogger",
"(",
"tag",
",",
"getFormatted",
"(",
"0",
")",
",",
"head",
"(",
"message",
")",
")",
"const",
"printTail",
"=",
"(",
"e",
",",
"i",
")",
"=>",
"levelLogger",
"(",
"spaces",
",",
"getFormatted",
"(",
"i",
"+",
"1",
")",
",",
"e",
")",
"P",
"(",
"tail",
",",
"indexedMap",
"(",
"printTail",
")",
")",
"(",
"message",
")",
"}",
"return",
"message",
"}",
"return",
"printArray",
"}",
"taggedLog",
".",
"map",
"=",
"mapLog",
"return",
"taggedLog",
"}"
] | Allow to select log level
@function genericLog
@param {LoggerInstance} logger Winston logger instance
@param {string} moduletag Module tag name
@param {string} logLevel Log level | [
"Allow",
"to",
"select",
"log",
"level"
] | e4074de0a6e972b651a3d38c722cb5d28a24a548 | https://github.com/zerobias/humint/blob/e4074de0a6e972b651a3d38c722cb5d28a24a548/index.js#L77-L151 | train |
zerobias/humint | index.js | mapLog | function mapLog(...tags) {
/**
* Array logge Prinst every value on separated line
* @function printArray
* @param {Array} message Printed list
* @returns {Array}
*/
function printArray(message) {
if (active) {
arrayCheck(message)
const tag = normalizeDefaults(tags)
//count length + 2. Also handles edge case with objects without 'length' field
const spaceLn = P(
length,
defaultTo(0),
add(2) )
const ln = sum( map( spaceLn, tags ) )
const spaces = new Array(ln)
.fill(' ')
.join('')
const getFormatted = num => chalk.green(`<${num}>`)
levelLogger( tag, getFormatted(0), head( message ) )
const printTail = (e, i) => levelLogger(spaces, getFormatted(i+1), e)
P(
tail,
indexedMap(printTail)
)(message)
}
return message
}
return printArray
} | javascript | function mapLog(...tags) {
/**
* Array logge Prinst every value on separated line
* @function printArray
* @param {Array} message Printed list
* @returns {Array}
*/
function printArray(message) {
if (active) {
arrayCheck(message)
const tag = normalizeDefaults(tags)
//count length + 2. Also handles edge case with objects without 'length' field
const spaceLn = P(
length,
defaultTo(0),
add(2) )
const ln = sum( map( spaceLn, tags ) )
const spaces = new Array(ln)
.fill(' ')
.join('')
const getFormatted = num => chalk.green(`<${num}>`)
levelLogger( tag, getFormatted(0), head( message ) )
const printTail = (e, i) => levelLogger(spaces, getFormatted(i+1), e)
P(
tail,
indexedMap(printTail)
)(message)
}
return message
}
return printArray
} | [
"function",
"mapLog",
"(",
"...",
"tags",
")",
"{",
"function",
"printArray",
"(",
"message",
")",
"{",
"if",
"(",
"active",
")",
"{",
"arrayCheck",
"(",
"message",
")",
"const",
"tag",
"=",
"normalizeDefaults",
"(",
"tags",
")",
"const",
"spaceLn",
"=",
"P",
"(",
"length",
",",
"defaultTo",
"(",
"0",
")",
",",
"add",
"(",
"2",
")",
")",
"const",
"ln",
"=",
"sum",
"(",
"map",
"(",
"spaceLn",
",",
"tags",
")",
")",
"const",
"spaces",
"=",
"new",
"Array",
"(",
"ln",
")",
".",
"fill",
"(",
"' '",
")",
".",
"join",
"(",
"''",
")",
"const",
"getFormatted",
"=",
"num",
"=>",
"chalk",
".",
"green",
"(",
"`",
"${",
"num",
"}",
"`",
")",
"levelLogger",
"(",
"tag",
",",
"getFormatted",
"(",
"0",
")",
",",
"head",
"(",
"message",
")",
")",
"const",
"printTail",
"=",
"(",
"e",
",",
"i",
")",
"=>",
"levelLogger",
"(",
"spaces",
",",
"getFormatted",
"(",
"i",
"+",
"1",
")",
",",
"e",
")",
"P",
"(",
"tail",
",",
"indexedMap",
"(",
"printTail",
")",
")",
"(",
"message",
")",
"}",
"return",
"message",
"}",
"return",
"printArray",
"}"
] | Array logge Prinst every value on separated line
@function mapLog
@param {...string} tags Optional message tags | [
"Array",
"logge",
"Prinst",
"every",
"value",
"on",
"separated",
"line"
] | e4074de0a6e972b651a3d38c722cb5d28a24a548 | https://github.com/zerobias/humint/blob/e4074de0a6e972b651a3d38c722cb5d28a24a548/index.js#L115-L148 | train |
zerobias/humint | index.js | Logger | function Logger(moduletag) {
const trimmedModule = trim(moduletag)
winston.loggers.add(trimmedModule, {
console: {
colorize: true,
label : trimmedModule
}
})
const logger = winston.loggers.get(trimmedModule)
const defs = genericLog(logger, trimmedModule)
defs.warn = genericLog(logger, trimmedModule, 'warn')
defs.error = genericLog(logger, trimmedModule, 'error')
defs.debug = genericLog(logger, trimmedModule, 'debug')
defs.info = genericLog(logger, trimmedModule, 'info')
return defs
} | javascript | function Logger(moduletag) {
const trimmedModule = trim(moduletag)
winston.loggers.add(trimmedModule, {
console: {
colorize: true,
label : trimmedModule
}
})
const logger = winston.loggers.get(trimmedModule)
const defs = genericLog(logger, trimmedModule)
defs.warn = genericLog(logger, trimmedModule, 'warn')
defs.error = genericLog(logger, trimmedModule, 'error')
defs.debug = genericLog(logger, trimmedModule, 'debug')
defs.info = genericLog(logger, trimmedModule, 'info')
return defs
} | [
"function",
"Logger",
"(",
"moduletag",
")",
"{",
"const",
"trimmedModule",
"=",
"trim",
"(",
"moduletag",
")",
"winston",
".",
"loggers",
".",
"add",
"(",
"trimmedModule",
",",
"{",
"console",
":",
"{",
"colorize",
":",
"true",
",",
"label",
":",
"trimmedModule",
"}",
"}",
")",
"const",
"logger",
"=",
"winston",
".",
"loggers",
".",
"get",
"(",
"trimmedModule",
")",
"const",
"defs",
"=",
"genericLog",
"(",
"logger",
",",
"trimmedModule",
")",
"defs",
".",
"warn",
"=",
"genericLog",
"(",
"logger",
",",
"trimmedModule",
",",
"'warn'",
")",
"defs",
".",
"error",
"=",
"genericLog",
"(",
"logger",
",",
"trimmedModule",
",",
"'error'",
")",
"defs",
".",
"debug",
"=",
"genericLog",
"(",
"logger",
",",
"trimmedModule",
",",
"'debug'",
")",
"defs",
".",
"info",
"=",
"genericLog",
"(",
"logger",
",",
"trimmedModule",
",",
"'info'",
")",
"return",
"defs",
"}"
] | Logging function based on winston library
@function Logger
@param {string} moduletag Name of apps module | [
"Logging",
"function",
"based",
"on",
"winston",
"library"
] | e4074de0a6e972b651a3d38c722cb5d28a24a548 | https://github.com/zerobias/humint/blob/e4074de0a6e972b651a3d38c722cb5d28a24a548/index.js#L157-L172 | train |
byron-dupreez/aws-core-utils | lambdas.js | getInvokedFunctionArnFunctionName | function getInvokedFunctionArnFunctionName(awsContext) {
const invokedFunctionArn = awsContext && awsContext.invokedFunctionArn;
const resources = getArnResources(invokedFunctionArn);
return resources.resource;
} | javascript | function getInvokedFunctionArnFunctionName(awsContext) {
const invokedFunctionArn = awsContext && awsContext.invokedFunctionArn;
const resources = getArnResources(invokedFunctionArn);
return resources.resource;
} | [
"function",
"getInvokedFunctionArnFunctionName",
"(",
"awsContext",
")",
"{",
"const",
"invokedFunctionArn",
"=",
"awsContext",
"&&",
"awsContext",
".",
"invokedFunctionArn",
";",
"const",
"resources",
"=",
"getArnResources",
"(",
"invokedFunctionArn",
")",
";",
"return",
"resources",
".",
"resource",
";",
"}"
] | Extracts and returns the function name from the given AWS context's invokedFunctionArn.
@param {AWSContext} awsContext - the AWS context
@returns {string} the extracted function name | [
"Extracts",
"and",
"returns",
"the",
"function",
"name",
"from",
"the",
"given",
"AWS",
"context",
"s",
"invokedFunctionArn",
"."
] | 2530155b5afc102f61658b28183a16027ecae86a | https://github.com/byron-dupreez/aws-core-utils/blob/2530155b5afc102f61658b28183a16027ecae86a/lambdas.js#L59-L63 | train |
CodeMan99/wotblitz.js | wotblitz.js | function(search, type, limit, fields) {
if (!search) return Promise.reject(new Error('wotblitz.account.list: search is required'));
return request({
hostname: hosts.wotb,
path: '/wotb/account/list/'
}, {
fields: fields ? fields.toString() : '',
limit: limit,
search: search,
type: type
});
} | javascript | function(search, type, limit, fields) {
if (!search) return Promise.reject(new Error('wotblitz.account.list: search is required'));
return request({
hostname: hosts.wotb,
path: '/wotb/account/list/'
}, {
fields: fields ? fields.toString() : '',
limit: limit,
search: search,
type: type
});
} | [
"function",
"(",
"search",
",",
"type",
",",
"limit",
",",
"fields",
")",
"{",
"if",
"(",
"!",
"search",
")",
"return",
"Promise",
".",
"reject",
"(",
"new",
"Error",
"(",
"'wotblitz.account.list: search is required'",
")",
")",
";",
"return",
"request",
"(",
"{",
"hostname",
":",
"hosts",
".",
"wotb",
",",
"path",
":",
"'/wotb/account/list/'",
"}",
",",
"{",
"fields",
":",
"fields",
"?",
"fields",
".",
"toString",
"(",
")",
":",
"''",
",",
"limit",
":",
"limit",
",",
"search",
":",
"search",
",",
"type",
":",
"type",
"}",
")",
";",
"}"
] | Search for a player.
@param {string} search value to match usernames
@param {string} [type] how to match, "startswith" or "exact"
@param {number} [limit] maximum number of entries to match
@param {string|string[]} [fields] response selection
@returns {Promise<Object[]> resolves to an array of matching accounts | [
"Search",
"for",
"a",
"player",
"."
] | d4a56e4523704418029e2b9846410b31a8d69478 | https://github.com/CodeMan99/wotblitz.js/blob/d4a56e4523704418029e2b9846410b31a8d69478/wotblitz.js#L158-L170 | train |
|
CodeMan99/wotblitz.js | wotblitz.js | function(access_token, expires_at) {
if (!access_token) return Promise.reject(new Error('wotblitz.auth.prolongate: access_token is required'));
return request({
hostname: hosts.wot,
path: '/wot/auth/prolongate/'
}, {
access_token: access_token,
expires_at: expires_at || 14 * 24 * 60 * 60 // 14 days in seconds
});
} | javascript | function(access_token, expires_at) {
if (!access_token) return Promise.reject(new Error('wotblitz.auth.prolongate: access_token is required'));
return request({
hostname: hosts.wot,
path: '/wot/auth/prolongate/'
}, {
access_token: access_token,
expires_at: expires_at || 14 * 24 * 60 * 60 // 14 days in seconds
});
} | [
"function",
"(",
"access_token",
",",
"expires_at",
")",
"{",
"if",
"(",
"!",
"access_token",
")",
"return",
"Promise",
".",
"reject",
"(",
"new",
"Error",
"(",
"'wotblitz.auth.prolongate: access_token is required'",
")",
")",
";",
"return",
"request",
"(",
"{",
"hostname",
":",
"hosts",
".",
"wot",
",",
"path",
":",
"'/wot/auth/prolongate/'",
"}",
",",
"{",
"access_token",
":",
"access_token",
",",
"expires_at",
":",
"expires_at",
"||",
"14",
"*",
"24",
"*",
"60",
"*",
"60",
"}",
")",
";",
"}"
] | Access token extension
@param {string} access_token user's authentication string
@param {number} [expires_at] date or time span of expiration (default: 14 days)
@returns {Promise<Object>} resolves to the new token and related information | [
"Access",
"token",
"extension"
] | d4a56e4523704418029e2b9846410b31a8d69478 | https://github.com/CodeMan99/wotblitz.js/blob/d4a56e4523704418029e2b9846410b31a8d69478/wotblitz.js#L264-L274 | train |
|
CodeMan99/wotblitz.js | wotblitz.js | function(access_token, message_id, filters, fields) {
if (!access_token) return Promise.reject(new Error('wotblitz.clanmessages.messages: access_token is required'));
return request({
hostname: hosts.wotb,
path: '/wotb/clanmessages/messages/'
}, Object.assign({
access_token: access_token,
message_id: message_id,
fields: fields ? fields.toString() : ''
}, filters, {
order_by: filters && filters.order_by ? filters.order_by.toString() : ''
}));
} | javascript | function(access_token, message_id, filters, fields) {
if (!access_token) return Promise.reject(new Error('wotblitz.clanmessages.messages: access_token is required'));
return request({
hostname: hosts.wotb,
path: '/wotb/clanmessages/messages/'
}, Object.assign({
access_token: access_token,
message_id: message_id,
fields: fields ? fields.toString() : ''
}, filters, {
order_by: filters && filters.order_by ? filters.order_by.toString() : ''
}));
} | [
"function",
"(",
"access_token",
",",
"message_id",
",",
"filters",
",",
"fields",
")",
"{",
"if",
"(",
"!",
"access_token",
")",
"return",
"Promise",
".",
"reject",
"(",
"new",
"Error",
"(",
"'wotblitz.clanmessages.messages: access_token is required'",
")",
")",
";",
"return",
"request",
"(",
"{",
"hostname",
":",
"hosts",
".",
"wotb",
",",
"path",
":",
"'/wotb/clanmessages/messages/'",
"}",
",",
"Object",
".",
"assign",
"(",
"{",
"access_token",
":",
"access_token",
",",
"message_id",
":",
"message_id",
",",
"fields",
":",
"fields",
"?",
"fields",
".",
"toString",
"(",
")",
":",
"''",
"}",
",",
"filters",
",",
"{",
"order_by",
":",
"filters",
"&&",
"filters",
".",
"order_by",
"?",
"filters",
".",
"order_by",
".",
"toString",
"(",
")",
":",
"''",
"}",
")",
")",
";",
"}"
] | The text and meta data of all conversation.
@param {string} access_token user's authentication string
@param {number} [message_id] a specific message
@param {Object} [filters] options
@param {number} [filters.page_no] which page
@param {number} [filters.limit] how many per page
@param {string|string[]} [filters.order_by] which field(s) to order the response (too many values to list)
@param {number|date} [filters.expires_before] only messages before this date (unix or ISO)
@param {number|date} [filters.expires_after] only messages on or after this date (unix or ISO)
@param {string} [filters.importance] only messages with this level, values "important" or "standard"
@param {string} [filters.status] only messages with this status, values "active" or "deleted"
@param {string} [filters.type] only messages of this type, values "general", "training", "meeting", or "battle"
@param {string|string[]} [fields] response selection
@returns {Promise<Object>} resolves to a message board object | [
"The",
"text",
"and",
"meta",
"data",
"of",
"all",
"conversation",
"."
] | d4a56e4523704418029e2b9846410b31a8d69478 | https://github.com/CodeMan99/wotblitz.js/blob/d4a56e4523704418029e2b9846410b31a8d69478/wotblitz.js#L311-L324 | train |
|
CodeMan99/wotblitz.js | wotblitz.js | function(access_token, title, text, type, importance, expires_at) {
if (!expires_at) return Promise.reject(new Error('wotblitz.clanmessages.create: all arguments are required'));
return request({
hostname: hosts.wotb,
path: '/wotb/clanmessages/create/'
}, {
access_token: access_token,
expires_at: expires_at,
importance: importance,
text: text,
title: title,
type: type
});
} | javascript | function(access_token, title, text, type, importance, expires_at) {
if (!expires_at) return Promise.reject(new Error('wotblitz.clanmessages.create: all arguments are required'));
return request({
hostname: hosts.wotb,
path: '/wotb/clanmessages/create/'
}, {
access_token: access_token,
expires_at: expires_at,
importance: importance,
text: text,
title: title,
type: type
});
} | [
"function",
"(",
"access_token",
",",
"title",
",",
"text",
",",
"type",
",",
"importance",
",",
"expires_at",
")",
"{",
"if",
"(",
"!",
"expires_at",
")",
"return",
"Promise",
".",
"reject",
"(",
"new",
"Error",
"(",
"'wotblitz.clanmessages.create: all arguments are required'",
")",
")",
";",
"return",
"request",
"(",
"{",
"hostname",
":",
"hosts",
".",
"wotb",
",",
"path",
":",
"'/wotb/clanmessages/create/'",
"}",
",",
"{",
"access_token",
":",
"access_token",
",",
"expires_at",
":",
"expires_at",
",",
"importance",
":",
"importance",
",",
"text",
":",
"text",
",",
"title",
":",
"title",
",",
"type",
":",
"type",
"}",
")",
";",
"}"
] | Post a new message.
@param {string} access_token user's authentication string
@param {string} title message topic
@param {string} text message body
@param {string} type message category, values "general", "training", "meeting", or "battle"
@param {string} importance values "important" or "standard"
@param {string} expires_at invalidation date
@returns {Promise<Object>} resolves to the `message_id` | [
"Post",
"a",
"new",
"message",
"."
] | d4a56e4523704418029e2b9846410b31a8d69478 | https://github.com/CodeMan99/wotblitz.js/blob/d4a56e4523704418029e2b9846410b31a8d69478/wotblitz.js#L336-L350 | train |
|
CodeMan99/wotblitz.js | wotblitz.js | function(access_token, message_id) {
if (!message_id) return Promise.reject(new Error('wotblitz.clanmessages.delete: all arguments are required'));
return request({
hostname: hosts.wotb,
path: '/wotb/clanmessages/delete/'
}, {
access_token: access_token,
message_id: message_id
});
} | javascript | function(access_token, message_id) {
if (!message_id) return Promise.reject(new Error('wotblitz.clanmessages.delete: all arguments are required'));
return request({
hostname: hosts.wotb,
path: '/wotb/clanmessages/delete/'
}, {
access_token: access_token,
message_id: message_id
});
} | [
"function",
"(",
"access_token",
",",
"message_id",
")",
"{",
"if",
"(",
"!",
"message_id",
")",
"return",
"Promise",
".",
"reject",
"(",
"new",
"Error",
"(",
"'wotblitz.clanmessages.delete: all arguments are required'",
")",
")",
";",
"return",
"request",
"(",
"{",
"hostname",
":",
"hosts",
".",
"wotb",
",",
"path",
":",
"'/wotb/clanmessages/delete/'",
"}",
",",
"{",
"access_token",
":",
"access_token",
",",
"message_id",
":",
"message_id",
"}",
")",
";",
"}"
] | Remove a message.
@param {string} access_token user's authentication string
@param {number} message_id exactly this message
@returns {Promise<Object>} resolves to an empty object | [
"Remove",
"a",
"message",
"."
] | d4a56e4523704418029e2b9846410b31a8d69478 | https://github.com/CodeMan99/wotblitz.js/blob/d4a56e4523704418029e2b9846410b31a8d69478/wotblitz.js#L358-L368 | train |
|
CodeMan99/wotblitz.js | wotblitz.js | function(access_token, message_id, action) {
if (!action) return Promise.reject(new Error('wotblitz.clanmessages.like: all arguments are required'));
return request({
hostname: hosts.wotb,
path: '/wotb/clanmessages/like/'
}, {
access_token,
action: action,
message_id: message_id
});
} | javascript | function(access_token, message_id, action) {
if (!action) return Promise.reject(new Error('wotblitz.clanmessages.like: all arguments are required'));
return request({
hostname: hosts.wotb,
path: '/wotb/clanmessages/like/'
}, {
access_token,
action: action,
message_id: message_id
});
} | [
"function",
"(",
"access_token",
",",
"message_id",
",",
"action",
")",
"{",
"if",
"(",
"!",
"action",
")",
"return",
"Promise",
".",
"reject",
"(",
"new",
"Error",
"(",
"'wotblitz.clanmessages.like: all arguments are required'",
")",
")",
";",
"return",
"request",
"(",
"{",
"hostname",
":",
"hosts",
".",
"wotb",
",",
"path",
":",
"'/wotb/clanmessages/like/'",
"}",
",",
"{",
"access_token",
",",
"action",
":",
"action",
",",
"message_id",
":",
"message_id",
"}",
")",
";",
"}"
] | Set like value on a message.
@param {string} access_token user's authentication string
@param {number} message_id exactly this message
@param {string} action literally "add" or "remove"
@returns {Promise<Object>} resolves to an empty object | [
"Set",
"like",
"value",
"on",
"a",
"message",
"."
] | d4a56e4523704418029e2b9846410b31a8d69478 | https://github.com/CodeMan99/wotblitz.js/blob/d4a56e4523704418029e2b9846410b31a8d69478/wotblitz.js#L377-L388 | train |
|
CodeMan99/wotblitz.js | wotblitz.js | function(access_token, message_id, fields) {
if (!access_token) return Promise.reject(new Error('wotblitz.clanmessages.likes: access_token is required'));
if (!message_id) return Promise.reject(new Error('wotblitz.clanmessages.likes: message_id is required'));
return request({
hostname: hosts.wotb,
path: '/wotb/clanmessages/likes/'
}, {
access_token: access_token,
message_id: message_id,
fields: fields ? fields.toString() : ''
});
} | javascript | function(access_token, message_id, fields) {
if (!access_token) return Promise.reject(new Error('wotblitz.clanmessages.likes: access_token is required'));
if (!message_id) return Promise.reject(new Error('wotblitz.clanmessages.likes: message_id is required'));
return request({
hostname: hosts.wotb,
path: '/wotb/clanmessages/likes/'
}, {
access_token: access_token,
message_id: message_id,
fields: fields ? fields.toString() : ''
});
} | [
"function",
"(",
"access_token",
",",
"message_id",
",",
"fields",
")",
"{",
"if",
"(",
"!",
"access_token",
")",
"return",
"Promise",
".",
"reject",
"(",
"new",
"Error",
"(",
"'wotblitz.clanmessages.likes: access_token is required'",
")",
")",
";",
"if",
"(",
"!",
"message_id",
")",
"return",
"Promise",
".",
"reject",
"(",
"new",
"Error",
"(",
"'wotblitz.clanmessages.likes: message_id is required'",
")",
")",
";",
"return",
"request",
"(",
"{",
"hostname",
":",
"hosts",
".",
"wotb",
",",
"path",
":",
"'/wotb/clanmessages/likes/'",
"}",
",",
"{",
"access_token",
":",
"access_token",
",",
"message_id",
":",
"message_id",
",",
"fields",
":",
"fields",
"?",
"fields",
".",
"toString",
"(",
")",
":",
"''",
"}",
")",
";",
"}"
] | All likes on a message.
@params {string} access_token user's authentication string
@params {number} message_id exactly this message
@params {string|string[]} [fields] response selection
@returns {Promise<Object[]>} resolves to list of by whom and when a like was added | [
"All",
"likes",
"on",
"a",
"message",
"."
] | d4a56e4523704418029e2b9846410b31a8d69478 | https://github.com/CodeMan99/wotblitz.js/blob/d4a56e4523704418029e2b9846410b31a8d69478/wotblitz.js#L397-L409 | train |
|
CodeMan99/wotblitz.js | wotblitz.js | function(search, page_no, limit, fields) {
return request({
hostname: hosts.wotb,
path: '/wotb/clans/list/'
}, {
search: search,
page_no: page_no,
limit: limit,
fields: fields ? fields.toString() : ''
});
} | javascript | function(search, page_no, limit, fields) {
return request({
hostname: hosts.wotb,
path: '/wotb/clans/list/'
}, {
search: search,
page_no: page_no,
limit: limit,
fields: fields ? fields.toString() : ''
});
} | [
"function",
"(",
"search",
",",
"page_no",
",",
"limit",
",",
"fields",
")",
"{",
"return",
"request",
"(",
"{",
"hostname",
":",
"hosts",
".",
"wotb",
",",
"path",
":",
"'/wotb/clans/list/'",
"}",
",",
"{",
"search",
":",
"search",
",",
"page_no",
":",
"page_no",
",",
"limit",
":",
"limit",
",",
"fields",
":",
"fields",
"?",
"fields",
".",
"toString",
"(",
")",
":",
"''",
"}",
")",
";",
"}"
] | List of clans with minimal details.
@param {string} [search] filter by clan name or tag
@param {number} [page_no] which page to return, starting at 1
@param {number} [limit] max count of entries
@param {string|string[]} [fields] response selection
@returns {Promise<Object[]>} resolves to a list of short clan descriptions | [
"List",
"of",
"clans",
"with",
"minimal",
"details",
"."
] | d4a56e4523704418029e2b9846410b31a8d69478 | https://github.com/CodeMan99/wotblitz.js/blob/d4a56e4523704418029e2b9846410b31a8d69478/wotblitz.js#L451-L461 | train |
|
CodeMan99/wotblitz.js | wotblitz.js | function(fields) {
return request({
hostname: hosts.wotb,
path: '/wotb/clans/glossary/'
}, {
fields: fields ? fields.toString() : ''
});
} | javascript | function(fields) {
return request({
hostname: hosts.wotb,
path: '/wotb/clans/glossary/'
}, {
fields: fields ? fields.toString() : ''
});
} | [
"function",
"(",
"fields",
")",
"{",
"return",
"request",
"(",
"{",
"hostname",
":",
"hosts",
".",
"wotb",
",",
"path",
":",
"'/wotb/clans/glossary/'",
"}",
",",
"{",
"fields",
":",
"fields",
"?",
"fields",
".",
"toString",
"(",
")",
":",
"''",
"}",
")",
";",
"}"
] | Meta information about clans.
@param {string|string[]} [fields] response selection
@returns {Promise<Object>} resolves to clan terminology definitions | [
"Meta",
"information",
"about",
"clans",
"."
] | d4a56e4523704418029e2b9846410b31a8d69478 | https://github.com/CodeMan99/wotblitz.js/blob/d4a56e4523704418029e2b9846410b31a8d69478/wotblitz.js#L508-L515 | train |
|
CodeMan99/wotblitz.js | wotblitz.js | function(tank_id, nation, fields) {
return request({
hostname: hosts.wotb,
path: '/wotb/encyclopedia/vehicles/'
}, {
tank_id: tank_id ? tank_id.toString() : '',
nation: nation ? nation.toString() : '',
fields: fields ? fields.toString() : ''
});
} | javascript | function(tank_id, nation, fields) {
return request({
hostname: hosts.wotb,
path: '/wotb/encyclopedia/vehicles/'
}, {
tank_id: tank_id ? tank_id.toString() : '',
nation: nation ? nation.toString() : '',
fields: fields ? fields.toString() : ''
});
} | [
"function",
"(",
"tank_id",
",",
"nation",
",",
"fields",
")",
"{",
"return",
"request",
"(",
"{",
"hostname",
":",
"hosts",
".",
"wotb",
",",
"path",
":",
"'/wotb/encyclopedia/vehicles/'",
"}",
",",
"{",
"tank_id",
":",
"tank_id",
"?",
"tank_id",
".",
"toString",
"(",
")",
":",
"''",
",",
"nation",
":",
"nation",
"?",
"nation",
".",
"toString",
"(",
")",
":",
"''",
",",
"fields",
":",
"fields",
"?",
"fields",
".",
"toString",
"(",
")",
":",
"''",
"}",
")",
";",
"}"
] | List of vehicle information
@param {number|number[]} [tank_id] limit to this vehicle id(s) only
@param {string|string[]} [nation] limit to vehicle in this tech tree(s)
@param {string|string[]} [fields] response selection
@returns {Promise<Object>} resolves to description of requested vehicles | [
"List",
"of",
"vehicle",
"information"
] | d4a56e4523704418029e2b9846410b31a8d69478 | https://github.com/CodeMan99/wotblitz.js/blob/d4a56e4523704418029e2b9846410b31a8d69478/wotblitz.js#L527-L536 | train |
|
CodeMan99/wotblitz.js | wotblitz.js | function(tank_id, profile_id, modules, fields) {
if (!tank_id) return Promise.reject(new Error('wotblitz.encyclopedia.vehicleprofile: tank_id is required'));
return request({
hostname: hosts.wotb,
path: '/wotb/encyclopedia/vehicleprofile/'
}, Object.assign({
tank_id: tank_id,
fields: fields ? fields.toString() : ''
}, modules || {
profile_id: profile_id
}));
} | javascript | function(tank_id, profile_id, modules, fields) {
if (!tank_id) return Promise.reject(new Error('wotblitz.encyclopedia.vehicleprofile: tank_id is required'));
return request({
hostname: hosts.wotb,
path: '/wotb/encyclopedia/vehicleprofile/'
}, Object.assign({
tank_id: tank_id,
fields: fields ? fields.toString() : ''
}, modules || {
profile_id: profile_id
}));
} | [
"function",
"(",
"tank_id",
",",
"profile_id",
",",
"modules",
",",
"fields",
")",
"{",
"if",
"(",
"!",
"tank_id",
")",
"return",
"Promise",
".",
"reject",
"(",
"new",
"Error",
"(",
"'wotblitz.encyclopedia.vehicleprofile: tank_id is required'",
")",
")",
";",
"return",
"request",
"(",
"{",
"hostname",
":",
"hosts",
".",
"wotb",
",",
"path",
":",
"'/wotb/encyclopedia/vehicleprofile/'",
"}",
",",
"Object",
".",
"assign",
"(",
"{",
"tank_id",
":",
"tank_id",
",",
"fields",
":",
"fields",
"?",
"fields",
".",
"toString",
"(",
")",
":",
"''",
"}",
",",
"modules",
"||",
"{",
"profile_id",
":",
"profile_id",
"}",
")",
")",
";",
"}"
] | Characteristics with different vehicle modules installed.
@param {string} tank_id vehicle to select
@param {string} [profile_id] shorthand returned by the "vehicleprofiles" route
@param {Object} [modules] specify modules individually (overrides profile_id)
@param {number} [modules.engine_id] which engine module to select
@param {number} [modules.gun_id] which gun module to select
@param {number} [modules.suspension_id] which suspension module to select
@param {number} [modules.turret_id] which turret module to select
@param {string|string[]} [fields] response selection
@returns {Promise<Object>} resolves to exact vehicle information | [
"Characteristics",
"with",
"different",
"vehicle",
"modules",
"installed",
"."
] | d4a56e4523704418029e2b9846410b31a8d69478 | https://github.com/CodeMan99/wotblitz.js/blob/d4a56e4523704418029e2b9846410b31a8d69478/wotblitz.js#L550-L562 | train |
|
CodeMan99/wotblitz.js | wotblitz.js | function(module_id, fields) {
return request({
hostname: hosts.wotb,
path: '/wotb/encyclopedia/modules/'
}, {
module_id: module_id ? module_id.toString() : '',
fields: fields ? fields.toString() : ''
});
} | javascript | function(module_id, fields) {
return request({
hostname: hosts.wotb,
path: '/wotb/encyclopedia/modules/'
}, {
module_id: module_id ? module_id.toString() : '',
fields: fields ? fields.toString() : ''
});
} | [
"function",
"(",
"module_id",
",",
"fields",
")",
"{",
"return",
"request",
"(",
"{",
"hostname",
":",
"hosts",
".",
"wotb",
",",
"path",
":",
"'/wotb/encyclopedia/modules/'",
"}",
",",
"{",
"module_id",
":",
"module_id",
"?",
"module_id",
".",
"toString",
"(",
")",
":",
"''",
",",
"fields",
":",
"fields",
"?",
"fields",
".",
"toString",
"(",
")",
":",
"''",
"}",
")",
";",
"}"
] | Information on any engine, suspension, gun, or turret.
@params {number|number[]} [module_id] id of any vehicle's module
@params {string|string[]} [fields] response selection
@returns {Promise<Object>} resolves to description of each module | [
"Information",
"on",
"any",
"engine",
"suspension",
"gun",
"or",
"turret",
"."
] | d4a56e4523704418029e2b9846410b31a8d69478 | https://github.com/CodeMan99/wotblitz.js/blob/d4a56e4523704418029e2b9846410b31a8d69478/wotblitz.js#L570-L578 | train |
|
CodeMan99/wotblitz.js | wotblitz.js | function(tank_id, provision_id, type, fields) {
return request({
hostname: hosts.wotb,
path: '/wotb/encyclopedia/provisions/'
}, {
tank_id: tank_id ? tank_id.toString() : '',
provision_id: provision_id ? provision_id.toString() : '',
type: type,
fields: fields ? fields.toString() : ''
});
} | javascript | function(tank_id, provision_id, type, fields) {
return request({
hostname: hosts.wotb,
path: '/wotb/encyclopedia/provisions/'
}, {
tank_id: tank_id ? tank_id.toString() : '',
provision_id: provision_id ? provision_id.toString() : '',
type: type,
fields: fields ? fields.toString() : ''
});
} | [
"function",
"(",
"tank_id",
",",
"provision_id",
",",
"type",
",",
"fields",
")",
"{",
"return",
"request",
"(",
"{",
"hostname",
":",
"hosts",
".",
"wotb",
",",
"path",
":",
"'/wotb/encyclopedia/provisions/'",
"}",
",",
"{",
"tank_id",
":",
"tank_id",
"?",
"tank_id",
".",
"toString",
"(",
")",
":",
"''",
",",
"provision_id",
":",
"provision_id",
"?",
"provision_id",
".",
"toString",
"(",
")",
":",
"''",
",",
"type",
":",
"type",
",",
"fields",
":",
"fields",
"?",
"fields",
".",
"toString",
"(",
")",
":",
"''",
"}",
")",
";",
"}"
] | Available equipment and provisions.
@param {number|number[]} [tank_id] select provisions for the given tank(s)
@param {number|number[]} [provision_id] item id
@param {string} [type] provision type, value "optionalDevice" or "equipment"
@param {string|string[]} [fields] response selection
@returns {Promise<Object>} resolves to description of each provision | [
"Available",
"equipment",
"and",
"provisions",
"."
] | d4a56e4523704418029e2b9846410b31a8d69478 | https://github.com/CodeMan99/wotblitz.js/blob/d4a56e4523704418029e2b9846410b31a8d69478/wotblitz.js#L588-L598 | train |
|
CodeMan99/wotblitz.js | wotblitz.js | function(skill_id, vehicle_type, fields) {
return request({
hostname: hosts.wotb,
path: '/wotb/encyclopedia/crewskills/'
}, {
skill_id: skill_id ? skill_id.toString() : '',
vehicle_type: vehicle_type ? vehicle_type.toString() : '',
fields: fields ? fields.toString() : ''
});
} | javascript | function(skill_id, vehicle_type, fields) {
return request({
hostname: hosts.wotb,
path: '/wotb/encyclopedia/crewskills/'
}, {
skill_id: skill_id ? skill_id.toString() : '',
vehicle_type: vehicle_type ? vehicle_type.toString() : '',
fields: fields ? fields.toString() : ''
});
} | [
"function",
"(",
"skill_id",
",",
"vehicle_type",
",",
"fields",
")",
"{",
"return",
"request",
"(",
"{",
"hostname",
":",
"hosts",
".",
"wotb",
",",
"path",
":",
"'/wotb/encyclopedia/crewskills/'",
"}",
",",
"{",
"skill_id",
":",
"skill_id",
"?",
"skill_id",
".",
"toString",
"(",
")",
":",
"''",
",",
"vehicle_type",
":",
"vehicle_type",
"?",
"vehicle_type",
".",
"toString",
"(",
")",
":",
"''",
",",
"fields",
":",
"fields",
"?",
"fields",
".",
"toString",
"(",
")",
":",
"''",
"}",
")",
";",
"}"
] | Description of crew skills.
@params {string|string[]} [skill_id] name of skill(s) to request
@params {string|string[]} [vehicle_type] select skill category
@params {string|string[]} [fields] response selection
@returns {Promise<Object>} resolves to the description | [
"Description",
"of",
"crew",
"skills",
"."
] | d4a56e4523704418029e2b9846410b31a8d69478 | https://github.com/CodeMan99/wotblitz.js/blob/d4a56e4523704418029e2b9846410b31a8d69478/wotblitz.js#L635-L644 | train |
|
CodeMan99/wotblitz.js | wotblitz.js | function(options, fields) {
options = Object.assign({
search: null,
status: null,
page_no: null,
limit: null
}, options, {
fields: fields ? fields.toString() : ''
});
if (Array.isArray(options.status)) options.status = options.status.toString();
return request({
hostname: hosts.wotb,
path: '/wotb/tournaments/list/'
}, options);
} | javascript | function(options, fields) {
options = Object.assign({
search: null,
status: null,
page_no: null,
limit: null
}, options, {
fields: fields ? fields.toString() : ''
});
if (Array.isArray(options.status)) options.status = options.status.toString();
return request({
hostname: hosts.wotb,
path: '/wotb/tournaments/list/'
}, options);
} | [
"function",
"(",
"options",
",",
"fields",
")",
"{",
"options",
"=",
"Object",
".",
"assign",
"(",
"{",
"search",
":",
"null",
",",
"status",
":",
"null",
",",
"page_no",
":",
"null",
",",
"limit",
":",
"null",
"}",
",",
"options",
",",
"{",
"fields",
":",
"fields",
"?",
"fields",
".",
"toString",
"(",
")",
":",
"''",
"}",
")",
";",
"if",
"(",
"Array",
".",
"isArray",
"(",
"options",
".",
"status",
")",
")",
"options",
".",
"status",
"=",
"options",
".",
"status",
".",
"toString",
"(",
")",
";",
"return",
"request",
"(",
"{",
"hostname",
":",
"hosts",
".",
"wotb",
",",
"path",
":",
"'/wotb/tournaments/list/'",
"}",
",",
"options",
")",
";",
"}"
] | List of all tournaments.
@param {Object} [options]
@param {string} [options.search]
@param {string|string[]} [options.status]
@param {number} [options.page_no]
@param {number} [options.limit]
@param {string|string[]} [fields] response selection
@returns {Promise<Object>} | [
"List",
"of",
"all",
"tournaments",
"."
] | d4a56e4523704418029e2b9846410b31a8d69478 | https://github.com/CodeMan99/wotblitz.js/blob/d4a56e4523704418029e2b9846410b31a8d69478/wotblitz.js#L749-L765 | train |
|
d5/deep-defaults | lib/index.js | _deepDefaults | function _deepDefaults(dest, src) {
if(_.isUndefined(dest) || _.isNull(dest) || !_.isPlainObject(dest)) { return dest; }
_.each(src, function(v, k) {
if(_.isUndefined(dest[k])) {
dest[k] = v;
} else if(_.isPlainObject(v)) {
_deepDefaults(dest[k], v);
}
});
return dest;
} | javascript | function _deepDefaults(dest, src) {
if(_.isUndefined(dest) || _.isNull(dest) || !_.isPlainObject(dest)) { return dest; }
_.each(src, function(v, k) {
if(_.isUndefined(dest[k])) {
dest[k] = v;
} else if(_.isPlainObject(v)) {
_deepDefaults(dest[k], v);
}
});
return dest;
} | [
"function",
"_deepDefaults",
"(",
"dest",
",",
"src",
")",
"{",
"if",
"(",
"_",
".",
"isUndefined",
"(",
"dest",
")",
"||",
"_",
".",
"isNull",
"(",
"dest",
")",
"||",
"!",
"_",
".",
"isPlainObject",
"(",
"dest",
")",
")",
"{",
"return",
"dest",
";",
"}",
"_",
".",
"each",
"(",
"src",
",",
"function",
"(",
"v",
",",
"k",
")",
"{",
"if",
"(",
"_",
".",
"isUndefined",
"(",
"dest",
"[",
"k",
"]",
")",
")",
"{",
"dest",
"[",
"k",
"]",
"=",
"v",
";",
"}",
"else",
"if",
"(",
"_",
".",
"isPlainObject",
"(",
"v",
")",
")",
"{",
"_deepDefaults",
"(",
"dest",
"[",
"k",
"]",
",",
"v",
")",
";",
"}",
"}",
")",
";",
"return",
"dest",
";",
"}"
] | Recursively assigns own enumerable properties of the source object to the destination object for all destination properties that resolve to undefined.
@param {Object} dest destination object; this object is modified.
@param {Object} src source object that has the defaults
@returns {Object} destination object | [
"Recursively",
"assigns",
"own",
"enumerable",
"properties",
"of",
"the",
"source",
"object",
"to",
"the",
"destination",
"object",
"for",
"all",
"destination",
"properties",
"that",
"resolve",
"to",
"undefined",
"."
] | 321d0e2231aa807d54e7f95d75c22048a806923f | https://github.com/d5/deep-defaults/blob/321d0e2231aa807d54e7f95d75c22048a806923f/lib/index.js#L11-L23 | train |
evanshortiss/browser-local-storage | lib/LocalStorage.js | genStorageKey | function genStorageKey (ns, key) {
return (ns === '') ? ns.concat(key) : ns.concat('.').concat(key);
} | javascript | function genStorageKey (ns, key) {
return (ns === '') ? ns.concat(key) : ns.concat('.').concat(key);
} | [
"function",
"genStorageKey",
"(",
"ns",
",",
"key",
")",
"{",
"return",
"(",
"ns",
"===",
"''",
")",
"?",
"ns",
".",
"concat",
"(",
"key",
")",
":",
"ns",
".",
"concat",
"(",
"'.'",
")",
".",
"concat",
"(",
"key",
")",
";",
"}"
] | Generate a period separated storage key
@param {String} ns Namespace being used
@param {String} key Actual key of the data
@return {String} The generated namespaced key
@api private | [
"Generate",
"a",
"period",
"separated",
"storage",
"key"
] | c1266354837ab71a04bad2ba40554474aa6381f9 | https://github.com/evanshortiss/browser-local-storage/blob/c1266354837ab71a04bad2ba40554474aa6381f9/lib/LocalStorage.js#L45-L47 | train |
evanshortiss/browser-local-storage | lib/LocalStorage.js | LocalStorage | function LocalStorage (params) {
events.EventEmitter.call(this);
if (!params || typeof params === 'string') {
params = {
ns: params || ''
};
}
this.ns = params.ns || '';
if (typeof this.ns !== 'string') {
throw new Error('Namespace must be a string.');
}
this.preSave = params.preSave || defProcessor;
this.postLoad = params.postLoad || defProcessor;
if (this.preSave && typeof this.preSave !== 'function') {
throw new Error('preSave option must be a function');
}
if (this.postLoad && typeof this.postLoad !== 'function') {
throw new Error('postLoad option must be a function');
}
this.EVENTS = EVENTS;
} | javascript | function LocalStorage (params) {
events.EventEmitter.call(this);
if (!params || typeof params === 'string') {
params = {
ns: params || ''
};
}
this.ns = params.ns || '';
if (typeof this.ns !== 'string') {
throw new Error('Namespace must be a string.');
}
this.preSave = params.preSave || defProcessor;
this.postLoad = params.postLoad || defProcessor;
if (this.preSave && typeof this.preSave !== 'function') {
throw new Error('preSave option must be a function');
}
if (this.postLoad && typeof this.postLoad !== 'function') {
throw new Error('postLoad option must be a function');
}
this.EVENTS = EVENTS;
} | [
"function",
"LocalStorage",
"(",
"params",
")",
"{",
"events",
".",
"EventEmitter",
".",
"call",
"(",
"this",
")",
";",
"if",
"(",
"!",
"params",
"||",
"typeof",
"params",
"===",
"'string'",
")",
"{",
"params",
"=",
"{",
"ns",
":",
"params",
"||",
"''",
"}",
";",
"}",
"this",
".",
"ns",
"=",
"params",
".",
"ns",
"||",
"''",
";",
"if",
"(",
"typeof",
"this",
".",
"ns",
"!==",
"'string'",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Namespace must be a string.'",
")",
";",
"}",
"this",
".",
"preSave",
"=",
"params",
".",
"preSave",
"||",
"defProcessor",
";",
"this",
".",
"postLoad",
"=",
"params",
".",
"postLoad",
"||",
"defProcessor",
";",
"if",
"(",
"this",
".",
"preSave",
"&&",
"typeof",
"this",
".",
"preSave",
"!==",
"'function'",
")",
"{",
"throw",
"new",
"Error",
"(",
"'preSave option must be a function'",
")",
";",
"}",
"if",
"(",
"this",
".",
"postLoad",
"&&",
"typeof",
"this",
".",
"postLoad",
"!==",
"'function'",
")",
"{",
"throw",
"new",
"Error",
"(",
"'postLoad option must be a function'",
")",
";",
"}",
"this",
".",
"EVENTS",
"=",
"EVENTS",
";",
"}"
] | Class used to provide a wrapper over localStorage
@param {String} [ns] Optional namespace for the adpater. | [
"Class",
"used",
"to",
"provide",
"a",
"wrapper",
"over",
"localStorage"
] | c1266354837ab71a04bad2ba40554474aa6381f9 | https://github.com/evanshortiss/browser-local-storage/blob/c1266354837ab71a04bad2ba40554474aa6381f9/lib/LocalStorage.js#L63-L90 | train |
scott-wyatt/sails-stripe | templates/Invoiceitem.template.js | function (invoiceitem, cb) {
Invoiceitem.findOrCreate(invoiceitem.id, invoiceitem)
.exec(function (err, foundInvoiceitem){
if (err) return cb(err);
if (foundInvoiceitem.lastStripeEvent > invoiceitem.lastStripeEvent) return cb(null, foundInvoiceitem);
if (foundInvoiceitem.lastStripeEvent == invoiceitem.lastStripeEvent) return Invoiceitem.afterStripeInvoiceitemUpdated(foundInvoiceitem, function(err, invoiceitem){ return cb(err, invoiceitem)});
Invoiceitem.update(foundInvoiceitem.id, invoiceitem)
.exec(function(err, updatedInvoiceitem){
if (err) return cb(err);
if (!updatedInvoiceitem) return cb(null,null);
Invoiceitem.afterStripeInvoiceitemUpdated(updatedInvoiceitem[0], function(err, invoiceitem){
cb(err, invoiceitem);
});
});
});
} | javascript | function (invoiceitem, cb) {
Invoiceitem.findOrCreate(invoiceitem.id, invoiceitem)
.exec(function (err, foundInvoiceitem){
if (err) return cb(err);
if (foundInvoiceitem.lastStripeEvent > invoiceitem.lastStripeEvent) return cb(null, foundInvoiceitem);
if (foundInvoiceitem.lastStripeEvent == invoiceitem.lastStripeEvent) return Invoiceitem.afterStripeInvoiceitemUpdated(foundInvoiceitem, function(err, invoiceitem){ return cb(err, invoiceitem)});
Invoiceitem.update(foundInvoiceitem.id, invoiceitem)
.exec(function(err, updatedInvoiceitem){
if (err) return cb(err);
if (!updatedInvoiceitem) return cb(null,null);
Invoiceitem.afterStripeInvoiceitemUpdated(updatedInvoiceitem[0], function(err, invoiceitem){
cb(err, invoiceitem);
});
});
});
} | [
"function",
"(",
"invoiceitem",
",",
"cb",
")",
"{",
"Invoiceitem",
".",
"findOrCreate",
"(",
"invoiceitem",
".",
"id",
",",
"invoiceitem",
")",
".",
"exec",
"(",
"function",
"(",
"err",
",",
"foundInvoiceitem",
")",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"err",
")",
";",
"if",
"(",
"foundInvoiceitem",
".",
"lastStripeEvent",
">",
"invoiceitem",
".",
"lastStripeEvent",
")",
"return",
"cb",
"(",
"null",
",",
"foundInvoiceitem",
")",
";",
"if",
"(",
"foundInvoiceitem",
".",
"lastStripeEvent",
"==",
"invoiceitem",
".",
"lastStripeEvent",
")",
"return",
"Invoiceitem",
".",
"afterStripeInvoiceitemUpdated",
"(",
"foundInvoiceitem",
",",
"function",
"(",
"err",
",",
"invoiceitem",
")",
"{",
"return",
"cb",
"(",
"err",
",",
"invoiceitem",
")",
"}",
")",
";",
"Invoiceitem",
".",
"update",
"(",
"foundInvoiceitem",
".",
"id",
",",
"invoiceitem",
")",
".",
"exec",
"(",
"function",
"(",
"err",
",",
"updatedInvoiceitem",
")",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"err",
")",
";",
"if",
"(",
"!",
"updatedInvoiceitem",
")",
"return",
"cb",
"(",
"null",
",",
"null",
")",
";",
"Invoiceitem",
".",
"afterStripeInvoiceitemUpdated",
"(",
"updatedInvoiceitem",
"[",
"0",
"]",
",",
"function",
"(",
"err",
",",
"invoiceitem",
")",
"{",
"cb",
"(",
"err",
",",
"invoiceitem",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | Stripe Webhook invoiceitem.updated | [
"Stripe",
"Webhook",
"invoiceitem",
".",
"updated"
] | 0766bc04a6893a07c842170f37b37200d6771425 | https://github.com/scott-wyatt/sails-stripe/blob/0766bc04a6893a07c842170f37b37200d6771425/templates/Invoiceitem.template.js#L90-L106 | train |
|
scott-wyatt/sails-stripe | templates/Invoiceitem.template.js | function (invoiceitem, cb) {
Invoiceitem.destroy(invoiceitem.id)
.exec(function (err, destroyedInvoiceitems){
if (err) return cb(err);
if (!destroyedInvoiceitems) return cb(null, null);
Invoiceitem.afterStripeInvoiceitemDeleted(destroyedInvoiceitems[0], function(err, invoiceitem){
cb(err, invoiceitem);
});
});
} | javascript | function (invoiceitem, cb) {
Invoiceitem.destroy(invoiceitem.id)
.exec(function (err, destroyedInvoiceitems){
if (err) return cb(err);
if (!destroyedInvoiceitems) return cb(null, null);
Invoiceitem.afterStripeInvoiceitemDeleted(destroyedInvoiceitems[0], function(err, invoiceitem){
cb(err, invoiceitem);
});
});
} | [
"function",
"(",
"invoiceitem",
",",
"cb",
")",
"{",
"Invoiceitem",
".",
"destroy",
"(",
"invoiceitem",
".",
"id",
")",
".",
"exec",
"(",
"function",
"(",
"err",
",",
"destroyedInvoiceitems",
")",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"err",
")",
";",
"if",
"(",
"!",
"destroyedInvoiceitems",
")",
"return",
"cb",
"(",
"null",
",",
"null",
")",
";",
"Invoiceitem",
".",
"afterStripeInvoiceitemDeleted",
"(",
"destroyedInvoiceitems",
"[",
"0",
"]",
",",
"function",
"(",
"err",
",",
"invoiceitem",
")",
"{",
"cb",
"(",
"err",
",",
"invoiceitem",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | Stripe Webhook invoiceitem.deleted | [
"Stripe",
"Webhook",
"invoiceitem",
".",
"deleted"
] | 0766bc04a6893a07c842170f37b37200d6771425 | https://github.com/scott-wyatt/sails-stripe/blob/0766bc04a6893a07c842170f37b37200d6771425/templates/Invoiceitem.template.js#L114-L124 | train |
|
om-mani-padme-hum/ezobjects-mysql | index.js | validateTableConfig | function validateTableConfig(obj) {
/** If configuration has missing or invalid 'tableName' configuration, throw error */
if ( typeof obj.tableName !== `string` || !obj.tableName.match(/^[a-z_]+$/) )
throw new Error(`ezobjects.validateTableConfig(): Configuration has missing or invalid 'tableName', must be string containing characters 'a-z_'.`);
validateClassConfig(obj);
} | javascript | function validateTableConfig(obj) {
/** If configuration has missing or invalid 'tableName' configuration, throw error */
if ( typeof obj.tableName !== `string` || !obj.tableName.match(/^[a-z_]+$/) )
throw new Error(`ezobjects.validateTableConfig(): Configuration has missing or invalid 'tableName', must be string containing characters 'a-z_'.`);
validateClassConfig(obj);
} | [
"function",
"validateTableConfig",
"(",
"obj",
")",
"{",
"if",
"(",
"typeof",
"obj",
".",
"tableName",
"!==",
"`",
"`",
"||",
"!",
"obj",
".",
"tableName",
".",
"match",
"(",
"/",
"^[a-z_]+$",
"/",
")",
")",
"throw",
"new",
"Error",
"(",
"`",
"`",
")",
";",
"validateClassConfig",
"(",
"obj",
")",
";",
"}"
] | Validate configuration for a creating MySQL table based on class configuration | [
"Validate",
"configuration",
"for",
"a",
"creating",
"MySQL",
"table",
"based",
"on",
"class",
"configuration"
] | 6c73476af9d2855e7c4d7b56176da3f57f1ae37b | https://github.com/om-mani-padme-hum/ezobjects-mysql/blob/6c73476af9d2855e7c4d7b56176da3f57f1ae37b/index.js#L415-L421 | train |
elb-min-uhh/markdown-elearnjs | assets/elearnjs/extensions/quiz/assets/js/quiz.js | ev_canvas | function ev_canvas(ev) {
if(!root.is('.blocked')) {
if(ev.layerX || ev.layerX == 0) { // Firefox
ev._x = ev.layerX;
ev._y = ev.layerY;
} else if(ev.offsetX || ev.offsetX == 0) { // Opera
ev._x = ev.offsetX;
ev._y = ev.offsetY;
}
// Call the event handler of the tool.
var func = tool[ev.type];
if(func) {
func(ev);
}
}
} | javascript | function ev_canvas(ev) {
if(!root.is('.blocked')) {
if(ev.layerX || ev.layerX == 0) { // Firefox
ev._x = ev.layerX;
ev._y = ev.layerY;
} else if(ev.offsetX || ev.offsetX == 0) { // Opera
ev._x = ev.offsetX;
ev._y = ev.offsetY;
}
// Call the event handler of the tool.
var func = tool[ev.type];
if(func) {
func(ev);
}
}
} | [
"function",
"ev_canvas",
"(",
"ev",
")",
"{",
"if",
"(",
"!",
"root",
".",
"is",
"(",
"'.blocked'",
")",
")",
"{",
"if",
"(",
"ev",
".",
"layerX",
"||",
"ev",
".",
"layerX",
"==",
"0",
")",
"{",
"ev",
".",
"_x",
"=",
"ev",
".",
"layerX",
";",
"ev",
".",
"_y",
"=",
"ev",
".",
"layerY",
";",
"}",
"else",
"if",
"(",
"ev",
".",
"offsetX",
"||",
"ev",
".",
"offsetX",
"==",
"0",
")",
"{",
"ev",
".",
"_x",
"=",
"ev",
".",
"offsetX",
";",
"ev",
".",
"_y",
"=",
"ev",
".",
"offsetY",
";",
"}",
"var",
"func",
"=",
"tool",
"[",
"ev",
".",
"type",
"]",
";",
"if",
"(",
"func",
")",
"{",
"func",
"(",
"ev",
")",
";",
"}",
"}",
"}"
] | The general-purpose event handler. This function just determines the mouse position relative to the canvas element. | [
"The",
"general",
"-",
"purpose",
"event",
"handler",
".",
"This",
"function",
"just",
"determines",
"the",
"mouse",
"position",
"relative",
"to",
"the",
"canvas",
"element",
"."
] | a09bcc497c3c50dd565b7f440fa1f7b62074d679 | https://github.com/elb-min-uhh/markdown-elearnjs/blob/a09bcc497c3c50dd565b7f440fa1f7b62074d679/assets/elearnjs/extensions/quiz/assets/js/quiz.js#L2207-L2223 | train |
scott-wyatt/sails-stripe | templates/Coupon.template.js | function (coupon, cb) {
Coupon.findOrCreate(coupon.id, coupon)
.exec(function (err, foundCoupon){
if (err) return cb(err);
if (foundCoupon.lastStripeEvent > coupon.lastStripeEvent) return cb(null, foundCoupon);
if (foundCoupon.lastStripeEvent == coupon.lastStripeEvent) return Coupon.afterStripeCouponCreated(foundCoupon, function(err, coupon){ return cb(err, coupon)});
Coupon.update(foundCoupon.id, coupon)
.exec(function(err, updatedCoupons){
if (err) return cb(err);
Coupon.afterStripeCouponCreated(updatedCoupons[0], function(err, coupon){
cb(err, coupon);
});
});
});
} | javascript | function (coupon, cb) {
Coupon.findOrCreate(coupon.id, coupon)
.exec(function (err, foundCoupon){
if (err) return cb(err);
if (foundCoupon.lastStripeEvent > coupon.lastStripeEvent) return cb(null, foundCoupon);
if (foundCoupon.lastStripeEvent == coupon.lastStripeEvent) return Coupon.afterStripeCouponCreated(foundCoupon, function(err, coupon){ return cb(err, coupon)});
Coupon.update(foundCoupon.id, coupon)
.exec(function(err, updatedCoupons){
if (err) return cb(err);
Coupon.afterStripeCouponCreated(updatedCoupons[0], function(err, coupon){
cb(err, coupon);
});
});
});
} | [
"function",
"(",
"coupon",
",",
"cb",
")",
"{",
"Coupon",
".",
"findOrCreate",
"(",
"coupon",
".",
"id",
",",
"coupon",
")",
".",
"exec",
"(",
"function",
"(",
"err",
",",
"foundCoupon",
")",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"err",
")",
";",
"if",
"(",
"foundCoupon",
".",
"lastStripeEvent",
">",
"coupon",
".",
"lastStripeEvent",
")",
"return",
"cb",
"(",
"null",
",",
"foundCoupon",
")",
";",
"if",
"(",
"foundCoupon",
".",
"lastStripeEvent",
"==",
"coupon",
".",
"lastStripeEvent",
")",
"return",
"Coupon",
".",
"afterStripeCouponCreated",
"(",
"foundCoupon",
",",
"function",
"(",
"err",
",",
"coupon",
")",
"{",
"return",
"cb",
"(",
"err",
",",
"coupon",
")",
"}",
")",
";",
"Coupon",
".",
"update",
"(",
"foundCoupon",
".",
"id",
",",
"coupon",
")",
".",
"exec",
"(",
"function",
"(",
"err",
",",
"updatedCoupons",
")",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"err",
")",
";",
"Coupon",
".",
"afterStripeCouponCreated",
"(",
"updatedCoupons",
"[",
"0",
"]",
",",
"function",
"(",
"err",
",",
"coupon",
")",
"{",
"cb",
"(",
"err",
",",
"coupon",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | Stripe Webhook coupon.created | [
"Stripe",
"Webhook",
"coupon",
".",
"created"
] | 0766bc04a6893a07c842170f37b37200d6771425 | https://github.com/scott-wyatt/sails-stripe/blob/0766bc04a6893a07c842170f37b37200d6771425/templates/Coupon.template.js#L75-L90 | train |
|
scott-wyatt/sails-stripe | templates/Coupon.template.js | function (coupon, cb) {
Coupon.destroy(coupon.id)
.exec(function (err, destroyedCoupons){
if (err) return cb(err);
if(!destroyedCoupons) return cb(null, null);
Coupon.afterStripeCouponDeleted(destroyedCoupons[0], function(err, coupon){
cb(null, coupon);
});
});
} | javascript | function (coupon, cb) {
Coupon.destroy(coupon.id)
.exec(function (err, destroyedCoupons){
if (err) return cb(err);
if(!destroyedCoupons) return cb(null, null);
Coupon.afterStripeCouponDeleted(destroyedCoupons[0], function(err, coupon){
cb(null, coupon);
});
});
} | [
"function",
"(",
"coupon",
",",
"cb",
")",
"{",
"Coupon",
".",
"destroy",
"(",
"coupon",
".",
"id",
")",
".",
"exec",
"(",
"function",
"(",
"err",
",",
"destroyedCoupons",
")",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"err",
")",
";",
"if",
"(",
"!",
"destroyedCoupons",
")",
"return",
"cb",
"(",
"null",
",",
"null",
")",
";",
"Coupon",
".",
"afterStripeCouponDeleted",
"(",
"destroyedCoupons",
"[",
"0",
"]",
",",
"function",
"(",
"err",
",",
"coupon",
")",
"{",
"cb",
"(",
"null",
",",
"coupon",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | Stripe Webhook coupon.deleted | [
"Stripe",
"Webhook",
"coupon",
".",
"deleted"
] | 0766bc04a6893a07c842170f37b37200d6771425 | https://github.com/scott-wyatt/sails-stripe/blob/0766bc04a6893a07c842170f37b37200d6771425/templates/Coupon.template.js#L98-L108 | train |
|
scott-wyatt/sails-stripe | templates/Stripeaccount.template.js | function (account, cb) {
Stripeaccount.findOrCreate(account.id, account)
.exec(function (err, foundAccount){
if (err) return cb(err);
Stripeaccount.update(foundAccount.id, account)
.exec(function(err, updatedAccounts){
if (err) return cb(err);
cb(null, updatedAccounts[0]);
});
});
} | javascript | function (account, cb) {
Stripeaccount.findOrCreate(account.id, account)
.exec(function (err, foundAccount){
if (err) return cb(err);
Stripeaccount.update(foundAccount.id, account)
.exec(function(err, updatedAccounts){
if (err) return cb(err);
cb(null, updatedAccounts[0]);
});
});
} | [
"function",
"(",
"account",
",",
"cb",
")",
"{",
"Stripeaccount",
".",
"findOrCreate",
"(",
"account",
".",
"id",
",",
"account",
")",
".",
"exec",
"(",
"function",
"(",
"err",
",",
"foundAccount",
")",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"err",
")",
";",
"Stripeaccount",
".",
"update",
"(",
"foundAccount",
".",
"id",
",",
"account",
")",
".",
"exec",
"(",
"function",
"(",
"err",
",",
"updatedAccounts",
")",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"err",
")",
";",
"cb",
"(",
"null",
",",
"updatedAccounts",
"[",
"0",
"]",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | Stripe Webhook account.updated | [
"Stripe",
"Webhook",
"account",
".",
"updated"
] | 0766bc04a6893a07c842170f37b37200d6771425 | https://github.com/scott-wyatt/sails-stripe/blob/0766bc04a6893a07c842170f37b37200d6771425/templates/Stripeaccount.template.js#L98-L109 | train |
|
mojaie/kiwiii | src/component/tree.js | checkboxValues | function checkboxValues(selection) {
return selection.select('.body')
.selectAll('input:checked').data().map(d => d.id);
} | javascript | function checkboxValues(selection) {
return selection.select('.body')
.selectAll('input:checked').data().map(d => d.id);
} | [
"function",
"checkboxValues",
"(",
"selection",
")",
"{",
"return",
"selection",
".",
"select",
"(",
"'.body'",
")",
".",
"selectAll",
"(",
"'input:checked'",
")",
".",
"data",
"(",
")",
".",
"map",
"(",
"d",
"=>",
"d",
".",
"id",
")",
";",
"}"
] | Return an array of ids that are checked
@param {d3.selection} selection - selection of node content | [
"Return",
"an",
"array",
"of",
"ids",
"that",
"are",
"checked"
] | 30d75685b1ab388b5f1467c753cacd090971ceba | https://github.com/mojaie/kiwiii/blob/30d75685b1ab388b5f1467c753cacd090971ceba/src/component/tree.js#L132-L135 | train |
xbtsw/makejs | lib/make.js | addDepsToRequiredTargets | function addDepsToRequiredTargets(target, parents){
if (parents.have(target)){
callback(new Error("Circular dependencies detected"));
return;
}
requiredTargets.add(target);
parents.add(target);
for(var deps in makeInst.targets[target].dependsOn.hash){
addDepsToRequiredTargets(deps, parents.clone());
}
} | javascript | function addDepsToRequiredTargets(target, parents){
if (parents.have(target)){
callback(new Error("Circular dependencies detected"));
return;
}
requiredTargets.add(target);
parents.add(target);
for(var deps in makeInst.targets[target].dependsOn.hash){
addDepsToRequiredTargets(deps, parents.clone());
}
} | [
"function",
"addDepsToRequiredTargets",
"(",
"target",
",",
"parents",
")",
"{",
"if",
"(",
"parents",
".",
"have",
"(",
"target",
")",
")",
"{",
"callback",
"(",
"new",
"Error",
"(",
"\"Circular dependencies detected\"",
")",
")",
";",
"return",
";",
"}",
"requiredTargets",
".",
"add",
"(",
"target",
")",
";",
"parents",
".",
"add",
"(",
"target",
")",
";",
"for",
"(",
"var",
"deps",
"in",
"makeInst",
".",
"targets",
"[",
"target",
"]",
".",
"dependsOn",
".",
"hash",
")",
"{",
"addDepsToRequiredTargets",
"(",
"deps",
",",
"parents",
".",
"clone",
"(",
")",
")",
";",
"}",
"}"
] | find all the required targets | [
"find",
"all",
"the",
"required",
"targets"
] | f43a52310bb1df625a5bf3ed9ea0b1654d638eb6 | https://github.com/xbtsw/makejs/blob/f43a52310bb1df625a5bf3ed9ea0b1654d638eb6/lib/make.js#L126-L136 | train |
jsantell/mock-s3 | lib/mpu.js | MPU | function MPU (ops) {
File.call(this, ops);
this._parts = {};
this._bufferParts = [];
this._data.UploadId = makeUploadId();
} | javascript | function MPU (ops) {
File.call(this, ops);
this._parts = {};
this._bufferParts = [];
this._data.UploadId = makeUploadId();
} | [
"function",
"MPU",
"(",
"ops",
")",
"{",
"File",
".",
"call",
"(",
"this",
",",
"ops",
")",
";",
"this",
".",
"_parts",
"=",
"{",
"}",
";",
"this",
".",
"_bufferParts",
"=",
"[",
"]",
";",
"this",
".",
"_data",
".",
"UploadId",
"=",
"makeUploadId",
"(",
")",
";",
"}"
] | Creates a new file for mock-s3.
@class | [
"Creates",
"a",
"new",
"file",
"for",
"mock",
"-",
"s3",
"."
] | d02e3b0558cc60c7887232b69df41e2b0fe09147 | https://github.com/jsantell/mock-s3/blob/d02e3b0558cc60c7887232b69df41e2b0fe09147/lib/mpu.js#L10-L15 | train |
jamiebuilds/backbone.storage | dist/backbone.storage.js | find | function find(model) {
var _this = this;
var forceFetch = arguments[1] === undefined ? false : arguments[1];
var record = this.records.get(model);
if (record && !forceFetch) {
return Promise.resolve(record);
} else {
model = this._ensureModel(model);
return Promise.resolve(model.fetch()).then(function () {
return _this.insert(model);
});
}
} | javascript | function find(model) {
var _this = this;
var forceFetch = arguments[1] === undefined ? false : arguments[1];
var record = this.records.get(model);
if (record && !forceFetch) {
return Promise.resolve(record);
} else {
model = this._ensureModel(model);
return Promise.resolve(model.fetch()).then(function () {
return _this.insert(model);
});
}
} | [
"function",
"find",
"(",
"model",
")",
"{",
"var",
"_this",
"=",
"this",
";",
"var",
"forceFetch",
"=",
"arguments",
"[",
"1",
"]",
"===",
"undefined",
"?",
"false",
":",
"arguments",
"[",
"1",
"]",
";",
"var",
"record",
"=",
"this",
".",
"records",
".",
"get",
"(",
"model",
")",
";",
"if",
"(",
"record",
"&&",
"!",
"forceFetch",
")",
"{",
"return",
"Promise",
".",
"resolve",
"(",
"record",
")",
";",
"}",
"else",
"{",
"model",
"=",
"this",
".",
"_ensureModel",
"(",
"model",
")",
";",
"return",
"Promise",
".",
"resolve",
"(",
"model",
".",
"fetch",
"(",
")",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"return",
"_this",
".",
"insert",
"(",
"model",
")",
";",
"}",
")",
";",
"}",
"}"
] | Find a specific model from the store or fetch it from the server and insert
it into the store.
@public
@instance
@method find
@memberOf Storage
@param {Number|String|Object|Backbone.Model} model - The model to find.
@param {Boolean} forceFetch - Force fetch model from server.
@returns {Promise} - A promise that will resolve to the model. | [
"Find",
"a",
"specific",
"model",
"from",
"the",
"store",
"or",
"fetch",
"it",
"from",
"the",
"server",
"and",
"insert",
"it",
"into",
"the",
"store",
"."
] | db8169a07b54f30baa4a8c3963c8cbefe2dd47c9 | https://github.com/jamiebuilds/backbone.storage/blob/db8169a07b54f30baa4a8c3963c8cbefe2dd47c9/dist/backbone.storage.js#L45-L58 | train |
jamiebuilds/backbone.storage | dist/backbone.storage.js | findAll | function findAll() {
var _this = this;
var options = arguments[0] === undefined ? {} : arguments[0];
var forceFetch = arguments[1] === undefined ? false : arguments[1];
if (this._hasSynced && !forceFetch) {
return Promise.resolve(this.records);
} else {
return Promise.resolve(this.records.fetch(options)).then(function () {
return _this.records;
});
}
} | javascript | function findAll() {
var _this = this;
var options = arguments[0] === undefined ? {} : arguments[0];
var forceFetch = arguments[1] === undefined ? false : arguments[1];
if (this._hasSynced && !forceFetch) {
return Promise.resolve(this.records);
} else {
return Promise.resolve(this.records.fetch(options)).then(function () {
return _this.records;
});
}
} | [
"function",
"findAll",
"(",
")",
"{",
"var",
"_this",
"=",
"this",
";",
"var",
"options",
"=",
"arguments",
"[",
"0",
"]",
"===",
"undefined",
"?",
"{",
"}",
":",
"arguments",
"[",
"0",
"]",
";",
"var",
"forceFetch",
"=",
"arguments",
"[",
"1",
"]",
"===",
"undefined",
"?",
"false",
":",
"arguments",
"[",
"1",
"]",
";",
"if",
"(",
"this",
".",
"_hasSynced",
"&&",
"!",
"forceFetch",
")",
"{",
"return",
"Promise",
".",
"resolve",
"(",
"this",
".",
"records",
")",
";",
"}",
"else",
"{",
"return",
"Promise",
".",
"resolve",
"(",
"this",
".",
"records",
".",
"fetch",
"(",
"options",
")",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"return",
"_this",
".",
"records",
";",
"}",
")",
";",
"}",
"}"
] | Find all the models in the store or fetch them from the server if they
haven't been fetched before.
@public
@instance
@method findAll
@memberOf Storage
@param {Object} options - Options to pass to collection fetch. Also allows
setting parameters on collection.
@param {Boolean} forceFetch - Force fetch model from server.
@returns {Promise} - A promise that will resolve to the entire collection. | [
"Find",
"all",
"the",
"models",
"in",
"the",
"store",
"or",
"fetch",
"them",
"from",
"the",
"server",
"if",
"they",
"haven",
"t",
"been",
"fetched",
"before",
"."
] | db8169a07b54f30baa4a8c3963c8cbefe2dd47c9 | https://github.com/jamiebuilds/backbone.storage/blob/db8169a07b54f30baa4a8c3963c8cbefe2dd47c9/dist/backbone.storage.js#L73-L84 | train |
jamiebuilds/backbone.storage | dist/backbone.storage.js | save | function save(model) {
var _this = this;
var record = this.records.get(model);
model = record || this._ensureModel(model);
return Promise.resolve(model.save()).then(function () {
if (!record) {
_this.insert(model);
}
return model;
});
} | javascript | function save(model) {
var _this = this;
var record = this.records.get(model);
model = record || this._ensureModel(model);
return Promise.resolve(model.save()).then(function () {
if (!record) {
_this.insert(model);
}
return model;
});
} | [
"function",
"save",
"(",
"model",
")",
"{",
"var",
"_this",
"=",
"this",
";",
"var",
"record",
"=",
"this",
".",
"records",
".",
"get",
"(",
"model",
")",
";",
"model",
"=",
"record",
"||",
"this",
".",
"_ensureModel",
"(",
"model",
")",
";",
"return",
"Promise",
".",
"resolve",
"(",
"model",
".",
"save",
"(",
")",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"if",
"(",
"!",
"record",
")",
"{",
"_this",
".",
"insert",
"(",
"model",
")",
";",
"}",
"return",
"model",
";",
"}",
")",
";",
"}"
] | Save a model to the server.
@public
@instance
@method save
@memberOf Storage
@param {Number|String|Object|Backbone.Model} model - The model to save
@returns {Promise} - A promise that will resolve to the saved model. | [
"Save",
"a",
"model",
"to",
"the",
"server",
"."
] | db8169a07b54f30baa4a8c3963c8cbefe2dd47c9 | https://github.com/jamiebuilds/backbone.storage/blob/db8169a07b54f30baa4a8c3963c8cbefe2dd47c9/dist/backbone.storage.js#L96-L106 | train |
jamiebuilds/backbone.storage | dist/backbone.storage.js | insert | function insert(model) {
model = this.records.add(model, { merge: true });
return Promise.resolve(model);
} | javascript | function insert(model) {
model = this.records.add(model, { merge: true });
return Promise.resolve(model);
} | [
"function",
"insert",
"(",
"model",
")",
"{",
"model",
"=",
"this",
".",
"records",
".",
"add",
"(",
"model",
",",
"{",
"merge",
":",
"true",
"}",
")",
";",
"return",
"Promise",
".",
"resolve",
"(",
"model",
")",
";",
"}"
] | Insert a model into the store.
@public
@instance
@method insert
@memberOf Storage
@params {Object|Backbone.Model} - The model to add.
@returns {Promise} - A promise that will resolve to the added model. | [
"Insert",
"a",
"model",
"into",
"the",
"store",
"."
] | db8169a07b54f30baa4a8c3963c8cbefe2dd47c9 | https://github.com/jamiebuilds/backbone.storage/blob/db8169a07b54f30baa4a8c3963c8cbefe2dd47c9/dist/backbone.storage.js#L118-L121 | train |
jamiebuilds/backbone.storage | dist/backbone.storage.js | _ensureModel | function _ensureModel(model) {
if (model instanceof this.model) {
return model;
} else if (typeof model === "object") {
return new this.model(model);
} else {
return new this.model({ id: model });
}
} | javascript | function _ensureModel(model) {
if (model instanceof this.model) {
return model;
} else if (typeof model === "object") {
return new this.model(model);
} else {
return new this.model({ id: model });
}
} | [
"function",
"_ensureModel",
"(",
"model",
")",
"{",
"if",
"(",
"model",
"instanceof",
"this",
".",
"model",
")",
"{",
"return",
"model",
";",
"}",
"else",
"if",
"(",
"typeof",
"model",
"===",
"\"object\"",
")",
"{",
"return",
"new",
"this",
".",
"model",
"(",
"model",
")",
";",
"}",
"else",
"{",
"return",
"new",
"this",
".",
"model",
"(",
"{",
"id",
":",
"model",
"}",
")",
";",
"}",
"}"
] | Ensure that we have a real model from an id, object, or model.
@private
@instance
@method _ensureModel
@memberOf Storage
@params {Number|String|Object|Backbone.Model} - An id, object, or model.
@returns {Backbone.Model} - The model. | [
"Ensure",
"that",
"we",
"have",
"a",
"real",
"model",
"from",
"an",
"id",
"object",
"or",
"model",
"."
] | db8169a07b54f30baa4a8c3963c8cbefe2dd47c9 | https://github.com/jamiebuilds/backbone.storage/blob/db8169a07b54f30baa4a8c3963c8cbefe2dd47c9/dist/backbone.storage.js#L133-L141 | train |
impromptu/impromptu | lib/Prompt.js | function(input, callback) {
// Handle non-function `input`.
if (!_.isFunction(input)) {
callback(null, input)
return
}
// Handle asynchronous `input` function.
if (input.length) {
input(callback)
return
}
// Handle synchronous `input` function.
var results = null
var err = null
try {
results = input()
} catch (e) {
err = e
}
callback(err, results)
} | javascript | function(input, callback) {
// Handle non-function `input`.
if (!_.isFunction(input)) {
callback(null, input)
return
}
// Handle asynchronous `input` function.
if (input.length) {
input(callback)
return
}
// Handle synchronous `input` function.
var results = null
var err = null
try {
results = input()
} catch (e) {
err = e
}
callback(err, results)
} | [
"function",
"(",
"input",
",",
"callback",
")",
"{",
"if",
"(",
"!",
"_",
".",
"isFunction",
"(",
"input",
")",
")",
"{",
"callback",
"(",
"null",
",",
"input",
")",
"return",
"}",
"if",
"(",
"input",
".",
"length",
")",
"{",
"input",
"(",
"callback",
")",
"return",
"}",
"var",
"results",
"=",
"null",
"var",
"err",
"=",
"null",
"try",
"{",
"results",
"=",
"input",
"(",
")",
"}",
"catch",
"(",
"e",
")",
"{",
"err",
"=",
"e",
"}",
"callback",
"(",
"err",
",",
"results",
")",
"}"
] | Allows any input to be treated asynchronously. | [
"Allows",
"any",
"input",
"to",
"be",
"treated",
"asynchronously",
"."
] | 829798eda62771d6a6ed971d87eef7a461932704 | https://github.com/impromptu/impromptu/blob/829798eda62771d6a6ed971d87eef7a461932704/lib/Prompt.js#L21-L44 | train |
|
XOP/sass-vars-to-js | src/index.js | sassVars | function sassVars (filePath) {
const declarations = collectDeclarations(filePath);
let variables = {};
if (!declarations.length) {
message('Warning: Zero declarations found');
return;
}
declarations.forEach(function (declaration) {
const parsedDeclaration = parseDeclaration(declaration);
const varName = parsedDeclaration.key;
let varValue = parsedDeclaration.value;
const valueType = getValueType(varValue);
/*
* $key: $value;
*/
if (valueType === 'var') {
const localVarName = varValue;
varValue = getVarValue(localVarName, variables);
if (!varValue) {
message(`Warning: Null value for variable ${localVarName}`);
}
}
/*
* $key: ($value-1 + $value-2) * $value-3 ... ;
*/
if (valueType === 'expression') {
// todo
}
/*
* $key: value;
*/
variables[varName] = varValue;
});
return variables;
} | javascript | function sassVars (filePath) {
const declarations = collectDeclarations(filePath);
let variables = {};
if (!declarations.length) {
message('Warning: Zero declarations found');
return;
}
declarations.forEach(function (declaration) {
const parsedDeclaration = parseDeclaration(declaration);
const varName = parsedDeclaration.key;
let varValue = parsedDeclaration.value;
const valueType = getValueType(varValue);
/*
* $key: $value;
*/
if (valueType === 'var') {
const localVarName = varValue;
varValue = getVarValue(localVarName, variables);
if (!varValue) {
message(`Warning: Null value for variable ${localVarName}`);
}
}
/*
* $key: ($value-1 + $value-2) * $value-3 ... ;
*/
if (valueType === 'expression') {
// todo
}
/*
* $key: value;
*/
variables[varName] = varValue;
});
return variables;
} | [
"function",
"sassVars",
"(",
"filePath",
")",
"{",
"const",
"declarations",
"=",
"collectDeclarations",
"(",
"filePath",
")",
";",
"let",
"variables",
"=",
"{",
"}",
";",
"if",
"(",
"!",
"declarations",
".",
"length",
")",
"{",
"message",
"(",
"'Warning: Zero declarations found'",
")",
";",
"return",
";",
"}",
"declarations",
".",
"forEach",
"(",
"function",
"(",
"declaration",
")",
"{",
"const",
"parsedDeclaration",
"=",
"parseDeclaration",
"(",
"declaration",
")",
";",
"const",
"varName",
"=",
"parsedDeclaration",
".",
"key",
";",
"let",
"varValue",
"=",
"parsedDeclaration",
".",
"value",
";",
"const",
"valueType",
"=",
"getValueType",
"(",
"varValue",
")",
";",
"if",
"(",
"valueType",
"===",
"'var'",
")",
"{",
"const",
"localVarName",
"=",
"varValue",
";",
"varValue",
"=",
"getVarValue",
"(",
"localVarName",
",",
"variables",
")",
";",
"if",
"(",
"!",
"varValue",
")",
"{",
"message",
"(",
"`",
"${",
"localVarName",
"}",
"`",
")",
";",
"}",
"}",
"if",
"(",
"valueType",
"===",
"'expression'",
")",
"{",
"}",
"variables",
"[",
"varName",
"]",
"=",
"varValue",
";",
"}",
")",
";",
"return",
"variables",
";",
"}"
] | Takes file.scss as an argument
Returns parsed variables hash-map
@param filePath
@returns {{}} | [
"Takes",
"file",
".",
"scss",
"as",
"an",
"argument",
"Returns",
"parsed",
"variables",
"hash",
"-",
"map"
] | 87ad8588701a9c2e69ace75931947d11698f25f0 | https://github.com/XOP/sass-vars-to-js/blob/87ad8588701a9c2e69ace75931947d11698f25f0/src/index.js#L13-L54 | train |
fnogatz/node-swtparser | lib/from-data-view.js | getOrderedPlayers | function getOrderedPlayers (tnmt) {
var res = []
for (var i = 0; i < tnmt.players.length; i++) {
res[tnmt.players[i].positionInSWT] = tnmt.players[i]['2020']
}
return res
} | javascript | function getOrderedPlayers (tnmt) {
var res = []
for (var i = 0; i < tnmt.players.length; i++) {
res[tnmt.players[i].positionInSWT] = tnmt.players[i]['2020']
}
return res
} | [
"function",
"getOrderedPlayers",
"(",
"tnmt",
")",
"{",
"var",
"res",
"=",
"[",
"]",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"tnmt",
".",
"players",
".",
"length",
";",
"i",
"++",
")",
"{",
"res",
"[",
"tnmt",
".",
"players",
"[",
"i",
"]",
".",
"positionInSWT",
"]",
"=",
"tnmt",
".",
"players",
"[",
"i",
"]",
"[",
"'2020'",
"]",
"}",
"return",
"res",
"}"
] | Takes a tournament and returns the players in order of
their occurences within the SWT.
@param {Object} tournament object after parsing process
@return {Array} of players | [
"Takes",
"a",
"tournament",
"and",
"returns",
"the",
"players",
"in",
"order",
"of",
"their",
"occurences",
"within",
"the",
"SWT",
"."
] | 4a109dcfef19ca5ca01fa7b4256ee57a2a3c1dd3 | https://github.com/fnogatz/node-swtparser/blob/4a109dcfef19ca5ca01fa7b4256ee57a2a3c1dd3/lib/from-data-view.js#L261-L267 | train |
fnogatz/node-swtparser | lib/from-data-view.js | getOrderedTeams | function getOrderedTeams (tnmt) {
var res = []
for (var i = 0; i < tnmt.teams.length; i++) {
res[tnmt.teams[i].positionInSWT] = tnmt.teams[i]['1018']
}
return res
} | javascript | function getOrderedTeams (tnmt) {
var res = []
for (var i = 0; i < tnmt.teams.length; i++) {
res[tnmt.teams[i].positionInSWT] = tnmt.teams[i]['1018']
}
return res
} | [
"function",
"getOrderedTeams",
"(",
"tnmt",
")",
"{",
"var",
"res",
"=",
"[",
"]",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"tnmt",
".",
"teams",
".",
"length",
";",
"i",
"++",
")",
"{",
"res",
"[",
"tnmt",
".",
"teams",
"[",
"i",
"]",
".",
"positionInSWT",
"]",
"=",
"tnmt",
".",
"teams",
"[",
"i",
"]",
"[",
"'1018'",
"]",
"}",
"return",
"res",
"}"
] | Takes a tournament and returns the teams in order of
their occurences within the SWT.
@param {Object} tournament object after parsing process
@return {Array} of teams | [
"Takes",
"a",
"tournament",
"and",
"returns",
"the",
"teams",
"in",
"order",
"of",
"their",
"occurences",
"within",
"the",
"SWT",
"."
] | 4a109dcfef19ca5ca01fa7b4256ee57a2a3c1dd3 | https://github.com/fnogatz/node-swtparser/blob/4a109dcfef19ca5ca01fa7b4256ee57a2a3c1dd3/lib/from-data-view.js#L276-L282 | train |
fnogatz/node-swtparser | lib/from-data-view.js | playerPairingFilter | function playerPairingFilter (tnmt) {
return function (pairing) {
// board number too high?
if (tnmt.general[35] && pairing[4006] > tnmt.general[34]) { return false }
// no color set?
if (pairing[4000] === '4000-0') { return false }
return true
}
} | javascript | function playerPairingFilter (tnmt) {
return function (pairing) {
// board number too high?
if (tnmt.general[35] && pairing[4006] > tnmt.general[34]) { return false }
// no color set?
if (pairing[4000] === '4000-0') { return false }
return true
}
} | [
"function",
"playerPairingFilter",
"(",
"tnmt",
")",
"{",
"return",
"function",
"(",
"pairing",
")",
"{",
"if",
"(",
"tnmt",
".",
"general",
"[",
"35",
"]",
"&&",
"pairing",
"[",
"4006",
"]",
">",
"tnmt",
".",
"general",
"[",
"34",
"]",
")",
"{",
"return",
"false",
"}",
"if",
"(",
"pairing",
"[",
"4000",
"]",
"===",
"'4000-0'",
")",
"{",
"return",
"false",
"}",
"return",
"true",
"}",
"}"
] | Filter function to remove dummy player pairings.
@param {Object} pairing
@return {Boolean} true -> valid pairing | [
"Filter",
"function",
"to",
"remove",
"dummy",
"player",
"pairings",
"."
] | 4a109dcfef19ca5ca01fa7b4256ee57a2a3c1dd3 | https://github.com/fnogatz/node-swtparser/blob/4a109dcfef19ca5ca01fa7b4256ee57a2a3c1dd3/lib/from-data-view.js#L289-L299 | train |
nwtjs/nwt | src/io/js/io.js | NWTIO | function NWTIO(args) {
this.req = new XMLHttpRequest();
this.config = {};
this.url = args[0];
// Data to send as
this.ioData = '';
var chainableSetters = ['success', 'failure', 'serialize'],
i,
setter,
mythis = this,
// Returns the setter function
getSetter = function (setter) {
return function (value) {
mythis.config[setter] = value;
return this;
}
};
for (i = 0, setter; setter = chainableSetters[i]; i++) {
this[setter] = getSetter(setter);
}
} | javascript | function NWTIO(args) {
this.req = new XMLHttpRequest();
this.config = {};
this.url = args[0];
// Data to send as
this.ioData = '';
var chainableSetters = ['success', 'failure', 'serialize'],
i,
setter,
mythis = this,
// Returns the setter function
getSetter = function (setter) {
return function (value) {
mythis.config[setter] = value;
return this;
}
};
for (i = 0, setter; setter = chainableSetters[i]; i++) {
this[setter] = getSetter(setter);
}
} | [
"function",
"NWTIO",
"(",
"args",
")",
"{",
"this",
".",
"req",
"=",
"new",
"XMLHttpRequest",
"(",
")",
";",
"this",
".",
"config",
"=",
"{",
"}",
";",
"this",
".",
"url",
"=",
"args",
"[",
"0",
"]",
";",
"this",
".",
"ioData",
"=",
"''",
";",
"var",
"chainableSetters",
"=",
"[",
"'success'",
",",
"'failure'",
",",
"'serialize'",
"]",
",",
"i",
",",
"setter",
",",
"mythis",
"=",
"this",
",",
"getSetter",
"=",
"function",
"(",
"setter",
")",
"{",
"return",
"function",
"(",
"value",
")",
"{",
"mythis",
".",
"config",
"[",
"setter",
"]",
"=",
"value",
";",
"return",
"this",
";",
"}",
"}",
";",
"for",
"(",
"i",
"=",
"0",
",",
"setter",
";",
"setter",
"=",
"chainableSetters",
"[",
"i",
"]",
";",
"i",
"++",
")",
"{",
"this",
"[",
"setter",
"]",
"=",
"getSetter",
"(",
"setter",
")",
";",
"}",
"}"
] | Provides ajax communication methods
The folllowing methods are chainable
success - success handler
failure - failure handler
serialize - serialize a form, selector, array, or object to send
@constructor | [
"Provides",
"ajax",
"communication",
"methods",
"The",
"folllowing",
"methods",
"are",
"chainable",
"success",
"-",
"success",
"handler",
"failure",
"-",
"failure",
"handler",
"serialize",
"-",
"serialize",
"a",
"form",
"selector",
"array",
"or",
"object",
"to",
"send"
] | 49991293e621846e435992b764265abb13a7346b | https://github.com/nwtjs/nwt/blob/49991293e621846e435992b764265abb13a7346b/src/io/js/io.js#L32-L56 | train |
nwtjs/nwt | src/io/js/io.js | function() {
var mythis = this;
this.req.onload = function() {
if (mythis.config.success) {
var response = new NWTIOResponse(mythis.req);
mythis.config.success(response);
}
};
this.req.onerror = function() {
if (mythis.config.failure) {
var response = new NWTIOResponse(mythis.req);
mythis.config.failure(response);
}
};
this.req.send(this.ioData ? this.ioData : null);
return this;
} | javascript | function() {
var mythis = this;
this.req.onload = function() {
if (mythis.config.success) {
var response = new NWTIOResponse(mythis.req);
mythis.config.success(response);
}
};
this.req.onerror = function() {
if (mythis.config.failure) {
var response = new NWTIOResponse(mythis.req);
mythis.config.failure(response);
}
};
this.req.send(this.ioData ? this.ioData : null);
return this;
} | [
"function",
"(",
")",
"{",
"var",
"mythis",
"=",
"this",
";",
"this",
".",
"req",
".",
"onload",
"=",
"function",
"(",
")",
"{",
"if",
"(",
"mythis",
".",
"config",
".",
"success",
")",
"{",
"var",
"response",
"=",
"new",
"NWTIOResponse",
"(",
"mythis",
".",
"req",
")",
";",
"mythis",
".",
"config",
".",
"success",
"(",
"response",
")",
";",
"}",
"}",
";",
"this",
".",
"req",
".",
"onerror",
"=",
"function",
"(",
")",
"{",
"if",
"(",
"mythis",
".",
"config",
".",
"failure",
")",
"{",
"var",
"response",
"=",
"new",
"NWTIOResponse",
"(",
"mythis",
".",
"req",
")",
";",
"mythis",
".",
"config",
".",
"failure",
"(",
"response",
")",
";",
"}",
"}",
";",
"this",
".",
"req",
".",
"send",
"(",
"this",
".",
"ioData",
"?",
"this",
".",
"ioData",
":",
"null",
")",
";",
"return",
"this",
";",
"}"
] | Runs the IO call
@param string Type of call | [
"Runs",
"the",
"IO",
"call"
] | 49991293e621846e435992b764265abb13a7346b | https://github.com/nwtjs/nwt/blob/49991293e621846e435992b764265abb13a7346b/src/io/js/io.js#L63-L81 | train |
|
nwtjs/nwt | src/io/js/io.js | function(data, method) {
var urlencodedForm = true;
if (typeof data == 'string') {
this.ioData = data;
} else if (typeof data == 'object' && data._node) {
if (data.getAttribute('enctype')) {
urlencodedForm = false;
}
this.ioData = new FormData(data._node);
}
var req = this.req,
method = method || 'POST';
req.open(method, this.url);
//Send the proper header information along with the request
// Send as form encoded if we do not have a file field
if (urlencodedForm) {
req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
}
return this._run();
} | javascript | function(data, method) {
var urlencodedForm = true;
if (typeof data == 'string') {
this.ioData = data;
} else if (typeof data == 'object' && data._node) {
if (data.getAttribute('enctype')) {
urlencodedForm = false;
}
this.ioData = new FormData(data._node);
}
var req = this.req,
method = method || 'POST';
req.open(method, this.url);
//Send the proper header information along with the request
// Send as form encoded if we do not have a file field
if (urlencodedForm) {
req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
}
return this._run();
} | [
"function",
"(",
"data",
",",
"method",
")",
"{",
"var",
"urlencodedForm",
"=",
"true",
";",
"if",
"(",
"typeof",
"data",
"==",
"'string'",
")",
"{",
"this",
".",
"ioData",
"=",
"data",
";",
"}",
"else",
"if",
"(",
"typeof",
"data",
"==",
"'object'",
"&&",
"data",
".",
"_node",
")",
"{",
"if",
"(",
"data",
".",
"getAttribute",
"(",
"'enctype'",
")",
")",
"{",
"urlencodedForm",
"=",
"false",
";",
"}",
"this",
".",
"ioData",
"=",
"new",
"FormData",
"(",
"data",
".",
"_node",
")",
";",
"}",
"var",
"req",
"=",
"this",
".",
"req",
",",
"method",
"=",
"method",
"||",
"'POST'",
";",
"req",
".",
"open",
"(",
"method",
",",
"this",
".",
"url",
")",
";",
"if",
"(",
"urlencodedForm",
")",
"{",
"req",
".",
"setRequestHeader",
"(",
"\"Content-type\"",
",",
"\"application/x-www-form-urlencoded\"",
")",
";",
"}",
"return",
"this",
".",
"_run",
"(",
")",
";",
"}"
] | Runs IO POST
We also use post for PUT or DELETE requests | [
"Runs",
"IO",
"POST",
"We",
"also",
"use",
"post",
"for",
"PUT",
"or",
"DELETE",
"requests"
] | 49991293e621846e435992b764265abb13a7346b | https://github.com/nwtjs/nwt/blob/49991293e621846e435992b764265abb13a7346b/src/io/js/io.js#L88-L115 | train |
|
nwtjs/nwt | src/io/js/io.js | function(data) {
// Strip out the old query string and append the new one
if (data) {
this.url = this.url.split('?', 1)[0] + '?' + data;
}
this.req.open('GET', this.url);
return this._run();
} | javascript | function(data) {
// Strip out the old query string and append the new one
if (data) {
this.url = this.url.split('?', 1)[0] + '?' + data;
}
this.req.open('GET', this.url);
return this._run();
} | [
"function",
"(",
"data",
")",
"{",
"if",
"(",
"data",
")",
"{",
"this",
".",
"url",
"=",
"this",
".",
"url",
".",
"split",
"(",
"'?'",
",",
"1",
")",
"[",
"0",
"]",
"+",
"'?'",
"+",
"data",
";",
"}",
"this",
".",
"req",
".",
"open",
"(",
"'GET'",
",",
"this",
".",
"url",
")",
";",
"return",
"this",
".",
"_run",
"(",
")",
";",
"}"
] | Runs IO GET
@param string We update the URL if we receive data to GET here | [
"Runs",
"IO",
"GET"
] | 49991293e621846e435992b764265abb13a7346b | https://github.com/nwtjs/nwt/blob/49991293e621846e435992b764265abb13a7346b/src/io/js/io.js#L122-L131 | train |
|
cludden/mycro | hooks/models.js | function(fn) {
asyncjs.each(modelNames, function(name, _fn) {
// get model definition
var modelDefinition = modelDefinitions[name];
modelDefinition.__name = name;
// get connection info
var connectionInfo = lib.findConnection(mycro, name);
if (!connectionInfo) {
mycro.log('silly', '[models] Unable to find explicit adapter for model (' + name + ')');
if (!defaultConnection ) {
return _fn('Unable to find adapter for model (' + name + ')');
} else {
connectionInfo = defaultConnection;
}
}
// validate handler exists
var adapter = connectionInfo.adapter;
if (!adapter.registerModel || !_.isFunction(adapter.registerModel) || adapter.registerModel.length < 3) {
return _fn('Invalid adapter api: adapters should define a `registerModel` method that accepts a connection object, model definition object, and a callback');
}
// hand off to adapter
var registerModelCallback = function(err, model) {
if (err) {
return _fn(err);
}
if (!model) {
return _fn('No model (' + name + ') returned from `adapter.registerModel`');
}
mycro.models[name] = model;
_fn();
};
if (adapter.registerModel.length === 3) {
return adapter.registerModel(connectionInfo.connection, modelDefinition, registerModelCallback);
} else if (adapter.registerModel.length === 4) {
return adapter.registerModel(connectionInfo.connection, modelDefinition, name, registerModelCallback);
} else {
return adapter.registerModel(connectionInfo.connection, modelDefinition, name, mycro, registerModelCallback);
}
}, fn);
} | javascript | function(fn) {
asyncjs.each(modelNames, function(name, _fn) {
// get model definition
var modelDefinition = modelDefinitions[name];
modelDefinition.__name = name;
// get connection info
var connectionInfo = lib.findConnection(mycro, name);
if (!connectionInfo) {
mycro.log('silly', '[models] Unable to find explicit adapter for model (' + name + ')');
if (!defaultConnection ) {
return _fn('Unable to find adapter for model (' + name + ')');
} else {
connectionInfo = defaultConnection;
}
}
// validate handler exists
var adapter = connectionInfo.adapter;
if (!adapter.registerModel || !_.isFunction(adapter.registerModel) || adapter.registerModel.length < 3) {
return _fn('Invalid adapter api: adapters should define a `registerModel` method that accepts a connection object, model definition object, and a callback');
}
// hand off to adapter
var registerModelCallback = function(err, model) {
if (err) {
return _fn(err);
}
if (!model) {
return _fn('No model (' + name + ') returned from `adapter.registerModel`');
}
mycro.models[name] = model;
_fn();
};
if (adapter.registerModel.length === 3) {
return adapter.registerModel(connectionInfo.connection, modelDefinition, registerModelCallback);
} else if (adapter.registerModel.length === 4) {
return adapter.registerModel(connectionInfo.connection, modelDefinition, name, registerModelCallback);
} else {
return adapter.registerModel(connectionInfo.connection, modelDefinition, name, mycro, registerModelCallback);
}
}, fn);
} | [
"function",
"(",
"fn",
")",
"{",
"asyncjs",
".",
"each",
"(",
"modelNames",
",",
"function",
"(",
"name",
",",
"_fn",
")",
"{",
"var",
"modelDefinition",
"=",
"modelDefinitions",
"[",
"name",
"]",
";",
"modelDefinition",
".",
"__name",
"=",
"name",
";",
"var",
"connectionInfo",
"=",
"lib",
".",
"findConnection",
"(",
"mycro",
",",
"name",
")",
";",
"if",
"(",
"!",
"connectionInfo",
")",
"{",
"mycro",
".",
"log",
"(",
"'silly'",
",",
"'[models] Unable to find explicit adapter for model ('",
"+",
"name",
"+",
"')'",
")",
";",
"if",
"(",
"!",
"defaultConnection",
")",
"{",
"return",
"_fn",
"(",
"'Unable to find adapter for model ('",
"+",
"name",
"+",
"')'",
")",
";",
"}",
"else",
"{",
"connectionInfo",
"=",
"defaultConnection",
";",
"}",
"}",
"var",
"adapter",
"=",
"connectionInfo",
".",
"adapter",
";",
"if",
"(",
"!",
"adapter",
".",
"registerModel",
"||",
"!",
"_",
".",
"isFunction",
"(",
"adapter",
".",
"registerModel",
")",
"||",
"adapter",
".",
"registerModel",
".",
"length",
"<",
"3",
")",
"{",
"return",
"_fn",
"(",
"'Invalid adapter api: adapters should define a `registerModel` method that accepts a connection object, model definition object, and a callback'",
")",
";",
"}",
"var",
"registerModelCallback",
"=",
"function",
"(",
"err",
",",
"model",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"_fn",
"(",
"err",
")",
";",
"}",
"if",
"(",
"!",
"model",
")",
"{",
"return",
"_fn",
"(",
"'No model ('",
"+",
"name",
"+",
"') returned from `adapter.registerModel`'",
")",
";",
"}",
"mycro",
".",
"models",
"[",
"name",
"]",
"=",
"model",
";",
"_fn",
"(",
")",
";",
"}",
";",
"if",
"(",
"adapter",
".",
"registerModel",
".",
"length",
"===",
"3",
")",
"{",
"return",
"adapter",
".",
"registerModel",
"(",
"connectionInfo",
".",
"connection",
",",
"modelDefinition",
",",
"registerModelCallback",
")",
";",
"}",
"else",
"if",
"(",
"adapter",
".",
"registerModel",
".",
"length",
"===",
"4",
")",
"{",
"return",
"adapter",
".",
"registerModel",
"(",
"connectionInfo",
".",
"connection",
",",
"modelDefinition",
",",
"name",
",",
"registerModelCallback",
")",
";",
"}",
"else",
"{",
"return",
"adapter",
".",
"registerModel",
"(",
"connectionInfo",
".",
"connection",
",",
"modelDefinition",
",",
"name",
",",
"mycro",
",",
"registerModelCallback",
")",
";",
"}",
"}",
",",
"fn",
")",
";",
"}"
] | hand model definitions to the appropriate adapter for construction | [
"hand",
"model",
"definitions",
"to",
"the",
"appropriate",
"adapter",
"for",
"construction"
] | 762e6ba0f38f37497eefb933252edc2c16bfb40b | https://github.com/cludden/mycro/blob/762e6ba0f38f37497eefb933252edc2c16bfb40b/hooks/models.js#L33-L75 | train |
|
cludden/mycro | hooks/models.js | function(err, model) {
if (err) {
return _fn(err);
}
if (!model) {
return _fn('No model (' + name + ') returned from `adapter.registerModel`');
}
mycro.models[name] = model;
_fn();
} | javascript | function(err, model) {
if (err) {
return _fn(err);
}
if (!model) {
return _fn('No model (' + name + ') returned from `adapter.registerModel`');
}
mycro.models[name] = model;
_fn();
} | [
"function",
"(",
"err",
",",
"model",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"_fn",
"(",
"err",
")",
";",
"}",
"if",
"(",
"!",
"model",
")",
"{",
"return",
"_fn",
"(",
"'No model ('",
"+",
"name",
"+",
"') returned from `adapter.registerModel`'",
")",
";",
"}",
"mycro",
".",
"models",
"[",
"name",
"]",
"=",
"model",
";",
"_fn",
"(",
")",
";",
"}"
] | hand off to adapter | [
"hand",
"off",
"to",
"adapter"
] | 762e6ba0f38f37497eefb933252edc2c16bfb40b | https://github.com/cludden/mycro/blob/762e6ba0f38f37497eefb933252edc2c16bfb40b/hooks/models.js#L57-L66 | train |
|
scienceai/graph-rdfa-processor | src/rdfa-processor.js | function(baseURI) {
var hash = baseURI.indexOf("#");
if (hash>=0) {
baseURI = baseURI.substring(0,hash);
}
if (options && options.baseURIMap) {
baseURI = options.baseURIMap(baseURI);
}
return baseURI;
} | javascript | function(baseURI) {
var hash = baseURI.indexOf("#");
if (hash>=0) {
baseURI = baseURI.substring(0,hash);
}
if (options && options.baseURIMap) {
baseURI = options.baseURIMap(baseURI);
}
return baseURI;
} | [
"function",
"(",
"baseURI",
")",
"{",
"var",
"hash",
"=",
"baseURI",
".",
"indexOf",
"(",
"\"#\"",
")",
";",
"if",
"(",
"hash",
">=",
"0",
")",
"{",
"baseURI",
"=",
"baseURI",
".",
"substring",
"(",
"0",
",",
"hash",
")",
";",
"}",
"if",
"(",
"options",
"&&",
"options",
".",
"baseURIMap",
")",
"{",
"baseURI",
"=",
"options",
".",
"baseURIMap",
"(",
"baseURI",
")",
";",
"}",
"return",
"baseURI",
";",
"}"
] | Fix for Firefox that includes the hash in the base URI | [
"Fix",
"for",
"Firefox",
"that",
"includes",
"the",
"hash",
"in",
"the",
"base",
"URI"
] | 39e00b3d498b2081524843717b287dfaa946c261 | https://github.com/scienceai/graph-rdfa-processor/blob/39e00b3d498b2081524843717b287dfaa946c261/src/rdfa-processor.js#L289-L298 | train |
|
scott-wyatt/sails-stripe | templates/Subscription.template.js | function (subscription, cb) {
Subscription.findOrCreate(subscription.id, subscription)
.exec(function (err, foundSubscription){
if (err) return cb(err);
if (foundSubscription.lastStripeEvent > subscription.lastStripeEvent) return cb(null, foundSubscription);
if (foundSubscription.lastStripeEvent == subscription.lastStripeEvent) return Subscription.afterStripeCustomerSubscriptionUpdated(foundSubscription, function(err, subscription){ return cb(err, subscription)});
Subscription.update(foundSubscription.id, subscription)
.exec(function(err, updatedSubscriptions){
if (err) return cb(err);
if(!updatedSubscriptions) return cb(null, null);
Subscription.afterStripeCustomerSubscriptionUpdated(updatedSubscriptions[0], function(err, subscription){
cb(err, subscription);
});
});
});
} | javascript | function (subscription, cb) {
Subscription.findOrCreate(subscription.id, subscription)
.exec(function (err, foundSubscription){
if (err) return cb(err);
if (foundSubscription.lastStripeEvent > subscription.lastStripeEvent) return cb(null, foundSubscription);
if (foundSubscription.lastStripeEvent == subscription.lastStripeEvent) return Subscription.afterStripeCustomerSubscriptionUpdated(foundSubscription, function(err, subscription){ return cb(err, subscription)});
Subscription.update(foundSubscription.id, subscription)
.exec(function(err, updatedSubscriptions){
if (err) return cb(err);
if(!updatedSubscriptions) return cb(null, null);
Subscription.afterStripeCustomerSubscriptionUpdated(updatedSubscriptions[0], function(err, subscription){
cb(err, subscription);
});
});
});
} | [
"function",
"(",
"subscription",
",",
"cb",
")",
"{",
"Subscription",
".",
"findOrCreate",
"(",
"subscription",
".",
"id",
",",
"subscription",
")",
".",
"exec",
"(",
"function",
"(",
"err",
",",
"foundSubscription",
")",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"err",
")",
";",
"if",
"(",
"foundSubscription",
".",
"lastStripeEvent",
">",
"subscription",
".",
"lastStripeEvent",
")",
"return",
"cb",
"(",
"null",
",",
"foundSubscription",
")",
";",
"if",
"(",
"foundSubscription",
".",
"lastStripeEvent",
"==",
"subscription",
".",
"lastStripeEvent",
")",
"return",
"Subscription",
".",
"afterStripeCustomerSubscriptionUpdated",
"(",
"foundSubscription",
",",
"function",
"(",
"err",
",",
"subscription",
")",
"{",
"return",
"cb",
"(",
"err",
",",
"subscription",
")",
"}",
")",
";",
"Subscription",
".",
"update",
"(",
"foundSubscription",
".",
"id",
",",
"subscription",
")",
".",
"exec",
"(",
"function",
"(",
"err",
",",
"updatedSubscriptions",
")",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"err",
")",
";",
"if",
"(",
"!",
"updatedSubscriptions",
")",
"return",
"cb",
"(",
"null",
",",
"null",
")",
";",
"Subscription",
".",
"afterStripeCustomerSubscriptionUpdated",
"(",
"updatedSubscriptions",
"[",
"0",
"]",
",",
"function",
"(",
"err",
",",
"subscription",
")",
"{",
"cb",
"(",
"err",
",",
"subscription",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | Stripe Webhook customer.subscription.updated | [
"Stripe",
"Webhook",
"customer",
".",
"subscription",
".",
"updated"
] | 0766bc04a6893a07c842170f37b37200d6771425 | https://github.com/scott-wyatt/sails-stripe/blob/0766bc04a6893a07c842170f37b37200d6771425/templates/Subscription.template.js#L126-L142 | train |
|
scott-wyatt/sails-stripe | templates/Subscription.template.js | function (subscription, cb) {
Subscription.destroy(subscription.id)
.exec(function (err, destroyedSubscriptions){
if (err) return cb(err);
if (!destroyedSubscriptions) return cb(null, subscription);
Subscription.afterStripeCustomerSubscriptionDeleted(destroyedSubscriptions[0], function(err, subscription){
cb(err, subscription);
});
});
} | javascript | function (subscription, cb) {
Subscription.destroy(subscription.id)
.exec(function (err, destroyedSubscriptions){
if (err) return cb(err);
if (!destroyedSubscriptions) return cb(null, subscription);
Subscription.afterStripeCustomerSubscriptionDeleted(destroyedSubscriptions[0], function(err, subscription){
cb(err, subscription);
});
});
} | [
"function",
"(",
"subscription",
",",
"cb",
")",
"{",
"Subscription",
".",
"destroy",
"(",
"subscription",
".",
"id",
")",
".",
"exec",
"(",
"function",
"(",
"err",
",",
"destroyedSubscriptions",
")",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"err",
")",
";",
"if",
"(",
"!",
"destroyedSubscriptions",
")",
"return",
"cb",
"(",
"null",
",",
"subscription",
")",
";",
"Subscription",
".",
"afterStripeCustomerSubscriptionDeleted",
"(",
"destroyedSubscriptions",
"[",
"0",
"]",
",",
"function",
"(",
"err",
",",
"subscription",
")",
"{",
"cb",
"(",
"err",
",",
"subscription",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | Stripe Webhook customer.subscription.deleted | [
"Stripe",
"Webhook",
"customer",
".",
"subscription",
".",
"deleted"
] | 0766bc04a6893a07c842170f37b37200d6771425 | https://github.com/scott-wyatt/sails-stripe/blob/0766bc04a6893a07c842170f37b37200d6771425/templates/Subscription.template.js#L150-L160 | train |
|
ChrisWren/mdlint | index.js | fetchRepoREADME | function fetchRepoREADME (repo) {
request({
uri: 'https://api.github.com/repos/' + repo + '/readme',
headers: _.extend(headers, {
// Get raw README content
'Accept': 'application/vnd.github.VERSION.raw'
})
},
function (error, response, body) {
if (!error && response.statusCode === 200) {
lintMarkdown(body, repo);
} else {
if (response.headers['x-ratelimit-remaining'] === '0') {
getAuthToken();
} else {
console.log('README for https://github.com/' + repo.blue + ' not found.'.red);
return;
}
}
});
} | javascript | function fetchRepoREADME (repo) {
request({
uri: 'https://api.github.com/repos/' + repo + '/readme',
headers: _.extend(headers, {
// Get raw README content
'Accept': 'application/vnd.github.VERSION.raw'
})
},
function (error, response, body) {
if (!error && response.statusCode === 200) {
lintMarkdown(body, repo);
} else {
if (response.headers['x-ratelimit-remaining'] === '0') {
getAuthToken();
} else {
console.log('README for https://github.com/' + repo.blue + ' not found.'.red);
return;
}
}
});
} | [
"function",
"fetchRepoREADME",
"(",
"repo",
")",
"{",
"request",
"(",
"{",
"uri",
":",
"'https://api.github.com/repos/'",
"+",
"repo",
"+",
"'/readme'",
",",
"headers",
":",
"_",
".",
"extend",
"(",
"headers",
",",
"{",
"'Accept'",
":",
"'application/vnd.github.VERSION.raw'",
"}",
")",
"}",
",",
"function",
"(",
"error",
",",
"response",
",",
"body",
")",
"{",
"if",
"(",
"!",
"error",
"&&",
"response",
".",
"statusCode",
"===",
"200",
")",
"{",
"lintMarkdown",
"(",
"body",
",",
"repo",
")",
";",
"}",
"else",
"{",
"if",
"(",
"response",
".",
"headers",
"[",
"'x-ratelimit-remaining'",
"]",
"===",
"'0'",
")",
"{",
"getAuthToken",
"(",
")",
";",
"}",
"else",
"{",
"console",
".",
"log",
"(",
"'README for https://github.com/'",
"+",
"repo",
".",
"blue",
"+",
"' not found.'",
".",
"red",
")",
";",
"return",
";",
"}",
"}",
"}",
")",
";",
"}"
] | Fetches a README from GitHub
@param {String} repo URL of repo to fetch | [
"Fetches",
"a",
"README",
"from",
"GitHub"
] | 15acc4b044f102644cba907699e793aecd053ab7 | https://github.com/ChrisWren/mdlint/blob/15acc4b044f102644cba907699e793aecd053ab7/index.js#L162-L183 | train |
ChrisWren/mdlint | index.js | lintMarkdown | function lintMarkdown (body, file) {
var codeBlocks = parseMarkdown(body);
didLogFileBreak = false;
var failedCodeBlocks = _.reject(_.compact(codeBlocks), function (codeBlock) {
return validateCodeBlock(codeBlock, file);
});
numFilesToParse--;
if (failedCodeBlocks.length === 0) {
if (program.verbose) {
console.log('Markdown passed linting for '.green + file.blue.bold + '\n');
} else if (numFilesToParse === 0) {
console.log('All markdown files passed linting'.green);
}
} else {
if (numFailedFiles % 2 === 0) {
console.log('Markdown failed linting for '.red + file.yellow);
} else {
console.log('Markdown failed linting for '.red + file.blue);
}
numFailedFiles++;
console.log('');
}
} | javascript | function lintMarkdown (body, file) {
var codeBlocks = parseMarkdown(body);
didLogFileBreak = false;
var failedCodeBlocks = _.reject(_.compact(codeBlocks), function (codeBlock) {
return validateCodeBlock(codeBlock, file);
});
numFilesToParse--;
if (failedCodeBlocks.length === 0) {
if (program.verbose) {
console.log('Markdown passed linting for '.green + file.blue.bold + '\n');
} else if (numFilesToParse === 0) {
console.log('All markdown files passed linting'.green);
}
} else {
if (numFailedFiles % 2 === 0) {
console.log('Markdown failed linting for '.red + file.yellow);
} else {
console.log('Markdown failed linting for '.red + file.blue);
}
numFailedFiles++;
console.log('');
}
} | [
"function",
"lintMarkdown",
"(",
"body",
",",
"file",
")",
"{",
"var",
"codeBlocks",
"=",
"parseMarkdown",
"(",
"body",
")",
";",
"didLogFileBreak",
"=",
"false",
";",
"var",
"failedCodeBlocks",
"=",
"_",
".",
"reject",
"(",
"_",
".",
"compact",
"(",
"codeBlocks",
")",
",",
"function",
"(",
"codeBlock",
")",
"{",
"return",
"validateCodeBlock",
"(",
"codeBlock",
",",
"file",
")",
";",
"}",
")",
";",
"numFilesToParse",
"--",
";",
"if",
"(",
"failedCodeBlocks",
".",
"length",
"===",
"0",
")",
"{",
"if",
"(",
"program",
".",
"verbose",
")",
"{",
"console",
".",
"log",
"(",
"'Markdown passed linting for '",
".",
"green",
"+",
"file",
".",
"blue",
".",
"bold",
"+",
"'\\n'",
")",
";",
"}",
"else",
"\\n",
"}",
"else",
"if",
"(",
"numFilesToParse",
"===",
"0",
")",
"{",
"console",
".",
"log",
"(",
"'All markdown files passed linting'",
".",
"green",
")",
";",
"}",
"}"
] | Parses the JavaScript code blocks from the markdown file
@param {String} body Body of markdown file
@param {String} file Filename | [
"Parses",
"the",
"JavaScript",
"code",
"blocks",
"from",
"the",
"markdown",
"file"
] | 15acc4b044f102644cba907699e793aecd053ab7 | https://github.com/ChrisWren/mdlint/blob/15acc4b044f102644cba907699e793aecd053ab7/index.js#L226-L252 | train |
ChrisWren/mdlint | index.js | logFileBreak | function logFileBreak (text) {
if (numFailedFiles % 2 === 0) {
console.log(text.yellow.inverse);
} else {
console.log(text.blue.inverse);
}
} | javascript | function logFileBreak (text) {
if (numFailedFiles % 2 === 0) {
console.log(text.yellow.inverse);
} else {
console.log(text.blue.inverse);
}
} | [
"function",
"logFileBreak",
"(",
"text",
")",
"{",
"if",
"(",
"numFailedFiles",
"%",
"2",
"===",
"0",
")",
"{",
"console",
".",
"log",
"(",
"text",
".",
"yellow",
".",
"inverse",
")",
";",
"}",
"else",
"{",
"console",
".",
"log",
"(",
"text",
".",
"blue",
".",
"inverse",
")",
";",
"}",
"}"
] | Logs a break between files for readability
@param {String} text Text to log | [
"Logs",
"a",
"break",
"between",
"files",
"for",
"readability"
] | 15acc4b044f102644cba907699e793aecd053ab7 | https://github.com/ChrisWren/mdlint/blob/15acc4b044f102644cba907699e793aecd053ab7/index.js#L258-L264 | train |
ChrisWren/mdlint | index.js | validateCodeBlock | function validateCodeBlock (codeBlock, file) {
var lang = codeBlock.lang;
var code = codeBlock.code;
if (lang === 'json') {
try {
JSON.parse(code);
} catch (e) {
console.log(e);
console.log(code);
return false;
}
return true;
} else if (lang === 'js' || lang === 'javascript') {
code = preprocessCode(code);
try {
esprima.parse(code, { tolerant: true });
} catch (e) {
// Get indeces from lineNumber and column
var line = e.lineNumber - 1;
var column = e.column - 1;
// Highlight error in code
code = code.split('\n');
code[line] = code[line].slice(0, column).magenta +
code[line][column].red +
code[line].slice(column + 1).magenta;
code = code.join('\n');
if (!didLogFileBreak) {
logFileBreak(file);
didLogFileBreak = true;
}
console.log(e);
console.log(code);
return false;
}
return true;
}
} | javascript | function validateCodeBlock (codeBlock, file) {
var lang = codeBlock.lang;
var code = codeBlock.code;
if (lang === 'json') {
try {
JSON.parse(code);
} catch (e) {
console.log(e);
console.log(code);
return false;
}
return true;
} else if (lang === 'js' || lang === 'javascript') {
code = preprocessCode(code);
try {
esprima.parse(code, { tolerant: true });
} catch (e) {
// Get indeces from lineNumber and column
var line = e.lineNumber - 1;
var column = e.column - 1;
// Highlight error in code
code = code.split('\n');
code[line] = code[line].slice(0, column).magenta +
code[line][column].red +
code[line].slice(column + 1).magenta;
code = code.join('\n');
if (!didLogFileBreak) {
logFileBreak(file);
didLogFileBreak = true;
}
console.log(e);
console.log(code);
return false;
}
return true;
}
} | [
"function",
"validateCodeBlock",
"(",
"codeBlock",
",",
"file",
")",
"{",
"var",
"lang",
"=",
"codeBlock",
".",
"lang",
";",
"var",
"code",
"=",
"codeBlock",
".",
"code",
";",
"if",
"(",
"lang",
"===",
"'json'",
")",
"{",
"try",
"{",
"JSON",
".",
"parse",
"(",
"code",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"console",
".",
"log",
"(",
"e",
")",
";",
"console",
".",
"log",
"(",
"code",
")",
";",
"return",
"false",
";",
"}",
"return",
"true",
";",
"}",
"else",
"if",
"(",
"lang",
"===",
"'js'",
"||",
"lang",
"===",
"'javascript'",
")",
"{",
"code",
"=",
"preprocessCode",
"(",
"code",
")",
";",
"try",
"{",
"esprima",
".",
"parse",
"(",
"code",
",",
"{",
"tolerant",
":",
"true",
"}",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"var",
"line",
"=",
"e",
".",
"lineNumber",
"-",
"1",
";",
"var",
"column",
"=",
"e",
".",
"column",
"-",
"1",
";",
"code",
"=",
"code",
".",
"split",
"(",
"'\\n'",
")",
";",
"\\n",
"code",
"[",
"line",
"]",
"=",
"code",
"[",
"line",
"]",
".",
"slice",
"(",
"0",
",",
"column",
")",
".",
"magenta",
"+",
"code",
"[",
"line",
"]",
"[",
"column",
"]",
".",
"red",
"+",
"code",
"[",
"line",
"]",
".",
"slice",
"(",
"column",
"+",
"1",
")",
".",
"magenta",
";",
"code",
"=",
"code",
".",
"join",
"(",
"'\\n'",
")",
";",
"\\n",
"if",
"(",
"!",
"didLogFileBreak",
")",
"{",
"logFileBreak",
"(",
"file",
")",
";",
"didLogFileBreak",
"=",
"true",
";",
"}",
"console",
".",
"log",
"(",
"e",
")",
";",
"}",
"console",
".",
"log",
"(",
"code",
")",
";",
"}",
"}"
] | Validates that code blocks are valid JavaScript
@param {Object} code A block of code from the markdown file containg the lang and code
@param {String} file Name of file currently being validated | [
"Validates",
"that",
"code",
"blocks",
"are",
"valid",
"JavaScript"
] | 15acc4b044f102644cba907699e793aecd053ab7 | https://github.com/ChrisWren/mdlint/blob/15acc4b044f102644cba907699e793aecd053ab7/index.js#L271-L315 | train |
ChrisWren/mdlint | index.js | getAuthToken | function getAuthToken () {
console.log('You have hit the rate limit for unauthenticated requests, please log in to raise your rate limit:\n'.red);
program.prompt('GitHub Username: ', function (user) {
console.log('\nAfter entering your password, hit return' + ' twice.\n'.green);
var authProcess = spawn('curl', [
'-u',
user,
'-d',
'{"scopes":["repo"],"note":"mdlint"}',
'-s',
'https://api.github.com/authorizations'
], {
stdio: [process.stdin, 'pipe', process.stderr]
});
authProcess.stdout.setEncoding('utf8');
authProcess.stdout.on('data', function (data) {
var response = JSON.parse(data);
if (response.message) {
console.log(response.message.red + '\n');
process.exit();
} else {
fs.writeFileSync(tokenFile, response.token);
console.log('Authenticated :). Now try your lint again. \n'.green);
process.exit();
}
});
});
} | javascript | function getAuthToken () {
console.log('You have hit the rate limit for unauthenticated requests, please log in to raise your rate limit:\n'.red);
program.prompt('GitHub Username: ', function (user) {
console.log('\nAfter entering your password, hit return' + ' twice.\n'.green);
var authProcess = spawn('curl', [
'-u',
user,
'-d',
'{"scopes":["repo"],"note":"mdlint"}',
'-s',
'https://api.github.com/authorizations'
], {
stdio: [process.stdin, 'pipe', process.stderr]
});
authProcess.stdout.setEncoding('utf8');
authProcess.stdout.on('data', function (data) {
var response = JSON.parse(data);
if (response.message) {
console.log(response.message.red + '\n');
process.exit();
} else {
fs.writeFileSync(tokenFile, response.token);
console.log('Authenticated :). Now try your lint again. \n'.green);
process.exit();
}
});
});
} | [
"function",
"getAuthToken",
"(",
")",
"{",
"console",
".",
"log",
"(",
"'You have hit the rate limit for unauthenticated requests, please log in to raise your rate limit:\\n'",
".",
"\\n",
")",
";",
"red",
"}"
] | Retrieves an auth token so that the user can exceed the uauthenticated rate limit | [
"Retrieves",
"an",
"auth",
"token",
"so",
"that",
"the",
"user",
"can",
"exceed",
"the",
"uauthenticated",
"rate",
"limit"
] | 15acc4b044f102644cba907699e793aecd053ab7 | https://github.com/ChrisWren/mdlint/blob/15acc4b044f102644cba907699e793aecd053ab7/index.js#L320-L350 | train |
ChrisWren/mdlint | index.js | preprocessCode | function preprocessCode (code) {
// Remove starting comments
while (code.indexOf('//') === 0) {
code = code.slice(code.indexOf('\n'));
}
// Starts with an object literal
if (code.indexOf('{') === 0) {
code = 'var json = ' + code;
// Starts with an object property
} else if (code.indexOf(':') !== -1 &&
code.indexOf(':') < code.indexOf(' ')) {
code = 'var json = {' + code + '}';
}
// Starts with an anonymous function
if (code.indexOf('function') === 0) {
code = 'var func = ' + code;
}
// Contains ...
return code.replace('...', '');
} | javascript | function preprocessCode (code) {
// Remove starting comments
while (code.indexOf('//') === 0) {
code = code.slice(code.indexOf('\n'));
}
// Starts with an object literal
if (code.indexOf('{') === 0) {
code = 'var json = ' + code;
// Starts with an object property
} else if (code.indexOf(':') !== -1 &&
code.indexOf(':') < code.indexOf(' ')) {
code = 'var json = {' + code + '}';
}
// Starts with an anonymous function
if (code.indexOf('function') === 0) {
code = 'var func = ' + code;
}
// Contains ...
return code.replace('...', '');
} | [
"function",
"preprocessCode",
"(",
"code",
")",
"{",
"while",
"(",
"code",
".",
"indexOf",
"(",
"'//'",
")",
"===",
"0",
")",
"{",
"code",
"=",
"code",
".",
"slice",
"(",
"code",
".",
"indexOf",
"(",
"'\\n'",
")",
")",
";",
"}",
"\\n",
"if",
"(",
"code",
".",
"indexOf",
"(",
"'{'",
")",
"===",
"0",
")",
"{",
"code",
"=",
"'var json = '",
"+",
"code",
";",
"}",
"else",
"if",
"(",
"code",
".",
"indexOf",
"(",
"':'",
")",
"!==",
"-",
"1",
"&&",
"code",
".",
"indexOf",
"(",
"':'",
")",
"<",
"code",
".",
"indexOf",
"(",
"' '",
")",
")",
"{",
"code",
"=",
"'var json = {'",
"+",
"code",
"+",
"'}'",
";",
"}",
"if",
"(",
"code",
".",
"indexOf",
"(",
"'function'",
")",
"===",
"0",
")",
"{",
"code",
"=",
"'var func = '",
"+",
"code",
";",
"}",
"}"
] | Preprocesses the code block and re-formats it to allow for partial code
@param {String} code A block of code from the markdown file
@return {String} Processed code transformed from partial code | [
"Preprocesses",
"the",
"code",
"block",
"and",
"re",
"-",
"formats",
"it",
"to",
"allow",
"for",
"partial",
"code"
] | 15acc4b044f102644cba907699e793aecd053ab7 | https://github.com/ChrisWren/mdlint/blob/15acc4b044f102644cba907699e793aecd053ab7/index.js#L357-L381 | train |
tprobinson/node-simple-dockerode | lib/processExec.js | processExec | function processExec(opts, createOpts, execOpts, callback) {
this.execRaw(createOpts, (createErr, exec) => {
if( createErr ) { callback(createErr); return }
exec.start(execOpts, (execErr, stream) => {
if( execErr ) { callback(execErr); return }
if( 'live' in opts && opts.live ) {
// If the user wants live streams, give them a function to attach to the builtin demuxStream
callback(null, (stdout, stderr) => {
if( stdout || stderr ) {
this.modem.demuxStream(stream, stdout, stderr)
}
// Allow an .on('end').
return stream
})
} else {
const results = {}
let callbackCalled = false
const callbackOnce = err => {
if( !callbackCalled ) {
callbackCalled = true
if( err ) {
Object.assign(results, {error: err})
}
// Inspect the exec and put that information into the results as well
// Allow this to be turned off via option later
// Workaround: if the user only has stdin and no stdout,
// the process will sometimes not immediately end.
let times = 10
const inspectLoop = () => {
exec.inspect((inspError, inspect) => {
if( inspect.ExitCode !== null ) {
if( times !== 10 ) {
inspect.tries = 10 - times
}
Object.assign(results, {inspect})
callback(inspError, results)
} else {
times--
setTimeout(inspectLoop, 50)
}
})
}
inspectLoop()
}
}
if( execOpts.Detach ) {
// Bitbucket the stream's data, so that it can close.
stream.on('data', () => {})
}
if( opts.stdin ) {
// Send the process whatever the user's going for.
if( isStream(opts.stdin) ) {
opts.stdin.pipe(stream)
} else {
const sender = new Stream.Readable()
sender.push(opts.stdin)
sender.push(null)
sender.pipe(stream)
}
}
if( opts.stdout || opts.stderr ) {
// Set up the battery to merge in its results when it's done. If it had an error, trigger the whole thing returning.
const battery = new StreamBattery(['stdout', 'stderr'], (battError, battResults) => {
Object.assign(results, battResults)
if( battError ) {
callbackOnce(battError)
}
})
// Start the stream demuxing
this.modem.demuxStream(stream, ...battery.streams)
stream.on('end', () => battery.end())
}
// Wait for the exec to end.
stream.on('end', callbackOnce)
stream.on('close', callbackOnce)
stream.on('error', callbackOnce)
}
})
})
} | javascript | function processExec(opts, createOpts, execOpts, callback) {
this.execRaw(createOpts, (createErr, exec) => {
if( createErr ) { callback(createErr); return }
exec.start(execOpts, (execErr, stream) => {
if( execErr ) { callback(execErr); return }
if( 'live' in opts && opts.live ) {
// If the user wants live streams, give them a function to attach to the builtin demuxStream
callback(null, (stdout, stderr) => {
if( stdout || stderr ) {
this.modem.demuxStream(stream, stdout, stderr)
}
// Allow an .on('end').
return stream
})
} else {
const results = {}
let callbackCalled = false
const callbackOnce = err => {
if( !callbackCalled ) {
callbackCalled = true
if( err ) {
Object.assign(results, {error: err})
}
// Inspect the exec and put that information into the results as well
// Allow this to be turned off via option later
// Workaround: if the user only has stdin and no stdout,
// the process will sometimes not immediately end.
let times = 10
const inspectLoop = () => {
exec.inspect((inspError, inspect) => {
if( inspect.ExitCode !== null ) {
if( times !== 10 ) {
inspect.tries = 10 - times
}
Object.assign(results, {inspect})
callback(inspError, results)
} else {
times--
setTimeout(inspectLoop, 50)
}
})
}
inspectLoop()
}
}
if( execOpts.Detach ) {
// Bitbucket the stream's data, so that it can close.
stream.on('data', () => {})
}
if( opts.stdin ) {
// Send the process whatever the user's going for.
if( isStream(opts.stdin) ) {
opts.stdin.pipe(stream)
} else {
const sender = new Stream.Readable()
sender.push(opts.stdin)
sender.push(null)
sender.pipe(stream)
}
}
if( opts.stdout || opts.stderr ) {
// Set up the battery to merge in its results when it's done. If it had an error, trigger the whole thing returning.
const battery = new StreamBattery(['stdout', 'stderr'], (battError, battResults) => {
Object.assign(results, battResults)
if( battError ) {
callbackOnce(battError)
}
})
// Start the stream demuxing
this.modem.demuxStream(stream, ...battery.streams)
stream.on('end', () => battery.end())
}
// Wait for the exec to end.
stream.on('end', callbackOnce)
stream.on('close', callbackOnce)
stream.on('error', callbackOnce)
}
})
})
} | [
"function",
"processExec",
"(",
"opts",
",",
"createOpts",
",",
"execOpts",
",",
"callback",
")",
"{",
"this",
".",
"execRaw",
"(",
"createOpts",
",",
"(",
"createErr",
",",
"exec",
")",
"=>",
"{",
"if",
"(",
"createErr",
")",
"{",
"callback",
"(",
"createErr",
")",
";",
"return",
"}",
"exec",
".",
"start",
"(",
"execOpts",
",",
"(",
"execErr",
",",
"stream",
")",
"=>",
"{",
"if",
"(",
"execErr",
")",
"{",
"callback",
"(",
"execErr",
")",
";",
"return",
"}",
"if",
"(",
"'live'",
"in",
"opts",
"&&",
"opts",
".",
"live",
")",
"{",
"callback",
"(",
"null",
",",
"(",
"stdout",
",",
"stderr",
")",
"=>",
"{",
"if",
"(",
"stdout",
"||",
"stderr",
")",
"{",
"this",
".",
"modem",
".",
"demuxStream",
"(",
"stream",
",",
"stdout",
",",
"stderr",
")",
"}",
"return",
"stream",
"}",
")",
"}",
"else",
"{",
"const",
"results",
"=",
"{",
"}",
"let",
"callbackCalled",
"=",
"false",
"const",
"callbackOnce",
"=",
"err",
"=>",
"{",
"if",
"(",
"!",
"callbackCalled",
")",
"{",
"callbackCalled",
"=",
"true",
"if",
"(",
"err",
")",
"{",
"Object",
".",
"assign",
"(",
"results",
",",
"{",
"error",
":",
"err",
"}",
")",
"}",
"let",
"times",
"=",
"10",
"const",
"inspectLoop",
"=",
"(",
")",
"=>",
"{",
"exec",
".",
"inspect",
"(",
"(",
"inspError",
",",
"inspect",
")",
"=>",
"{",
"if",
"(",
"inspect",
".",
"ExitCode",
"!==",
"null",
")",
"{",
"if",
"(",
"times",
"!==",
"10",
")",
"{",
"inspect",
".",
"tries",
"=",
"10",
"-",
"times",
"}",
"Object",
".",
"assign",
"(",
"results",
",",
"{",
"inspect",
"}",
")",
"callback",
"(",
"inspError",
",",
"results",
")",
"}",
"else",
"{",
"times",
"--",
"setTimeout",
"(",
"inspectLoop",
",",
"50",
")",
"}",
"}",
")",
"}",
"inspectLoop",
"(",
")",
"}",
"}",
"if",
"(",
"execOpts",
".",
"Detach",
")",
"{",
"stream",
".",
"on",
"(",
"'data'",
",",
"(",
")",
"=>",
"{",
"}",
")",
"}",
"if",
"(",
"opts",
".",
"stdin",
")",
"{",
"if",
"(",
"isStream",
"(",
"opts",
".",
"stdin",
")",
")",
"{",
"opts",
".",
"stdin",
".",
"pipe",
"(",
"stream",
")",
"}",
"else",
"{",
"const",
"sender",
"=",
"new",
"Stream",
".",
"Readable",
"(",
")",
"sender",
".",
"push",
"(",
"opts",
".",
"stdin",
")",
"sender",
".",
"push",
"(",
"null",
")",
"sender",
".",
"pipe",
"(",
"stream",
")",
"}",
"}",
"if",
"(",
"opts",
".",
"stdout",
"||",
"opts",
".",
"stderr",
")",
"{",
"const",
"battery",
"=",
"new",
"StreamBattery",
"(",
"[",
"'stdout'",
",",
"'stderr'",
"]",
",",
"(",
"battError",
",",
"battResults",
")",
"=>",
"{",
"Object",
".",
"assign",
"(",
"results",
",",
"battResults",
")",
"if",
"(",
"battError",
")",
"{",
"callbackOnce",
"(",
"battError",
")",
"}",
"}",
")",
"this",
".",
"modem",
".",
"demuxStream",
"(",
"stream",
",",
"...",
"battery",
".",
"streams",
")",
"stream",
".",
"on",
"(",
"'end'",
",",
"(",
")",
"=>",
"battery",
".",
"end",
"(",
")",
")",
"}",
"stream",
".",
"on",
"(",
"'end'",
",",
"callbackOnce",
")",
"stream",
".",
"on",
"(",
"'close'",
",",
"callbackOnce",
")",
"stream",
".",
"on",
"(",
"'error'",
",",
"callbackOnce",
")",
"}",
"}",
")",
"}",
")",
"}"
] | A version of exec that wraps Dockerode's, reducing the stream handling for most use cases.
@param {Array<string>} Cmd The command to execute, in exec array form.
@param {Object} opts Object of options.
@param {boolean} opts.stdout True/false, if true, user will receive a stdout key with the output
@param {boolean} opts.stderr True/false, if true, user will receive a stderr key with the output
@param {string|Stream} opts.stdin If this key exists, whatever the user puts in here will be sent to the container.
@param {boolean} opts.live If true, the user will receive a function to plug into the demuxer, instead of finished values.
@param {Object} createOpts Args for the normal exec.create, processed via {@link processArgs}
@param {Object} execOpts Args for the normal exec.start, processed via {@link processArgs}
@param {function} callback Will be called with either a function to plug into demuxer, or an object with whatever output keys the user requested. | [
"A",
"version",
"of",
"exec",
"that",
"wraps",
"Dockerode",
"s",
"reducing",
"the",
"stream",
"handling",
"for",
"most",
"use",
"cases",
"."
] | b201490ac82859d560e5a687fee7a8410700a87a | https://github.com/tprobinson/node-simple-dockerode/blob/b201490ac82859d560e5a687fee7a8410700a87a/lib/processExec.js#L17-L103 | train |
brandonheyer/mazejs | js/foundation/foundation.forms.js | function() {
// Internal reference.
var _self = this;
// Loop through our hidden element collection.
_self.hidden.each( function( i ) {
// Cache this element.
var $elem = $( this ),
_tmp = _self.tmp[ i ]; // Get the stored 'style' value for this element.
// If the stored value is undefined.
if( _tmp === undefined )
// Remove the style attribute.
$elem.removeAttr( 'style' );
else
// Otherwise, reset the element style attribute.
$elem.attr( 'style', _tmp );
});
// Reset the tmp array.
_self.tmp = [];
// Reset the hidden elements variable.
_self.hidden = null;
} | javascript | function() {
// Internal reference.
var _self = this;
// Loop through our hidden element collection.
_self.hidden.each( function( i ) {
// Cache this element.
var $elem = $( this ),
_tmp = _self.tmp[ i ]; // Get the stored 'style' value for this element.
// If the stored value is undefined.
if( _tmp === undefined )
// Remove the style attribute.
$elem.removeAttr( 'style' );
else
// Otherwise, reset the element style attribute.
$elem.attr( 'style', _tmp );
});
// Reset the tmp array.
_self.tmp = [];
// Reset the hidden elements variable.
_self.hidden = null;
} | [
"function",
"(",
")",
"{",
"var",
"_self",
"=",
"this",
";",
"_self",
".",
"hidden",
".",
"each",
"(",
"function",
"(",
"i",
")",
"{",
"var",
"$elem",
"=",
"$",
"(",
"this",
")",
",",
"_tmp",
"=",
"_self",
".",
"tmp",
"[",
"i",
"]",
";",
"if",
"(",
"_tmp",
"===",
"undefined",
")",
"$elem",
".",
"removeAttr",
"(",
"'style'",
")",
";",
"else",
"$elem",
".",
"attr",
"(",
"'style'",
",",
"_tmp",
")",
";",
"}",
")",
";",
"_self",
".",
"tmp",
"=",
"[",
"]",
";",
"_self",
".",
"hidden",
"=",
"null",
";",
"}"
] | end adjust
Resets the elements previous state.
@method reset | [
"end",
"adjust",
"Resets",
"the",
"elements",
"previous",
"state",
"."
] | 5efffc0279eeb061a71ba243313d165c16300fe6 | https://github.com/brandonheyer/mazejs/blob/5efffc0279eeb061a71ba243313d165c16300fe6/js/foundation/foundation.forms.js#L396-L419 | train |
|
scott-wyatt/sails-stripe | templates/Transfer.template.js | function (transfer, cb) {
Transfer.findOrCreate(transfer.id, transfer)
.exec(function (err, foundTransfer){
if (err) return cb(err);
if (foundTransfer.lastStripeEvent > transfer.lastStripeEvent) return cb(null, foundTransfer);
if (foundTransfer.lastStripeEvent == transfer.lastStripeEvent) return Transfer.afterStripeTransferCreated(foundTransfer, function(err, transfer){ return cb(err, transfer)});
Transfer.update(foundTransfer.id, transfer)
.exec(function(err, updatedTransfers){
if (err) return cb(err);
if(!updatedTransfers) return cb(null, null);
Transfer.afterStripeTransferCreated(updatedTransfers[0], function(err, transfer){
cb(err, transfer);
});
});
});
} | javascript | function (transfer, cb) {
Transfer.findOrCreate(transfer.id, transfer)
.exec(function (err, foundTransfer){
if (err) return cb(err);
if (foundTransfer.lastStripeEvent > transfer.lastStripeEvent) return cb(null, foundTransfer);
if (foundTransfer.lastStripeEvent == transfer.lastStripeEvent) return Transfer.afterStripeTransferCreated(foundTransfer, function(err, transfer){ return cb(err, transfer)});
Transfer.update(foundTransfer.id, transfer)
.exec(function(err, updatedTransfers){
if (err) return cb(err);
if(!updatedTransfers) return cb(null, null);
Transfer.afterStripeTransferCreated(updatedTransfers[0], function(err, transfer){
cb(err, transfer);
});
});
});
} | [
"function",
"(",
"transfer",
",",
"cb",
")",
"{",
"Transfer",
".",
"findOrCreate",
"(",
"transfer",
".",
"id",
",",
"transfer",
")",
".",
"exec",
"(",
"function",
"(",
"err",
",",
"foundTransfer",
")",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"err",
")",
";",
"if",
"(",
"foundTransfer",
".",
"lastStripeEvent",
">",
"transfer",
".",
"lastStripeEvent",
")",
"return",
"cb",
"(",
"null",
",",
"foundTransfer",
")",
";",
"if",
"(",
"foundTransfer",
".",
"lastStripeEvent",
"==",
"transfer",
".",
"lastStripeEvent",
")",
"return",
"Transfer",
".",
"afterStripeTransferCreated",
"(",
"foundTransfer",
",",
"function",
"(",
"err",
",",
"transfer",
")",
"{",
"return",
"cb",
"(",
"err",
",",
"transfer",
")",
"}",
")",
";",
"Transfer",
".",
"update",
"(",
"foundTransfer",
".",
"id",
",",
"transfer",
")",
".",
"exec",
"(",
"function",
"(",
"err",
",",
"updatedTransfers",
")",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"err",
")",
";",
"if",
"(",
"!",
"updatedTransfers",
")",
"return",
"cb",
"(",
"null",
",",
"null",
")",
";",
"Transfer",
".",
"afterStripeTransferCreated",
"(",
"updatedTransfers",
"[",
"0",
"]",
",",
"function",
"(",
"err",
",",
"transfer",
")",
"{",
"cb",
"(",
"err",
",",
"transfer",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | Stripe Webhook transfer.created | [
"Stripe",
"Webhook",
"transfer",
".",
"created"
] | 0766bc04a6893a07c842170f37b37200d6771425 | https://github.com/scott-wyatt/sails-stripe/blob/0766bc04a6893a07c842170f37b37200d6771425/templates/Transfer.template.js#L102-L118 | train |
|
nfroidure/jsarch | src/jsarch.js | initJSArch | async function initJSArch({ CONFIG, EOL, glob, fs, parser, log = noop }) {
return jsArch;
/**
* Compile an run a template
* @param {Object} options
* Options (destructured)
* @param {Object} options.cwd
* Current working directory
* @param {Object} options.patterns
* Patterns to look files for (see node-glob)
* @param {Object} options.eol
* End of line character (default to the OS one)
* @param {Object} options.titleLevel
* The base title level of the output makdown document
* @param {Object} options.base
* The base directory for the ARCHITECTURE.md references
* @return {Promise<String>}
* Computed architecture notes as a markdown file
*/
async function jsArch({
cwd,
patterns,
eol,
titleLevel = TITLE_LEVEL,
base = BASE,
}) {
eol = eol || EOL;
const files = await _computePatterns({ glob, log }, cwd, patterns);
const architectureNotes = _linearize(
await Promise.all(
files.map(_extractArchitectureNotes.bind(null, { parser, fs, log })),
),
);
const content = architectureNotes
.sort(compareNotes)
.reduce((content, architectureNote) => {
let linesLink =
'#L' +
architectureNote.loc.start.line +
'-L' +
architectureNote.loc.end.line;
if (CONFIG.gitProvider.toLowerCase() === 'bitbucket') {
linesLink =
'#' +
path.basename(architectureNote.filePath) +
'-' +
architectureNote.loc.start.line +
':' +
architectureNote.loc.end.line;
}
return (
content +
eol +
eol +
titleLevel +
architectureNote.num
.split('.')
.map(() => '#')
.join('') +
' ' +
architectureNote.title +
eol +
eol +
architectureNote.content.replace(
new RegExp(
'([\r\n]+)[ \t]{' + architectureNote.loc.start.column + '}',
'g',
),
'$1',
) +
eol +
eol +
'[See in context](' +
base +
'/' +
path.relative(cwd, architectureNote.filePath) +
linesLink +
')' +
eol +
eol
);
}, '');
if (content) {
return (
JSARCH_PREFIX.replace(EOL_REGEXP, eol) +
titleLevel +
' Architecture Notes' +
eol +
eol +
content
);
}
return content;
}
} | javascript | async function initJSArch({ CONFIG, EOL, glob, fs, parser, log = noop }) {
return jsArch;
/**
* Compile an run a template
* @param {Object} options
* Options (destructured)
* @param {Object} options.cwd
* Current working directory
* @param {Object} options.patterns
* Patterns to look files for (see node-glob)
* @param {Object} options.eol
* End of line character (default to the OS one)
* @param {Object} options.titleLevel
* The base title level of the output makdown document
* @param {Object} options.base
* The base directory for the ARCHITECTURE.md references
* @return {Promise<String>}
* Computed architecture notes as a markdown file
*/
async function jsArch({
cwd,
patterns,
eol,
titleLevel = TITLE_LEVEL,
base = BASE,
}) {
eol = eol || EOL;
const files = await _computePatterns({ glob, log }, cwd, patterns);
const architectureNotes = _linearize(
await Promise.all(
files.map(_extractArchitectureNotes.bind(null, { parser, fs, log })),
),
);
const content = architectureNotes
.sort(compareNotes)
.reduce((content, architectureNote) => {
let linesLink =
'#L' +
architectureNote.loc.start.line +
'-L' +
architectureNote.loc.end.line;
if (CONFIG.gitProvider.toLowerCase() === 'bitbucket') {
linesLink =
'#' +
path.basename(architectureNote.filePath) +
'-' +
architectureNote.loc.start.line +
':' +
architectureNote.loc.end.line;
}
return (
content +
eol +
eol +
titleLevel +
architectureNote.num
.split('.')
.map(() => '#')
.join('') +
' ' +
architectureNote.title +
eol +
eol +
architectureNote.content.replace(
new RegExp(
'([\r\n]+)[ \t]{' + architectureNote.loc.start.column + '}',
'g',
),
'$1',
) +
eol +
eol +
'[See in context](' +
base +
'/' +
path.relative(cwd, architectureNote.filePath) +
linesLink +
')' +
eol +
eol
);
}, '');
if (content) {
return (
JSARCH_PREFIX.replace(EOL_REGEXP, eol) +
titleLevel +
' Architecture Notes' +
eol +
eol +
content
);
}
return content;
}
} | [
"async",
"function",
"initJSArch",
"(",
"{",
"CONFIG",
",",
"EOL",
",",
"glob",
",",
"fs",
",",
"parser",
",",
"log",
"=",
"noop",
"}",
")",
"{",
"return",
"jsArch",
";",
"async",
"function",
"jsArch",
"(",
"{",
"cwd",
",",
"patterns",
",",
"eol",
",",
"titleLevel",
"=",
"TITLE_LEVEL",
",",
"base",
"=",
"BASE",
",",
"}",
")",
"{",
"eol",
"=",
"eol",
"||",
"EOL",
";",
"const",
"files",
"=",
"await",
"_computePatterns",
"(",
"{",
"glob",
",",
"log",
"}",
",",
"cwd",
",",
"patterns",
")",
";",
"const",
"architectureNotes",
"=",
"_linearize",
"(",
"await",
"Promise",
".",
"all",
"(",
"files",
".",
"map",
"(",
"_extractArchitectureNotes",
".",
"bind",
"(",
"null",
",",
"{",
"parser",
",",
"fs",
",",
"log",
"}",
")",
")",
",",
")",
",",
")",
";",
"const",
"content",
"=",
"architectureNotes",
".",
"sort",
"(",
"compareNotes",
")",
".",
"reduce",
"(",
"(",
"content",
",",
"architectureNote",
")",
"=>",
"{",
"let",
"linesLink",
"=",
"'#L'",
"+",
"architectureNote",
".",
"loc",
".",
"start",
".",
"line",
"+",
"'-L'",
"+",
"architectureNote",
".",
"loc",
".",
"end",
".",
"line",
";",
"if",
"(",
"CONFIG",
".",
"gitProvider",
".",
"toLowerCase",
"(",
")",
"===",
"'bitbucket'",
")",
"{",
"linesLink",
"=",
"'#'",
"+",
"path",
".",
"basename",
"(",
"architectureNote",
".",
"filePath",
")",
"+",
"'-'",
"+",
"architectureNote",
".",
"loc",
".",
"start",
".",
"line",
"+",
"':'",
"+",
"architectureNote",
".",
"loc",
".",
"end",
".",
"line",
";",
"}",
"return",
"(",
"content",
"+",
"eol",
"+",
"eol",
"+",
"titleLevel",
"+",
"architectureNote",
".",
"num",
".",
"split",
"(",
"'.'",
")",
".",
"map",
"(",
"(",
")",
"=>",
"'#'",
")",
".",
"join",
"(",
"''",
")",
"+",
"' '",
"+",
"architectureNote",
".",
"title",
"+",
"eol",
"+",
"eol",
"+",
"architectureNote",
".",
"content",
".",
"replace",
"(",
"new",
"RegExp",
"(",
"'([\\r\\n]+)[ \\t]{'",
"+",
"\\r",
"+",
"\\n",
",",
"\\t",
",",
")",
",",
"architectureNote",
".",
"loc",
".",
"start",
".",
"column",
",",
")",
"+",
"'}'",
"+",
"'g'",
"+",
"'$1'",
"+",
"eol",
"+",
"eol",
"+",
"'[See in context]('",
"+",
"base",
"+",
"'/'",
"+",
"path",
".",
"relative",
"(",
"cwd",
",",
"architectureNote",
".",
"filePath",
")",
"+",
"linesLink",
")",
";",
"}",
",",
"')'",
")",
";",
"eol",
"eol",
"}",
"}"
] | Declare jsArch in the dependency injection system
@param {Object} services
Services (provided by the dependency injector)
@param {Object} services.CONFIG
The JSArch config
@param {Object} services.EOL
The OS EOL chars
@param {Object} services.glob
Globbing service
@param {Object} services.fs
File system service
@param {Object} services.parser
Parser service
@param {Object} [services.log = noop]
Logging service
@returns {Promise<Function>} | [
"Declare",
"jsArch",
"in",
"the",
"dependency",
"injection",
"system"
] | df23251b90d64794d733d4fdebfbb31a03b9fe1c | https://github.com/nfroidure/jsarch/blob/df23251b90d64794d733d4fdebfbb31a03b9fe1c/src/jsarch.js#L102-L198 | train |
byron-dupreez/aws-core-utils | dynamodb-doc-client-utils.js | getItem | function getItem(tableName, key, opts, desc, context) {
try {
const params = {
TableName: tableName,
Key: key
};
if (opts) merge(opts, params, mergeOpts);
if (context.traceEnabled) context.trace(`Loading ${desc} from ${tableName} using params (${JSON.stringify(params)})`);
return context.dynamoDBDocClient.get(params).promise()
.then(result => {
if (context.traceEnabled) context.trace(`Loaded ${desc} from ${tableName} - result (${JSON.stringify(result)})`);
if (result && typeof result === 'object') {
return result;
}
throw new TypeError(`Unexpected result from get ${desc} from ${tableName} - result (${JSON.stringify(result)})`);
})
.catch(err => {
context.error(`Failed to load ${desc} from ${tableName}`, err);
throw err;
});
} catch (err) {
context.error(`Failed to load ${desc} from ${tableName}`, err);
return Promise.reject(err);
}
} | javascript | function getItem(tableName, key, opts, desc, context) {
try {
const params = {
TableName: tableName,
Key: key
};
if (opts) merge(opts, params, mergeOpts);
if (context.traceEnabled) context.trace(`Loading ${desc} from ${tableName} using params (${JSON.stringify(params)})`);
return context.dynamoDBDocClient.get(params).promise()
.then(result => {
if (context.traceEnabled) context.trace(`Loaded ${desc} from ${tableName} - result (${JSON.stringify(result)})`);
if (result && typeof result === 'object') {
return result;
}
throw new TypeError(`Unexpected result from get ${desc} from ${tableName} - result (${JSON.stringify(result)})`);
})
.catch(err => {
context.error(`Failed to load ${desc} from ${tableName}`, err);
throw err;
});
} catch (err) {
context.error(`Failed to load ${desc} from ${tableName}`, err);
return Promise.reject(err);
}
} | [
"function",
"getItem",
"(",
"tableName",
",",
"key",
",",
"opts",
",",
"desc",
",",
"context",
")",
"{",
"try",
"{",
"const",
"params",
"=",
"{",
"TableName",
":",
"tableName",
",",
"Key",
":",
"key",
"}",
";",
"if",
"(",
"opts",
")",
"merge",
"(",
"opts",
",",
"params",
",",
"mergeOpts",
")",
";",
"if",
"(",
"context",
".",
"traceEnabled",
")",
"context",
".",
"trace",
"(",
"`",
"${",
"desc",
"}",
"${",
"tableName",
"}",
"${",
"JSON",
".",
"stringify",
"(",
"params",
")",
"}",
"`",
")",
";",
"return",
"context",
".",
"dynamoDBDocClient",
".",
"get",
"(",
"params",
")",
".",
"promise",
"(",
")",
".",
"then",
"(",
"result",
"=>",
"{",
"if",
"(",
"context",
".",
"traceEnabled",
")",
"context",
".",
"trace",
"(",
"`",
"${",
"desc",
"}",
"${",
"tableName",
"}",
"${",
"JSON",
".",
"stringify",
"(",
"result",
")",
"}",
"`",
")",
";",
"if",
"(",
"result",
"&&",
"typeof",
"result",
"===",
"'object'",
")",
"{",
"return",
"result",
";",
"}",
"throw",
"new",
"TypeError",
"(",
"`",
"${",
"desc",
"}",
"${",
"tableName",
"}",
"${",
"JSON",
".",
"stringify",
"(",
"result",
")",
"}",
"`",
")",
";",
"}",
")",
".",
"catch",
"(",
"err",
"=>",
"{",
"context",
".",
"error",
"(",
"`",
"${",
"desc",
"}",
"${",
"tableName",
"}",
"`",
",",
"err",
")",
";",
"throw",
"err",
";",
"}",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"context",
".",
"error",
"(",
"`",
"${",
"desc",
"}",
"${",
"tableName",
"}",
"`",
",",
"err",
")",
";",
"return",
"Promise",
".",
"reject",
"(",
"err",
")",
";",
"}",
"}"
] | Gets the item with the given key from the named DynamoDB table.
@param {string} tableName - the name of the DynamoDB table from which to load
@param {K} key - the key of the item to get
@param {DynamoGetOpts|undefined} [opts] - optional DynamoDB `get` parameter options to use
@param {string} desc - a description of the item being requested for logging purposes
@param {StandardContext} context - the context to use
@return {Promise.<DynamoGetResult.<I>>} a promise that will resolve with the result or reject with an error
@template I,K | [
"Gets",
"the",
"item",
"with",
"the",
"given",
"key",
"from",
"the",
"named",
"DynamoDB",
"table",
"."
] | 2530155b5afc102f61658b28183a16027ecae86a | https://github.com/byron-dupreez/aws-core-utils/blob/2530155b5afc102f61658b28183a16027ecae86a/dynamodb-doc-client-utils.js#L33-L60 | train |
byron-dupreez/aws-core-utils | dynamodb-doc-client-utils.js | updateProjectionExpression | function updateProjectionExpression(opts, expressions) {
if (!expressions || !Array.isArray(expressions) || expressions.length <= 0) return opts;
if (!opts) opts = {};
const projectionExpressions = opts.ProjectionExpression ?
opts.ProjectionExpression.split(',').filter(isNotBlank).map(trim) : [];
expressions.forEach(expression => {
if (isNotBlank(expression) && projectionExpressions.indexOf(expression) === -1) {
projectionExpressions.push(trim(expression));
}
});
const projectionExpression = projectionExpressions.length > 0 ? projectionExpressions.join(',') : undefined;
opts.ProjectionExpression = isNotBlank(projectionExpression) ? projectionExpression : undefined;
return opts;
} | javascript | function updateProjectionExpression(opts, expressions) {
if (!expressions || !Array.isArray(expressions) || expressions.length <= 0) return opts;
if (!opts) opts = {};
const projectionExpressions = opts.ProjectionExpression ?
opts.ProjectionExpression.split(',').filter(isNotBlank).map(trim) : [];
expressions.forEach(expression => {
if (isNotBlank(expression) && projectionExpressions.indexOf(expression) === -1) {
projectionExpressions.push(trim(expression));
}
});
const projectionExpression = projectionExpressions.length > 0 ? projectionExpressions.join(',') : undefined;
opts.ProjectionExpression = isNotBlank(projectionExpression) ? projectionExpression : undefined;
return opts;
} | [
"function",
"updateProjectionExpression",
"(",
"opts",
",",
"expressions",
")",
"{",
"if",
"(",
"!",
"expressions",
"||",
"!",
"Array",
".",
"isArray",
"(",
"expressions",
")",
"||",
"expressions",
".",
"length",
"<=",
"0",
")",
"return",
"opts",
";",
"if",
"(",
"!",
"opts",
")",
"opts",
"=",
"{",
"}",
";",
"const",
"projectionExpressions",
"=",
"opts",
".",
"ProjectionExpression",
"?",
"opts",
".",
"ProjectionExpression",
".",
"split",
"(",
"','",
")",
".",
"filter",
"(",
"isNotBlank",
")",
".",
"map",
"(",
"trim",
")",
":",
"[",
"]",
";",
"expressions",
".",
"forEach",
"(",
"expression",
"=>",
"{",
"if",
"(",
"isNotBlank",
"(",
"expression",
")",
"&&",
"projectionExpressions",
".",
"indexOf",
"(",
"expression",
")",
"===",
"-",
"1",
")",
"{",
"projectionExpressions",
".",
"push",
"(",
"trim",
"(",
"expression",
")",
")",
";",
"}",
"}",
")",
";",
"const",
"projectionExpression",
"=",
"projectionExpressions",
".",
"length",
">",
"0",
"?",
"projectionExpressions",
".",
"join",
"(",
"','",
")",
":",
"undefined",
";",
"opts",
".",
"ProjectionExpression",
"=",
"isNotBlank",
"(",
"projectionExpression",
")",
"?",
"projectionExpression",
":",
"undefined",
";",
"return",
"opts",
";",
"}"
] | Updates the ProjectionExpression property of the given opts with the given extra expressions.
@param {DynamoGetOpts|DynamoQueryOpts|Object|undefined} opts - the options to update
@param {string[]} expressions - the expressions to add
@return {DynamoGetOpts|DynamoQueryOpts|Object} the updated options | [
"Updates",
"the",
"ProjectionExpression",
"property",
"of",
"the",
"given",
"opts",
"with",
"the",
"given",
"extra",
"expressions",
"."
] | 2530155b5afc102f61658b28183a16027ecae86a | https://github.com/byron-dupreez/aws-core-utils/blob/2530155b5afc102f61658b28183a16027ecae86a/dynamodb-doc-client-utils.js#L68-L84 | train |
byron-dupreez/aws-core-utils | dynamodb-doc-client-utils.js | updateExpressionAttributeNames | function updateExpressionAttributeNames(opts, expressionAttributeNames) {
if (!expressionAttributeNames || typeof expressionAttributeNames !== 'object') return opts;
if (!opts) opts = {};
if (!opts.ExpressionAttributeNames) opts.ExpressionAttributeNames = {};
const keys = Object.getOwnPropertyNames(expressionAttributeNames);
keys.forEach(key => {
opts.ExpressionAttributeNames[key] = expressionAttributeNames[key];
});
return opts;
} | javascript | function updateExpressionAttributeNames(opts, expressionAttributeNames) {
if (!expressionAttributeNames || typeof expressionAttributeNames !== 'object') return opts;
if (!opts) opts = {};
if (!opts.ExpressionAttributeNames) opts.ExpressionAttributeNames = {};
const keys = Object.getOwnPropertyNames(expressionAttributeNames);
keys.forEach(key => {
opts.ExpressionAttributeNames[key] = expressionAttributeNames[key];
});
return opts;
} | [
"function",
"updateExpressionAttributeNames",
"(",
"opts",
",",
"expressionAttributeNames",
")",
"{",
"if",
"(",
"!",
"expressionAttributeNames",
"||",
"typeof",
"expressionAttributeNames",
"!==",
"'object'",
")",
"return",
"opts",
";",
"if",
"(",
"!",
"opts",
")",
"opts",
"=",
"{",
"}",
";",
"if",
"(",
"!",
"opts",
".",
"ExpressionAttributeNames",
")",
"opts",
".",
"ExpressionAttributeNames",
"=",
"{",
"}",
";",
"const",
"keys",
"=",
"Object",
".",
"getOwnPropertyNames",
"(",
"expressionAttributeNames",
")",
";",
"keys",
".",
"forEach",
"(",
"key",
"=>",
"{",
"opts",
".",
"ExpressionAttributeNames",
"[",
"key",
"]",
"=",
"expressionAttributeNames",
"[",
"key",
"]",
";",
"}",
")",
";",
"return",
"opts",
";",
"}"
] | Updates the ExpressionAttributeNames map of the given opts with the given map of extra expression attribute names.
@param {DynamoGetOpts|DynamoQueryOpts|Object|undefined} opts - the options to update
@param {Object.<string, string>} expressionAttributeNames - the map of extra expression attribute names to add
@return {DynamoGetOpts|DynamoQueryOpts|Object} the updated options | [
"Updates",
"the",
"ExpressionAttributeNames",
"map",
"of",
"the",
"given",
"opts",
"with",
"the",
"given",
"map",
"of",
"extra",
"expression",
"attribute",
"names",
"."
] | 2530155b5afc102f61658b28183a16027ecae86a | https://github.com/byron-dupreez/aws-core-utils/blob/2530155b5afc102f61658b28183a16027ecae86a/dynamodb-doc-client-utils.js#L92-L103 | train |
byron-dupreez/aws-core-utils | dynamodb-doc-client-utils.js | updateExpressionAttributeValues | function updateExpressionAttributeValues(opts, expressionAttributeValues) {
if (!expressionAttributeValues || typeof expressionAttributeValues !== 'object') return opts;
if (!opts) opts = {};
if (!opts.ExpressionAttributeValues) opts.ExpressionAttributeValues = {};
const keys = Object.getOwnPropertyNames(expressionAttributeValues);
keys.forEach(key => {
opts.ExpressionAttributeValues[key] = expressionAttributeValues[key];
});
return opts;
} | javascript | function updateExpressionAttributeValues(opts, expressionAttributeValues) {
if (!expressionAttributeValues || typeof expressionAttributeValues !== 'object') return opts;
if (!opts) opts = {};
if (!opts.ExpressionAttributeValues) opts.ExpressionAttributeValues = {};
const keys = Object.getOwnPropertyNames(expressionAttributeValues);
keys.forEach(key => {
opts.ExpressionAttributeValues[key] = expressionAttributeValues[key];
});
return opts;
} | [
"function",
"updateExpressionAttributeValues",
"(",
"opts",
",",
"expressionAttributeValues",
")",
"{",
"if",
"(",
"!",
"expressionAttributeValues",
"||",
"typeof",
"expressionAttributeValues",
"!==",
"'object'",
")",
"return",
"opts",
";",
"if",
"(",
"!",
"opts",
")",
"opts",
"=",
"{",
"}",
";",
"if",
"(",
"!",
"opts",
".",
"ExpressionAttributeValues",
")",
"opts",
".",
"ExpressionAttributeValues",
"=",
"{",
"}",
";",
"const",
"keys",
"=",
"Object",
".",
"getOwnPropertyNames",
"(",
"expressionAttributeValues",
")",
";",
"keys",
".",
"forEach",
"(",
"key",
"=>",
"{",
"opts",
".",
"ExpressionAttributeValues",
"[",
"key",
"]",
"=",
"expressionAttributeValues",
"[",
"key",
"]",
";",
"}",
")",
";",
"return",
"opts",
";",
"}"
] | Updates the ExpressionAttributeValues map of the given opts with the given map of extra expression attribute names.
@param {DynamoQueryOpts|Object|undefined} opts - the options to update
@param {Object.<string, string>} expressionAttributeValues - the map of extra expression attribute names to add
@return {DynamoQueryOpts|Object} the updated options | [
"Updates",
"the",
"ExpressionAttributeValues",
"map",
"of",
"the",
"given",
"opts",
"with",
"the",
"given",
"map",
"of",
"extra",
"expression",
"attribute",
"names",
"."
] | 2530155b5afc102f61658b28183a16027ecae86a | https://github.com/byron-dupreez/aws-core-utils/blob/2530155b5afc102f61658b28183a16027ecae86a/dynamodb-doc-client-utils.js#L111-L122 | train |
scott-wyatt/sails-stripe | templates/Card.template.js | function (card, cb) {
Card.findOrCreate(card.id, card)
.exec(function (err, foundCard){
if (err) return cb(err);
if (foundCard.lastStripeEvent > card.lastStripeEvent) return cb(null, foundCard);
if (foundCard.lastStripeEvent == card.lastStripeEvent) return Card.afterStripeCustomerCardUpdated(foundCard, function(err, card){ return cb(err, card)});
Card.update(foundCard.id, card)
.exec(function(err, updatedCards){
if (err) return cb(err);
if (!updatedCards) return cb(null, null);
Card.afterStripeCustomerCardUpdated(updatedCards[0], function(err, card){
cb(err, card);
});
});
});
} | javascript | function (card, cb) {
Card.findOrCreate(card.id, card)
.exec(function (err, foundCard){
if (err) return cb(err);
if (foundCard.lastStripeEvent > card.lastStripeEvent) return cb(null, foundCard);
if (foundCard.lastStripeEvent == card.lastStripeEvent) return Card.afterStripeCustomerCardUpdated(foundCard, function(err, card){ return cb(err, card)});
Card.update(foundCard.id, card)
.exec(function(err, updatedCards){
if (err) return cb(err);
if (!updatedCards) return cb(null, null);
Card.afterStripeCustomerCardUpdated(updatedCards[0], function(err, card){
cb(err, card);
});
});
});
} | [
"function",
"(",
"card",
",",
"cb",
")",
"{",
"Card",
".",
"findOrCreate",
"(",
"card",
".",
"id",
",",
"card",
")",
".",
"exec",
"(",
"function",
"(",
"err",
",",
"foundCard",
")",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"err",
")",
";",
"if",
"(",
"foundCard",
".",
"lastStripeEvent",
">",
"card",
".",
"lastStripeEvent",
")",
"return",
"cb",
"(",
"null",
",",
"foundCard",
")",
";",
"if",
"(",
"foundCard",
".",
"lastStripeEvent",
"==",
"card",
".",
"lastStripeEvent",
")",
"return",
"Card",
".",
"afterStripeCustomerCardUpdated",
"(",
"foundCard",
",",
"function",
"(",
"err",
",",
"card",
")",
"{",
"return",
"cb",
"(",
"err",
",",
"card",
")",
"}",
")",
";",
"Card",
".",
"update",
"(",
"foundCard",
".",
"id",
",",
"card",
")",
".",
"exec",
"(",
"function",
"(",
"err",
",",
"updatedCards",
")",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"err",
")",
";",
"if",
"(",
"!",
"updatedCards",
")",
"return",
"cb",
"(",
"null",
",",
"null",
")",
";",
"Card",
".",
"afterStripeCustomerCardUpdated",
"(",
"updatedCards",
"[",
"0",
"]",
",",
"function",
"(",
"err",
",",
"card",
")",
"{",
"cb",
"(",
"err",
",",
"card",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | Stripe Webhook customer.card.updated | [
"Stripe",
"Webhook",
"customer",
".",
"card",
".",
"updated"
] | 0766bc04a6893a07c842170f37b37200d6771425 | https://github.com/scott-wyatt/sails-stripe/blob/0766bc04a6893a07c842170f37b37200d6771425/templates/Card.template.js#L111-L127 | train |
|
scott-wyatt/sails-stripe | templates/Card.template.js | function (card, cb) {
Card.destroy(card.id)
.exec(function (err, destroyedCards){
if (err) return cb(err);
if (!destroyedCards) return cb(null, null);
Card.afterStripeCustomerCardDeleted(destroyedCards[0], function(err, card){
cb(null, card);
});
});
} | javascript | function (card, cb) {
Card.destroy(card.id)
.exec(function (err, destroyedCards){
if (err) return cb(err);
if (!destroyedCards) return cb(null, null);
Card.afterStripeCustomerCardDeleted(destroyedCards[0], function(err, card){
cb(null, card);
});
});
} | [
"function",
"(",
"card",
",",
"cb",
")",
"{",
"Card",
".",
"destroy",
"(",
"card",
".",
"id",
")",
".",
"exec",
"(",
"function",
"(",
"err",
",",
"destroyedCards",
")",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"err",
")",
";",
"if",
"(",
"!",
"destroyedCards",
")",
"return",
"cb",
"(",
"null",
",",
"null",
")",
";",
"Card",
".",
"afterStripeCustomerCardDeleted",
"(",
"destroyedCards",
"[",
"0",
"]",
",",
"function",
"(",
"err",
",",
"card",
")",
"{",
"cb",
"(",
"null",
",",
"card",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | Stripe Webhook customer.card.deleted | [
"Stripe",
"Webhook",
"customer",
".",
"card",
".",
"deleted"
] | 0766bc04a6893a07c842170f37b37200d6771425 | https://github.com/scott-wyatt/sails-stripe/blob/0766bc04a6893a07c842170f37b37200d6771425/templates/Card.template.js#L135-L145 | train |
|
contactlab/ikonograph | demo/svgxuse.js | getOrigin | function getOrigin(loc) {
var a;
if (loc.protocol !== undefined) {
a = loc;
} else {
a = document.createElement("a");
a.href = loc;
}
return a.protocol.replace(/:/g, "") + a.host;
} | javascript | function getOrigin(loc) {
var a;
if (loc.protocol !== undefined) {
a = loc;
} else {
a = document.createElement("a");
a.href = loc;
}
return a.protocol.replace(/:/g, "") + a.host;
} | [
"function",
"getOrigin",
"(",
"loc",
")",
"{",
"var",
"a",
";",
"if",
"(",
"loc",
".",
"protocol",
"!==",
"undefined",
")",
"{",
"a",
"=",
"loc",
";",
"}",
"else",
"{",
"a",
"=",
"document",
".",
"createElement",
"(",
"\"a\"",
")",
";",
"a",
".",
"href",
"=",
"loc",
";",
"}",
"return",
"a",
".",
"protocol",
".",
"replace",
"(",
"/",
":",
"/",
"g",
",",
"\"\"",
")",
"+",
"a",
".",
"host",
";",
"}"
] | In IE 9, cross origin requests can only be sent using XDomainRequest. XDomainRequest would fail if CORS headers are not set. Therefore, XDomainRequest should only be used with cross origin requests. | [
"In",
"IE",
"9",
"cross",
"origin",
"requests",
"can",
"only",
"be",
"sent",
"using",
"XDomainRequest",
".",
"XDomainRequest",
"would",
"fail",
"if",
"CORS",
"headers",
"are",
"not",
"set",
".",
"Therefore",
"XDomainRequest",
"should",
"only",
"be",
"used",
"with",
"cross",
"origin",
"requests",
"."
] | f95a8fa571d3143aa6ad3542b21681a04f5d235e | https://github.com/contactlab/ikonograph/blob/f95a8fa571d3143aa6ad3542b21681a04f5d235e/demo/svgxuse.js#L53-L62 | train |
Fizzadar/selected.js | selected/selected.js | function(ev) {
var regex = new RegExp(searchBox.value, 'i'),
targets = optionsList.querySelectorAll('li');
for (var i=0; i<targets.length; i++) {
var target = targets[i];
// With multiple active options are never shown in the options list, with single
// we show both the active/inactive options with the active highlighted
if(multiple && target.classList.contains('active'))
continue;
if(!target.textContent.match(regex)) {
target.style.display = 'none';
} else {
target.style.display = 'block';
}
};
searchBox.style.width = ((searchBox.value.length * selected.textWidth) + 25) + 'px';
moveOptionList();
} | javascript | function(ev) {
var regex = new RegExp(searchBox.value, 'i'),
targets = optionsList.querySelectorAll('li');
for (var i=0; i<targets.length; i++) {
var target = targets[i];
// With multiple active options are never shown in the options list, with single
// we show both the active/inactive options with the active highlighted
if(multiple && target.classList.contains('active'))
continue;
if(!target.textContent.match(regex)) {
target.style.display = 'none';
} else {
target.style.display = 'block';
}
};
searchBox.style.width = ((searchBox.value.length * selected.textWidth) + 25) + 'px';
moveOptionList();
} | [
"function",
"(",
"ev",
")",
"{",
"var",
"regex",
"=",
"new",
"RegExp",
"(",
"searchBox",
".",
"value",
",",
"'i'",
")",
",",
"targets",
"=",
"optionsList",
".",
"querySelectorAll",
"(",
"'li'",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"targets",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"target",
"=",
"targets",
"[",
"i",
"]",
";",
"if",
"(",
"multiple",
"&&",
"target",
".",
"classList",
".",
"contains",
"(",
"'active'",
")",
")",
"continue",
";",
"if",
"(",
"!",
"target",
".",
"textContent",
".",
"match",
"(",
"regex",
")",
")",
"{",
"target",
".",
"style",
".",
"display",
"=",
"'none'",
";",
"}",
"else",
"{",
"target",
".",
"style",
".",
"display",
"=",
"'block'",
";",
"}",
"}",
";",
"searchBox",
".",
"style",
".",
"width",
"=",
"(",
"(",
"searchBox",
".",
"value",
".",
"length",
"*",
"selected",
".",
"textWidth",
")",
"+",
"25",
")",
"+",
"'px'",
";",
"moveOptionList",
"(",
")",
";",
"}"
] | Filter options list by searchbox results | [
"Filter",
"options",
"list",
"by",
"searchbox",
"results"
] | 0fd1c02ddf0b9e7f1796a88744b3fc8be811bfb3 | https://github.com/Fizzadar/selected.js/blob/0fd1c02ddf0b9e7f1796a88744b3fc8be811bfb3/selected/selected.js#L70-L91 | train |
|
Fizzadar/selected.js | selected/selected.js | function(option, selected) {
var item = document.createElement('li');
item.textContent = option.textContent;
var activate = function() {
// If multiple we just remove this option from the list
if (multiple) {
item.style.display = 'none';
// If single ensure no other options are selected, but keep in the list
} else {
for (var i=0; i<options.length; i++) {
if (options[i]._deselected)
options[i]._deselected.classList.remove('active');
}
}
item.classList.add('active');
}
item.addEventListener('click', function(ev) {
activate();
selectOption(option); // create "selected" option
});
if (selected) {
activate();
}
optionsList.appendChild(item);
option._deselected = item;
} | javascript | function(option, selected) {
var item = document.createElement('li');
item.textContent = option.textContent;
var activate = function() {
// If multiple we just remove this option from the list
if (multiple) {
item.style.display = 'none';
// If single ensure no other options are selected, but keep in the list
} else {
for (var i=0; i<options.length; i++) {
if (options[i]._deselected)
options[i]._deselected.classList.remove('active');
}
}
item.classList.add('active');
}
item.addEventListener('click', function(ev) {
activate();
selectOption(option); // create "selected" option
});
if (selected) {
activate();
}
optionsList.appendChild(item);
option._deselected = item;
} | [
"function",
"(",
"option",
",",
"selected",
")",
"{",
"var",
"item",
"=",
"document",
".",
"createElement",
"(",
"'li'",
")",
";",
"item",
".",
"textContent",
"=",
"option",
".",
"textContent",
";",
"var",
"activate",
"=",
"function",
"(",
")",
"{",
"if",
"(",
"multiple",
")",
"{",
"item",
".",
"style",
".",
"display",
"=",
"'none'",
";",
"}",
"else",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"options",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"options",
"[",
"i",
"]",
".",
"_deselected",
")",
"options",
"[",
"i",
"]",
".",
"_deselected",
".",
"classList",
".",
"remove",
"(",
"'active'",
")",
";",
"}",
"}",
"item",
".",
"classList",
".",
"add",
"(",
"'active'",
")",
";",
"}",
"item",
".",
"addEventListener",
"(",
"'click'",
",",
"function",
"(",
"ev",
")",
"{",
"activate",
"(",
")",
";",
"selectOption",
"(",
"option",
")",
";",
"}",
")",
";",
"if",
"(",
"selected",
")",
"{",
"activate",
"(",
")",
";",
"}",
"optionsList",
".",
"appendChild",
"(",
"item",
")",
";",
"option",
".",
"_deselected",
"=",
"item",
";",
"}"
] | Create "deselected" option this is here because we _always_ have a full list of items in the optionList basically this means when we deselect something, it will always return to the original list position, rather than appending to the end | [
"Create",
"deselected",
"option",
"this",
"is",
"here",
"because",
"we",
"_always_",
"have",
"a",
"full",
"list",
"of",
"items",
"in",
"the",
"optionList",
"basically",
"this",
"means",
"when",
"we",
"deselect",
"something",
"it",
"will",
"always",
"return",
"to",
"the",
"original",
"list",
"position",
"rather",
"than",
"appending",
"to",
"the",
"end"
] | 0fd1c02ddf0b9e7f1796a88744b3fc8be811bfb3 | https://github.com/Fizzadar/selected.js/blob/0fd1c02ddf0b9e7f1796a88744b3fc8be811bfb3/selected/selected.js#L98-L130 | train |
|
daffl/connect-injector | lib/connect-injector.js | function () {
var self = this;
if (typeof this._isIntercepted === 'undefined') {
// Got through all injector objects
each(res.injectors, function (obj) {
if (obj.when(req, res)) {
self._isIntercepted = true;
obj.active = true;
}
});
if (!this._isIntercepted) {
this._isIntercepted = false;
}
debug('first time _interceptCheck ran', this._isIntercepted);
}
return this._isIntercepted;
} | javascript | function () {
var self = this;
if (typeof this._isIntercepted === 'undefined') {
// Got through all injector objects
each(res.injectors, function (obj) {
if (obj.when(req, res)) {
self._isIntercepted = true;
obj.active = true;
}
});
if (!this._isIntercepted) {
this._isIntercepted = false;
}
debug('first time _interceptCheck ran', this._isIntercepted);
}
return this._isIntercepted;
} | [
"function",
"(",
")",
"{",
"var",
"self",
"=",
"this",
";",
"if",
"(",
"typeof",
"this",
".",
"_isIntercepted",
"===",
"'undefined'",
")",
"{",
"each",
"(",
"res",
".",
"injectors",
",",
"function",
"(",
"obj",
")",
"{",
"if",
"(",
"obj",
".",
"when",
"(",
"req",
",",
"res",
")",
")",
"{",
"self",
".",
"_isIntercepted",
"=",
"true",
";",
"obj",
".",
"active",
"=",
"true",
";",
"}",
"}",
")",
";",
"if",
"(",
"!",
"this",
".",
"_isIntercepted",
")",
"{",
"this",
".",
"_isIntercepted",
"=",
"false",
";",
"}",
"debug",
"(",
"'first time _interceptCheck ran'",
",",
"this",
".",
"_isIntercepted",
")",
";",
"}",
"return",
"this",
".",
"_isIntercepted",
";",
"}"
] | Checks if this response should be intercepted | [
"Checks",
"if",
"this",
"response",
"should",
"be",
"intercepted"
] | a23b7c93b60464ca43273c58cba2c07b890124f0 | https://github.com/daffl/connect-injector/blob/a23b7c93b60464ca43273c58cba2c07b890124f0/lib/connect-injector.js#L42-L59 | train |
|
daffl/connect-injector | lib/connect-injector.js | function(status, reasonPhrase, headers) {
var self = this;
each(headers || reasonPhrase, function(value, name) {
self.setHeader(name, value);
});
return this._super(status, typeof reasonPhrase === 'string' ? reasonPhrase : undefined);
} | javascript | function(status, reasonPhrase, headers) {
var self = this;
each(headers || reasonPhrase, function(value, name) {
self.setHeader(name, value);
});
return this._super(status, typeof reasonPhrase === 'string' ? reasonPhrase : undefined);
} | [
"function",
"(",
"status",
",",
"reasonPhrase",
",",
"headers",
")",
"{",
"var",
"self",
"=",
"this",
";",
"each",
"(",
"headers",
"||",
"reasonPhrase",
",",
"function",
"(",
"value",
",",
"name",
")",
"{",
"self",
".",
"setHeader",
"(",
"name",
",",
"value",
")",
";",
"}",
")",
";",
"return",
"this",
".",
"_super",
"(",
"status",
",",
"typeof",
"reasonPhrase",
"===",
"'string'",
"?",
"reasonPhrase",
":",
"undefined",
")",
";",
"}"
] | Overwrite writeHead since it can also set the headers and we need to override the transfer-encoding | [
"Overwrite",
"writeHead",
"since",
"it",
"can",
"also",
"set",
"the",
"headers",
"and",
"we",
"need",
"to",
"override",
"the",
"transfer",
"-",
"encoding"
] | a23b7c93b60464ca43273c58cba2c07b890124f0 | https://github.com/daffl/connect-injector/blob/a23b7c93b60464ca43273c58cba2c07b890124f0/lib/connect-injector.js#L74-L82 | train |
|
daffl/connect-injector | lib/connect-injector.js | function (chunk, encoding) {
if (this._interceptCheck()) {
if(!this._interceptBuffer) {
debug('initializing _interceptBuffer');
this._interceptBuffer = new WritableStream();
}
return this._interceptBuffer.write(chunk, encoding);
}
return this._super.apply(this, arguments);
} | javascript | function (chunk, encoding) {
if (this._interceptCheck()) {
if(!this._interceptBuffer) {
debug('initializing _interceptBuffer');
this._interceptBuffer = new WritableStream();
}
return this._interceptBuffer.write(chunk, encoding);
}
return this._super.apply(this, arguments);
} | [
"function",
"(",
"chunk",
",",
"encoding",
")",
"{",
"if",
"(",
"this",
".",
"_interceptCheck",
"(",
")",
")",
"{",
"if",
"(",
"!",
"this",
".",
"_interceptBuffer",
")",
"{",
"debug",
"(",
"'initializing _interceptBuffer'",
")",
";",
"this",
".",
"_interceptBuffer",
"=",
"new",
"WritableStream",
"(",
")",
";",
"}",
"return",
"this",
".",
"_interceptBuffer",
".",
"write",
"(",
"chunk",
",",
"encoding",
")",
";",
"}",
"return",
"this",
".",
"_super",
".",
"apply",
"(",
"this",
",",
"arguments",
")",
";",
"}"
] | Write into the buffer if this request is intercepted | [
"Write",
"into",
"the",
"buffer",
"if",
"this",
"request",
"is",
"intercepted"
] | a23b7c93b60464ca43273c58cba2c07b890124f0 | https://github.com/daffl/connect-injector/blob/a23b7c93b60464ca43273c58cba2c07b890124f0/lib/connect-injector.js#L85-L96 | train |
|
daffl/connect-injector | lib/connect-injector.js | function (data, encoding) {
var self = this;
var _super = this._super.bind(this);
if (!this._interceptCheck()) {
debug('not intercepting, ending with original .end');
return _super(data, encoding);
}
if (data) {
this.write(data, encoding);
}
debug('resetting to original response.write');
this.write = oldWrite;
// Responses without a body can just be ended
if(!this._hasBody || !this._interceptBuffer) {
debug('ending empty resopnse without injecting anything');
return _super();
}
var gzipped = this.getHeader('content-encoding') === 'gzip';
var chain = Q(this._interceptBuffer.getContents());
if(gzipped) {
debug('unzipping content');
// Unzip the buffer
chain = chain.then(function(buffer) {
return Q.nfcall(zlib.gunzip, buffer);
});
}
this.injectors.forEach(function(injector) {
// Run all converters, if they are active
// In series, using the previous output
if(injector.active) {
debug('adding injector to chain');
var converter = injector.converter.bind(self);
chain = chain.then(function(prev) {
return Q.nfcall(converter, prev, req, res);
});
}
});
if(gzipped) {
debug('re-zipping content');
// Zip it again
chain = chain.then(function(result) {
return Q.nfcall(zlib.gzip, result);
});
}
chain.then(_super).fail(function(e) {
debug('injector chain failed, emitting error event');
self.emit('error', e);
});
return true;
} | javascript | function (data, encoding) {
var self = this;
var _super = this._super.bind(this);
if (!this._interceptCheck()) {
debug('not intercepting, ending with original .end');
return _super(data, encoding);
}
if (data) {
this.write(data, encoding);
}
debug('resetting to original response.write');
this.write = oldWrite;
// Responses without a body can just be ended
if(!this._hasBody || !this._interceptBuffer) {
debug('ending empty resopnse without injecting anything');
return _super();
}
var gzipped = this.getHeader('content-encoding') === 'gzip';
var chain = Q(this._interceptBuffer.getContents());
if(gzipped) {
debug('unzipping content');
// Unzip the buffer
chain = chain.then(function(buffer) {
return Q.nfcall(zlib.gunzip, buffer);
});
}
this.injectors.forEach(function(injector) {
// Run all converters, if they are active
// In series, using the previous output
if(injector.active) {
debug('adding injector to chain');
var converter = injector.converter.bind(self);
chain = chain.then(function(prev) {
return Q.nfcall(converter, prev, req, res);
});
}
});
if(gzipped) {
debug('re-zipping content');
// Zip it again
chain = chain.then(function(result) {
return Q.nfcall(zlib.gzip, result);
});
}
chain.then(_super).fail(function(e) {
debug('injector chain failed, emitting error event');
self.emit('error', e);
});
return true;
} | [
"function",
"(",
"data",
",",
"encoding",
")",
"{",
"var",
"self",
"=",
"this",
";",
"var",
"_super",
"=",
"this",
".",
"_super",
".",
"bind",
"(",
"this",
")",
";",
"if",
"(",
"!",
"this",
".",
"_interceptCheck",
"(",
")",
")",
"{",
"debug",
"(",
"'not intercepting, ending with original .end'",
")",
";",
"return",
"_super",
"(",
"data",
",",
"encoding",
")",
";",
"}",
"if",
"(",
"data",
")",
"{",
"this",
".",
"write",
"(",
"data",
",",
"encoding",
")",
";",
"}",
"debug",
"(",
"'resetting to original response.write'",
")",
";",
"this",
".",
"write",
"=",
"oldWrite",
";",
"if",
"(",
"!",
"this",
".",
"_hasBody",
"||",
"!",
"this",
".",
"_interceptBuffer",
")",
"{",
"debug",
"(",
"'ending empty resopnse without injecting anything'",
")",
";",
"return",
"_super",
"(",
")",
";",
"}",
"var",
"gzipped",
"=",
"this",
".",
"getHeader",
"(",
"'content-encoding'",
")",
"===",
"'gzip'",
";",
"var",
"chain",
"=",
"Q",
"(",
"this",
".",
"_interceptBuffer",
".",
"getContents",
"(",
")",
")",
";",
"if",
"(",
"gzipped",
")",
"{",
"debug",
"(",
"'unzipping content'",
")",
";",
"chain",
"=",
"chain",
".",
"then",
"(",
"function",
"(",
"buffer",
")",
"{",
"return",
"Q",
".",
"nfcall",
"(",
"zlib",
".",
"gunzip",
",",
"buffer",
")",
";",
"}",
")",
";",
"}",
"this",
".",
"injectors",
".",
"forEach",
"(",
"function",
"(",
"injector",
")",
"{",
"if",
"(",
"injector",
".",
"active",
")",
"{",
"debug",
"(",
"'adding injector to chain'",
")",
";",
"var",
"converter",
"=",
"injector",
".",
"converter",
".",
"bind",
"(",
"self",
")",
";",
"chain",
"=",
"chain",
".",
"then",
"(",
"function",
"(",
"prev",
")",
"{",
"return",
"Q",
".",
"nfcall",
"(",
"converter",
",",
"prev",
",",
"req",
",",
"res",
")",
";",
"}",
")",
";",
"}",
"}",
")",
";",
"if",
"(",
"gzipped",
")",
"{",
"debug",
"(",
"'re-zipping content'",
")",
";",
"chain",
"=",
"chain",
".",
"then",
"(",
"function",
"(",
"result",
")",
"{",
"return",
"Q",
".",
"nfcall",
"(",
"zlib",
".",
"gzip",
",",
"result",
")",
";",
"}",
")",
";",
"}",
"chain",
".",
"then",
"(",
"_super",
")",
".",
"fail",
"(",
"function",
"(",
"e",
")",
"{",
"debug",
"(",
"'injector chain failed, emitting error event'",
")",
";",
"self",
".",
"emit",
"(",
"'error'",
",",
"e",
")",
";",
"}",
")",
";",
"return",
"true",
";",
"}"
] | End the request. | [
"End",
"the",
"request",
"."
] | a23b7c93b60464ca43273c58cba2c07b890124f0 | https://github.com/daffl/connect-injector/blob/a23b7c93b60464ca43273c58cba2c07b890124f0/lib/connect-injector.js#L99-L158 | train |
|
jonschlinkert/export-files | index.js | isJavaScriptFile | function isJavaScriptFile(filepath) {
if (!fs.statSync(filepath).isFile()) {
return false;
}
if (path.basename(filepath) === 'index.js') {
return false;
}
return filepath.slice(-3) === '.js';
} | javascript | function isJavaScriptFile(filepath) {
if (!fs.statSync(filepath).isFile()) {
return false;
}
if (path.basename(filepath) === 'index.js') {
return false;
}
return filepath.slice(-3) === '.js';
} | [
"function",
"isJavaScriptFile",
"(",
"filepath",
")",
"{",
"if",
"(",
"!",
"fs",
".",
"statSync",
"(",
"filepath",
")",
".",
"isFile",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"path",
".",
"basename",
"(",
"filepath",
")",
"===",
"'index.js'",
")",
"{",
"return",
"false",
";",
"}",
"return",
"filepath",
".",
"slice",
"(",
"-",
"3",
")",
"===",
"'.js'",
";",
"}"
] | Return true if the file is a `.js` file.
@param {String} filepath
@return {Boolean} | [
"Return",
"true",
"if",
"the",
"file",
"is",
"a",
".",
"js",
"file",
"."
] | 2e99117e0925da4ca3154baf1bd404e2a4269a97 | https://github.com/jonschlinkert/export-files/blob/2e99117e0925da4ca3154baf1bd404e2a4269a97/index.js#L42-L50 | train |
cuttingsoup/react-native-firebase-local-cache | dist/index.js | onValue | function onValue(dbRef, snapCallback, processedCallback, cancelCallbackOrContext, context) {
var storageKey = getStorageKeyFromDbRef(dbRef, 'value');
return _reactNative.AsyncStorage.getItem(storageKey).then(function (value) {
// Called processedCallback with cached value.
if (value !== null) {
var cachedVal = JSON.parse(value);
callWithContext(processedCallback, cachedVal, cancelCallbackOrContext, context);
}
}).then(function () {
var callbackPeak = function callbackPeak(snap) {
var processed = snapCallback.bind(this)(snap);
snapPeak[storageKey] = JSON.stringify(processed);
processedCallback.bind(this)(processed);
};
dbRef.on('value', callbackPeak, cancelCallbackOrContext, context);
});
} | javascript | function onValue(dbRef, snapCallback, processedCallback, cancelCallbackOrContext, context) {
var storageKey = getStorageKeyFromDbRef(dbRef, 'value');
return _reactNative.AsyncStorage.getItem(storageKey).then(function (value) {
// Called processedCallback with cached value.
if (value !== null) {
var cachedVal = JSON.parse(value);
callWithContext(processedCallback, cachedVal, cancelCallbackOrContext, context);
}
}).then(function () {
var callbackPeak = function callbackPeak(snap) {
var processed = snapCallback.bind(this)(snap);
snapPeak[storageKey] = JSON.stringify(processed);
processedCallback.bind(this)(processed);
};
dbRef.on('value', callbackPeak, cancelCallbackOrContext, context);
});
} | [
"function",
"onValue",
"(",
"dbRef",
",",
"snapCallback",
",",
"processedCallback",
",",
"cancelCallbackOrContext",
",",
"context",
")",
"{",
"var",
"storageKey",
"=",
"getStorageKeyFromDbRef",
"(",
"dbRef",
",",
"'value'",
")",
";",
"return",
"_reactNative",
".",
"AsyncStorage",
".",
"getItem",
"(",
"storageKey",
")",
".",
"then",
"(",
"function",
"(",
"value",
")",
"{",
"if",
"(",
"value",
"!==",
"null",
")",
"{",
"var",
"cachedVal",
"=",
"JSON",
".",
"parse",
"(",
"value",
")",
";",
"callWithContext",
"(",
"processedCallback",
",",
"cachedVal",
",",
"cancelCallbackOrContext",
",",
"context",
")",
";",
"}",
"}",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"var",
"callbackPeak",
"=",
"function",
"callbackPeak",
"(",
"snap",
")",
"{",
"var",
"processed",
"=",
"snapCallback",
".",
"bind",
"(",
"this",
")",
"(",
"snap",
")",
";",
"snapPeak",
"[",
"storageKey",
"]",
"=",
"JSON",
".",
"stringify",
"(",
"processed",
")",
";",
"processedCallback",
".",
"bind",
"(",
"this",
")",
"(",
"processed",
")",
";",
"}",
";",
"dbRef",
".",
"on",
"(",
"'value'",
",",
"callbackPeak",
",",
"cancelCallbackOrContext",
",",
"context",
")",
";",
"}",
")",
";",
"}"
] | Create an 'value' on listener that will first return a cached version of the endpoint.
@param {firebase.database.Reference} dbRef Firebase database reference to listen at.
@param {Function} snapCallback Callback called when a new snapshot is available. Should return a JSON.stringify-able object that will be cached.
@param {Function} processedCallback Callback called with data returned by snapCallback, or cached data if available.
@param {Function|Object} cancelCallbackOrContext An optional callback that will be notified if your event subscription is ever canceled because your client does not have permission to read this data (or it had permission but has now lost it). This callback will be passed an Error object indicating why the failure occurred.
@param {Object} context If provided, this object will be used as this when calling your callback(s).
@returns {Promise} Resolves when the cache has been read and listener attached to DB ref. | [
"Create",
"an",
"value",
"on",
"listener",
"that",
"will",
"first",
"return",
"a",
"cached",
"version",
"of",
"the",
"endpoint",
"."
] | db755a66d6936710e85161ecfced56a1ea432887 | https://github.com/cuttingsoup/react-native-firebase-local-cache/blob/db755a66d6936710e85161ecfced56a1ea432887/dist/index.js#L58-L75 | train |
cuttingsoup/react-native-firebase-local-cache | dist/index.js | offValue | function offValue(dbRef) {
var storageKey = getStorageKeyFromDbRef(dbRef, 'value');
//Turn listener off.
dbRef.off();
return new Promise(function (resolve, reject) {
if (storageKey in snapPeak) {
var dataToCache = snapPeak[storageKey];
delete snapPeak[storageKey];
resolve(_reactNative.AsyncStorage.setItem(storageKey, dataToCache));
} else {
resolve(null);
}
});
} | javascript | function offValue(dbRef) {
var storageKey = getStorageKeyFromDbRef(dbRef, 'value');
//Turn listener off.
dbRef.off();
return new Promise(function (resolve, reject) {
if (storageKey in snapPeak) {
var dataToCache = snapPeak[storageKey];
delete snapPeak[storageKey];
resolve(_reactNative.AsyncStorage.setItem(storageKey, dataToCache));
} else {
resolve(null);
}
});
} | [
"function",
"offValue",
"(",
"dbRef",
")",
"{",
"var",
"storageKey",
"=",
"getStorageKeyFromDbRef",
"(",
"dbRef",
",",
"'value'",
")",
";",
"dbRef",
".",
"off",
"(",
")",
";",
"return",
"new",
"Promise",
"(",
"function",
"(",
"resolve",
",",
"reject",
")",
"{",
"if",
"(",
"storageKey",
"in",
"snapPeak",
")",
"{",
"var",
"dataToCache",
"=",
"snapPeak",
"[",
"storageKey",
"]",
";",
"delete",
"snapPeak",
"[",
"storageKey",
"]",
";",
"resolve",
"(",
"_reactNative",
".",
"AsyncStorage",
".",
"setItem",
"(",
"storageKey",
",",
"dataToCache",
")",
")",
";",
"}",
"else",
"{",
"resolve",
"(",
"null",
")",
";",
"}",
"}",
")",
";",
"}"
] | Remove any listeners from the specified ref, and save any existing data to the cache.
@param {firebase.database.Reference} dbRef Firebase database reference to clear.
@returns {Promise} Promis that will resolve after listener is switched off and cache has been written. | [
"Remove",
"any",
"listeners",
"from",
"the",
"specified",
"ref",
"and",
"save",
"any",
"existing",
"data",
"to",
"the",
"cache",
"."
] | db755a66d6936710e85161ecfced56a1ea432887 | https://github.com/cuttingsoup/react-native-firebase-local-cache/blob/db755a66d6936710e85161ecfced56a1ea432887/dist/index.js#L83-L98 | train |
cuttingsoup/react-native-firebase-local-cache | dist/index.js | onChildAdded | function onChildAdded(dbRef, fromCacheCallback, newDataArrivingCallback, snapCallback, cancelCallbackOrContext, context) {
var storageKey = getStorageKeyFromDbRef(dbRef, 'child_added');
return _reactNative.AsyncStorage.getItem(storageKey).then(function (value) {
// Called processedCallback with cached value.
if (value !== null) {
var cachedVal = JSON.parse(value);
callWithContext(fromCacheCallback, cachedVal, cancelCallbackOrContext, context);
}
}).then(function () {
var firstData = true;
var callbackIntercept = function callbackIntercept(snap) {
//Call the data arriving callback the first time new data comes in.
if (firstData) {
firstData = false;
newDataArrivingCallback.bind(this)();
}
//Then call the snapCallback as normal.
snapCallback.bind(this)(snap);
};
dbRef.on('child_added', callbackIntercept, cancelCallbackOrContext, context);
});
} | javascript | function onChildAdded(dbRef, fromCacheCallback, newDataArrivingCallback, snapCallback, cancelCallbackOrContext, context) {
var storageKey = getStorageKeyFromDbRef(dbRef, 'child_added');
return _reactNative.AsyncStorage.getItem(storageKey).then(function (value) {
// Called processedCallback with cached value.
if (value !== null) {
var cachedVal = JSON.parse(value);
callWithContext(fromCacheCallback, cachedVal, cancelCallbackOrContext, context);
}
}).then(function () {
var firstData = true;
var callbackIntercept = function callbackIntercept(snap) {
//Call the data arriving callback the first time new data comes in.
if (firstData) {
firstData = false;
newDataArrivingCallback.bind(this)();
}
//Then call the snapCallback as normal.
snapCallback.bind(this)(snap);
};
dbRef.on('child_added', callbackIntercept, cancelCallbackOrContext, context);
});
} | [
"function",
"onChildAdded",
"(",
"dbRef",
",",
"fromCacheCallback",
",",
"newDataArrivingCallback",
",",
"snapCallback",
",",
"cancelCallbackOrContext",
",",
"context",
")",
"{",
"var",
"storageKey",
"=",
"getStorageKeyFromDbRef",
"(",
"dbRef",
",",
"'child_added'",
")",
";",
"return",
"_reactNative",
".",
"AsyncStorage",
".",
"getItem",
"(",
"storageKey",
")",
".",
"then",
"(",
"function",
"(",
"value",
")",
"{",
"if",
"(",
"value",
"!==",
"null",
")",
"{",
"var",
"cachedVal",
"=",
"JSON",
".",
"parse",
"(",
"value",
")",
";",
"callWithContext",
"(",
"fromCacheCallback",
",",
"cachedVal",
",",
"cancelCallbackOrContext",
",",
"context",
")",
";",
"}",
"}",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"var",
"firstData",
"=",
"true",
";",
"var",
"callbackIntercept",
"=",
"function",
"callbackIntercept",
"(",
"snap",
")",
"{",
"if",
"(",
"firstData",
")",
"{",
"firstData",
"=",
"false",
";",
"newDataArrivingCallback",
".",
"bind",
"(",
"this",
")",
"(",
")",
";",
"}",
"snapCallback",
".",
"bind",
"(",
"this",
")",
"(",
"snap",
")",
";",
"}",
";",
"dbRef",
".",
"on",
"(",
"'child_added'",
",",
"callbackIntercept",
",",
"cancelCallbackOrContext",
",",
"context",
")",
";",
"}",
")",
";",
"}"
] | Create an 'child_added' on listener that will first return any cached data saved by a call to offChildAdded. When fresh data arrives, newDataArrivingCallback will be called once, followed by the standard snap callback. From this point on only the snapCallback will be called.
@param {firebase.database.Reference} dbRef Firebase database reference to listen at.
@param {*} fromCacheCallback Callback that will be called with cached data if any is available.
@param {*} newDataArrivingCallback Callback called immediately before fresh data starts arriving.
@param {*} snapCallback Callback called when new data snapshots arrive from the server.
@param {*} cancelCallbackOrContext Optional callback that will be called in the case of an error, e.g. forbidden.
@param {*} context Optional context that will be bound to `this` in callbacks.
@returns {Promise} Resolves when the cache has been read and listener attached to DB ref. | [
"Create",
"an",
"child_added",
"on",
"listener",
"that",
"will",
"first",
"return",
"any",
"cached",
"data",
"saved",
"by",
"a",
"call",
"to",
"offChildAdded",
".",
"When",
"fresh",
"data",
"arrives",
"newDataArrivingCallback",
"will",
"be",
"called",
"once",
"followed",
"by",
"the",
"standard",
"snap",
"callback",
".",
"From",
"this",
"point",
"on",
"only",
"the",
"snapCallback",
"will",
"be",
"called",
"."
] | db755a66d6936710e85161ecfced56a1ea432887 | https://github.com/cuttingsoup/react-native-firebase-local-cache/blob/db755a66d6936710e85161ecfced56a1ea432887/dist/index.js#L111-L135 | train |
cuttingsoup/react-native-firebase-local-cache | dist/index.js | offChildAdded | function offChildAdded(dbRef, dataToCache) {
var storageKey = getStorageKeyFromDbRef(dbRef, 'child_added');
//Turn listener off.
dbRef.off();
return new Promise(function (resolve, reject) {
resolve(_reactNative.AsyncStorage.setItem(storageKey, JSON.stringify(dataToCache)));
});
} | javascript | function offChildAdded(dbRef, dataToCache) {
var storageKey = getStorageKeyFromDbRef(dbRef, 'child_added');
//Turn listener off.
dbRef.off();
return new Promise(function (resolve, reject) {
resolve(_reactNative.AsyncStorage.setItem(storageKey, JSON.stringify(dataToCache)));
});
} | [
"function",
"offChildAdded",
"(",
"dbRef",
",",
"dataToCache",
")",
"{",
"var",
"storageKey",
"=",
"getStorageKeyFromDbRef",
"(",
"dbRef",
",",
"'child_added'",
")",
";",
"dbRef",
".",
"off",
"(",
")",
";",
"return",
"new",
"Promise",
"(",
"function",
"(",
"resolve",
",",
"reject",
")",
"{",
"resolve",
"(",
"_reactNative",
".",
"AsyncStorage",
".",
"setItem",
"(",
"storageKey",
",",
"JSON",
".",
"stringify",
"(",
"dataToCache",
")",
")",
")",
";",
"}",
")",
";",
"}"
] | Turn off listeners at a certain database.Reference, and cache the data passed in so that it can be passed to a new "child_added" listener if one is created.
@param {*} dbRef Reference to stop listening at.
@param {*} dataToCache Data that should be cached for this location. Tip: [].slice(-20) to keep the latest 20 items. | [
"Turn",
"off",
"listeners",
"at",
"a",
"certain",
"database",
".",
"Reference",
"and",
"cache",
"the",
"data",
"passed",
"in",
"so",
"that",
"it",
"can",
"be",
"passed",
"to",
"a",
"new",
"child_added",
"listener",
"if",
"one",
"is",
"created",
"."
] | db755a66d6936710e85161ecfced56a1ea432887 | https://github.com/cuttingsoup/react-native-firebase-local-cache/blob/db755a66d6936710e85161ecfced56a1ea432887/dist/index.js#L143-L152 | train |
cuttingsoup/react-native-firebase-local-cache | dist/index.js | onChildRemoved | function onChildRemoved(dbRef, callback, cancelCallbackOrContext, context) {
return dbRef.on('child_removed', callback, cancelCallbackOrContext, context);
} | javascript | function onChildRemoved(dbRef, callback, cancelCallbackOrContext, context) {
return dbRef.on('child_removed', callback, cancelCallbackOrContext, context);
} | [
"function",
"onChildRemoved",
"(",
"dbRef",
",",
"callback",
",",
"cancelCallbackOrContext",
",",
"context",
")",
"{",
"return",
"dbRef",
".",
"on",
"(",
"'child_removed'",
",",
"callback",
",",
"cancelCallbackOrContext",
",",
"context",
")",
";",
"}"
] | Wrapper around Firebase on child_removed listener.
@param {*} dbRef Database reference to listen at.
@param {*} callback A callback that fires when the specified event occurs. The callback will be passed a DataSnapshot. For ordering purposes, "child_added", "child_changed", and "child_moved" will also be passed a string containing the key of the previous child, by sort order, or null if it is the first child.
@param {*} cancelCallbackOrContext An optional callback that will be notified if your event subscription is ever canceled because your client does not have permission to read this data (or it had permission but has now lost it). This callback will be passed an Error object indicating why the failure occurred.
@param {*} context If provided, this object will be used as this when calling your callback(s). | [
"Wrapper",
"around",
"Firebase",
"on",
"child_removed",
"listener",
"."
] | db755a66d6936710e85161ecfced56a1ea432887 | https://github.com/cuttingsoup/react-native-firebase-local-cache/blob/db755a66d6936710e85161ecfced56a1ea432887/dist/index.js#L162-L164 | train |
cuttingsoup/react-native-firebase-local-cache | dist/index.js | onChildChanged | function onChildChanged(dbRef, callback, cancelCallbackOrContext, context) {
return dbRef.on('child_changed', callback, cancelCallbackOrContext, context);
} | javascript | function onChildChanged(dbRef, callback, cancelCallbackOrContext, context) {
return dbRef.on('child_changed', callback, cancelCallbackOrContext, context);
} | [
"function",
"onChildChanged",
"(",
"dbRef",
",",
"callback",
",",
"cancelCallbackOrContext",
",",
"context",
")",
"{",
"return",
"dbRef",
".",
"on",
"(",
"'child_changed'",
",",
"callback",
",",
"cancelCallbackOrContext",
",",
"context",
")",
";",
"}"
] | Wrapper around Firebase on child_changed listener.
@param {*} dbRef Database reference to listen at.
@param {*} callback A callback that fires when the specified event occurs. The callback will be passed a DataSnapshot. For ordering purposes, "child_added", "child_changed", and "child_moved" will also be passed a string containing the key of the previous child, by sort order, or null if it is the first child.
@param {*} cancelCallbackOrContext An optional callback that will be notified if your event subscription is ever canceled because your client does not have permission to read this data (or it had permission but has now lost it). This callback will be passed an Error object indicating why the failure occurred.
@param {*} context If provided, this object will be used as this when calling your callback(s). | [
"Wrapper",
"around",
"Firebase",
"on",
"child_changed",
"listener",
"."
] | db755a66d6936710e85161ecfced56a1ea432887 | https://github.com/cuttingsoup/react-native-firebase-local-cache/blob/db755a66d6936710e85161ecfced56a1ea432887/dist/index.js#L174-L176 | train |
cuttingsoup/react-native-firebase-local-cache | dist/index.js | onChildMoved | function onChildMoved(dbRef, callback, cancelCallbackOrContext, context) {
return dbRef.on('child_moved', callback, cancelCallbackOrContext, context);
} | javascript | function onChildMoved(dbRef, callback, cancelCallbackOrContext, context) {
return dbRef.on('child_moved', callback, cancelCallbackOrContext, context);
} | [
"function",
"onChildMoved",
"(",
"dbRef",
",",
"callback",
",",
"cancelCallbackOrContext",
",",
"context",
")",
"{",
"return",
"dbRef",
".",
"on",
"(",
"'child_moved'",
",",
"callback",
",",
"cancelCallbackOrContext",
",",
"context",
")",
";",
"}"
] | Wrapper around Firebase on child_moved listener.
@param {*} dbRef Database reference to listen at.
@param {*} callback A callback that fires when the specified event occurs. The callback will be passed a DataSnapshot. For ordering purposes, "child_added", "child_changed", and "child_moved" will also be passed a string containing the key of the previous child, by sort order, or null if it is the first child.
@param {*} cancelCallbackOrContext An optional callback that will be notified if your event subscription is ever canceled because your client does not have permission to read this data (or it had permission but has now lost it). This callback will be passed an Error object indicating why the failure occurred.
@param {*} context If provided, this object will be used as this when calling your callback(s). | [
"Wrapper",
"around",
"Firebase",
"on",
"child_moved",
"listener",
"."
] | db755a66d6936710e85161ecfced56a1ea432887 | https://github.com/cuttingsoup/react-native-firebase-local-cache/blob/db755a66d6936710e85161ecfced56a1ea432887/dist/index.js#L186-L188 | train |
cuttingsoup/react-native-firebase-local-cache | dist/index.js | twice | function twice(dbRef, snapCallback, processedCallback, cancelCallbackOrContext, context) {
var storageKey = getStorageKeyFromDbRef(dbRef, 'twice');
return _reactNative.AsyncStorage.getItem(storageKey).then(function (value) {
// Called processedCallback with cached value.
if (value !== null) {
var cachedVal = JSON.parse(value);
callWithContext(processedCallback, cachedVal, cancelCallbackOrContext, context);
}
}).then(function () {
var callbackPeak = function callbackPeak(snap) {
var processed = snapCallback.bind(this)(snap);
//Store to cache.
_reactNative.AsyncStorage.setItem(storageKey, JSON.stringify(processed)).then(function () {
processedCallback.bind(this)(processed);
}.bind(this));
};
dbRef.once('value', callbackPeak, cancelCallbackOrContext, context);
});
} | javascript | function twice(dbRef, snapCallback, processedCallback, cancelCallbackOrContext, context) {
var storageKey = getStorageKeyFromDbRef(dbRef, 'twice');
return _reactNative.AsyncStorage.getItem(storageKey).then(function (value) {
// Called processedCallback with cached value.
if (value !== null) {
var cachedVal = JSON.parse(value);
callWithContext(processedCallback, cachedVal, cancelCallbackOrContext, context);
}
}).then(function () {
var callbackPeak = function callbackPeak(snap) {
var processed = snapCallback.bind(this)(snap);
//Store to cache.
_reactNative.AsyncStorage.setItem(storageKey, JSON.stringify(processed)).then(function () {
processedCallback.bind(this)(processed);
}.bind(this));
};
dbRef.once('value', callbackPeak, cancelCallbackOrContext, context);
});
} | [
"function",
"twice",
"(",
"dbRef",
",",
"snapCallback",
",",
"processedCallback",
",",
"cancelCallbackOrContext",
",",
"context",
")",
"{",
"var",
"storageKey",
"=",
"getStorageKeyFromDbRef",
"(",
"dbRef",
",",
"'twice'",
")",
";",
"return",
"_reactNative",
".",
"AsyncStorage",
".",
"getItem",
"(",
"storageKey",
")",
".",
"then",
"(",
"function",
"(",
"value",
")",
"{",
"if",
"(",
"value",
"!==",
"null",
")",
"{",
"var",
"cachedVal",
"=",
"JSON",
".",
"parse",
"(",
"value",
")",
";",
"callWithContext",
"(",
"processedCallback",
",",
"cachedVal",
",",
"cancelCallbackOrContext",
",",
"context",
")",
";",
"}",
"}",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"var",
"callbackPeak",
"=",
"function",
"callbackPeak",
"(",
"snap",
")",
"{",
"var",
"processed",
"=",
"snapCallback",
".",
"bind",
"(",
"this",
")",
"(",
"snap",
")",
";",
"_reactNative",
".",
"AsyncStorage",
".",
"setItem",
"(",
"storageKey",
",",
"JSON",
".",
"stringify",
"(",
"processed",
")",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"processedCallback",
".",
"bind",
"(",
"this",
")",
"(",
"processed",
")",
";",
"}",
".",
"bind",
"(",
"this",
")",
")",
";",
"}",
";",
"dbRef",
".",
"once",
"(",
"'value'",
",",
"callbackPeak",
",",
"cancelCallbackOrContext",
",",
"context",
")",
";",
"}",
")",
";",
"}"
] | Twice, one better than once! Operates in a similar way to `onValue`, however `snapCallback` will only ever be called once when fresh data arrives. The value returned by `snapCallback` will be cached immediately, then passed to the `processedCallback`. If cached data is available when the listener is first turned on, it will be loaded and passed to `processedCallback`. Once data is cached then, each call to `twice` will call `processedCallback` twice, once with cached data, then once with fresh data after being processed by `snapCallback`.
@param {*} dbRef Database reference to listen at.
@param {Function} snapCallback Callback called when a new snapshot is available. Should return a JSON.stringify-able object that will be cached.
@param {Function} processedCallback Callback called maximum of twice - once with cached data, once with freshly processed data.
@param {Function|Object} cancelCallbackOrContext An optional callback that will be notified if your event subscription is ever canceled because your client does not have permission to read this data (or it had permission but has now lost it). This callback will be passed an Error object indicating why the failure occurred.
@param {Object} context If provided, this object will be used as this when calling your callback(s).
@returns {Promise} Resolves when the cache has been read and listener attached to DB ref. | [
"Twice",
"one",
"better",
"than",
"once!",
"Operates",
"in",
"a",
"similar",
"way",
"to",
"onValue",
"however",
"snapCallback",
"will",
"only",
"ever",
"be",
"called",
"once",
"when",
"fresh",
"data",
"arrives",
".",
"The",
"value",
"returned",
"by",
"snapCallback",
"will",
"be",
"cached",
"immediately",
"then",
"passed",
"to",
"the",
"processedCallback",
".",
"If",
"cached",
"data",
"is",
"available",
"when",
"the",
"listener",
"is",
"first",
"turned",
"on",
"it",
"will",
"be",
"loaded",
"and",
"passed",
"to",
"processedCallback",
".",
"Once",
"data",
"is",
"cached",
"then",
"each",
"call",
"to",
"twice",
"will",
"call",
"processedCallback",
"twice",
"once",
"with",
"cached",
"data",
"then",
"once",
"with",
"fresh",
"data",
"after",
"being",
"processed",
"by",
"snapCallback",
"."
] | db755a66d6936710e85161ecfced56a1ea432887 | https://github.com/cuttingsoup/react-native-firebase-local-cache/blob/db755a66d6936710e85161ecfced56a1ea432887/dist/index.js#L200-L219 | train |
cuttingsoup/react-native-firebase-local-cache | dist/index.js | clearCacheForRef | function clearCacheForRef(dbRef) {
var location = dbRef.toString().substring(dbRef.root.toString().length);
var promises = [];
acceptedOnVerbs.forEach(function (eventType) {
var storageKey = '@FirebaseLocalCache:' + eventType + ':' + location;
promises.push(_reactNative.AsyncStorage.removeItem(storageKey));
});
return Promise.all(promises);
} | javascript | function clearCacheForRef(dbRef) {
var location = dbRef.toString().substring(dbRef.root.toString().length);
var promises = [];
acceptedOnVerbs.forEach(function (eventType) {
var storageKey = '@FirebaseLocalCache:' + eventType + ':' + location;
promises.push(_reactNative.AsyncStorage.removeItem(storageKey));
});
return Promise.all(promises);
} | [
"function",
"clearCacheForRef",
"(",
"dbRef",
")",
"{",
"var",
"location",
"=",
"dbRef",
".",
"toString",
"(",
")",
".",
"substring",
"(",
"dbRef",
".",
"root",
".",
"toString",
"(",
")",
".",
"length",
")",
";",
"var",
"promises",
"=",
"[",
"]",
";",
"acceptedOnVerbs",
".",
"forEach",
"(",
"function",
"(",
"eventType",
")",
"{",
"var",
"storageKey",
"=",
"'@FirebaseLocalCache:'",
"+",
"eventType",
"+",
"':'",
"+",
"location",
";",
"promises",
".",
"push",
"(",
"_reactNative",
".",
"AsyncStorage",
".",
"removeItem",
"(",
"storageKey",
")",
")",
";",
"}",
")",
";",
"return",
"Promise",
".",
"all",
"(",
"promises",
")",
";",
"}"
] | Remove the currently cached data for a particular database.Reference. If there are any listeners still active, they will re-write their data to the cache when the .off method is called.
@param {firebase.database.Reference} dbRef Firebase database reference to clear.
@returns {Promise} Promise that resolves once all cached data for this ref has been cleared. | [
"Remove",
"the",
"currently",
"cached",
"data",
"for",
"a",
"particular",
"database",
".",
"Reference",
".",
"If",
"there",
"are",
"any",
"listeners",
"still",
"active",
"they",
"will",
"re",
"-",
"write",
"their",
"data",
"to",
"the",
"cache",
"when",
"the",
".",
"off",
"method",
"is",
"called",
"."
] | db755a66d6936710e85161ecfced56a1ea432887 | https://github.com/cuttingsoup/react-native-firebase-local-cache/blob/db755a66d6936710e85161ecfced56a1ea432887/dist/index.js#L227-L238 | train |
cuttingsoup/react-native-firebase-local-cache | dist/index.js | clearCache | function clearCache() {
return _reactNative.AsyncStorage.getAllKeys().then(function (keys) {
var promises = [];
keys.forEach(function (key) {
if (key.startsWith('@FirebaseLocalCache:')) {
//delete it from the cache if it exists.
promises.push(_reactNative.AsyncStorage.removeItem(key));
}
});
return Promise.all(promises);
});
} | javascript | function clearCache() {
return _reactNative.AsyncStorage.getAllKeys().then(function (keys) {
var promises = [];
keys.forEach(function (key) {
if (key.startsWith('@FirebaseLocalCache:')) {
//delete it from the cache if it exists.
promises.push(_reactNative.AsyncStorage.removeItem(key));
}
});
return Promise.all(promises);
});
} | [
"function",
"clearCache",
"(",
")",
"{",
"return",
"_reactNative",
".",
"AsyncStorage",
".",
"getAllKeys",
"(",
")",
".",
"then",
"(",
"function",
"(",
"keys",
")",
"{",
"var",
"promises",
"=",
"[",
"]",
";",
"keys",
".",
"forEach",
"(",
"function",
"(",
"key",
")",
"{",
"if",
"(",
"key",
".",
"startsWith",
"(",
"'@FirebaseLocalCache:'",
")",
")",
"{",
"promises",
".",
"push",
"(",
"_reactNative",
".",
"AsyncStorage",
".",
"removeItem",
"(",
"key",
")",
")",
";",
"}",
"}",
")",
";",
"return",
"Promise",
".",
"all",
"(",
"promises",
")",
";",
"}",
")",
";",
"}"
] | Remove all currently cached data. If there are any listeners still active, they will re-write their data to the cache when the .off method is called.
@returns {Promise} Promise that resolves when all cached data has been deleted. | [
"Remove",
"all",
"currently",
"cached",
"data",
".",
"If",
"there",
"are",
"any",
"listeners",
"still",
"active",
"they",
"will",
"re",
"-",
"write",
"their",
"data",
"to",
"the",
"cache",
"when",
"the",
".",
"off",
"method",
"is",
"called",
"."
] | db755a66d6936710e85161ecfced56a1ea432887 | https://github.com/cuttingsoup/react-native-firebase-local-cache/blob/db755a66d6936710e85161ecfced56a1ea432887/dist/index.js#L245-L258 | train |
tirish/steam-shortcut-editor | lib/parser.js | parseIntValue | function parseIntValue(input) {
let value = input.buf.readInt32LE(input.i);
input.i += 4;
return value;
} | javascript | function parseIntValue(input) {
let value = input.buf.readInt32LE(input.i);
input.i += 4;
return value;
} | [
"function",
"parseIntValue",
"(",
"input",
")",
"{",
"let",
"value",
"=",
"input",
".",
"buf",
".",
"readInt32LE",
"(",
"input",
".",
"i",
")",
";",
"input",
".",
"i",
"+=",
"4",
";",
"return",
"value",
";",
"}"
] | LE 32 bit number | [
"LE",
"32",
"bit",
"number"
] | f60bfa1b7ef836bd29669e7eab42698433e07621 | https://github.com/tirish/steam-shortcut-editor/blob/f60bfa1b7ef836bd29669e7eab42698433e07621/lib/parser.js#L22-L27 | train |
danShumway/serverboy.js | src/gameboy_core/audio/XAudioServer.js | XAudioJSMediaStreamPushAudio | function XAudioJSMediaStreamPushAudio(event) {
var index = 0;
var audioLengthRequested = event.data;
var samplesPerCallbackAll = XAudioJSSamplesPerCallback * XAudioJSChannelsAllocated;
var XAudioJSMediaStreamLengthAlias = audioLengthRequested % XAudioJSSamplesPerCallback;
audioLengthRequested = audioLengthRequested - (XAudioJSMediaStreamLengthAliasCounter - (XAudioJSMediaStreamLengthAliasCounter % XAudioJSSamplesPerCallback)) - XAudioJSMediaStreamLengthAlias + XAudioJSSamplesPerCallback;
XAudioJSMediaStreamLengthAliasCounter -= XAudioJSMediaStreamLengthAliasCounter - (XAudioJSMediaStreamLengthAliasCounter % XAudioJSSamplesPerCallback);
XAudioJSMediaStreamLengthAliasCounter += XAudioJSSamplesPerCallback - XAudioJSMediaStreamLengthAlias;
if (XAudioJSMediaStreamBuffer.length != samplesPerCallbackAll) {
XAudioJSMediaStreamBuffer = new Float32Array(samplesPerCallbackAll);
}
XAudioJSResampleRefill();
while (index < audioLengthRequested) {
var index2 = 0;
while (index2 < samplesPerCallbackAll && XAudioJSResampleBufferStart != XAudioJSResampleBufferEnd) {
XAudioJSMediaStreamBuffer[index2++] = XAudioJSResampledBuffer[XAudioJSResampleBufferStart++];
if (XAudioJSResampleBufferStart == XAudioJSResampleBufferSize) {
XAudioJSResampleBufferStart = 0;
}
}
XAudioJSMediaStreamWorker.postMessage([0, XAudioJSMediaStreamBuffer]);
index += XAudioJSSamplesPerCallback;
}
} | javascript | function XAudioJSMediaStreamPushAudio(event) {
var index = 0;
var audioLengthRequested = event.data;
var samplesPerCallbackAll = XAudioJSSamplesPerCallback * XAudioJSChannelsAllocated;
var XAudioJSMediaStreamLengthAlias = audioLengthRequested % XAudioJSSamplesPerCallback;
audioLengthRequested = audioLengthRequested - (XAudioJSMediaStreamLengthAliasCounter - (XAudioJSMediaStreamLengthAliasCounter % XAudioJSSamplesPerCallback)) - XAudioJSMediaStreamLengthAlias + XAudioJSSamplesPerCallback;
XAudioJSMediaStreamLengthAliasCounter -= XAudioJSMediaStreamLengthAliasCounter - (XAudioJSMediaStreamLengthAliasCounter % XAudioJSSamplesPerCallback);
XAudioJSMediaStreamLengthAliasCounter += XAudioJSSamplesPerCallback - XAudioJSMediaStreamLengthAlias;
if (XAudioJSMediaStreamBuffer.length != samplesPerCallbackAll) {
XAudioJSMediaStreamBuffer = new Float32Array(samplesPerCallbackAll);
}
XAudioJSResampleRefill();
while (index < audioLengthRequested) {
var index2 = 0;
while (index2 < samplesPerCallbackAll && XAudioJSResampleBufferStart != XAudioJSResampleBufferEnd) {
XAudioJSMediaStreamBuffer[index2++] = XAudioJSResampledBuffer[XAudioJSResampleBufferStart++];
if (XAudioJSResampleBufferStart == XAudioJSResampleBufferSize) {
XAudioJSResampleBufferStart = 0;
}
}
XAudioJSMediaStreamWorker.postMessage([0, XAudioJSMediaStreamBuffer]);
index += XAudioJSSamplesPerCallback;
}
} | [
"function",
"XAudioJSMediaStreamPushAudio",
"(",
"event",
")",
"{",
"var",
"index",
"=",
"0",
";",
"var",
"audioLengthRequested",
"=",
"event",
".",
"data",
";",
"var",
"samplesPerCallbackAll",
"=",
"XAudioJSSamplesPerCallback",
"*",
"XAudioJSChannelsAllocated",
";",
"var",
"XAudioJSMediaStreamLengthAlias",
"=",
"audioLengthRequested",
"%",
"XAudioJSSamplesPerCallback",
";",
"audioLengthRequested",
"=",
"audioLengthRequested",
"-",
"(",
"XAudioJSMediaStreamLengthAliasCounter",
"-",
"(",
"XAudioJSMediaStreamLengthAliasCounter",
"%",
"XAudioJSSamplesPerCallback",
")",
")",
"-",
"XAudioJSMediaStreamLengthAlias",
"+",
"XAudioJSSamplesPerCallback",
";",
"XAudioJSMediaStreamLengthAliasCounter",
"-=",
"XAudioJSMediaStreamLengthAliasCounter",
"-",
"(",
"XAudioJSMediaStreamLengthAliasCounter",
"%",
"XAudioJSSamplesPerCallback",
")",
";",
"XAudioJSMediaStreamLengthAliasCounter",
"+=",
"XAudioJSSamplesPerCallback",
"-",
"XAudioJSMediaStreamLengthAlias",
";",
"if",
"(",
"XAudioJSMediaStreamBuffer",
".",
"length",
"!=",
"samplesPerCallbackAll",
")",
"{",
"XAudioJSMediaStreamBuffer",
"=",
"new",
"Float32Array",
"(",
"samplesPerCallbackAll",
")",
";",
"}",
"XAudioJSResampleRefill",
"(",
")",
";",
"while",
"(",
"index",
"<",
"audioLengthRequested",
")",
"{",
"var",
"index2",
"=",
"0",
";",
"while",
"(",
"index2",
"<",
"samplesPerCallbackAll",
"&&",
"XAudioJSResampleBufferStart",
"!=",
"XAudioJSResampleBufferEnd",
")",
"{",
"XAudioJSMediaStreamBuffer",
"[",
"index2",
"++",
"]",
"=",
"XAudioJSResampledBuffer",
"[",
"XAudioJSResampleBufferStart",
"++",
"]",
";",
"if",
"(",
"XAudioJSResampleBufferStart",
"==",
"XAudioJSResampleBufferSize",
")",
"{",
"XAudioJSResampleBufferStart",
"=",
"0",
";",
"}",
"}",
"XAudioJSMediaStreamWorker",
".",
"postMessage",
"(",
"[",
"0",
",",
"XAudioJSMediaStreamBuffer",
"]",
")",
";",
"index",
"+=",
"XAudioJSSamplesPerCallback",
";",
"}",
"}"
] | MediaStream API buffer push | [
"MediaStream",
"API",
"buffer",
"push"
] | 68f0ac88b5b280f64de2c8ae6d57d8a84cbe3628 | https://github.com/danShumway/serverboy.js/blob/68f0ac88b5b280f64de2c8ae6d57d8a84cbe3628/src/gameboy_core/audio/XAudioServer.js#L445-L468 | train |
byron-dupreez/aws-core-utils | lambda-utils.js | listEventSourceMappings | function listEventSourceMappings(lambda, params, logger) {
logger = logger || console;
const functionName = params.FunctionName;
const listEventSourceMappingsAsync = Promises.wrap(lambda.listEventSourceMappings);
const startMs = Date.now();
return listEventSourceMappingsAsync.call(lambda, params).then(
result => {
if (logger.traceEnabled) {
const mappings = Array.isArray(result.EventSourceMappings) ? result.EventSourceMappings : [];
const n = mappings.length;
logger.trace(`Found ${n} event source mapping${n !== 1 ? 's' : ''} for ${functionName} - took ${Date.now() - startMs} ms - result (${JSON.stringify(result)})`);
}
return result;
},
err => {
logger.error(`Failed to list event source mappings for function (${functionName}) - took ${Date.now() - startMs} ms`, err);
throw err;
}
);
} | javascript | function listEventSourceMappings(lambda, params, logger) {
logger = logger || console;
const functionName = params.FunctionName;
const listEventSourceMappingsAsync = Promises.wrap(lambda.listEventSourceMappings);
const startMs = Date.now();
return listEventSourceMappingsAsync.call(lambda, params).then(
result => {
if (logger.traceEnabled) {
const mappings = Array.isArray(result.EventSourceMappings) ? result.EventSourceMappings : [];
const n = mappings.length;
logger.trace(`Found ${n} event source mapping${n !== 1 ? 's' : ''} for ${functionName} - took ${Date.now() - startMs} ms - result (${JSON.stringify(result)})`);
}
return result;
},
err => {
logger.error(`Failed to list event source mappings for function (${functionName}) - took ${Date.now() - startMs} ms`, err);
throw err;
}
);
} | [
"function",
"listEventSourceMappings",
"(",
"lambda",
",",
"params",
",",
"logger",
")",
"{",
"logger",
"=",
"logger",
"||",
"console",
";",
"const",
"functionName",
"=",
"params",
".",
"FunctionName",
";",
"const",
"listEventSourceMappingsAsync",
"=",
"Promises",
".",
"wrap",
"(",
"lambda",
".",
"listEventSourceMappings",
")",
";",
"const",
"startMs",
"=",
"Date",
".",
"now",
"(",
")",
";",
"return",
"listEventSourceMappingsAsync",
".",
"call",
"(",
"lambda",
",",
"params",
")",
".",
"then",
"(",
"result",
"=>",
"{",
"if",
"(",
"logger",
".",
"traceEnabled",
")",
"{",
"const",
"mappings",
"=",
"Array",
".",
"isArray",
"(",
"result",
".",
"EventSourceMappings",
")",
"?",
"result",
".",
"EventSourceMappings",
":",
"[",
"]",
";",
"const",
"n",
"=",
"mappings",
".",
"length",
";",
"logger",
".",
"trace",
"(",
"`",
"${",
"n",
"}",
"${",
"n",
"!==",
"1",
"?",
"'s'",
":",
"''",
"}",
"${",
"functionName",
"}",
"${",
"Date",
".",
"now",
"(",
")",
"-",
"startMs",
"}",
"${",
"JSON",
".",
"stringify",
"(",
"result",
")",
"}",
"`",
")",
";",
"}",
"return",
"result",
";",
"}",
",",
"err",
"=>",
"{",
"logger",
".",
"error",
"(",
"`",
"${",
"functionName",
"}",
"${",
"Date",
".",
"now",
"(",
")",
"-",
"startMs",
"}",
"`",
",",
"err",
")",
";",
"throw",
"err",
";",
"}",
")",
";",
"}"
] | Lists the event source mappings for the given function name.
@param {AWS.Lambda|AwsLambda} lambda - the AWS.Lambda instance to use
@param {ListEventSourceMappingsParams} params - the parameters to use
@param {Logger|console|undefined} [logger] - the logger to use (defaults to console if omitted)
@returns {Promise.<ListEventSourceMappingsResult>} | [
"Lists",
"the",
"event",
"source",
"mappings",
"for",
"the",
"given",
"function",
"name",
"."
] | 2530155b5afc102f61658b28183a16027ecae86a | https://github.com/byron-dupreez/aws-core-utils/blob/2530155b5afc102f61658b28183a16027ecae86a/lambda-utils.js#L39-L58 | train |
byron-dupreez/aws-core-utils | lambda-utils.js | updateEventSourceMapping | function updateEventSourceMapping(lambda, params, logger) {
logger = logger || console;
const functionName = params.FunctionName;
const uuid = params.UUID;
const updateEventSourceMappingAsync = Promises.wrap(lambda.updateEventSourceMapping);
const startMs = Date.now();
return updateEventSourceMappingAsync.call(lambda, params).then(
result => {
logger.info(`Updated event source mapping (${uuid}) for function (${functionName}) - took ${Date.now() - startMs} ms - result (${JSON.stringify(result)})`);
return result;
},
err => {
logger.error(`Failed to update event source mapping (${uuid}) for function (${functionName}) - took ${Date.now() - startMs} ms`, err);
throw err;
}
);
} | javascript | function updateEventSourceMapping(lambda, params, logger) {
logger = logger || console;
const functionName = params.FunctionName;
const uuid = params.UUID;
const updateEventSourceMappingAsync = Promises.wrap(lambda.updateEventSourceMapping);
const startMs = Date.now();
return updateEventSourceMappingAsync.call(lambda, params).then(
result => {
logger.info(`Updated event source mapping (${uuid}) for function (${functionName}) - took ${Date.now() - startMs} ms - result (${JSON.stringify(result)})`);
return result;
},
err => {
logger.error(`Failed to update event source mapping (${uuid}) for function (${functionName}) - took ${Date.now() - startMs} ms`, err);
throw err;
}
);
} | [
"function",
"updateEventSourceMapping",
"(",
"lambda",
",",
"params",
",",
"logger",
")",
"{",
"logger",
"=",
"logger",
"||",
"console",
";",
"const",
"functionName",
"=",
"params",
".",
"FunctionName",
";",
"const",
"uuid",
"=",
"params",
".",
"UUID",
";",
"const",
"updateEventSourceMappingAsync",
"=",
"Promises",
".",
"wrap",
"(",
"lambda",
".",
"updateEventSourceMapping",
")",
";",
"const",
"startMs",
"=",
"Date",
".",
"now",
"(",
")",
";",
"return",
"updateEventSourceMappingAsync",
".",
"call",
"(",
"lambda",
",",
"params",
")",
".",
"then",
"(",
"result",
"=>",
"{",
"logger",
".",
"info",
"(",
"`",
"${",
"uuid",
"}",
"${",
"functionName",
"}",
"${",
"Date",
".",
"now",
"(",
")",
"-",
"startMs",
"}",
"${",
"JSON",
".",
"stringify",
"(",
"result",
")",
"}",
"`",
")",
";",
"return",
"result",
";",
"}",
",",
"err",
"=>",
"{",
"logger",
".",
"error",
"(",
"`",
"${",
"uuid",
"}",
"${",
"functionName",
"}",
"${",
"Date",
".",
"now",
"(",
")",
"-",
"startMs",
"}",
"`",
",",
"err",
")",
";",
"throw",
"err",
";",
"}",
")",
";",
"}"
] | Updates the Lambda function event source mapping identified by the given parameters with the given parameter values.
@param {AWS.Lambda|AwsLambda} lambda - the AWS.Lambda instance to use
@param {UpdateEventSourceMappingParams} params - the parameters to use
@param {Logger|console|undefined} [logger] - the logger to use (defaults to console if omitted)
@returns {Promise.<*>} a promise of the result returned by AWS Lambda | [
"Updates",
"the",
"Lambda",
"function",
"event",
"source",
"mapping",
"identified",
"by",
"the",
"given",
"parameters",
"with",
"the",
"given",
"parameter",
"values",
"."
] | 2530155b5afc102f61658b28183a16027ecae86a | https://github.com/byron-dupreez/aws-core-utils/blob/2530155b5afc102f61658b28183a16027ecae86a/lambda-utils.js#L67-L83 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.