id
int32 0
58k
| 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
|
---|---|---|---|---|---|---|---|---|---|---|---|
48,000 | jhermsmeier/node-json-web-key | lib/jwk.js | bnToBuffer | function bnToBuffer( bn ) {
var hex = bn.toString( 16 )
hex = hex.length % 2 === 1 ? '0' + hex : hex
return Buffer.from( hex, 'hex' )
} | javascript | function bnToBuffer( bn ) {
var hex = bn.toString( 16 )
hex = hex.length % 2 === 1 ? '0' + hex : hex
return Buffer.from( hex, 'hex' )
} | [
"function",
"bnToBuffer",
"(",
"bn",
")",
"{",
"var",
"hex",
"=",
"bn",
".",
"toString",
"(",
"16",
")",
"hex",
"=",
"hex",
".",
"length",
"%",
"2",
"===",
"1",
"?",
"'0'",
"+",
"hex",
":",
"hex",
"return",
"Buffer",
".",
"from",
"(",
"hex",
",",
"'hex'",
")",
"}"
] | Convert a BigNum into a Buffer
@internal
@param {BigNum} bn
@return {Buffer} | [
"Convert",
"a",
"BigNum",
"into",
"a",
"Buffer"
] | d2fec07c55baebea142b0c2098cf82a883a91be8 | https://github.com/jhermsmeier/node-json-web-key/blob/d2fec07c55baebea142b0c2098cf82a883a91be8/lib/jwk.js#L29-L33 |
48,001 | jhermsmeier/node-satcat | lib/satellite.js | extract | function extract( line, from, to ) {
return line.substring( from, to )
.replace( /^\s+|\s+$/g, '' )
} | javascript | function extract( line, from, to ) {
return line.substring( from, to )
.replace( /^\s+|\s+$/g, '' )
} | [
"function",
"extract",
"(",
"line",
",",
"from",
",",
"to",
")",
"{",
"return",
"line",
".",
"substring",
"(",
"from",
",",
"to",
")",
".",
"replace",
"(",
"/",
"^\\s+|\\s+$",
"/",
"g",
",",
"''",
")",
"}"
] | Extract a given range from a line
@internal
@param {String} line
@param {Number} from
@param {Number} to
@returns {String} | [
"Extract",
"a",
"given",
"range",
"from",
"a",
"line"
] | ba64b113ddf7a74f864baef414c22ea16a747034 | https://github.com/jhermsmeier/node-satcat/blob/ba64b113ddf7a74f864baef414c22ea16a747034/lib/satellite.js#L54-L57 |
48,002 | kibertoad/objection-utils | repositories/lib/services/repository.factory.js | getCustomRepository | function getCustomRepository(RepositoryClass, knex, entityModel) {
validate.inheritsFrom(
RepositoryClass,
EntityRepository,
'Custom repository class must inherit from EntityRepository'
);
return memoizedGetCustomRepository(...arguments);
} | javascript | function getCustomRepository(RepositoryClass, knex, entityModel) {
validate.inheritsFrom(
RepositoryClass,
EntityRepository,
'Custom repository class must inherit from EntityRepository'
);
return memoizedGetCustomRepository(...arguments);
} | [
"function",
"getCustomRepository",
"(",
"RepositoryClass",
",",
"knex",
",",
"entityModel",
")",
"{",
"validate",
".",
"inheritsFrom",
"(",
"RepositoryClass",
",",
"EntityRepository",
",",
"'Custom repository class must inherit from EntityRepository'",
")",
";",
"return",
"memoizedGetCustomRepository",
"(",
"...",
"arguments",
")",
";",
"}"
] | Get repository singleton for a given db and entity. Also passes any given arguments in addition to mandatory first
three to the constructor
@param {class<T>} RepositoryClass
@param {Knex} knex
@param {Model} entityModel
@returns {T} | [
"Get",
"repository",
"singleton",
"for",
"a",
"given",
"db",
"and",
"entity",
".",
"Also",
"passes",
"any",
"given",
"arguments",
"in",
"addition",
"to",
"mandatory",
"first",
"three",
"to",
"the",
"constructor"
] | 6da0bc3ef1185ae52d77fb0af5630a5433dbd917 | https://github.com/kibertoad/objection-utils/blob/6da0bc3ef1185ae52d77fb0af5630a5433dbd917/repositories/lib/services/repository.factory.js#L74-L81 |
48,003 | cszatma/jest-supertest-cookie-fix | src/index.js | FixedAgent | function FixedAgent(app, options) {
if (!(this instanceof FixedAgent)) {
return new FixedAgent(app, options);
}
Agent.call(this, app, options);
} | javascript | function FixedAgent(app, options) {
if (!(this instanceof FixedAgent)) {
return new FixedAgent(app, options);
}
Agent.call(this, app, options);
} | [
"function",
"FixedAgent",
"(",
"app",
",",
"options",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"FixedAgent",
")",
")",
"{",
"return",
"new",
"FixedAgent",
"(",
"app",
",",
"options",
")",
";",
"}",
"Agent",
".",
"call",
"(",
"this",
",",
"app",
",",
"options",
")",
";",
"}"
] | Initializes a new supertest agent which its _saveCookies method
fixed to work with jest.
@param {Function|Server} app
@param {Object} options
@returns {FixedAgent}
@constructor
@api public | [
"Initializes",
"a",
"new",
"supertest",
"agent",
"which",
"its",
"_saveCookies",
"method",
"fixed",
"to",
"work",
"with",
"jest",
"."
] | 61f61015c2093c151fd03cab0dc87d93820cde1c | https://github.com/cszatma/jest-supertest-cookie-fix/blob/61f61015c2093c151fd03cab0dc87d93820cde1c/src/index.js#L12-L18 |
48,004 | cszatma/jest-supertest-cookie-fix | src/index.js | fixedSaveCookies | function fixedSaveCookies(res) {
const cookies = res.headers['set-cookie'];
if (cookies) {
const fixedCookies = cookies.reduce(
(cookies, cookie) => cookies.concat(cookie.split(/,(?!\s)/)),
[]
);
this.jar.setCookies(fixedCookies);
}
} | javascript | function fixedSaveCookies(res) {
const cookies = res.headers['set-cookie'];
if (cookies) {
const fixedCookies = cookies.reduce(
(cookies, cookie) => cookies.concat(cookie.split(/,(?!\s)/)),
[]
);
this.jar.setCookies(fixedCookies);
}
} | [
"function",
"fixedSaveCookies",
"(",
"res",
")",
"{",
"const",
"cookies",
"=",
"res",
".",
"headers",
"[",
"'set-cookie'",
"]",
";",
"if",
"(",
"cookies",
")",
"{",
"const",
"fixedCookies",
"=",
"cookies",
".",
"reduce",
"(",
"(",
"cookies",
",",
"cookie",
")",
"=>",
"cookies",
".",
"concat",
"(",
"cookie",
".",
"split",
"(",
"/",
",(?!\\s)",
"/",
")",
")",
",",
"[",
"]",
")",
";",
"this",
".",
"jar",
".",
"setCookies",
"(",
"fixedCookies",
")",
";",
"}",
"}"
] | Fixes jest's set-cookie behavior. Jest normally sets the cookie as a single string instead of an array.
This function splits the string and transforms it into an array the way it should be.
@param {Response} res
@api private | [
"Fixes",
"jest",
"s",
"set",
"-",
"cookie",
"behavior",
".",
"Jest",
"normally",
"sets",
"the",
"cookie",
"as",
"a",
"single",
"string",
"instead",
"of",
"an",
"array",
".",
"This",
"function",
"splits",
"the",
"string",
"and",
"transforms",
"it",
"into",
"an",
"array",
"the",
"way",
"it",
"should",
"be",
"."
] | 61f61015c2093c151fd03cab0dc87d93820cde1c | https://github.com/cszatma/jest-supertest-cookie-fix/blob/61f61015c2093c151fd03cab0dc87d93820cde1c/src/index.js#L56-L66 |
48,005 | anyfs/anyfs | lib/plugins/core/writeFile.js | writeFile | function writeFile(fs, p, content, method, cb) {
fs.metadata(p)
.then(function(metadata) {
if (metadata.is_dir) {
throw fs.error('EISDIR');
}
}, function(e) {
if (e.code === 'ENOENT') {
var parent = path.dirname(p);
return this.mkdir(parent);
} else {
throw e;
}
})
.then(function() {
return this._promise(method, p, content);
})
.done(cb, cb);
} | javascript | function writeFile(fs, p, content, method, cb) {
fs.metadata(p)
.then(function(metadata) {
if (metadata.is_dir) {
throw fs.error('EISDIR');
}
}, function(e) {
if (e.code === 'ENOENT') {
var parent = path.dirname(p);
return this.mkdir(parent);
} else {
throw e;
}
})
.then(function() {
return this._promise(method, p, content);
})
.done(cb, cb);
} | [
"function",
"writeFile",
"(",
"fs",
",",
"p",
",",
"content",
",",
"method",
",",
"cb",
")",
"{",
"fs",
".",
"metadata",
"(",
"p",
")",
".",
"then",
"(",
"function",
"(",
"metadata",
")",
"{",
"if",
"(",
"metadata",
".",
"is_dir",
")",
"{",
"throw",
"fs",
".",
"error",
"(",
"'EISDIR'",
")",
";",
"}",
"}",
",",
"function",
"(",
"e",
")",
"{",
"if",
"(",
"e",
".",
"code",
"===",
"'ENOENT'",
")",
"{",
"var",
"parent",
"=",
"path",
".",
"dirname",
"(",
"p",
")",
";",
"return",
"this",
".",
"mkdir",
"(",
"parent",
")",
";",
"}",
"else",
"{",
"throw",
"e",
";",
"}",
"}",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"return",
"this",
".",
"_promise",
"(",
"method",
",",
"p",
",",
"content",
")",
";",
"}",
")",
".",
"done",
"(",
"cb",
",",
"cb",
")",
";",
"}"
] | write file - expensive way. | [
"write",
"file",
"-",
"expensive",
"way",
"."
] | bbaec164fd74cbc977245af45b0b1e3d0772b6ff | https://github.com/anyfs/anyfs/blob/bbaec164fd74cbc977245af45b0b1e3d0772b6ff/lib/plugins/core/writeFile.js#L6-L24 |
48,006 | joneit/filter-tree | js/copy-input.js | copy | function copy(el, text) {
var result, lastText;
if (text) {
lastText = el.value;
el.value = text;
} else {
text = el.value;
}
el.value = multiLineTrim(text);
try {
el.select();
result = document.execCommand('copy');
} catch (err) {
result = false;
} finally {
if (lastText !== undefined) {
el.value = lastText;
}
el.blur();
}
return result;
} | javascript | function copy(el, text) {
var result, lastText;
if (text) {
lastText = el.value;
el.value = text;
} else {
text = el.value;
}
el.value = multiLineTrim(text);
try {
el.select();
result = document.execCommand('copy');
} catch (err) {
result = false;
} finally {
if (lastText !== undefined) {
el.value = lastText;
}
el.blur();
}
return result;
} | [
"function",
"copy",
"(",
"el",
",",
"text",
")",
"{",
"var",
"result",
",",
"lastText",
";",
"if",
"(",
"text",
")",
"{",
"lastText",
"=",
"el",
".",
"value",
";",
"el",
".",
"value",
"=",
"text",
";",
"}",
"else",
"{",
"text",
"=",
"el",
".",
"value",
";",
"}",
"el",
".",
"value",
"=",
"multiLineTrim",
"(",
"text",
")",
";",
"try",
"{",
"el",
".",
"select",
"(",
")",
";",
"result",
"=",
"document",
".",
"execCommand",
"(",
"'copy'",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"result",
"=",
"false",
";",
"}",
"finally",
"{",
"if",
"(",
"lastText",
"!==",
"undefined",
")",
"{",
"el",
".",
"value",
"=",
"lastText",
";",
"}",
"el",
".",
"blur",
"(",
")",
";",
"}",
"return",
"result",
";",
"}"
] | 1. Trim the text in the given input element
2. select it
3. copy it to the clipboard
4. deselect it
5. return it
@param {HTMLElement|HTMLTextAreaElement} el
@param {string} [text=el.value] - Text to copy.
@returns {undefined|string} Trimmed text in element or undefined if unable to copy. | [
"1",
".",
"Trim",
"the",
"text",
"in",
"the",
"given",
"input",
"element",
"2",
".",
"select",
"it",
"3",
".",
"copy",
"it",
"to",
"the",
"clipboard",
"4",
".",
"deselect",
"it",
"5",
".",
"return",
"it"
] | c070a4045fced3e4ab20ed2e0c706c9a5fd07d1e | https://github.com/joneit/filter-tree/blob/c070a4045fced3e4ab20ed2e0c706c9a5fd07d1e/js/copy-input.js#L39-L63 |
48,007 | rtm/upward | src/Ren.js | update | function update(v, i, params, {oldValue}) {
switch (i) {
case 'children': _unobserveChildren(oldValue); _observeChildren(v); break;
case 'attrs': _unobserveAttrs (oldValue); _observeAttrs (v); break;
}
} | javascript | function update(v, i, params, {oldValue}) {
switch (i) {
case 'children': _unobserveChildren(oldValue); _observeChildren(v); break;
case 'attrs': _unobserveAttrs (oldValue); _observeAttrs (v); break;
}
} | [
"function",
"update",
"(",
"v",
",",
"i",
",",
"params",
",",
"{",
"oldValue",
"}",
")",
"{",
"switch",
"(",
"i",
")",
"{",
"case",
"'children'",
":",
"_unobserveChildren",
"(",
"oldValue",
")",
";",
"_observeChildren",
"(",
"v",
")",
";",
"break",
";",
"case",
"'attrs'",
":",
"_unobserveAttrs",
"(",
"oldValue",
")",
";",
"_observeAttrs",
"(",
"v",
")",
";",
"break",
";",
"}",
"}"
] | When parameters change, tear down and resetup observers. | [
"When",
"parameters",
"change",
"tear",
"down",
"and",
"resetup",
"observers",
"."
] | 82495c34f70c9a4336a3b34cc6781e5662324c03 | https://github.com/rtm/upward/blob/82495c34f70c9a4336a3b34cc6781e5662324c03/src/Ren.js#L82-L87 |
48,008 | alexindigo/batcher | lib/report.js | report | function report(type, state, params)
{
var reporter = defaultReporter;
// get rest of arguments
params = Array.prototype.slice.call(arguments, 1);
// `init` and `done` types don't have command associated with them
if (['init', 'done'].indexOf(type) == -1)
{
// second (1) position is for command
// if command present get string representation of it
params[1] = stringifyCommand(state, params[1]);
}
if (state && state.options && state.options.reporter)
{
reporter = state.options.reporter;
}
reporter[type].apply(null, params);
} | javascript | function report(type, state, params)
{
var reporter = defaultReporter;
// get rest of arguments
params = Array.prototype.slice.call(arguments, 1);
// `init` and `done` types don't have command associated with them
if (['init', 'done'].indexOf(type) == -1)
{
// second (1) position is for command
// if command present get string representation of it
params[1] = stringifyCommand(state, params[1]);
}
if (state && state.options && state.options.reporter)
{
reporter = state.options.reporter;
}
reporter[type].apply(null, params);
} | [
"function",
"report",
"(",
"type",
",",
"state",
",",
"params",
")",
"{",
"var",
"reporter",
"=",
"defaultReporter",
";",
"// get rest of arguments",
"params",
"=",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"arguments",
",",
"1",
")",
";",
"// `init` and `done` types don't have command associated with them",
"if",
"(",
"[",
"'init'",
",",
"'done'",
"]",
".",
"indexOf",
"(",
"type",
")",
"==",
"-",
"1",
")",
"{",
"// second (1) position is for command",
"// if command present get string representation of it",
"params",
"[",
"1",
"]",
"=",
"stringifyCommand",
"(",
"state",
",",
"params",
"[",
"1",
"]",
")",
";",
"}",
"if",
"(",
"state",
"&&",
"state",
".",
"options",
"&&",
"state",
".",
"options",
".",
"reporter",
")",
"{",
"reporter",
"=",
"state",
".",
"options",
".",
"reporter",
";",
"}",
"reporter",
"[",
"type",
"]",
".",
"apply",
"(",
"null",
",",
"params",
")",
";",
"}"
] | Generates report via default or custom reporter
@private
@param {string} type - type of the report
@param {object} state - current state
@param {...mixed} [params] - extra parameters to report
@returns {void} | [
"Generates",
"report",
"via",
"default",
"or",
"custom",
"reporter"
] | 73d9c8c994f915688db0627ea3b4854ead771138 | https://github.com/alexindigo/batcher/blob/73d9c8c994f915688db0627ea3b4854ead771138/lib/report.js#L17-L38 |
48,009 | alexindigo/batcher | lib/report.js | stringifyCommand | function stringifyCommand(state, command)
{
var name;
if (typeof command == 'function')
{
name = typeof command.commandDescription == 'function'
? command.commandDescription(state)
: Function.prototype.toString.call(command)
;
// truncate long functions
name = name.split('\n');
// remove inline comments
name = name.filter((line) => !line.match(/^\s*\/\//));
name = name
.map((line) => line.replace(/^([^'"]*)\s*\/\/.*$/, '$1')) // remove end of line comments
.map((line) => line.trim()) // remove extra space
;
if (name.length > 6)
{
// get side lines
name.splice(3, name.length - 5);
// join first and last lines
name = [name.slice(0, name.length - 2).join(' '), name.slice(-2).join(' ')].join(' ... ');
}
else
{
name = name.join(' ');
}
}
else if (Array.isArray(command))
{
name = '[' + command.join(', ') + ']';
}
else if (typeOf(command) == 'object')
{
name = JSON.stringify(command);
}
else
{
name = '' + command;
}
return name;
} | javascript | function stringifyCommand(state, command)
{
var name;
if (typeof command == 'function')
{
name = typeof command.commandDescription == 'function'
? command.commandDescription(state)
: Function.prototype.toString.call(command)
;
// truncate long functions
name = name.split('\n');
// remove inline comments
name = name.filter((line) => !line.match(/^\s*\/\//));
name = name
.map((line) => line.replace(/^([^'"]*)\s*\/\/.*$/, '$1')) // remove end of line comments
.map((line) => line.trim()) // remove extra space
;
if (name.length > 6)
{
// get side lines
name.splice(3, name.length - 5);
// join first and last lines
name = [name.slice(0, name.length - 2).join(' '), name.slice(-2).join(' ')].join(' ... ');
}
else
{
name = name.join(' ');
}
}
else if (Array.isArray(command))
{
name = '[' + command.join(', ') + ']';
}
else if (typeOf(command) == 'object')
{
name = JSON.stringify(command);
}
else
{
name = '' + command;
}
return name;
} | [
"function",
"stringifyCommand",
"(",
"state",
",",
"command",
")",
"{",
"var",
"name",
";",
"if",
"(",
"typeof",
"command",
"==",
"'function'",
")",
"{",
"name",
"=",
"typeof",
"command",
".",
"commandDescription",
"==",
"'function'",
"?",
"command",
".",
"commandDescription",
"(",
"state",
")",
":",
"Function",
".",
"prototype",
".",
"toString",
".",
"call",
"(",
"command",
")",
";",
"// truncate long functions",
"name",
"=",
"name",
".",
"split",
"(",
"'\\n'",
")",
";",
"// remove inline comments",
"name",
"=",
"name",
".",
"filter",
"(",
"(",
"line",
")",
"=>",
"!",
"line",
".",
"match",
"(",
"/",
"^\\s*\\/\\/",
"/",
")",
")",
";",
"name",
"=",
"name",
".",
"map",
"(",
"(",
"line",
")",
"=>",
"line",
".",
"replace",
"(",
"/",
"^([^'\"]*)\\s*\\/\\/.*$",
"/",
",",
"'$1'",
")",
")",
"// remove end of line comments",
".",
"map",
"(",
"(",
"line",
")",
"=>",
"line",
".",
"trim",
"(",
")",
")",
"// remove extra space",
";",
"if",
"(",
"name",
".",
"length",
">",
"6",
")",
"{",
"// get side lines",
"name",
".",
"splice",
"(",
"3",
",",
"name",
".",
"length",
"-",
"5",
")",
";",
"// join first and last lines",
"name",
"=",
"[",
"name",
".",
"slice",
"(",
"0",
",",
"name",
".",
"length",
"-",
"2",
")",
".",
"join",
"(",
"' '",
")",
",",
"name",
".",
"slice",
"(",
"-",
"2",
")",
".",
"join",
"(",
"' '",
")",
"]",
".",
"join",
"(",
"' ... '",
")",
";",
"}",
"else",
"{",
"name",
"=",
"name",
".",
"join",
"(",
"' '",
")",
";",
"}",
"}",
"else",
"if",
"(",
"Array",
".",
"isArray",
"(",
"command",
")",
")",
"{",
"name",
"=",
"'['",
"+",
"command",
".",
"join",
"(",
"', '",
")",
"+",
"']'",
";",
"}",
"else",
"if",
"(",
"typeOf",
"(",
"command",
")",
"==",
"'object'",
")",
"{",
"name",
"=",
"JSON",
".",
"stringify",
"(",
"command",
")",
";",
"}",
"else",
"{",
"name",
"=",
"''",
"+",
"command",
";",
"}",
"return",
"name",
";",
"}"
] | Gets command description out of command object
@private
@param {object} state - current state
@param {mixed} command - command object
@returns {string} - description of the command | [
"Gets",
"command",
"description",
"out",
"of",
"command",
"object"
] | 73d9c8c994f915688db0627ea3b4854ead771138 | https://github.com/alexindigo/batcher/blob/73d9c8c994f915688db0627ea3b4854ead771138/lib/report.js#L48-L96 |
48,010 | joneit/filter-tree | js/FilterNode.js | function() {
if (this.parent) {
var newListItem = document.createElement(CHILD_TAG);
if (this.notesEl) {
newListItem.appendChild(this.notesEl);
}
if (!this.keep) {
var el = this.templates.get('removeButton');
el.addEventListener('click', this.remove.bind(this));
newListItem.appendChild(el);
}
newListItem.appendChild(this.el);
this.parent.el.querySelector(CHILDREN_TAG).appendChild(newListItem);
}
} | javascript | function() {
if (this.parent) {
var newListItem = document.createElement(CHILD_TAG);
if (this.notesEl) {
newListItem.appendChild(this.notesEl);
}
if (!this.keep) {
var el = this.templates.get('removeButton');
el.addEventListener('click', this.remove.bind(this));
newListItem.appendChild(el);
}
newListItem.appendChild(this.el);
this.parent.el.querySelector(CHILDREN_TAG).appendChild(newListItem);
}
} | [
"function",
"(",
")",
"{",
"if",
"(",
"this",
".",
"parent",
")",
"{",
"var",
"newListItem",
"=",
"document",
".",
"createElement",
"(",
"CHILD_TAG",
")",
";",
"if",
"(",
"this",
".",
"notesEl",
")",
"{",
"newListItem",
".",
"appendChild",
"(",
"this",
".",
"notesEl",
")",
";",
"}",
"if",
"(",
"!",
"this",
".",
"keep",
")",
"{",
"var",
"el",
"=",
"this",
".",
"templates",
".",
"get",
"(",
"'removeButton'",
")",
";",
"el",
".",
"addEventListener",
"(",
"'click'",
",",
"this",
".",
"remove",
".",
"bind",
"(",
"this",
")",
")",
";",
"newListItem",
".",
"appendChild",
"(",
"el",
")",
";",
"}",
"newListItem",
".",
"appendChild",
"(",
"this",
".",
"el",
")",
";",
"this",
".",
"parent",
".",
"el",
".",
"querySelector",
"(",
"CHILDREN_TAG",
")",
".",
"appendChild",
"(",
"newListItem",
")",
";",
"}",
"}"
] | Insert each subtree into its parent node along with a "delete" button.
NOTE: The root tree (which has no parent) must be inserted into the DOM by the instantiating code (without a delete button).
@memberOf FilterNode# | [
"Insert",
"each",
"subtree",
"into",
"its",
"parent",
"node",
"along",
"with",
"a",
"delete",
"button",
"."
] | c070a4045fced3e4ab20ed2e0c706c9a5fd07d1e | https://github.com/joneit/filter-tree/blob/c070a4045fced3e4ab20ed2e0c706c9a5fd07d1e/js/FilterNode.js#L187-L205 |
|
48,011 | YuhangGe/node-freetype | lib/parse/hmtx.js | parseHmtxTable | function parseHmtxTable(data, start, numMetrics, numGlyphs, glyphs) {
var p, i, glyph, advanceWidth, leftSideBearing;
p = new parse.Parser(data, start);
for (i = 0; i < numGlyphs; i += 1) {
// If the font is monospaced, only one entry is needed. This last entry applies to all subsequent glyphs.
if (i < numMetrics) {
advanceWidth = p.parseUShort();
leftSideBearing = p.parseShort();
}
glyph = glyphs[i];
glyph.advanceWidth = advanceWidth;
glyph.leftSideBearing = leftSideBearing;
}
} | javascript | function parseHmtxTable(data, start, numMetrics, numGlyphs, glyphs) {
var p, i, glyph, advanceWidth, leftSideBearing;
p = new parse.Parser(data, start);
for (i = 0; i < numGlyphs; i += 1) {
// If the font is monospaced, only one entry is needed. This last entry applies to all subsequent glyphs.
if (i < numMetrics) {
advanceWidth = p.parseUShort();
leftSideBearing = p.parseShort();
}
glyph = glyphs[i];
glyph.advanceWidth = advanceWidth;
glyph.leftSideBearing = leftSideBearing;
}
} | [
"function",
"parseHmtxTable",
"(",
"data",
",",
"start",
",",
"numMetrics",
",",
"numGlyphs",
",",
"glyphs",
")",
"{",
"var",
"p",
",",
"i",
",",
"glyph",
",",
"advanceWidth",
",",
"leftSideBearing",
";",
"p",
"=",
"new",
"parse",
".",
"Parser",
"(",
"data",
",",
"start",
")",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"numGlyphs",
";",
"i",
"+=",
"1",
")",
"{",
"// If the font is monospaced, only one entry is needed. This last entry applies to all subsequent glyphs.",
"if",
"(",
"i",
"<",
"numMetrics",
")",
"{",
"advanceWidth",
"=",
"p",
".",
"parseUShort",
"(",
")",
";",
"leftSideBearing",
"=",
"p",
".",
"parseShort",
"(",
")",
";",
"}",
"glyph",
"=",
"glyphs",
"[",
"i",
"]",
";",
"glyph",
".",
"advanceWidth",
"=",
"advanceWidth",
";",
"glyph",
".",
"leftSideBearing",
"=",
"leftSideBearing",
";",
"}",
"}"
] | Parse the `hmtx` table, which contains the horizontal metrics for all glyphs. This function augments the glyph array, adding the advanceWidth and leftSideBearing to each glyph. | [
"Parse",
"the",
"hmtx",
"table",
"which",
"contains",
"the",
"horizontal",
"metrics",
"for",
"all",
"glyphs",
".",
"This",
"function",
"augments",
"the",
"glyph",
"array",
"adding",
"the",
"advanceWidth",
"and",
"leftSideBearing",
"to",
"each",
"glyph",
"."
] | 4c8d2e2503f088ffbd61e613a23b9ff2e64d3489 | https://github.com/YuhangGe/node-freetype/blob/4c8d2e2503f088ffbd61e613a23b9ff2e64d3489/lib/parse/hmtx.js#L10-L23 |
48,012 | alexindigo/batcher | index.js | iterator | function iterator(state, tasks, callback)
{
var keys
, tasksLeft = tasks.length
, task = tasks.shift()
;
if (tasksLeft === 0)
{
return callback(null, state);
}
// init current task reference
state._currentTask = {waiters: {}};
if (typeOf(task) == 'object')
{
// update state with new options
// to make it available for all the subcommands
if (typeOf(task.options) == 'object')
{
state.options = extend(state.options || {}, task.options);
// no need to process it further
delete task.options;
}
// generate list of properties to update
keys = Object.keys(task);
}
// convert non-array and non-object elements
// into single element arrays
if (typeof task != 'object')
{
task = [task];
}
execute(state, task, keys, function(err, modifiedState)
{
// reset current task
// if it's error and modified state
// isn't provided, use context
(modifiedState || state)._currentTask = undefined; // eslint-disable-line no-undefined
if (err) return callback(err);
// proceed to the next element
iterator(modifiedState, tasks, callback);
});
} | javascript | function iterator(state, tasks, callback)
{
var keys
, tasksLeft = tasks.length
, task = tasks.shift()
;
if (tasksLeft === 0)
{
return callback(null, state);
}
// init current task reference
state._currentTask = {waiters: {}};
if (typeOf(task) == 'object')
{
// update state with new options
// to make it available for all the subcommands
if (typeOf(task.options) == 'object')
{
state.options = extend(state.options || {}, task.options);
// no need to process it further
delete task.options;
}
// generate list of properties to update
keys = Object.keys(task);
}
// convert non-array and non-object elements
// into single element arrays
if (typeof task != 'object')
{
task = [task];
}
execute(state, task, keys, function(err, modifiedState)
{
// reset current task
// if it's error and modified state
// isn't provided, use context
(modifiedState || state)._currentTask = undefined; // eslint-disable-line no-undefined
if (err) return callback(err);
// proceed to the next element
iterator(modifiedState, tasks, callback);
});
} | [
"function",
"iterator",
"(",
"state",
",",
"tasks",
",",
"callback",
")",
"{",
"var",
"keys",
",",
"tasksLeft",
"=",
"tasks",
".",
"length",
",",
"task",
"=",
"tasks",
".",
"shift",
"(",
")",
";",
"if",
"(",
"tasksLeft",
"===",
"0",
")",
"{",
"return",
"callback",
"(",
"null",
",",
"state",
")",
";",
"}",
"// init current task reference",
"state",
".",
"_currentTask",
"=",
"{",
"waiters",
":",
"{",
"}",
"}",
";",
"if",
"(",
"typeOf",
"(",
"task",
")",
"==",
"'object'",
")",
"{",
"// update state with new options",
"// to make it available for all the subcommands",
"if",
"(",
"typeOf",
"(",
"task",
".",
"options",
")",
"==",
"'object'",
")",
"{",
"state",
".",
"options",
"=",
"extend",
"(",
"state",
".",
"options",
"||",
"{",
"}",
",",
"task",
".",
"options",
")",
";",
"// no need to process it further",
"delete",
"task",
".",
"options",
";",
"}",
"// generate list of properties to update",
"keys",
"=",
"Object",
".",
"keys",
"(",
"task",
")",
";",
"}",
"// convert non-array and non-object elements",
"// into single element arrays",
"if",
"(",
"typeof",
"task",
"!=",
"'object'",
")",
"{",
"task",
"=",
"[",
"task",
"]",
";",
"}",
"execute",
"(",
"state",
",",
"task",
",",
"keys",
",",
"function",
"(",
"err",
",",
"modifiedState",
")",
"{",
"// reset current task",
"// if it's error and modified state",
"// isn't provided, use context",
"(",
"modifiedState",
"||",
"state",
")",
".",
"_currentTask",
"=",
"undefined",
";",
"// eslint-disable-line no-undefined",
"if",
"(",
"err",
")",
"return",
"callback",
"(",
"err",
")",
";",
"// proceed to the next element",
"iterator",
"(",
"modifiedState",
",",
"tasks",
",",
"callback",
")",
";",
"}",
")",
";",
"}"
] | Iterates over batch tasks with provided state object
@private
@param {object} state - current state
@param {array} tasks - list of tasks to execute
@param {function} callback - invoked after all tasks have been processed
@returns {void} | [
"Iterates",
"over",
"batch",
"tasks",
"with",
"provided",
"state",
"object"
] | 73d9c8c994f915688db0627ea3b4854ead771138 | https://github.com/alexindigo/batcher/blob/73d9c8c994f915688db0627ea3b4854ead771138/index.js#L97-L147 |
48,013 | alexindigo/batcher | index.js | execute | function execute(state, task, keys, callback)
{
var key
, control
, assignment = 'ASSIGNMENT'
// get list of commands left for this iteration
, commandsLeft = (keys || task).length
, command = (keys || task).shift()
// job id within given task
, jobId = commandsLeft
;
// we're done here
// wait for all the commands
if (commandsLeft === 0)
{
// if it's last one proceed to callback
if (Object.keys(state._currentTask.waiters).length === 0)
{
callback(null, state); // eslint-disable-line callback-return
}
return;
}
if (keys)
{
key = command;
command = task[command];
// consider anything but strings, functions and arrays as direct state modifiers
// there is no one right way to merge arrays, so leave it for custom functions
if (['array', 'function', 'string'].indexOf(typeOf(command)) == -1)
{
report('start', state, assignment);
// do shallow merge, until we needed otherwise
state[key] = typeOf(command) == 'object' ? extend(state[key], command) : command;
report('store', state, assignment, key);
report('output', state, assignment, command);
execute(state, task, keys, callback);
return;
}
}
report('start', state, command);
// run the command and get terminator reference
// if it'd need to be stopped
control = run(clone(command), state, function(err, data)
{
// clean up waiters
delete state._currentTask.waiters[jobId];
if (err)
{
report('error', state, command, err);
cleanWaiters(state);
return callback(err);
}
// modify state if requested
if (key)
{
state[key] = data;
report('store', state, command, key);
}
report('output', state, command, data);
// if it's last one proceed to callback
if (Object.keys(state._currentTask.waiters).length === 0)
{
callback(null, state); // eslint-disable-line callback-return
return;
}
});
// if no control object returned
// means run task was prematurely terminated
// do not proceed
if (!control)
{
return;
}
// keep reference to command related elements
state._currentTask.waiters[jobId] =
{
command : command,
callback : control.callback,
terminator : control.terminator
};
// proceed to the next command within task
execute(state, task, keys, callback);
} | javascript | function execute(state, task, keys, callback)
{
var key
, control
, assignment = 'ASSIGNMENT'
// get list of commands left for this iteration
, commandsLeft = (keys || task).length
, command = (keys || task).shift()
// job id within given task
, jobId = commandsLeft
;
// we're done here
// wait for all the commands
if (commandsLeft === 0)
{
// if it's last one proceed to callback
if (Object.keys(state._currentTask.waiters).length === 0)
{
callback(null, state); // eslint-disable-line callback-return
}
return;
}
if (keys)
{
key = command;
command = task[command];
// consider anything but strings, functions and arrays as direct state modifiers
// there is no one right way to merge arrays, so leave it for custom functions
if (['array', 'function', 'string'].indexOf(typeOf(command)) == -1)
{
report('start', state, assignment);
// do shallow merge, until we needed otherwise
state[key] = typeOf(command) == 'object' ? extend(state[key], command) : command;
report('store', state, assignment, key);
report('output', state, assignment, command);
execute(state, task, keys, callback);
return;
}
}
report('start', state, command);
// run the command and get terminator reference
// if it'd need to be stopped
control = run(clone(command), state, function(err, data)
{
// clean up waiters
delete state._currentTask.waiters[jobId];
if (err)
{
report('error', state, command, err);
cleanWaiters(state);
return callback(err);
}
// modify state if requested
if (key)
{
state[key] = data;
report('store', state, command, key);
}
report('output', state, command, data);
// if it's last one proceed to callback
if (Object.keys(state._currentTask.waiters).length === 0)
{
callback(null, state); // eslint-disable-line callback-return
return;
}
});
// if no control object returned
// means run task was prematurely terminated
// do not proceed
if (!control)
{
return;
}
// keep reference to command related elements
state._currentTask.waiters[jobId] =
{
command : command,
callback : control.callback,
terminator : control.terminator
};
// proceed to the next command within task
execute(state, task, keys, callback);
} | [
"function",
"execute",
"(",
"state",
",",
"task",
",",
"keys",
",",
"callback",
")",
"{",
"var",
"key",
",",
"control",
",",
"assignment",
"=",
"'ASSIGNMENT'",
"// get list of commands left for this iteration",
",",
"commandsLeft",
"=",
"(",
"keys",
"||",
"task",
")",
".",
"length",
",",
"command",
"=",
"(",
"keys",
"||",
"task",
")",
".",
"shift",
"(",
")",
"// job id within given task",
",",
"jobId",
"=",
"commandsLeft",
";",
"// we're done here",
"// wait for all the commands",
"if",
"(",
"commandsLeft",
"===",
"0",
")",
"{",
"// if it's last one proceed to callback",
"if",
"(",
"Object",
".",
"keys",
"(",
"state",
".",
"_currentTask",
".",
"waiters",
")",
".",
"length",
"===",
"0",
")",
"{",
"callback",
"(",
"null",
",",
"state",
")",
";",
"// eslint-disable-line callback-return",
"}",
"return",
";",
"}",
"if",
"(",
"keys",
")",
"{",
"key",
"=",
"command",
";",
"command",
"=",
"task",
"[",
"command",
"]",
";",
"// consider anything but strings, functions and arrays as direct state modifiers",
"// there is no one right way to merge arrays, so leave it for custom functions",
"if",
"(",
"[",
"'array'",
",",
"'function'",
",",
"'string'",
"]",
".",
"indexOf",
"(",
"typeOf",
"(",
"command",
")",
")",
"==",
"-",
"1",
")",
"{",
"report",
"(",
"'start'",
",",
"state",
",",
"assignment",
")",
";",
"// do shallow merge, until we needed otherwise",
"state",
"[",
"key",
"]",
"=",
"typeOf",
"(",
"command",
")",
"==",
"'object'",
"?",
"extend",
"(",
"state",
"[",
"key",
"]",
",",
"command",
")",
":",
"command",
";",
"report",
"(",
"'store'",
",",
"state",
",",
"assignment",
",",
"key",
")",
";",
"report",
"(",
"'output'",
",",
"state",
",",
"assignment",
",",
"command",
")",
";",
"execute",
"(",
"state",
",",
"task",
",",
"keys",
",",
"callback",
")",
";",
"return",
";",
"}",
"}",
"report",
"(",
"'start'",
",",
"state",
",",
"command",
")",
";",
"// run the command and get terminator reference",
"// if it'd need to be stopped",
"control",
"=",
"run",
"(",
"clone",
"(",
"command",
")",
",",
"state",
",",
"function",
"(",
"err",
",",
"data",
")",
"{",
"// clean up waiters",
"delete",
"state",
".",
"_currentTask",
".",
"waiters",
"[",
"jobId",
"]",
";",
"if",
"(",
"err",
")",
"{",
"report",
"(",
"'error'",
",",
"state",
",",
"command",
",",
"err",
")",
";",
"cleanWaiters",
"(",
"state",
")",
";",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"// modify state if requested",
"if",
"(",
"key",
")",
"{",
"state",
"[",
"key",
"]",
"=",
"data",
";",
"report",
"(",
"'store'",
",",
"state",
",",
"command",
",",
"key",
")",
";",
"}",
"report",
"(",
"'output'",
",",
"state",
",",
"command",
",",
"data",
")",
";",
"// if it's last one proceed to callback",
"if",
"(",
"Object",
".",
"keys",
"(",
"state",
".",
"_currentTask",
".",
"waiters",
")",
".",
"length",
"===",
"0",
")",
"{",
"callback",
"(",
"null",
",",
"state",
")",
";",
"// eslint-disable-line callback-return",
"return",
";",
"}",
"}",
")",
";",
"// if no control object returned",
"// means run task was prematurely terminated",
"// do not proceed",
"if",
"(",
"!",
"control",
")",
"{",
"return",
";",
"}",
"// keep reference to command related elements",
"state",
".",
"_currentTask",
".",
"waiters",
"[",
"jobId",
"]",
"=",
"{",
"command",
":",
"command",
",",
"callback",
":",
"control",
".",
"callback",
",",
"terminator",
":",
"control",
".",
"terminator",
"}",
";",
"// proceed to the next command within task",
"execute",
"(",
"state",
",",
"task",
",",
"keys",
",",
"callback",
")",
";",
"}"
] | Executes provided task with state object context
@private
@param {object} state - current state
@param {array} task - list of commands to execute
@param {array|undefined} keys - list of task names
@param {function} callback - invoked after all commands have been executed
@returns {void} | [
"Executes",
"provided",
"task",
"with",
"state",
"object",
"context"
] | 73d9c8c994f915688db0627ea3b4854ead771138 | https://github.com/alexindigo/batcher/blob/73d9c8c994f915688db0627ea3b4854ead771138/index.js#L159-L257 |
48,014 | alexindigo/batcher | index.js | cleanWaiters | function cleanWaiters(state)
{
var list = state._currentTask.waiters;
Object.keys(list).forEach(function(job)
{
// prevent callback from execution
// by modifying up `once`'s `called` property
list[job].callback.called = true;
// if called it will return false
list[job].callback.value = false;
// send termination signal to the job
list[job].terminator();
// report termination
report('killed', state, list[job].command);
delete list[job];
});
} | javascript | function cleanWaiters(state)
{
var list = state._currentTask.waiters;
Object.keys(list).forEach(function(job)
{
// prevent callback from execution
// by modifying up `once`'s `called` property
list[job].callback.called = true;
// if called it will return false
list[job].callback.value = false;
// send termination signal to the job
list[job].terminator();
// report termination
report('killed', state, list[job].command);
delete list[job];
});
} | [
"function",
"cleanWaiters",
"(",
"state",
")",
"{",
"var",
"list",
"=",
"state",
".",
"_currentTask",
".",
"waiters",
";",
"Object",
".",
"keys",
"(",
"list",
")",
".",
"forEach",
"(",
"function",
"(",
"job",
")",
"{",
"// prevent callback from execution",
"// by modifying up `once`'s `called` property",
"list",
"[",
"job",
"]",
".",
"callback",
".",
"called",
"=",
"true",
";",
"// if called it will return false",
"list",
"[",
"job",
"]",
".",
"callback",
".",
"value",
"=",
"false",
";",
"// send termination signal to the job",
"list",
"[",
"job",
"]",
".",
"terminator",
"(",
")",
";",
"// report termination",
"report",
"(",
"'killed'",
",",
"state",
",",
"list",
"[",
"job",
"]",
".",
"command",
")",
";",
"delete",
"list",
"[",
"job",
"]",
";",
"}",
")",
";",
"}"
] | Cleans leftover jobs provided by the list
@param {object} state - current state
@returns {void} | [
"Cleans",
"leftover",
"jobs",
"provided",
"by",
"the",
"list"
] | 73d9c8c994f915688db0627ea3b4854ead771138 | https://github.com/alexindigo/batcher/blob/73d9c8c994f915688db0627ea3b4854ead771138/index.js#L320-L341 |
48,015 | areslabs/babel-plugin-import-css | src/cssWatch.js | recallInMap | function recallInMap(resMap, absPath) {
if (resMap.has(absPath) && resMap.get(absPath).size > 0) {
for (let keyPath of resMap.get(absPath)) {
//update first
forceUpdate(keyPath)
recallInMap(resMap, keyPath)
}
}
} | javascript | function recallInMap(resMap, absPath) {
if (resMap.has(absPath) && resMap.get(absPath).size > 0) {
for (let keyPath of resMap.get(absPath)) {
//update first
forceUpdate(keyPath)
recallInMap(resMap, keyPath)
}
}
} | [
"function",
"recallInMap",
"(",
"resMap",
",",
"absPath",
")",
"{",
"if",
"(",
"resMap",
".",
"has",
"(",
"absPath",
")",
"&&",
"resMap",
".",
"get",
"(",
"absPath",
")",
".",
"size",
">",
"0",
")",
"{",
"for",
"(",
"let",
"keyPath",
"of",
"resMap",
".",
"get",
"(",
"absPath",
")",
")",
"{",
"//update first",
"forceUpdate",
"(",
"keyPath",
")",
"recallInMap",
"(",
"resMap",
",",
"keyPath",
")",
"}",
"}",
"}"
] | Modify related css files recursively
@param resMap
@param absPath | [
"Modify",
"related",
"css",
"files",
"recursively"
] | b90d3a4ec3a644edcaa1c803314e2c39de1d29c9 | https://github.com/areslabs/babel-plugin-import-css/blob/b90d3a4ec3a644edcaa1c803314e2c39de1d29c9/src/cssWatch.js#L138-L146 |
48,016 | bookmansoft/gamecloud | facade/events/user/relogin.js | handle | function handle(event) {
if(event.data.type == 1 || event.data.type == 3 || event.data.type == 7){
facade.models.login().findCreateFind({
where:{
uid: event.user.id,
type: event.data.type,
},
defaults: {
uid: event.user.id,
type: event.data.type,
time: event.data.time
},
});
}
} | javascript | function handle(event) {
if(event.data.type == 1 || event.data.type == 3 || event.data.type == 7){
facade.models.login().findCreateFind({
where:{
uid: event.user.id,
type: event.data.type,
},
defaults: {
uid: event.user.id,
type: event.data.type,
time: event.data.time
},
});
}
} | [
"function",
"handle",
"(",
"event",
")",
"{",
"if",
"(",
"event",
".",
"data",
".",
"type",
"==",
"1",
"||",
"event",
".",
"data",
".",
"type",
"==",
"3",
"||",
"event",
".",
"data",
".",
"type",
"==",
"7",
")",
"{",
"facade",
".",
"models",
".",
"login",
"(",
")",
".",
"findCreateFind",
"(",
"{",
"where",
":",
"{",
"uid",
":",
"event",
".",
"user",
".",
"id",
",",
"type",
":",
"event",
".",
"data",
".",
"type",
",",
"}",
",",
"defaults",
":",
"{",
"uid",
":",
"event",
".",
"user",
".",
"id",
",",
"type",
":",
"event",
".",
"data",
".",
"type",
",",
"time",
":",
"event",
".",
"data",
".",
"time",
"}",
",",
"}",
")",
";",
"}",
"}"
] | Created by admin on 2017-05-26.
@param {EventData} event | [
"Created",
"by",
"admin",
"on",
"2017",
"-",
"05",
"-",
"26",
"."
] | cff1a3eeaab392756f4e7b188451f419755d679d | https://github.com/bookmansoft/gamecloud/blob/cff1a3eeaab392756f4e7b188451f419755d679d/facade/events/user/relogin.js#L7-L21 |
48,017 | anywhichway/wsfetch | javascript/ractive.js | get | function get ( keypath ) {
if ( !keypath ) return this._element.parentFragment.findContext().get( true );
var model = resolveReference( this._element.parentFragment, keypath );
return model ? model.get( true ) : undefined;
} | javascript | function get ( keypath ) {
if ( !keypath ) return this._element.parentFragment.findContext().get( true );
var model = resolveReference( this._element.parentFragment, keypath );
return model ? model.get( true ) : undefined;
} | [
"function",
"get",
"(",
"keypath",
")",
"{",
"if",
"(",
"!",
"keypath",
")",
"return",
"this",
".",
"_element",
".",
"parentFragment",
".",
"findContext",
"(",
")",
".",
"get",
"(",
"true",
")",
";",
"var",
"model",
"=",
"resolveReference",
"(",
"this",
".",
"_element",
".",
"parentFragment",
",",
"keypath",
")",
";",
"return",
"model",
"?",
"model",
".",
"get",
"(",
"true",
")",
":",
"undefined",
";",
"}"
] | get relative keypaths and values | [
"get",
"relative",
"keypaths",
"and",
"values"
] | 74d81a9537a748e9c6c04ffccf74f71b5eebddfa | https://github.com/anywhichway/wsfetch/blob/74d81a9537a748e9c6c04ffccf74f71b5eebddfa/javascript/ractive.js#L3653-L3659 |
48,018 | anywhichway/wsfetch | javascript/ractive.js | add$1 | function add$1 ( keypath, value ) {
if ( value === undefined ) value = 1;
if ( !isNumeric( value ) ) throw new Error( 'Bad arguments' );
return set( this.ractive, build$1( this, keypath, value ).map( function ( pair ) {
var model = pair[0], val = pair[1], value = model.get();
if ( !isNumeric( val ) || !isNumeric( value ) ) throw new Error( 'Cannot add non-numeric value' );
return [ model, value + val ];
}) );
} | javascript | function add$1 ( keypath, value ) {
if ( value === undefined ) value = 1;
if ( !isNumeric( value ) ) throw new Error( 'Bad arguments' );
return set( this.ractive, build$1( this, keypath, value ).map( function ( pair ) {
var model = pair[0], val = pair[1], value = model.get();
if ( !isNumeric( val ) || !isNumeric( value ) ) throw new Error( 'Cannot add non-numeric value' );
return [ model, value + val ];
}) );
} | [
"function",
"add$1",
"(",
"keypath",
",",
"value",
")",
"{",
"if",
"(",
"value",
"===",
"undefined",
")",
"value",
"=",
"1",
";",
"if",
"(",
"!",
"isNumeric",
"(",
"value",
")",
")",
"throw",
"new",
"Error",
"(",
"'Bad arguments'",
")",
";",
"return",
"set",
"(",
"this",
".",
"ractive",
",",
"build$1",
"(",
"this",
",",
"keypath",
",",
"value",
")",
".",
"map",
"(",
"function",
"(",
"pair",
")",
"{",
"var",
"model",
"=",
"pair",
"[",
"0",
"]",
",",
"val",
"=",
"pair",
"[",
"1",
"]",
",",
"value",
"=",
"model",
".",
"get",
"(",
")",
";",
"if",
"(",
"!",
"isNumeric",
"(",
"val",
")",
"||",
"!",
"isNumeric",
"(",
"value",
")",
")",
"throw",
"new",
"Error",
"(",
"'Cannot add non-numeric value'",
")",
";",
"return",
"[",
"model",
",",
"value",
"+",
"val",
"]",
";",
"}",
")",
")",
";",
"}"
] | the usual mutation suspects | [
"the",
"usual",
"mutation",
"suspects"
] | 74d81a9537a748e9c6c04ffccf74f71b5eebddfa | https://github.com/anywhichway/wsfetch/blob/74d81a9537a748e9c6c04ffccf74f71b5eebddfa/javascript/ractive.js#L3677-L3685 |
48,019 | anywhichway/wsfetch | javascript/ractive.js | function ( Parent, proto, options ) {
if ( !options.css ) return;
var id = uuid();
var styles = options.noCssTransform ? options.css : transformCss( options.css, id );
proto.cssId = id;
addCSS( { id: id, styles: styles } );
} | javascript | function ( Parent, proto, options ) {
if ( !options.css ) return;
var id = uuid();
var styles = options.noCssTransform ? options.css : transformCss( options.css, id );
proto.cssId = id;
addCSS( { id: id, styles: styles } );
} | [
"function",
"(",
"Parent",
",",
"proto",
",",
"options",
")",
"{",
"if",
"(",
"!",
"options",
".",
"css",
")",
"return",
";",
"var",
"id",
"=",
"uuid",
"(",
")",
";",
"var",
"styles",
"=",
"options",
".",
"noCssTransform",
"?",
"options",
".",
"css",
":",
"transformCss",
"(",
"options",
".",
"css",
",",
"id",
")",
";",
"proto",
".",
"cssId",
"=",
"id",
";",
"addCSS",
"(",
"{",
"id",
":",
"id",
",",
"styles",
":",
"styles",
"}",
")",
";",
"}"
] | Called when creating a new component definition | [
"Called",
"when",
"creating",
"a",
"new",
"component",
"definition"
] | 74d81a9537a748e9c6c04ffccf74f71b5eebddfa | https://github.com/anywhichway/wsfetch/blob/74d81a9537a748e9c6c04ffccf74f71b5eebddfa/javascript/ractive.js#L4772-L4782 |
|
48,020 | anywhichway/wsfetch | javascript/ractive.js | makeQuotedStringMatcher | function makeQuotedStringMatcher ( okQuote ) {
return function ( parser ) {
var literal = '"';
var done = false;
var next;
while ( !done ) {
next = ( parser.matchPattern( stringMiddlePattern ) || parser.matchPattern( escapeSequencePattern ) ||
parser.matchString( okQuote ) );
if ( next ) {
if ( next === ("\"") ) {
literal += "\\\"";
} else if ( next === ("\\'") ) {
literal += "'";
} else {
literal += next;
}
} else {
next = parser.matchPattern( lineContinuationPattern );
if ( next ) {
// convert \(newline-like) into a \u escape, which is allowed in JSON
literal += '\\u' + ( '000' + next.charCodeAt(1).toString(16) ).slice( -4 );
} else {
done = true;
}
}
}
literal += '"';
// use JSON.parse to interpret escapes
return JSON.parse( literal );
};
} | javascript | function makeQuotedStringMatcher ( okQuote ) {
return function ( parser ) {
var literal = '"';
var done = false;
var next;
while ( !done ) {
next = ( parser.matchPattern( stringMiddlePattern ) || parser.matchPattern( escapeSequencePattern ) ||
parser.matchString( okQuote ) );
if ( next ) {
if ( next === ("\"") ) {
literal += "\\\"";
} else if ( next === ("\\'") ) {
literal += "'";
} else {
literal += next;
}
} else {
next = parser.matchPattern( lineContinuationPattern );
if ( next ) {
// convert \(newline-like) into a \u escape, which is allowed in JSON
literal += '\\u' + ( '000' + next.charCodeAt(1).toString(16) ).slice( -4 );
} else {
done = true;
}
}
}
literal += '"';
// use JSON.parse to interpret escapes
return JSON.parse( literal );
};
} | [
"function",
"makeQuotedStringMatcher",
"(",
"okQuote",
")",
"{",
"return",
"function",
"(",
"parser",
")",
"{",
"var",
"literal",
"=",
"'\"'",
";",
"var",
"done",
"=",
"false",
";",
"var",
"next",
";",
"while",
"(",
"!",
"done",
")",
"{",
"next",
"=",
"(",
"parser",
".",
"matchPattern",
"(",
"stringMiddlePattern",
")",
"||",
"parser",
".",
"matchPattern",
"(",
"escapeSequencePattern",
")",
"||",
"parser",
".",
"matchString",
"(",
"okQuote",
")",
")",
";",
"if",
"(",
"next",
")",
"{",
"if",
"(",
"next",
"===",
"(",
"\"\\\"\"",
")",
")",
"{",
"literal",
"+=",
"\"\\\\\\\"\"",
";",
"}",
"else",
"if",
"(",
"next",
"===",
"(",
"\"\\\\'\"",
")",
")",
"{",
"literal",
"+=",
"\"'\"",
";",
"}",
"else",
"{",
"literal",
"+=",
"next",
";",
"}",
"}",
"else",
"{",
"next",
"=",
"parser",
".",
"matchPattern",
"(",
"lineContinuationPattern",
")",
";",
"if",
"(",
"next",
")",
"{",
"// convert \\(newline-like) into a \\u escape, which is allowed in JSON",
"literal",
"+=",
"'\\\\u'",
"+",
"(",
"'000'",
"+",
"next",
".",
"charCodeAt",
"(",
"1",
")",
".",
"toString",
"(",
"16",
")",
")",
".",
"slice",
"(",
"-",
"4",
")",
";",
"}",
"else",
"{",
"done",
"=",
"true",
";",
"}",
"}",
"}",
"literal",
"+=",
"'\"'",
";",
"// use JSON.parse to interpret escapes",
"return",
"JSON",
".",
"parse",
"(",
"literal",
")",
";",
"}",
";",
"}"
] | Helper for defining getDoubleQuotedString and getSingleQuotedString. | [
"Helper",
"for",
"defining",
"getDoubleQuotedString",
"and",
"getSingleQuotedString",
"."
] | 74d81a9537a748e9c6c04ffccf74f71b5eebddfa | https://github.com/anywhichway/wsfetch/blob/74d81a9537a748e9c6c04ffccf74f71b5eebddfa/javascript/ractive.js#L5416-L5449 |
48,021 | anywhichway/wsfetch | javascript/ractive.js | getConditional | function getConditional ( parser ) {
var start, expression, ifTrue, ifFalse;
expression = readLogicalOr$1( parser );
if ( !expression ) {
return null;
}
start = parser.pos;
parser.allowWhitespace();
if ( !parser.matchString( '?' ) ) {
parser.pos = start;
return expression;
}
parser.allowWhitespace();
ifTrue = readExpression( parser );
if ( !ifTrue ) {
parser.error( expectedExpression );
}
parser.allowWhitespace();
if ( !parser.matchString( ':' ) ) {
parser.error( 'Expected ":"' );
}
parser.allowWhitespace();
ifFalse = readExpression( parser );
if ( !ifFalse ) {
parser.error( expectedExpression );
}
return {
t: CONDITIONAL,
o: [ expression, ifTrue, ifFalse ]
};
} | javascript | function getConditional ( parser ) {
var start, expression, ifTrue, ifFalse;
expression = readLogicalOr$1( parser );
if ( !expression ) {
return null;
}
start = parser.pos;
parser.allowWhitespace();
if ( !parser.matchString( '?' ) ) {
parser.pos = start;
return expression;
}
parser.allowWhitespace();
ifTrue = readExpression( parser );
if ( !ifTrue ) {
parser.error( expectedExpression );
}
parser.allowWhitespace();
if ( !parser.matchString( ':' ) ) {
parser.error( 'Expected ":"' );
}
parser.allowWhitespace();
ifFalse = readExpression( parser );
if ( !ifFalse ) {
parser.error( expectedExpression );
}
return {
t: CONDITIONAL,
o: [ expression, ifTrue, ifFalse ]
};
} | [
"function",
"getConditional",
"(",
"parser",
")",
"{",
"var",
"start",
",",
"expression",
",",
"ifTrue",
",",
"ifFalse",
";",
"expression",
"=",
"readLogicalOr$1",
"(",
"parser",
")",
";",
"if",
"(",
"!",
"expression",
")",
"{",
"return",
"null",
";",
"}",
"start",
"=",
"parser",
".",
"pos",
";",
"parser",
".",
"allowWhitespace",
"(",
")",
";",
"if",
"(",
"!",
"parser",
".",
"matchString",
"(",
"'?'",
")",
")",
"{",
"parser",
".",
"pos",
"=",
"start",
";",
"return",
"expression",
";",
"}",
"parser",
".",
"allowWhitespace",
"(",
")",
";",
"ifTrue",
"=",
"readExpression",
"(",
"parser",
")",
";",
"if",
"(",
"!",
"ifTrue",
")",
"{",
"parser",
".",
"error",
"(",
"expectedExpression",
")",
";",
"}",
"parser",
".",
"allowWhitespace",
"(",
")",
";",
"if",
"(",
"!",
"parser",
".",
"matchString",
"(",
"':'",
")",
")",
"{",
"parser",
".",
"error",
"(",
"'Expected \":\"'",
")",
";",
"}",
"parser",
".",
"allowWhitespace",
"(",
")",
";",
"ifFalse",
"=",
"readExpression",
"(",
"parser",
")",
";",
"if",
"(",
"!",
"ifFalse",
")",
"{",
"parser",
".",
"error",
"(",
"expectedExpression",
")",
";",
"}",
"return",
"{",
"t",
":",
"CONDITIONAL",
",",
"o",
":",
"[",
"expression",
",",
"ifTrue",
",",
"ifFalse",
"]",
"}",
";",
"}"
] | The conditional operator is the lowest precedence operator, so we start here | [
"The",
"conditional",
"operator",
"is",
"the",
"lowest",
"precedence",
"operator",
"so",
"we",
"start",
"here"
] | 74d81a9537a748e9c6c04ffccf74f71b5eebddfa | https://github.com/anywhichway/wsfetch/blob/74d81a9537a748e9c6c04ffccf74f71b5eebddfa/javascript/ractive.js#L6013-L6054 |
48,022 | anywhichway/wsfetch | javascript/ractive.js | truncateStack | function truncateStack ( stack ) {
if ( !stack ) return '';
var lines = stack.split( '\n' );
var name = Computation.name + '.getValue';
var truncated = [];
var len = lines.length;
for ( var i = 1; i < len; i += 1 ) {
var line = lines[i];
if ( ~line.indexOf( name ) ) {
return truncated.join( '\n' );
} else {
truncated.push( line );
}
}
} | javascript | function truncateStack ( stack ) {
if ( !stack ) return '';
var lines = stack.split( '\n' );
var name = Computation.name + '.getValue';
var truncated = [];
var len = lines.length;
for ( var i = 1; i < len; i += 1 ) {
var line = lines[i];
if ( ~line.indexOf( name ) ) {
return truncated.join( '\n' );
} else {
truncated.push( line );
}
}
} | [
"function",
"truncateStack",
"(",
"stack",
")",
"{",
"if",
"(",
"!",
"stack",
")",
"return",
"''",
";",
"var",
"lines",
"=",
"stack",
".",
"split",
"(",
"'\\n'",
")",
";",
"var",
"name",
"=",
"Computation",
".",
"name",
"+",
"'.getValue'",
";",
"var",
"truncated",
"=",
"[",
"]",
";",
"var",
"len",
"=",
"lines",
".",
"length",
";",
"for",
"(",
"var",
"i",
"=",
"1",
";",
"i",
"<",
"len",
";",
"i",
"+=",
"1",
")",
"{",
"var",
"line",
"=",
"lines",
"[",
"i",
"]",
";",
"if",
"(",
"~",
"line",
".",
"indexOf",
"(",
"name",
")",
")",
"{",
"return",
"truncated",
".",
"join",
"(",
"'\\n'",
")",
";",
"}",
"else",
"{",
"truncated",
".",
"push",
"(",
"line",
")",
";",
"}",
"}",
"}"
] | Ditto. This function truncates the stack to only include app code | [
"Ditto",
".",
"This",
"function",
"truncates",
"the",
"stack",
"to",
"only",
"include",
"app",
"code"
] | 74d81a9537a748e9c6c04ffccf74f71b5eebddfa | https://github.com/anywhichway/wsfetch/blob/74d81a9537a748e9c6c04ffccf74f71b5eebddfa/javascript/ractive.js#L10589-L10607 |
48,023 | anywhichway/wsfetch | javascript/ractive.js | Ractive$teardown | function Ractive$teardown () {
if ( this.torndown ) {
warnIfDebug( 'ractive.teardown() was called on a Ractive instance that was already torn down' );
return Promise$1.resolve();
}
this.torndown = true;
this.fragment.unbind();
this.viewmodel.teardown();
this._observers.forEach( cancel );
if ( this.fragment.rendered && this.el.__ractive_instances__ ) {
removeFromArray( this.el.__ractive_instances__, this );
}
this.shouldDestroy = true;
var promise = ( this.fragment.rendered ? this.unrender() : Promise$1.resolve() );
teardownHook$1.fire( this );
return promise;
} | javascript | function Ractive$teardown () {
if ( this.torndown ) {
warnIfDebug( 'ractive.teardown() was called on a Ractive instance that was already torn down' );
return Promise$1.resolve();
}
this.torndown = true;
this.fragment.unbind();
this.viewmodel.teardown();
this._observers.forEach( cancel );
if ( this.fragment.rendered && this.el.__ractive_instances__ ) {
removeFromArray( this.el.__ractive_instances__, this );
}
this.shouldDestroy = true;
var promise = ( this.fragment.rendered ? this.unrender() : Promise$1.resolve() );
teardownHook$1.fire( this );
return promise;
} | [
"function",
"Ractive$teardown",
"(",
")",
"{",
"if",
"(",
"this",
".",
"torndown",
")",
"{",
"warnIfDebug",
"(",
"'ractive.teardown() was called on a Ractive instance that was already torn down'",
")",
";",
"return",
"Promise$1",
".",
"resolve",
"(",
")",
";",
"}",
"this",
".",
"torndown",
"=",
"true",
";",
"this",
".",
"fragment",
".",
"unbind",
"(",
")",
";",
"this",
".",
"viewmodel",
".",
"teardown",
"(",
")",
";",
"this",
".",
"_observers",
".",
"forEach",
"(",
"cancel",
")",
";",
"if",
"(",
"this",
".",
"fragment",
".",
"rendered",
"&&",
"this",
".",
"el",
".",
"__ractive_instances__",
")",
"{",
"removeFromArray",
"(",
"this",
".",
"el",
".",
"__ractive_instances__",
",",
"this",
")",
";",
"}",
"this",
".",
"shouldDestroy",
"=",
"true",
";",
"var",
"promise",
"=",
"(",
"this",
".",
"fragment",
".",
"rendered",
"?",
"this",
".",
"unrender",
"(",
")",
":",
"Promise$1",
".",
"resolve",
"(",
")",
")",
";",
"teardownHook$1",
".",
"fire",
"(",
"this",
")",
";",
"return",
"promise",
";",
"}"
] | Teardown. This goes through the root fragment and all its children, removing observers and generally cleaning up after itself | [
"Teardown",
".",
"This",
"goes",
"through",
"the",
"root",
"fragment",
"and",
"all",
"its",
"children",
"removing",
"observers",
"and",
"generally",
"cleaning",
"up",
"after",
"itself"
] | 74d81a9537a748e9c6c04ffccf74f71b5eebddfa | https://github.com/anywhichway/wsfetch/blob/74d81a9537a748e9c6c04ffccf74f71b5eebddfa/javascript/ractive.js#L16604-L16626 |
48,024 | capaj/array-sugar | array-sugar.js | function(test, fromEnd) {
var i;
if (typeof test !== 'function') return undefined;
if (fromEnd) {
i = this.length;
while (i--) {
if (test(this[i], i, this)) {
return this[i];
}
}
} else {
i = 0;
while (i < this.length) {
if (test(this[i], i, this)) {
return this[i];
}
i++;
}
}
return null;
} | javascript | function(test, fromEnd) {
var i;
if (typeof test !== 'function') return undefined;
if (fromEnd) {
i = this.length;
while (i--) {
if (test(this[i], i, this)) {
return this[i];
}
}
} else {
i = 0;
while (i < this.length) {
if (test(this[i], i, this)) {
return this[i];
}
i++;
}
}
return null;
} | [
"function",
"(",
"test",
",",
"fromEnd",
")",
"{",
"var",
"i",
";",
"if",
"(",
"typeof",
"test",
"!==",
"'function'",
")",
"return",
"undefined",
";",
"if",
"(",
"fromEnd",
")",
"{",
"i",
"=",
"this",
".",
"length",
";",
"while",
"(",
"i",
"--",
")",
"{",
"if",
"(",
"test",
"(",
"this",
"[",
"i",
"]",
",",
"i",
",",
"this",
")",
")",
"{",
"return",
"this",
"[",
"i",
"]",
";",
"}",
"}",
"}",
"else",
"{",
"i",
"=",
"0",
";",
"while",
"(",
"i",
"<",
"this",
".",
"length",
")",
"{",
"if",
"(",
"test",
"(",
"this",
"[",
"i",
"]",
",",
"i",
",",
"this",
")",
")",
"{",
"return",
"this",
"[",
"i",
"]",
";",
"}",
"i",
"++",
";",
"}",
"}",
"return",
"null",
";",
"}"
] | traverses array and returns first element on which test function returns true
@param {Function<Boolean>} test
@param {Boolean} fromEnd pass true if you want to traverse array from end to beginning
@returns {*|null|undefined} an element of an array, or undefined when passed param is not a function | [
"traverses",
"array",
"and",
"returns",
"first",
"element",
"on",
"which",
"test",
"function",
"returns",
"true"
] | 43cee8e2dd166e46b88535dd7e149b8d71991f35 | https://github.com/capaj/array-sugar/blob/43cee8e2dd166e46b88535dd7e149b8d71991f35/array-sugar.js#L128-L148 |
|
48,025 | capaj/array-sugar | array-sugar.js | function(count, direction) {
return direction ? this.concat(this.splice(0, count)) : this.splice(this.length - count).concat(this);
} | javascript | function(count, direction) {
return direction ? this.concat(this.splice(0, count)) : this.splice(this.length - count).concat(this);
} | [
"function",
"(",
"count",
",",
"direction",
")",
"{",
"return",
"direction",
"?",
"this",
".",
"concat",
"(",
"this",
".",
"splice",
"(",
"0",
",",
"count",
")",
")",
":",
"this",
".",
"splice",
"(",
"this",
".",
"length",
"-",
"count",
")",
".",
"concat",
"(",
"this",
")",
";",
"}"
] | Rotates an array by given number of fields in given direction
@param {Number} count
@param {boolean} direction true for shifting array to the left
@returns {Array} | [
"Rotates",
"an",
"array",
"by",
"given",
"number",
"of",
"fields",
"in",
"given",
"direction"
] | 43cee8e2dd166e46b88535dd7e149b8d71991f35 | https://github.com/capaj/array-sugar/blob/43cee8e2dd166e46b88535dd7e149b8d71991f35/array-sugar.js#L214-L216 |
|
48,026 | NikxDa/node-spotify-helper | src/spotifyAppleScriptApi.js | promiseWrapper | function promiseWrapper (resolve, reject) {
// Wait for the process to exit
process.on ("exit", (code) => {
// Did the process crash?
if (code !== 0) reject (process.stderr.textContent);
// Resolve
resolve (process.stdout.textContent);
});
// Pipe the script into stdin and end
process.stdin.write (script);
process.stdin.end ();
} | javascript | function promiseWrapper (resolve, reject) {
// Wait for the process to exit
process.on ("exit", (code) => {
// Did the process crash?
if (code !== 0) reject (process.stderr.textContent);
// Resolve
resolve (process.stdout.textContent);
});
// Pipe the script into stdin and end
process.stdin.write (script);
process.stdin.end ();
} | [
"function",
"promiseWrapper",
"(",
"resolve",
",",
"reject",
")",
"{",
"// Wait for the process to exit",
"process",
".",
"on",
"(",
"\"exit\"",
",",
"(",
"code",
")",
"=>",
"{",
"// Did the process crash?",
"if",
"(",
"code",
"!==",
"0",
")",
"reject",
"(",
"process",
".",
"stderr",
".",
"textContent",
")",
";",
"// Resolve",
"resolve",
"(",
"process",
".",
"stdout",
".",
"textContent",
")",
";",
"}",
")",
";",
"// Pipe the script into stdin and end",
"process",
".",
"stdin",
".",
"write",
"(",
"script",
")",
";",
"process",
".",
"stdin",
".",
"end",
"(",
")",
";",
"}"
] | Wrapper for the Promise | [
"Wrapper",
"for",
"the",
"Promise"
] | a60f4fca3c9e608981770960ef5417004d25a6a6 | https://github.com/NikxDa/node-spotify-helper/blob/a60f4fca3c9e608981770960ef5417004d25a6a6/src/spotifyAppleScriptApi.js#L452-L465 |
48,027 | alexindigo/batcher | lib/run_command.js | run | function run(params, command, callback)
{
var job;
// decouple commands
command = clone(command);
// start command execution and get job reference
job = executioner(command, stringify(extend(this, params)), this.options || {}, callback);
// make ready to call task termination function
return partial(executioner.terminate, job);
} | javascript | function run(params, command, callback)
{
var job;
// decouple commands
command = clone(command);
// start command execution and get job reference
job = executioner(command, stringify(extend(this, params)), this.options || {}, callback);
// make ready to call task termination function
return partial(executioner.terminate, job);
} | [
"function",
"run",
"(",
"params",
",",
"command",
",",
"callback",
")",
"{",
"var",
"job",
";",
"// decouple commands",
"command",
"=",
"clone",
"(",
"command",
")",
";",
"// start command execution and get job reference",
"job",
"=",
"executioner",
"(",
"command",
",",
"stringify",
"(",
"extend",
"(",
"this",
",",
"params",
")",
")",
",",
"this",
".",
"options",
"||",
"{",
"}",
",",
"callback",
")",
";",
"// make ready to call task termination function",
"return",
"partial",
"(",
"executioner",
".",
"terminate",
",",
"job",
")",
";",
"}"
] | Runs provided command within state context
@param {object} params - extra execution-time parameters
@param {string|array} command - command to run
@param {function} callback - invoked after command finished executing
@returns {void} | [
"Runs",
"provided",
"command",
"within",
"state",
"context"
] | 73d9c8c994f915688db0627ea3b4854ead771138 | https://github.com/alexindigo/batcher/blob/73d9c8c994f915688db0627ea3b4854ead771138/lib/run_command.js#L19-L31 |
48,028 | alexindigo/batcher | lib/run_command.js | stringify | function stringify(origin)
{
var i, keys, prepared = {};
keys = Object.keys(origin);
i = keys.length;
while (i--)
{
// skip un-stringable things
if (typeOf(origin[keys[i]]) == 'function'
|| typeOf(origin[keys[i]]) == 'object')
{
continue;
}
// export it
prepared[keys[i]] = origin[keys[i]];
// make it shell ready
if (typeOf(prepared[keys[i]]) == 'boolean')
{
prepared[keys[i]] = prepared[keys[i]] ? '1' : '';
}
if (typeOf(prepared[keys[i]]) == 'undefined' || typeOf(prepared[keys[i]]) == 'null')
{
prepared[keys[i]] = '';
}
// convert everything else to string
prepared[keys[i]] = prepared[keys[i]].toString();
}
return prepared;
} | javascript | function stringify(origin)
{
var i, keys, prepared = {};
keys = Object.keys(origin);
i = keys.length;
while (i--)
{
// skip un-stringable things
if (typeOf(origin[keys[i]]) == 'function'
|| typeOf(origin[keys[i]]) == 'object')
{
continue;
}
// export it
prepared[keys[i]] = origin[keys[i]];
// make it shell ready
if (typeOf(prepared[keys[i]]) == 'boolean')
{
prepared[keys[i]] = prepared[keys[i]] ? '1' : '';
}
if (typeOf(prepared[keys[i]]) == 'undefined' || typeOf(prepared[keys[i]]) == 'null')
{
prepared[keys[i]] = '';
}
// convert everything else to string
prepared[keys[i]] = prepared[keys[i]].toString();
}
return prepared;
} | [
"function",
"stringify",
"(",
"origin",
")",
"{",
"var",
"i",
",",
"keys",
",",
"prepared",
"=",
"{",
"}",
";",
"keys",
"=",
"Object",
".",
"keys",
"(",
"origin",
")",
";",
"i",
"=",
"keys",
".",
"length",
";",
"while",
"(",
"i",
"--",
")",
"{",
"// skip un-stringable things",
"if",
"(",
"typeOf",
"(",
"origin",
"[",
"keys",
"[",
"i",
"]",
"]",
")",
"==",
"'function'",
"||",
"typeOf",
"(",
"origin",
"[",
"keys",
"[",
"i",
"]",
"]",
")",
"==",
"'object'",
")",
"{",
"continue",
";",
"}",
"// export it",
"prepared",
"[",
"keys",
"[",
"i",
"]",
"]",
"=",
"origin",
"[",
"keys",
"[",
"i",
"]",
"]",
";",
"// make it shell ready",
"if",
"(",
"typeOf",
"(",
"prepared",
"[",
"keys",
"[",
"i",
"]",
"]",
")",
"==",
"'boolean'",
")",
"{",
"prepared",
"[",
"keys",
"[",
"i",
"]",
"]",
"=",
"prepared",
"[",
"keys",
"[",
"i",
"]",
"]",
"?",
"'1'",
":",
"''",
";",
"}",
"if",
"(",
"typeOf",
"(",
"prepared",
"[",
"keys",
"[",
"i",
"]",
"]",
")",
"==",
"'undefined'",
"||",
"typeOf",
"(",
"prepared",
"[",
"keys",
"[",
"i",
"]",
"]",
")",
"==",
"'null'",
")",
"{",
"prepared",
"[",
"keys",
"[",
"i",
"]",
"]",
"=",
"''",
";",
"}",
"// convert everything else to string",
"prepared",
"[",
"keys",
"[",
"i",
"]",
"]",
"=",
"prepared",
"[",
"keys",
"[",
"i",
"]",
"]",
".",
"toString",
"(",
")",
";",
"}",
"return",
"prepared",
";",
"}"
] | Decouples and "stringifies" provided object
to use with `executioner` shell runner
@param {object} origin - params object
@returns {object} - new object with stringified properties | [
"Decouples",
"and",
"stringifies",
"provided",
"object",
"to",
"use",
"with",
"executioner",
"shell",
"runner"
] | 73d9c8c994f915688db0627ea3b4854ead771138 | https://github.com/alexindigo/batcher/blob/73d9c8c994f915688db0627ea3b4854ead771138/lib/run_command.js#L40-L75 |
48,029 | chrisJohn404/ljm-ffi | lib/ljm-ffi.js | allocateAndFillSyncFunctionArgs | function allocateAndFillSyncFunctionArgs(functionInfo, funcArgs, userArgs) {
functionInfo.requiredArgTypes.forEach(function(type, i) {
var buf = ljTypeOps[type].allocate(userArgs[i]);
buf = ljTypeOps[type].fill(buf, userArgs[i]);
funcArgs.push(buf);
});
} | javascript | function allocateAndFillSyncFunctionArgs(functionInfo, funcArgs, userArgs) {
functionInfo.requiredArgTypes.forEach(function(type, i) {
var buf = ljTypeOps[type].allocate(userArgs[i]);
buf = ljTypeOps[type].fill(buf, userArgs[i]);
funcArgs.push(buf);
});
} | [
"function",
"allocateAndFillSyncFunctionArgs",
"(",
"functionInfo",
",",
"funcArgs",
",",
"userArgs",
")",
"{",
"functionInfo",
".",
"requiredArgTypes",
".",
"forEach",
"(",
"function",
"(",
"type",
",",
"i",
")",
"{",
"var",
"buf",
"=",
"ljTypeOps",
"[",
"type",
"]",
".",
"allocate",
"(",
"userArgs",
"[",
"i",
"]",
")",
";",
"buf",
"=",
"ljTypeOps",
"[",
"type",
"]",
".",
"fill",
"(",
"buf",
",",
"userArgs",
"[",
"i",
"]",
")",
";",
"funcArgs",
".",
"push",
"(",
"buf",
")",
";",
"}",
")",
";",
"}"
] | Define a function that is used to allocate and fill buffers to communicate with the LJM library through ffi. | [
"Define",
"a",
"function",
"that",
"is",
"used",
"to",
"allocate",
"and",
"fill",
"buffers",
"to",
"communicate",
"with",
"the",
"LJM",
"library",
"through",
"ffi",
"."
] | 5f2bb940988f1cedb4182180a891ac8973f07a3d | https://github.com/chrisJohn404/ljm-ffi/blob/5f2bb940988f1cedb4182180a891ac8973f07a3d/lib/ljm-ffi.js#L714-L720 |
48,030 | chrisJohn404/ljm-ffi | lib/ljm-ffi.js | parseAndStoreSyncFunctionArgs | function parseAndStoreSyncFunctionArgs(functionInfo, funcArgs, saveObj) {
functionInfo.requiredArgTypes.forEach(function(type, i) {
var buf = funcArgs[i];
var parsedVal = ljTypeOps[type].parse(buf);
var argName = functionInfo.requiredArgNames[i];
saveObj[argName] = parsedVal;
});
} | javascript | function parseAndStoreSyncFunctionArgs(functionInfo, funcArgs, saveObj) {
functionInfo.requiredArgTypes.forEach(function(type, i) {
var buf = funcArgs[i];
var parsedVal = ljTypeOps[type].parse(buf);
var argName = functionInfo.requiredArgNames[i];
saveObj[argName] = parsedVal;
});
} | [
"function",
"parseAndStoreSyncFunctionArgs",
"(",
"functionInfo",
",",
"funcArgs",
",",
"saveObj",
")",
"{",
"functionInfo",
".",
"requiredArgTypes",
".",
"forEach",
"(",
"function",
"(",
"type",
",",
"i",
")",
"{",
"var",
"buf",
"=",
"funcArgs",
"[",
"i",
"]",
";",
"var",
"parsedVal",
"=",
"ljTypeOps",
"[",
"type",
"]",
".",
"parse",
"(",
"buf",
")",
";",
"var",
"argName",
"=",
"functionInfo",
".",
"requiredArgNames",
"[",
"i",
"]",
";",
"saveObj",
"[",
"argName",
"]",
"=",
"parsedVal",
";",
"}",
")",
";",
"}"
] | Define a function that is used to parse the values altered by LJM through the ffi library & save them to a return-object. | [
"Define",
"a",
"function",
"that",
"is",
"used",
"to",
"parse",
"the",
"values",
"altered",
"by",
"LJM",
"through",
"the",
"ffi",
"library",
"&",
"save",
"them",
"to",
"a",
"return",
"-",
"object",
"."
] | 5f2bb940988f1cedb4182180a891ac8973f07a3d | https://github.com/chrisJohn404/ljm-ffi/blob/5f2bb940988f1cedb4182180a891ac8973f07a3d/lib/ljm-ffi.js#L724-L731 |
48,031 | chrisJohn404/ljm-ffi | lib/ljm-ffi.js | createSyncFunction | function createSyncFunction(functionName, functionInfo) {
return function syncLJMFunction() {
if(arguments.length != functionInfo.args.length) {
var errStr = 'Invalid number of arguments. Should be: ';
errStr += functionInfo.args.length.toString() + '. ';
errStr += 'Given: ' + arguments.length + '. ';
errStr += getFunctionArgNames(functionInfo).join(', ');
errStr += '.';
console.error('Error in ljm-ffi syncLJMFunction', errStr);
throw new LJMFFIError(errStr);
} else {
// Create an array that will be filled with values to call the
// LJM function with.
var funcArgs = [];
// Parse and fill the function arguments array with data.
allocateAndFillSyncFunctionArgs(functionInfo, funcArgs, arguments);
// Execute the synchronous LJM function.
var ljmFunction = liblabjack[functionName];
var ljmError = ljmFunction.apply(this, funcArgs);
// Create an object to be returned.
var retObj = {
'ljmError': ljmError,
};
if(ljmError !== 0) {
retObj.errorInfo = modbus_map.getErrorInfo(ljmError);
}
// Fill the object being returned with data.
parseAndStoreSyncFunctionArgs(functionInfo, funcArgs, retObj);
return retObj;
}
};
} | javascript | function createSyncFunction(functionName, functionInfo) {
return function syncLJMFunction() {
if(arguments.length != functionInfo.args.length) {
var errStr = 'Invalid number of arguments. Should be: ';
errStr += functionInfo.args.length.toString() + '. ';
errStr += 'Given: ' + arguments.length + '. ';
errStr += getFunctionArgNames(functionInfo).join(', ');
errStr += '.';
console.error('Error in ljm-ffi syncLJMFunction', errStr);
throw new LJMFFIError(errStr);
} else {
// Create an array that will be filled with values to call the
// LJM function with.
var funcArgs = [];
// Parse and fill the function arguments array with data.
allocateAndFillSyncFunctionArgs(functionInfo, funcArgs, arguments);
// Execute the synchronous LJM function.
var ljmFunction = liblabjack[functionName];
var ljmError = ljmFunction.apply(this, funcArgs);
// Create an object to be returned.
var retObj = {
'ljmError': ljmError,
};
if(ljmError !== 0) {
retObj.errorInfo = modbus_map.getErrorInfo(ljmError);
}
// Fill the object being returned with data.
parseAndStoreSyncFunctionArgs(functionInfo, funcArgs, retObj);
return retObj;
}
};
} | [
"function",
"createSyncFunction",
"(",
"functionName",
",",
"functionInfo",
")",
"{",
"return",
"function",
"syncLJMFunction",
"(",
")",
"{",
"if",
"(",
"arguments",
".",
"length",
"!=",
"functionInfo",
".",
"args",
".",
"length",
")",
"{",
"var",
"errStr",
"=",
"'Invalid number of arguments. Should be: '",
";",
"errStr",
"+=",
"functionInfo",
".",
"args",
".",
"length",
".",
"toString",
"(",
")",
"+",
"'. '",
";",
"errStr",
"+=",
"'Given: '",
"+",
"arguments",
".",
"length",
"+",
"'. '",
";",
"errStr",
"+=",
"getFunctionArgNames",
"(",
"functionInfo",
")",
".",
"join",
"(",
"', '",
")",
";",
"errStr",
"+=",
"'.'",
";",
"console",
".",
"error",
"(",
"'Error in ljm-ffi syncLJMFunction'",
",",
"errStr",
")",
";",
"throw",
"new",
"LJMFFIError",
"(",
"errStr",
")",
";",
"}",
"else",
"{",
"// Create an array that will be filled with values to call the",
"// LJM function with.",
"var",
"funcArgs",
"=",
"[",
"]",
";",
"// Parse and fill the function arguments array with data.",
"allocateAndFillSyncFunctionArgs",
"(",
"functionInfo",
",",
"funcArgs",
",",
"arguments",
")",
";",
"// Execute the synchronous LJM function.",
"var",
"ljmFunction",
"=",
"liblabjack",
"[",
"functionName",
"]",
";",
"var",
"ljmError",
"=",
"ljmFunction",
".",
"apply",
"(",
"this",
",",
"funcArgs",
")",
";",
"// Create an object to be returned.",
"var",
"retObj",
"=",
"{",
"'ljmError'",
":",
"ljmError",
",",
"}",
";",
"if",
"(",
"ljmError",
"!==",
"0",
")",
"{",
"retObj",
".",
"errorInfo",
"=",
"modbus_map",
".",
"getErrorInfo",
"(",
"ljmError",
")",
";",
"}",
"// Fill the object being returned with data.",
"parseAndStoreSyncFunctionArgs",
"(",
"functionInfo",
",",
"funcArgs",
",",
"retObj",
")",
";",
"return",
"retObj",
";",
"}",
"}",
";",
"}"
] | Define a function that creates functions that can call LJM synchronously. | [
"Define",
"a",
"function",
"that",
"creates",
"functions",
"that",
"can",
"call",
"LJM",
"synchronously",
"."
] | 5f2bb940988f1cedb4182180a891ac8973f07a3d | https://github.com/chrisJohn404/ljm-ffi/blob/5f2bb940988f1cedb4182180a891ac8973f07a3d/lib/ljm-ffi.js#L734-L769 |
48,032 | chrisJohn404/ljm-ffi | lib/ljm-ffi.js | createAsyncFunction | function createAsyncFunction(functionName, functionInfo) {
return function asyncLJMFunction() {
var userCB;
function cb(err, res) {
if(err) {
console.error('Error Reported by Async Function', functionName);
}
// Create an object to be returned.
var ljmError = res;
var retObj = {
'ljmError': ljmError,
};
if(ljmError !== 0) {
retObj.errorInfo = modbus_map.getErrorInfo(ljmError);
}
// Fill the object being returned with data.
parseAndStoreSyncFunctionArgs(functionInfo, funcArgs, retObj);
// Execute the user's callback function.
userCB(retObj);
return;
}
// Check arg-length + 1 for the callback.
if(arguments.length != (functionInfo.args.length + 1)) {
var errStr = 'Invalid number of arguments. Should be: ';
errStr += functionInfo.args.length.toString() + '. ';
errStr += getFunctionArgNames(functionInfo).join(', ');
errStr += ', ' + 'callback.';
throw new LJMFFIError(errStr);
// } else if(typeof(arguments[arguments.length]) !== 'function') {
// var errStr
} else {
if(typeof(arguments[functionInfo.args.length]) !== 'function') {
userCB = function() {};
} else {
userCB = arguments[functionInfo.args.length];
}
// Create an array that will be filled with values to call the
// LJM function with.
var funcArgs = [];
// Parse and fill the function arguments array with data.
allocateAndFillSyncFunctionArgs(functionInfo, funcArgs, arguments);
// Over-write the function callback in the arguments list.
funcArgs[funcArgs.length] = cb;
// Execute the asynchronous LJM function.
var ljmFunction = liblabjack[functionName].async;
ljmFunction.apply(this, funcArgs);
return;
}
};
} | javascript | function createAsyncFunction(functionName, functionInfo) {
return function asyncLJMFunction() {
var userCB;
function cb(err, res) {
if(err) {
console.error('Error Reported by Async Function', functionName);
}
// Create an object to be returned.
var ljmError = res;
var retObj = {
'ljmError': ljmError,
};
if(ljmError !== 0) {
retObj.errorInfo = modbus_map.getErrorInfo(ljmError);
}
// Fill the object being returned with data.
parseAndStoreSyncFunctionArgs(functionInfo, funcArgs, retObj);
// Execute the user's callback function.
userCB(retObj);
return;
}
// Check arg-length + 1 for the callback.
if(arguments.length != (functionInfo.args.length + 1)) {
var errStr = 'Invalid number of arguments. Should be: ';
errStr += functionInfo.args.length.toString() + '. ';
errStr += getFunctionArgNames(functionInfo).join(', ');
errStr += ', ' + 'callback.';
throw new LJMFFIError(errStr);
// } else if(typeof(arguments[arguments.length]) !== 'function') {
// var errStr
} else {
if(typeof(arguments[functionInfo.args.length]) !== 'function') {
userCB = function() {};
} else {
userCB = arguments[functionInfo.args.length];
}
// Create an array that will be filled with values to call the
// LJM function with.
var funcArgs = [];
// Parse and fill the function arguments array with data.
allocateAndFillSyncFunctionArgs(functionInfo, funcArgs, arguments);
// Over-write the function callback in the arguments list.
funcArgs[funcArgs.length] = cb;
// Execute the asynchronous LJM function.
var ljmFunction = liblabjack[functionName].async;
ljmFunction.apply(this, funcArgs);
return;
}
};
} | [
"function",
"createAsyncFunction",
"(",
"functionName",
",",
"functionInfo",
")",
"{",
"return",
"function",
"asyncLJMFunction",
"(",
")",
"{",
"var",
"userCB",
";",
"function",
"cb",
"(",
"err",
",",
"res",
")",
"{",
"if",
"(",
"err",
")",
"{",
"console",
".",
"error",
"(",
"'Error Reported by Async Function'",
",",
"functionName",
")",
";",
"}",
"// Create an object to be returned.",
"var",
"ljmError",
"=",
"res",
";",
"var",
"retObj",
"=",
"{",
"'ljmError'",
":",
"ljmError",
",",
"}",
";",
"if",
"(",
"ljmError",
"!==",
"0",
")",
"{",
"retObj",
".",
"errorInfo",
"=",
"modbus_map",
".",
"getErrorInfo",
"(",
"ljmError",
")",
";",
"}",
"// Fill the object being returned with data.",
"parseAndStoreSyncFunctionArgs",
"(",
"functionInfo",
",",
"funcArgs",
",",
"retObj",
")",
";",
"// Execute the user's callback function.",
"userCB",
"(",
"retObj",
")",
";",
"return",
";",
"}",
"// Check arg-length + 1 for the callback.",
"if",
"(",
"arguments",
".",
"length",
"!=",
"(",
"functionInfo",
".",
"args",
".",
"length",
"+",
"1",
")",
")",
"{",
"var",
"errStr",
"=",
"'Invalid number of arguments. Should be: '",
";",
"errStr",
"+=",
"functionInfo",
".",
"args",
".",
"length",
".",
"toString",
"(",
")",
"+",
"'. '",
";",
"errStr",
"+=",
"getFunctionArgNames",
"(",
"functionInfo",
")",
".",
"join",
"(",
"', '",
")",
";",
"errStr",
"+=",
"', '",
"+",
"'callback.'",
";",
"throw",
"new",
"LJMFFIError",
"(",
"errStr",
")",
";",
"// } else if(typeof(arguments[arguments.length]) !== 'function') {",
"// var errStr",
"}",
"else",
"{",
"if",
"(",
"typeof",
"(",
"arguments",
"[",
"functionInfo",
".",
"args",
".",
"length",
"]",
")",
"!==",
"'function'",
")",
"{",
"userCB",
"=",
"function",
"(",
")",
"{",
"}",
";",
"}",
"else",
"{",
"userCB",
"=",
"arguments",
"[",
"functionInfo",
".",
"args",
".",
"length",
"]",
";",
"}",
"// Create an array that will be filled with values to call the",
"// LJM function with.",
"var",
"funcArgs",
"=",
"[",
"]",
";",
"// Parse and fill the function arguments array with data.",
"allocateAndFillSyncFunctionArgs",
"(",
"functionInfo",
",",
"funcArgs",
",",
"arguments",
")",
";",
"// Over-write the function callback in the arguments list.",
"funcArgs",
"[",
"funcArgs",
".",
"length",
"]",
"=",
"cb",
";",
"// Execute the asynchronous LJM function.",
"var",
"ljmFunction",
"=",
"liblabjack",
"[",
"functionName",
"]",
".",
"async",
";",
"ljmFunction",
".",
"apply",
"(",
"this",
",",
"funcArgs",
")",
";",
"return",
";",
"}",
"}",
";",
"}"
] | Define a function that creates functions that can call LJM asynchronously. | [
"Define",
"a",
"function",
"that",
"creates",
"functions",
"that",
"can",
"call",
"LJM",
"asynchronously",
"."
] | 5f2bb940988f1cedb4182180a891ac8973f07a3d | https://github.com/chrisJohn404/ljm-ffi/blob/5f2bb940988f1cedb4182180a891ac8973f07a3d/lib/ljm-ffi.js#L820-L880 |
48,033 | chrisJohn404/ljm-ffi | lib/ljm-ffi.js | createSafeAsyncFunction | function createSafeAsyncFunction(functionName, functionInfo) {
return function safeAsyncFunction() {
// Define a variable to store the error string in.
var errStr;
// Check to make sure the arguments seem to be valid.
if(arguments.length != (functionInfo.args.length + 1)) {
// Throw an error if an invalid number of arguments were found.
errStr = 'Invalid number of arguments. Should be: ';
errStr += functionInfo.args.length.toString() + '. ';
errStr += getFunctionArgNames(functionInfo).join(', ');
errStr += '.';
throw new LJMFFIError(errStr);
} else {
if(typeof(arguments[functionInfo.args.length]) !== 'function') {
// Throw an error if the last argument is not a function. This
// is mandatory for all async function calls.
errStr = 'Invalid argument; last argument must be a function ';
errStr += 'but was not. Function name: \'';
errStr += functionName;
errStr += '\'.';
throw new LJMFFIError(errStr);
}
// Get a reference to the LJM function being called.
var ljmFunction = ffi_liblabjack[functionName].async;
// Check to make sure that the function being called has been
// defined.
if(typeof(ljmFunction) === 'function') {
// Define a variable to store the ljmError value in.
var ljmError;
try {
// Execute the synchronous LJM function.
ljmError = ljmFunction.apply(this, arguments);
} catch(err) {
// Throw an error if the function being called doesn't exist.
errStr = 'The function: ';
errStr += functionName;
errStr += ' is not implemented by the installed version of LJM.';
throw new LJMFFIError(errStr);
}
// Return the ljmError
return ljmError;
} else {
// Throw an error if the function being called doesn't exist.
errStr = 'The function: ';
errStr += functionName;
errStr += ' is not implemented by the installed version of LJM.';
throw new LJMFFIError(errStr);
}
}
};
} | javascript | function createSafeAsyncFunction(functionName, functionInfo) {
return function safeAsyncFunction() {
// Define a variable to store the error string in.
var errStr;
// Check to make sure the arguments seem to be valid.
if(arguments.length != (functionInfo.args.length + 1)) {
// Throw an error if an invalid number of arguments were found.
errStr = 'Invalid number of arguments. Should be: ';
errStr += functionInfo.args.length.toString() + '. ';
errStr += getFunctionArgNames(functionInfo).join(', ');
errStr += '.';
throw new LJMFFIError(errStr);
} else {
if(typeof(arguments[functionInfo.args.length]) !== 'function') {
// Throw an error if the last argument is not a function. This
// is mandatory for all async function calls.
errStr = 'Invalid argument; last argument must be a function ';
errStr += 'but was not. Function name: \'';
errStr += functionName;
errStr += '\'.';
throw new LJMFFIError(errStr);
}
// Get a reference to the LJM function being called.
var ljmFunction = ffi_liblabjack[functionName].async;
// Check to make sure that the function being called has been
// defined.
if(typeof(ljmFunction) === 'function') {
// Define a variable to store the ljmError value in.
var ljmError;
try {
// Execute the synchronous LJM function.
ljmError = ljmFunction.apply(this, arguments);
} catch(err) {
// Throw an error if the function being called doesn't exist.
errStr = 'The function: ';
errStr += functionName;
errStr += ' is not implemented by the installed version of LJM.';
throw new LJMFFIError(errStr);
}
// Return the ljmError
return ljmError;
} else {
// Throw an error if the function being called doesn't exist.
errStr = 'The function: ';
errStr += functionName;
errStr += ' is not implemented by the installed version of LJM.';
throw new LJMFFIError(errStr);
}
}
};
} | [
"function",
"createSafeAsyncFunction",
"(",
"functionName",
",",
"functionInfo",
")",
"{",
"return",
"function",
"safeAsyncFunction",
"(",
")",
"{",
"// Define a variable to store the error string in.",
"var",
"errStr",
";",
"// Check to make sure the arguments seem to be valid.",
"if",
"(",
"arguments",
".",
"length",
"!=",
"(",
"functionInfo",
".",
"args",
".",
"length",
"+",
"1",
")",
")",
"{",
"// Throw an error if an invalid number of arguments were found.",
"errStr",
"=",
"'Invalid number of arguments. Should be: '",
";",
"errStr",
"+=",
"functionInfo",
".",
"args",
".",
"length",
".",
"toString",
"(",
")",
"+",
"'. '",
";",
"errStr",
"+=",
"getFunctionArgNames",
"(",
"functionInfo",
")",
".",
"join",
"(",
"', '",
")",
";",
"errStr",
"+=",
"'.'",
";",
"throw",
"new",
"LJMFFIError",
"(",
"errStr",
")",
";",
"}",
"else",
"{",
"if",
"(",
"typeof",
"(",
"arguments",
"[",
"functionInfo",
".",
"args",
".",
"length",
"]",
")",
"!==",
"'function'",
")",
"{",
"// Throw an error if the last argument is not a function. This",
"// is mandatory for all async function calls.",
"errStr",
"=",
"'Invalid argument; last argument must be a function '",
";",
"errStr",
"+=",
"'but was not. Function name: \\''",
";",
"errStr",
"+=",
"functionName",
";",
"errStr",
"+=",
"'\\'.'",
";",
"throw",
"new",
"LJMFFIError",
"(",
"errStr",
")",
";",
"}",
"// Get a reference to the LJM function being called.",
"var",
"ljmFunction",
"=",
"ffi_liblabjack",
"[",
"functionName",
"]",
".",
"async",
";",
"// Check to make sure that the function being called has been",
"// defined.",
"if",
"(",
"typeof",
"(",
"ljmFunction",
")",
"===",
"'function'",
")",
"{",
"// Define a variable to store the ljmError value in.",
"var",
"ljmError",
";",
"try",
"{",
"// Execute the synchronous LJM function.",
"ljmError",
"=",
"ljmFunction",
".",
"apply",
"(",
"this",
",",
"arguments",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"// Throw an error if the function being called doesn't exist.",
"errStr",
"=",
"'The function: '",
";",
"errStr",
"+=",
"functionName",
";",
"errStr",
"+=",
"' is not implemented by the installed version of LJM.'",
";",
"throw",
"new",
"LJMFFIError",
"(",
"errStr",
")",
";",
"}",
"// Return the ljmError",
"return",
"ljmError",
";",
"}",
"else",
"{",
"// Throw an error if the function being called doesn't exist.",
"errStr",
"=",
"'The function: '",
";",
"errStr",
"+=",
"functionName",
";",
"errStr",
"+=",
"' is not implemented by the installed version of LJM.'",
";",
"throw",
"new",
"LJMFFIError",
"(",
"errStr",
")",
";",
"}",
"}",
"}",
";",
"}"
] | Define a function that creates safe LJM ffi calls. | [
"Define",
"a",
"function",
"that",
"creates",
"safe",
"LJM",
"ffi",
"calls",
"."
] | 5f2bb940988f1cedb4182180a891ac8973f07a3d | https://github.com/chrisJohn404/ljm-ffi/blob/5f2bb940988f1cedb4182180a891ac8973f07a3d/lib/ljm-ffi.js#L883-L938 |
48,034 | fczbkk/the-box | src/utilities/get-boxes-around.js | makeUnique | function makeUnique (boxes = []) {
// boxes converted to string, for easier comparison
const ref = [];
const result = [];
boxes.forEach((item) => {
const item_string = item.toString();
if (ref.indexOf(item_string) === -1) {
ref.push(item_string);
result.push(item);
}
});
return result;
} | javascript | function makeUnique (boxes = []) {
// boxes converted to string, for easier comparison
const ref = [];
const result = [];
boxes.forEach((item) => {
const item_string = item.toString();
if (ref.indexOf(item_string) === -1) {
ref.push(item_string);
result.push(item);
}
});
return result;
} | [
"function",
"makeUnique",
"(",
"boxes",
"=",
"[",
"]",
")",
"{",
"// boxes converted to string, for easier comparison",
"const",
"ref",
"=",
"[",
"]",
";",
"const",
"result",
"=",
"[",
"]",
";",
"boxes",
".",
"forEach",
"(",
"(",
"item",
")",
"=>",
"{",
"const",
"item_string",
"=",
"item",
".",
"toString",
"(",
")",
";",
"if",
"(",
"ref",
".",
"indexOf",
"(",
"item_string",
")",
"===",
"-",
"1",
")",
"{",
"ref",
".",
"push",
"(",
"item_string",
")",
";",
"result",
".",
"push",
"(",
"item",
")",
";",
"}",
"}",
")",
";",
"return",
"result",
";",
"}"
] | Accepts list of Boxes, returns list of unique Boxes.
@param {Array.<Box>} [boxes=[]]
@returns {Array.<Box>}
@ignore | [
"Accepts",
"list",
"of",
"Boxes",
"returns",
"list",
"of",
"unique",
"Boxes",
"."
] | 337efc6bd00f92565dac8abffeb271b03caae2ba | https://github.com/fczbkk/the-box/blob/337efc6bd00f92565dac8abffeb271b03caae2ba/src/utilities/get-boxes-around.js#L69-L83 |
48,035 | henrytseng/angular-state-loadable | src/services/loadable-manager.js | function(src) {
var _deferred = $q.defer();
// Instance
var _loadable = {
src: src,
// Loading completion flag
isComplete: false,
promise: _deferred.promise,
// TODO switch to $document
$element: document.createElement('script')
};
// Build DOM element
_loadable.$element.src = src;
_loadable.$element.type = 'text/javascript';
_loadable.$element.async = false;
_head.insertBefore(_loadable.$element, _head.firstChild);
// Mark loading in progress
_loadingList.push(_loadable);
// Completion
_loadable.$element.onload = _loadable.$element.onreadystatechange = function() {
if(!_loadable.isComplete && (!this.readyState || this.readyState === "loaded" || this.readyState === "complete")) {
_loadable.isComplete = true;
_loadable.$element.onload = _loadable.$element.onreadystatechange = null;
if(_head && _loadable.$element.parentNode) {
_head.removeChild(_loadable.$element);
}
// Mark complete
var i = _loadingList.indexOf(_loadable);
if(i !== -1) {
_loadingList.splice(i, 1);
}
_completedList.push(_loadable);
_deferred.resolve(_loadable);
}
};
return _loadable;
} | javascript | function(src) {
var _deferred = $q.defer();
// Instance
var _loadable = {
src: src,
// Loading completion flag
isComplete: false,
promise: _deferred.promise,
// TODO switch to $document
$element: document.createElement('script')
};
// Build DOM element
_loadable.$element.src = src;
_loadable.$element.type = 'text/javascript';
_loadable.$element.async = false;
_head.insertBefore(_loadable.$element, _head.firstChild);
// Mark loading in progress
_loadingList.push(_loadable);
// Completion
_loadable.$element.onload = _loadable.$element.onreadystatechange = function() {
if(!_loadable.isComplete && (!this.readyState || this.readyState === "loaded" || this.readyState === "complete")) {
_loadable.isComplete = true;
_loadable.$element.onload = _loadable.$element.onreadystatechange = null;
if(_head && _loadable.$element.parentNode) {
_head.removeChild(_loadable.$element);
}
// Mark complete
var i = _loadingList.indexOf(_loadable);
if(i !== -1) {
_loadingList.splice(i, 1);
}
_completedList.push(_loadable);
_deferred.resolve(_loadable);
}
};
return _loadable;
} | [
"function",
"(",
"src",
")",
"{",
"var",
"_deferred",
"=",
"$q",
".",
"defer",
"(",
")",
";",
"// Instance",
"var",
"_loadable",
"=",
"{",
"src",
":",
"src",
",",
"// Loading completion flag",
"isComplete",
":",
"false",
",",
"promise",
":",
"_deferred",
".",
"promise",
",",
"// TODO switch to $document",
"$element",
":",
"document",
".",
"createElement",
"(",
"'script'",
")",
"}",
";",
"// Build DOM element",
"_loadable",
".",
"$element",
".",
"src",
"=",
"src",
";",
"_loadable",
".",
"$element",
".",
"type",
"=",
"'text/javascript'",
";",
"_loadable",
".",
"$element",
".",
"async",
"=",
"false",
";",
"_head",
".",
"insertBefore",
"(",
"_loadable",
".",
"$element",
",",
"_head",
".",
"firstChild",
")",
";",
"// Mark loading in progress",
"_loadingList",
".",
"push",
"(",
"_loadable",
")",
";",
"// Completion",
"_loadable",
".",
"$element",
".",
"onload",
"=",
"_loadable",
".",
"$element",
".",
"onreadystatechange",
"=",
"function",
"(",
")",
"{",
"if",
"(",
"!",
"_loadable",
".",
"isComplete",
"&&",
"(",
"!",
"this",
".",
"readyState",
"||",
"this",
".",
"readyState",
"===",
"\"loaded\"",
"||",
"this",
".",
"readyState",
"===",
"\"complete\"",
")",
")",
"{",
"_loadable",
".",
"isComplete",
"=",
"true",
";",
"_loadable",
".",
"$element",
".",
"onload",
"=",
"_loadable",
".",
"$element",
".",
"onreadystatechange",
"=",
"null",
";",
"if",
"(",
"_head",
"&&",
"_loadable",
".",
"$element",
".",
"parentNode",
")",
"{",
"_head",
".",
"removeChild",
"(",
"_loadable",
".",
"$element",
")",
";",
"}",
"// Mark complete",
"var",
"i",
"=",
"_loadingList",
".",
"indexOf",
"(",
"_loadable",
")",
";",
"if",
"(",
"i",
"!==",
"-",
"1",
")",
"{",
"_loadingList",
".",
"splice",
"(",
"i",
",",
"1",
")",
";",
"}",
"_completedList",
".",
"push",
"(",
"_loadable",
")",
";",
"_deferred",
".",
"resolve",
"(",
"_loadable",
")",
";",
"}",
"}",
";",
"return",
"_loadable",
";",
"}"
] | A loaded resource, adds self to DOM, self manage progress
@return {_Loadable} An instance | [
"A",
"loaded",
"resource",
"adds",
"self",
"to",
"DOM",
"self",
"manage",
"progress"
] | dd905296935ef62b468f1b151ade2652635e8f9f | https://github.com/henrytseng/angular-state-loadable/blob/dd905296935ef62b468f1b151ade2652635e8f9f/src/services/loadable-manager.js#L25-L75 |
|
48,036 | henrytseng/angular-state-loadable | src/services/loadable-manager.js | function(src) {
var loadable;
// Valid state name required
if(!src || src === '') {
var error;
error = new Error('Loadable requires a valid source.');
error.code = 'invalidname';
throw error;
}
// Already exists
if(_loadableHash[src]) {
loadable = _loadableHash[src];
// Create new
} else {
// Create new instance
loadable = new _Loadable(src);
_loadableHash[src] = loadable;
// Broadcast creation, progress
$rootScope.$broadcast('$loadableCreated', loadable);
$rootScope.$broadcast('$loadableProgress', _getProgress());
// Completion
loadable.promise.then(function() {
// Broadcast complete
$rootScope.$broadcast('$loadableProgress', _getProgress());
if(_loadingList.length === 0) {
$rootScope.$broadcast('$loadableComplete', loadable);
}
});
}
return loadable;
} | javascript | function(src) {
var loadable;
// Valid state name required
if(!src || src === '') {
var error;
error = new Error('Loadable requires a valid source.');
error.code = 'invalidname';
throw error;
}
// Already exists
if(_loadableHash[src]) {
loadable = _loadableHash[src];
// Create new
} else {
// Create new instance
loadable = new _Loadable(src);
_loadableHash[src] = loadable;
// Broadcast creation, progress
$rootScope.$broadcast('$loadableCreated', loadable);
$rootScope.$broadcast('$loadableProgress', _getProgress());
// Completion
loadable.promise.then(function() {
// Broadcast complete
$rootScope.$broadcast('$loadableProgress', _getProgress());
if(_loadingList.length === 0) {
$rootScope.$broadcast('$loadableComplete', loadable);
}
});
}
return loadable;
} | [
"function",
"(",
"src",
")",
"{",
"var",
"loadable",
";",
"// Valid state name required",
"if",
"(",
"!",
"src",
"||",
"src",
"===",
"''",
")",
"{",
"var",
"error",
";",
"error",
"=",
"new",
"Error",
"(",
"'Loadable requires a valid source.'",
")",
";",
"error",
".",
"code",
"=",
"'invalidname'",
";",
"throw",
"error",
";",
"}",
"// Already exists",
"if",
"(",
"_loadableHash",
"[",
"src",
"]",
")",
"{",
"loadable",
"=",
"_loadableHash",
"[",
"src",
"]",
";",
"// Create new",
"}",
"else",
"{",
"// Create new instance",
"loadable",
"=",
"new",
"_Loadable",
"(",
"src",
")",
";",
"_loadableHash",
"[",
"src",
"]",
"=",
"loadable",
";",
"// Broadcast creation, progress",
"$rootScope",
".",
"$broadcast",
"(",
"'$loadableCreated'",
",",
"loadable",
")",
";",
"$rootScope",
".",
"$broadcast",
"(",
"'$loadableProgress'",
",",
"_getProgress",
"(",
")",
")",
";",
"// Completion",
"loadable",
".",
"promise",
".",
"then",
"(",
"function",
"(",
")",
"{",
"// Broadcast complete",
"$rootScope",
".",
"$broadcast",
"(",
"'$loadableProgress'",
",",
"_getProgress",
"(",
")",
")",
";",
"if",
"(",
"_loadingList",
".",
"length",
"===",
"0",
")",
"{",
"$rootScope",
".",
"$broadcast",
"(",
"'$loadableComplete'",
",",
"loadable",
")",
";",
"}",
"}",
")",
";",
"}",
"return",
"loadable",
";",
"}"
] | Create a _Loadable. Does not replace previously created instances.
@param {String} src A source path for script asset
@return {_Loadable} A loadable instance | [
"Create",
"a",
"_Loadable",
".",
"Does",
"not",
"replace",
"previously",
"created",
"instances",
"."
] | dd905296935ef62b468f1b151ade2652635e8f9f | https://github.com/henrytseng/angular-state-loadable/blob/dd905296935ef62b468f1b151ade2652635e8f9f/src/services/loadable-manager.js#L94-L131 |
|
48,037 | henrytseng/angular-state-loadable | src/services/loadable-manager.js | function() {
var deferred = $q.defer();
var current = $state.current();
// Evaluate
if(current) {
var sources = (typeof current.load === 'string' ? [current.load] : current.load) || [];
// Get promises
$q.all(sources
.map(function(src) {
return _createLoadable(src);
})
.filter(function(loadable) {
return !loadable.isComplete;
})
.map(function(loadable) {
return loadable.promise;
})
)
.then(function() {
deferred.resolve();
}, function(err) {
$rootScope.$broadcast('$loadableError', err);
deferred.reject(err);
});
// No state
} else {
deferred.resolve();
}
return deferred.promise;
} | javascript | function() {
var deferred = $q.defer();
var current = $state.current();
// Evaluate
if(current) {
var sources = (typeof current.load === 'string' ? [current.load] : current.load) || [];
// Get promises
$q.all(sources
.map(function(src) {
return _createLoadable(src);
})
.filter(function(loadable) {
return !loadable.isComplete;
})
.map(function(loadable) {
return loadable.promise;
})
)
.then(function() {
deferred.resolve();
}, function(err) {
$rootScope.$broadcast('$loadableError', err);
deferred.reject(err);
});
// No state
} else {
deferred.resolve();
}
return deferred.promise;
} | [
"function",
"(",
")",
"{",
"var",
"deferred",
"=",
"$q",
".",
"defer",
"(",
")",
";",
"var",
"current",
"=",
"$state",
".",
"current",
"(",
")",
";",
"// Evaluate",
"if",
"(",
"current",
")",
"{",
"var",
"sources",
"=",
"(",
"typeof",
"current",
".",
"load",
"===",
"'string'",
"?",
"[",
"current",
".",
"load",
"]",
":",
"current",
".",
"load",
")",
"||",
"[",
"]",
";",
"// Get promises",
"$q",
".",
"all",
"(",
"sources",
".",
"map",
"(",
"function",
"(",
"src",
")",
"{",
"return",
"_createLoadable",
"(",
"src",
")",
";",
"}",
")",
".",
"filter",
"(",
"function",
"(",
"loadable",
")",
"{",
"return",
"!",
"loadable",
".",
"isComplete",
";",
"}",
")",
".",
"map",
"(",
"function",
"(",
"loadable",
")",
"{",
"return",
"loadable",
".",
"promise",
";",
"}",
")",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"deferred",
".",
"resolve",
"(",
")",
";",
"}",
",",
"function",
"(",
"err",
")",
"{",
"$rootScope",
".",
"$broadcast",
"(",
"'$loadableError'",
",",
"err",
")",
";",
"deferred",
".",
"reject",
"(",
"err",
")",
";",
"}",
")",
";",
"// No state",
"}",
"else",
"{",
"deferred",
".",
"resolve",
"(",
")",
";",
"}",
"return",
"deferred",
".",
"promise",
";",
"}"
] | Load all required items
@return {Promise} A promise fulfilled when the resources are loaded | [
"Load",
"all",
"required",
"items"
] | dd905296935ef62b468f1b151ade2652635e8f9f | https://github.com/henrytseng/angular-state-loadable/blob/dd905296935ef62b468f1b151ade2652635e8f9f/src/services/loadable-manager.js#L138-L173 |
|
48,038 | nicktindall/cyclon.p2p-rtc-client | lib/SocketIOSignallingService.js | postToFirstAvailableServer | function postToFirstAvailableServer (destinationNode, signallingServers, path, message) {
return new Promise(function (resolve, reject) {
if (signallingServers.length === 0) {
reject(new Utils.UnreachableError(createUnreachableErrorMessage(destinationNode)));
}
else {
//noinspection JSCheckFunctionSignatures
httpRequestService.post(url.resolve(signallingServers[0].signallingApiBase, path), message)
.then(resolve)
.catch(function (error) {
logger.warn("An error occurred sending signalling message using " + signallingServers[0].signallingApiBase + " trying next signalling server", error);
postToFirstAvailableServer(destinationNode, signallingServers.slice(1), path, message).then(resolve, reject);
});
}
});
} | javascript | function postToFirstAvailableServer (destinationNode, signallingServers, path, message) {
return new Promise(function (resolve, reject) {
if (signallingServers.length === 0) {
reject(new Utils.UnreachableError(createUnreachableErrorMessage(destinationNode)));
}
else {
//noinspection JSCheckFunctionSignatures
httpRequestService.post(url.resolve(signallingServers[0].signallingApiBase, path), message)
.then(resolve)
.catch(function (error) {
logger.warn("An error occurred sending signalling message using " + signallingServers[0].signallingApiBase + " trying next signalling server", error);
postToFirstAvailableServer(destinationNode, signallingServers.slice(1), path, message).then(resolve, reject);
});
}
});
} | [
"function",
"postToFirstAvailableServer",
"(",
"destinationNode",
",",
"signallingServers",
",",
"path",
",",
"message",
")",
"{",
"return",
"new",
"Promise",
"(",
"function",
"(",
"resolve",
",",
"reject",
")",
"{",
"if",
"(",
"signallingServers",
".",
"length",
"===",
"0",
")",
"{",
"reject",
"(",
"new",
"Utils",
".",
"UnreachableError",
"(",
"createUnreachableErrorMessage",
"(",
"destinationNode",
")",
")",
")",
";",
"}",
"else",
"{",
"//noinspection JSCheckFunctionSignatures",
"httpRequestService",
".",
"post",
"(",
"url",
".",
"resolve",
"(",
"signallingServers",
"[",
"0",
"]",
".",
"signallingApiBase",
",",
"path",
")",
",",
"message",
")",
".",
"then",
"(",
"resolve",
")",
".",
"catch",
"(",
"function",
"(",
"error",
")",
"{",
"logger",
".",
"warn",
"(",
"\"An error occurred sending signalling message using \"",
"+",
"signallingServers",
"[",
"0",
"]",
".",
"signallingApiBase",
"+",
"\" trying next signalling server\"",
",",
"error",
")",
";",
"postToFirstAvailableServer",
"(",
"destinationNode",
",",
"signallingServers",
".",
"slice",
"(",
"1",
")",
",",
"path",
",",
"message",
")",
".",
"then",
"(",
"resolve",
",",
"reject",
")",
";",
"}",
")",
";",
"}",
"}",
")",
";",
"}"
] | Post an object to the first available signalling server
@param destinationNode
@param signallingServers
@param path
@param message
@returns {Promise} | [
"Post",
"an",
"object",
"to",
"the",
"first",
"available",
"signalling",
"server"
] | eb586ce288a6ad7e1b221280825037e855b03904 | https://github.com/nicktindall/cyclon.p2p-rtc-client/blob/eb586ce288a6ad7e1b221280825037e855b03904/lib/SocketIOSignallingService.js#L184-L200 |
48,039 | jhermsmeier/node-scuid | lib/scuid.js | pad | function pad( str, chr, n ) {
return (chr.repeat( Math.max( n - str.length, 0 ) ) + str).substr(-n)
} | javascript | function pad( str, chr, n ) {
return (chr.repeat( Math.max( n - str.length, 0 ) ) + str).substr(-n)
} | [
"function",
"pad",
"(",
"str",
",",
"chr",
",",
"n",
")",
"{",
"return",
"(",
"chr",
".",
"repeat",
"(",
"Math",
".",
"max",
"(",
"n",
"-",
"str",
".",
"length",
",",
"0",
")",
")",
"+",
"str",
")",
".",
"substr",
"(",
"-",
"n",
")",
"}"
] | Pad a string to length `n` with `chr`
@param {String} str
@param {String} chr
@param {Number} n
@return {String} | [
"Pad",
"a",
"string",
"to",
"length",
"n",
"with",
"chr"
] | 84e96962ff5eaae2ab2bcc2a9fae615e15204695 | https://github.com/jhermsmeier/node-scuid/blob/84e96962ff5eaae2ab2bcc2a9fae615e15204695/lib/scuid.js#L10-L12 |
48,040 | jhermsmeier/node-scuid | lib/scuid.js | function() {
var block = this.rng.random() * this.discreteValues << 0
return pad( block.toString( this.base ), this.fill, this.blockSize )
} | javascript | function() {
var block = this.rng.random() * this.discreteValues << 0
return pad( block.toString( this.base ), this.fill, this.blockSize )
} | [
"function",
"(",
")",
"{",
"var",
"block",
"=",
"this",
".",
"rng",
".",
"random",
"(",
")",
"*",
"this",
".",
"discreteValues",
"<<",
"0",
"return",
"pad",
"(",
"block",
".",
"toString",
"(",
"this",
".",
"base",
")",
",",
"this",
".",
"fill",
",",
"this",
".",
"blockSize",
")",
"}"
] | Generate a block of `blockSize` random characters
@return {String} | [
"Generate",
"a",
"block",
"of",
"blockSize",
"random",
"characters"
] | 84e96962ff5eaae2ab2bcc2a9fae615e15204695 | https://github.com/jhermsmeier/node-scuid/blob/84e96962ff5eaae2ab2bcc2a9fae615e15204695/lib/scuid.js#L127-L130 |
|
48,041 | jhermsmeier/node-scuid | lib/scuid.js | function() {
return this.timestamp().substr( -2 ) +
this.count().toString( this.base ).substr( -4 ) +
this._fingerprint[0] +
this._fingerprint[ this._fingerprint.length - 1 ] +
this.randomBlock().substr( -2 )
} | javascript | function() {
return this.timestamp().substr( -2 ) +
this.count().toString( this.base ).substr( -4 ) +
this._fingerprint[0] +
this._fingerprint[ this._fingerprint.length - 1 ] +
this.randomBlock().substr( -2 )
} | [
"function",
"(",
")",
"{",
"return",
"this",
".",
"timestamp",
"(",
")",
".",
"substr",
"(",
"-",
"2",
")",
"+",
"this",
".",
"count",
"(",
")",
".",
"toString",
"(",
"this",
".",
"base",
")",
".",
"substr",
"(",
"-",
"4",
")",
"+",
"this",
".",
"_fingerprint",
"[",
"0",
"]",
"+",
"this",
".",
"_fingerprint",
"[",
"this",
".",
"_fingerprint",
".",
"length",
"-",
"1",
"]",
"+",
"this",
".",
"randomBlock",
"(",
")",
".",
"substr",
"(",
"-",
"2",
")",
"}"
] | Generate a slug
@return {String} slug | [
"Generate",
"a",
"slug"
] | 84e96962ff5eaae2ab2bcc2a9fae615e15204695 | https://github.com/jhermsmeier/node-scuid/blob/84e96962ff5eaae2ab2bcc2a9fae615e15204695/lib/scuid.js#L162-L168 |
|
48,042 | oliverwoodings/pkgify | lib/pkgify.js | findPackage | function findPackage(config, match) {
var map = getPackageMap(config.relativeTo, config.packages);
return _.reduce(map, function (prev, pkg) {
// Resolve using last priority. Priority:
// 1. package is a file
// 2. package granularity (done by file depth)
if (pkg.regexp.test(match) && (!prev || (pkg.dir && prev.dir && pkg.depth >= pkg.depth) || pkg.file)) {
return pkg;
} else {
return prev;
}
}, null);
} | javascript | function findPackage(config, match) {
var map = getPackageMap(config.relativeTo, config.packages);
return _.reduce(map, function (prev, pkg) {
// Resolve using last priority. Priority:
// 1. package is a file
// 2. package granularity (done by file depth)
if (pkg.regexp.test(match) && (!prev || (pkg.dir && prev.dir && pkg.depth >= pkg.depth) || pkg.file)) {
return pkg;
} else {
return prev;
}
}, null);
} | [
"function",
"findPackage",
"(",
"config",
",",
"match",
")",
"{",
"var",
"map",
"=",
"getPackageMap",
"(",
"config",
".",
"relativeTo",
",",
"config",
".",
"packages",
")",
";",
"return",
"_",
".",
"reduce",
"(",
"map",
",",
"function",
"(",
"prev",
",",
"pkg",
")",
"{",
"// Resolve using last priority. Priority:",
"// 1. package is a file",
"// 2. package granularity (done by file depth)",
"if",
"(",
"pkg",
".",
"regexp",
".",
"test",
"(",
"match",
")",
"&&",
"(",
"!",
"prev",
"||",
"(",
"pkg",
".",
"dir",
"&&",
"prev",
".",
"dir",
"&&",
"pkg",
".",
"depth",
">=",
"pkg",
".",
"depth",
")",
"||",
"pkg",
".",
"file",
")",
")",
"{",
"return",
"pkg",
";",
"}",
"else",
"{",
"return",
"prev",
";",
"}",
"}",
",",
"null",
")",
";",
"}"
] | Try and find a package for the match | [
"Try",
"and",
"find",
"a",
"package",
"for",
"the",
"match"
] | 838d1858fc633f9cd99e91ec5902be50ec7089f0 | https://github.com/oliverwoodings/pkgify/blob/838d1858fc633f9cd99e91ec5902be50ec7089f0/lib/pkgify.js#L32-L47 |
48,043 | neoziro/angular-match | angular-match.js | matchDirective | function matchDirective($parse) {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attrs, ctrl) {
scope.$watch(function () {
return [scope.$eval(attrs.match), ctrl.$viewValue];
}, function (values) {
ctrl.$setValidity('match', values[0] === values[1]);
}, true);
}
};
} | javascript | function matchDirective($parse) {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attrs, ctrl) {
scope.$watch(function () {
return [scope.$eval(attrs.match), ctrl.$viewValue];
}, function (values) {
ctrl.$setValidity('match', values[0] === values[1]);
}, true);
}
};
} | [
"function",
"matchDirective",
"(",
"$parse",
")",
"{",
"return",
"{",
"restrict",
":",
"'A'",
",",
"require",
":",
"'ngModel'",
",",
"link",
":",
"function",
"(",
"scope",
",",
"element",
",",
"attrs",
",",
"ctrl",
")",
"{",
"scope",
".",
"$watch",
"(",
"function",
"(",
")",
"{",
"return",
"[",
"scope",
".",
"$eval",
"(",
"attrs",
".",
"match",
")",
",",
"ctrl",
".",
"$viewValue",
"]",
";",
"}",
",",
"function",
"(",
"values",
")",
"{",
"ctrl",
".",
"$setValidity",
"(",
"'match'",
",",
"values",
"[",
"0",
"]",
"===",
"values",
"[",
"1",
"]",
")",
";",
"}",
",",
"true",
")",
";",
"}",
"}",
";",
"}"
] | Match directive.
@example
<input type="password" ng-match="password"> | [
"Match",
"directive",
"."
] | e77ca02b7ca8dcccec7a6d7e471e3dc11f15978c | https://github.com/neoziro/angular-match/blob/e77ca02b7ca8dcccec7a6d7e471e3dc11f15978c/angular-match.js#L14-L26 |
48,044 | pauldenotter/nautical | lib/base.js | Base | function Base(client, endpoint) {
var base = this;
/**
* Get a list of all records for the current API
*
* @method list
* @param {Object} query - OPTIONAL querystring params
* @param {Function} callback
*/
base.list = function() {
return function(query, callback) {
var q = '';
if (query && 'function' === typeof callback)
q = '?' + querystring.stringify(query);
client.exec({
path: '/' + endpoint + q
}, arguments[arguments.length - 1]);
};
};
/**
* Get a single record by its key
*
* @method fetch
* @param {Integer|String} key
* @param {Function} callback
*/
base.fetch = function() {
return function(key, callback) {
client.exec({
path: '/' + endpoint + '/' + key
}, callback);
};
};
/**
* Create a new record
*
* @method create
* @param {Object|String} data
* @param {Function} callback
*/
base.create = function() {
return function(data, callback) {
client.exec({
method: 'POST',
path: '/' + endpoint,
body: data
}, callback);
};
};
/**
* Update a record
*
* @method update
* @param {Integer|String} key
* @param {Object|String} data
* @param {Function} callback
*/
base.update = function() {
return function(key, data, callback) {
client.exec({
method: 'PUT',
path: '/' + endpoint + '/' + key,
body: data
}, callback);
};
};
/**
* Remove a record
*
* @method remove
* @param {Integer|String} key
* @param {Function} callback
*/
base.remove = function() {
return function(key, callback) {
client.exec({
method: 'DELETE',
path: '/' + endpoint + '/' + key
}, callback);
};
};
/**
* Do requested action
*
* @method doAction
* @param {Integer|String} key
* @param {String} action
* @param {Object} body
* @param {Function} callback
*/
base.doAction = function() {
return function(key, action, body, callback) {
body = body || {};
body.type = action;
client.exec({
method: 'POST',
path: '/' + endpoint + '/' + key + '/actions',
body: body
}, callback);
};
};
} | javascript | function Base(client, endpoint) {
var base = this;
/**
* Get a list of all records for the current API
*
* @method list
* @param {Object} query - OPTIONAL querystring params
* @param {Function} callback
*/
base.list = function() {
return function(query, callback) {
var q = '';
if (query && 'function' === typeof callback)
q = '?' + querystring.stringify(query);
client.exec({
path: '/' + endpoint + q
}, arguments[arguments.length - 1]);
};
};
/**
* Get a single record by its key
*
* @method fetch
* @param {Integer|String} key
* @param {Function} callback
*/
base.fetch = function() {
return function(key, callback) {
client.exec({
path: '/' + endpoint + '/' + key
}, callback);
};
};
/**
* Create a new record
*
* @method create
* @param {Object|String} data
* @param {Function} callback
*/
base.create = function() {
return function(data, callback) {
client.exec({
method: 'POST',
path: '/' + endpoint,
body: data
}, callback);
};
};
/**
* Update a record
*
* @method update
* @param {Integer|String} key
* @param {Object|String} data
* @param {Function} callback
*/
base.update = function() {
return function(key, data, callback) {
client.exec({
method: 'PUT',
path: '/' + endpoint + '/' + key,
body: data
}, callback);
};
};
/**
* Remove a record
*
* @method remove
* @param {Integer|String} key
* @param {Function} callback
*/
base.remove = function() {
return function(key, callback) {
client.exec({
method: 'DELETE',
path: '/' + endpoint + '/' + key
}, callback);
};
};
/**
* Do requested action
*
* @method doAction
* @param {Integer|String} key
* @param {String} action
* @param {Object} body
* @param {Function} callback
*/
base.doAction = function() {
return function(key, action, body, callback) {
body = body || {};
body.type = action;
client.exec({
method: 'POST',
path: '/' + endpoint + '/' + key + '/actions',
body: body
}, callback);
};
};
} | [
"function",
"Base",
"(",
"client",
",",
"endpoint",
")",
"{",
"var",
"base",
"=",
"this",
";",
"/**\n\t * Get a list of all records for the current API\n\t *\n\t * @method list\n\t * @param {Object} query - OPTIONAL querystring params\n\t * @param {Function} callback\n\t */",
"base",
".",
"list",
"=",
"function",
"(",
")",
"{",
"return",
"function",
"(",
"query",
",",
"callback",
")",
"{",
"var",
"q",
"=",
"''",
";",
"if",
"(",
"query",
"&&",
"'function'",
"===",
"typeof",
"callback",
")",
"q",
"=",
"'?'",
"+",
"querystring",
".",
"stringify",
"(",
"query",
")",
";",
"client",
".",
"exec",
"(",
"{",
"path",
":",
"'/'",
"+",
"endpoint",
"+",
"q",
"}",
",",
"arguments",
"[",
"arguments",
".",
"length",
"-",
"1",
"]",
")",
";",
"}",
";",
"}",
";",
"/**\n\t * Get a single record by its key\n\t *\n\t * @method fetch\n\t * @param {Integer|String} key\n\t * @param {Function} callback\n\t */",
"base",
".",
"fetch",
"=",
"function",
"(",
")",
"{",
"return",
"function",
"(",
"key",
",",
"callback",
")",
"{",
"client",
".",
"exec",
"(",
"{",
"path",
":",
"'/'",
"+",
"endpoint",
"+",
"'/'",
"+",
"key",
"}",
",",
"callback",
")",
";",
"}",
";",
"}",
";",
"/**\n\t * Create a new record\n\t *\n\t * @method create\n\t * @param {Object|String} data\n\t * @param {Function} callback\n\t */",
"base",
".",
"create",
"=",
"function",
"(",
")",
"{",
"return",
"function",
"(",
"data",
",",
"callback",
")",
"{",
"client",
".",
"exec",
"(",
"{",
"method",
":",
"'POST'",
",",
"path",
":",
"'/'",
"+",
"endpoint",
",",
"body",
":",
"data",
"}",
",",
"callback",
")",
";",
"}",
";",
"}",
";",
"/**\n\t * Update a record\n\t *\n\t * @method update\n\t * @param {Integer|String} key\n\t * @param {Object|String} data\n\t * @param {Function} callback\n\t */",
"base",
".",
"update",
"=",
"function",
"(",
")",
"{",
"return",
"function",
"(",
"key",
",",
"data",
",",
"callback",
")",
"{",
"client",
".",
"exec",
"(",
"{",
"method",
":",
"'PUT'",
",",
"path",
":",
"'/'",
"+",
"endpoint",
"+",
"'/'",
"+",
"key",
",",
"body",
":",
"data",
"}",
",",
"callback",
")",
";",
"}",
";",
"}",
";",
"/**\n\t * Remove a record\n\t *\n\t * @method remove\n\t * @param {Integer|String} key\n\t * @param {Function} callback\n\t */",
"base",
".",
"remove",
"=",
"function",
"(",
")",
"{",
"return",
"function",
"(",
"key",
",",
"callback",
")",
"{",
"client",
".",
"exec",
"(",
"{",
"method",
":",
"'DELETE'",
",",
"path",
":",
"'/'",
"+",
"endpoint",
"+",
"'/'",
"+",
"key",
"}",
",",
"callback",
")",
";",
"}",
";",
"}",
";",
"/**\n\t * Do requested action\n\t *\n\t * @method doAction\n\t * @param {Integer|String} key\n\t * @param {String} action\n\t * @param {Object} body\n\t * @param {Function} callback\n\t */",
"base",
".",
"doAction",
"=",
"function",
"(",
")",
"{",
"return",
"function",
"(",
"key",
",",
"action",
",",
"body",
",",
"callback",
")",
"{",
"body",
"=",
"body",
"||",
"{",
"}",
";",
"body",
".",
"type",
"=",
"action",
";",
"client",
".",
"exec",
"(",
"{",
"method",
":",
"'POST'",
",",
"path",
":",
"'/'",
"+",
"endpoint",
"+",
"'/'",
"+",
"key",
"+",
"'/actions'",
",",
"body",
":",
"body",
"}",
",",
"callback",
")",
";",
"}",
";",
"}",
";",
"}"
] | Wrapper to provide basic functions for the API's
@class Base
@static | [
"Wrapper",
"to",
"provide",
"basic",
"functions",
"for",
"the",
"API",
"s"
] | 40707648c10073a356a424e6c9f75b642df7a7c7 | https://github.com/pauldenotter/nautical/blob/40707648c10073a356a424e6c9f75b642df7a7c7/lib/base.js#L9-L119 |
48,045 | zackurben/event-chain | lib/Chain.js | function(config) {
this.events = new EventEmitter();
this.config = config || {};
// Allow someone to change the complete event label.
if (!this.config.complete) {
this.config.complete = '__complete';
}
debug('Chain created with the following configuration: ' + JSON.stringify(this.config));
} | javascript | function(config) {
this.events = new EventEmitter();
this.config = config || {};
// Allow someone to change the complete event label.
if (!this.config.complete) {
this.config.complete = '__complete';
}
debug('Chain created with the following configuration: ' + JSON.stringify(this.config));
} | [
"function",
"(",
"config",
")",
"{",
"this",
".",
"events",
"=",
"new",
"EventEmitter",
"(",
")",
";",
"this",
".",
"config",
"=",
"config",
"||",
"{",
"}",
";",
"// Allow someone to change the complete event label.",
"if",
"(",
"!",
"this",
".",
"config",
".",
"complete",
")",
"{",
"this",
".",
"config",
".",
"complete",
"=",
"'__complete'",
";",
"}",
"debug",
"(",
"'Chain created with the following configuration: '",
"+",
"JSON",
".",
"stringify",
"(",
"this",
".",
"config",
")",
")",
";",
"}"
] | The primary container for chained events.
@param config
An optional configuration object.
@constructor | [
"The",
"primary",
"container",
"for",
"chained",
"events",
"."
] | d6b12f569afb58cb6b01e85dbb7dbf320583ed7b | https://github.com/zackurben/event-chain/blob/d6b12f569afb58cb6b01e85dbb7dbf320583ed7b/lib/Chain.js#L15-L25 |
|
48,046 | kibertoad/objection-utils | repositories/lib/services/entity.repository.js | _validateIsModel | function _validateIsModel(model) {
let parentClass = Object.getPrototypeOf(model);
while (parentClass.name !== 'Model' && parentClass.name !== '') {
parentClass = Object.getPrototypeOf(parentClass);
}
validationUtils.booleanTrue(
parentClass.name === 'Model',
'Parameter is not an Objection.js model'
);
} | javascript | function _validateIsModel(model) {
let parentClass = Object.getPrototypeOf(model);
while (parentClass.name !== 'Model' && parentClass.name !== '') {
parentClass = Object.getPrototypeOf(parentClass);
}
validationUtils.booleanTrue(
parentClass.name === 'Model',
'Parameter is not an Objection.js model'
);
} | [
"function",
"_validateIsModel",
"(",
"model",
")",
"{",
"let",
"parentClass",
"=",
"Object",
".",
"getPrototypeOf",
"(",
"model",
")",
";",
"while",
"(",
"parentClass",
".",
"name",
"!==",
"'Model'",
"&&",
"parentClass",
".",
"name",
"!==",
"''",
")",
"{",
"parentClass",
"=",
"Object",
".",
"getPrototypeOf",
"(",
"parentClass",
")",
";",
"}",
"validationUtils",
".",
"booleanTrue",
"(",
"parentClass",
".",
"name",
"===",
"'Model'",
",",
"'Parameter is not an Objection.js model'",
")",
";",
"}"
] | This is only invoked on the startup, so we can make this check non-trivial | [
"This",
"is",
"only",
"invoked",
"on",
"the",
"startup",
"so",
"we",
"can",
"make",
"this",
"check",
"non",
"-",
"trivial"
] | 6da0bc3ef1185ae52d77fb0af5630a5433dbd917 | https://github.com/kibertoad/objection-utils/blob/6da0bc3ef1185ae52d77fb0af5630a5433dbd917/repositories/lib/services/entity.repository.js#L202-L211 |
48,047 | stormcolor/grel | dist/grel/nclgl.js | doNativeWasm | function doNativeWasm(global, env, providedBuffer) {
if (typeof WebAssembly !== 'object') {
err('no native wasm support detected');
return false;
}
// prepare memory import
if (!(Module['wasmMemory'] instanceof WebAssembly.Memory)) {
err('no native wasm Memory in use');
return false;
}
env['memory'] = Module['wasmMemory'];
// Load the wasm module and create an instance of using native support in the JS engine.
info['global'] = {
'NaN': NaN,
'Infinity': Infinity
};
info['global.Math'] = Math;
info['env'] = env;
// handle a generated wasm instance, receiving its exports and
// performing other necessary setup
function receiveInstance(instance, module) {
exports = instance.exports;
if (exports.memory) mergeMemory(exports.memory);
Module['asm'] = exports;
Module["usingWasm"] = true;
removeRunDependency('wasm-instantiate');
}
addRunDependency('wasm-instantiate');
// User shell pages can write their own Module.instantiateWasm = function(imports, successCallback) callback
// to manually instantiate the Wasm module themselves. This allows pages to run the instantiation parallel
// to any other async startup actions they are performing.
if (Module['instantiateWasm']) {
try {
return Module['instantiateWasm'](info, receiveInstance);
} catch(e) {
err('Module.instantiateWasm callback failed with error: ' + e);
return false;
}
}
function receiveInstantiatedSource(output) {
// 'output' is a WebAssemblyInstantiatedSource object which has both the module and instance.
// receiveInstance() will swap in the exports (to Module.asm) so they can be called
receiveInstance(output['instance'], output['module']);
}
function instantiateArrayBuffer(receiver) {
getBinaryPromise().then(function(binary) {
return WebAssembly.instantiate(binary, info);
}).then(receiver).catch(function(reason) {
err('failed to asynchronously prepare wasm: ' + reason);
abort(reason);
});
}
// Prefer streaming instantiation if available.
if (!Module['wasmBinary'] &&
typeof WebAssembly.instantiateStreaming === 'function' &&
!isDataURI(wasmBinaryFile) &&
typeof fetch === 'function') {
WebAssembly.instantiateStreaming(fetch(wasmBinaryFile, { credentials: 'same-origin' }), info)
.then(receiveInstantiatedSource)
.catch(function(reason) {
// We expect the most common failure cause to be a bad MIME type for the binary,
// in which case falling back to ArrayBuffer instantiation should work.
err('wasm streaming compile failed: ' + reason);
err('falling back to ArrayBuffer instantiation');
instantiateArrayBuffer(receiveInstantiatedSource);
});
} else {
instantiateArrayBuffer(receiveInstantiatedSource);
}
return {}; // no exports yet; we'll fill them in later
} | javascript | function doNativeWasm(global, env, providedBuffer) {
if (typeof WebAssembly !== 'object') {
err('no native wasm support detected');
return false;
}
// prepare memory import
if (!(Module['wasmMemory'] instanceof WebAssembly.Memory)) {
err('no native wasm Memory in use');
return false;
}
env['memory'] = Module['wasmMemory'];
// Load the wasm module and create an instance of using native support in the JS engine.
info['global'] = {
'NaN': NaN,
'Infinity': Infinity
};
info['global.Math'] = Math;
info['env'] = env;
// handle a generated wasm instance, receiving its exports and
// performing other necessary setup
function receiveInstance(instance, module) {
exports = instance.exports;
if (exports.memory) mergeMemory(exports.memory);
Module['asm'] = exports;
Module["usingWasm"] = true;
removeRunDependency('wasm-instantiate');
}
addRunDependency('wasm-instantiate');
// User shell pages can write their own Module.instantiateWasm = function(imports, successCallback) callback
// to manually instantiate the Wasm module themselves. This allows pages to run the instantiation parallel
// to any other async startup actions they are performing.
if (Module['instantiateWasm']) {
try {
return Module['instantiateWasm'](info, receiveInstance);
} catch(e) {
err('Module.instantiateWasm callback failed with error: ' + e);
return false;
}
}
function receiveInstantiatedSource(output) {
// 'output' is a WebAssemblyInstantiatedSource object which has both the module and instance.
// receiveInstance() will swap in the exports (to Module.asm) so they can be called
receiveInstance(output['instance'], output['module']);
}
function instantiateArrayBuffer(receiver) {
getBinaryPromise().then(function(binary) {
return WebAssembly.instantiate(binary, info);
}).then(receiver).catch(function(reason) {
err('failed to asynchronously prepare wasm: ' + reason);
abort(reason);
});
}
// Prefer streaming instantiation if available.
if (!Module['wasmBinary'] &&
typeof WebAssembly.instantiateStreaming === 'function' &&
!isDataURI(wasmBinaryFile) &&
typeof fetch === 'function') {
WebAssembly.instantiateStreaming(fetch(wasmBinaryFile, { credentials: 'same-origin' }), info)
.then(receiveInstantiatedSource)
.catch(function(reason) {
// We expect the most common failure cause to be a bad MIME type for the binary,
// in which case falling back to ArrayBuffer instantiation should work.
err('wasm streaming compile failed: ' + reason);
err('falling back to ArrayBuffer instantiation');
instantiateArrayBuffer(receiveInstantiatedSource);
});
} else {
instantiateArrayBuffer(receiveInstantiatedSource);
}
return {}; // no exports yet; we'll fill them in later
} | [
"function",
"doNativeWasm",
"(",
"global",
",",
"env",
",",
"providedBuffer",
")",
"{",
"if",
"(",
"typeof",
"WebAssembly",
"!==",
"'object'",
")",
"{",
"err",
"(",
"'no native wasm support detected'",
")",
";",
"return",
"false",
";",
"}",
"// prepare memory import",
"if",
"(",
"!",
"(",
"Module",
"[",
"'wasmMemory'",
"]",
"instanceof",
"WebAssembly",
".",
"Memory",
")",
")",
"{",
"err",
"(",
"'no native wasm Memory in use'",
")",
";",
"return",
"false",
";",
"}",
"env",
"[",
"'memory'",
"]",
"=",
"Module",
"[",
"'wasmMemory'",
"]",
";",
"// Load the wasm module and create an instance of using native support in the JS engine.",
"info",
"[",
"'global'",
"]",
"=",
"{",
"'NaN'",
":",
"NaN",
",",
"'Infinity'",
":",
"Infinity",
"}",
";",
"info",
"[",
"'global.Math'",
"]",
"=",
"Math",
";",
"info",
"[",
"'env'",
"]",
"=",
"env",
";",
"// handle a generated wasm instance, receiving its exports and",
"// performing other necessary setup",
"function",
"receiveInstance",
"(",
"instance",
",",
"module",
")",
"{",
"exports",
"=",
"instance",
".",
"exports",
";",
"if",
"(",
"exports",
".",
"memory",
")",
"mergeMemory",
"(",
"exports",
".",
"memory",
")",
";",
"Module",
"[",
"'asm'",
"]",
"=",
"exports",
";",
"Module",
"[",
"\"usingWasm\"",
"]",
"=",
"true",
";",
"removeRunDependency",
"(",
"'wasm-instantiate'",
")",
";",
"}",
"addRunDependency",
"(",
"'wasm-instantiate'",
")",
";",
"// User shell pages can write their own Module.instantiateWasm = function(imports, successCallback) callback",
"// to manually instantiate the Wasm module themselves. This allows pages to run the instantiation parallel",
"// to any other async startup actions they are performing.",
"if",
"(",
"Module",
"[",
"'instantiateWasm'",
"]",
")",
"{",
"try",
"{",
"return",
"Module",
"[",
"'instantiateWasm'",
"]",
"(",
"info",
",",
"receiveInstance",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"err",
"(",
"'Module.instantiateWasm callback failed with error: '",
"+",
"e",
")",
";",
"return",
"false",
";",
"}",
"}",
"function",
"receiveInstantiatedSource",
"(",
"output",
")",
"{",
"// 'output' is a WebAssemblyInstantiatedSource object which has both the module and instance.",
"// receiveInstance() will swap in the exports (to Module.asm) so they can be called",
"receiveInstance",
"(",
"output",
"[",
"'instance'",
"]",
",",
"output",
"[",
"'module'",
"]",
")",
";",
"}",
"function",
"instantiateArrayBuffer",
"(",
"receiver",
")",
"{",
"getBinaryPromise",
"(",
")",
".",
"then",
"(",
"function",
"(",
"binary",
")",
"{",
"return",
"WebAssembly",
".",
"instantiate",
"(",
"binary",
",",
"info",
")",
";",
"}",
")",
".",
"then",
"(",
"receiver",
")",
".",
"catch",
"(",
"function",
"(",
"reason",
")",
"{",
"err",
"(",
"'failed to asynchronously prepare wasm: '",
"+",
"reason",
")",
";",
"abort",
"(",
"reason",
")",
";",
"}",
")",
";",
"}",
"// Prefer streaming instantiation if available.",
"if",
"(",
"!",
"Module",
"[",
"'wasmBinary'",
"]",
"&&",
"typeof",
"WebAssembly",
".",
"instantiateStreaming",
"===",
"'function'",
"&&",
"!",
"isDataURI",
"(",
"wasmBinaryFile",
")",
"&&",
"typeof",
"fetch",
"===",
"'function'",
")",
"{",
"WebAssembly",
".",
"instantiateStreaming",
"(",
"fetch",
"(",
"wasmBinaryFile",
",",
"{",
"credentials",
":",
"'same-origin'",
"}",
")",
",",
"info",
")",
".",
"then",
"(",
"receiveInstantiatedSource",
")",
".",
"catch",
"(",
"function",
"(",
"reason",
")",
"{",
"// We expect the most common failure cause to be a bad MIME type for the binary,",
"// in which case falling back to ArrayBuffer instantiation should work.",
"err",
"(",
"'wasm streaming compile failed: '",
"+",
"reason",
")",
";",
"err",
"(",
"'falling back to ArrayBuffer instantiation'",
")",
";",
"instantiateArrayBuffer",
"(",
"receiveInstantiatedSource",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"instantiateArrayBuffer",
"(",
"receiveInstantiatedSource",
")",
";",
"}",
"return",
"{",
"}",
";",
"// no exports yet; we'll fill them in later",
"}"
] | do-method functions | [
"do",
"-",
"method",
"functions"
] | 37cd769a029cec5dcd75c43e1e0dba4737fa011a | https://github.com/stormcolor/grel/blob/37cd769a029cec5dcd75c43e1e0dba4737fa011a/dist/grel/nclgl.js#L1515-L1587 |
48,048 | stormcolor/grel | dist/grel/nclgl.js | function(event) {
var e = event || window.event;
JSEvents.fillMouseEventData(JSEvents.wheelEvent, e, target);
HEAPF64[(((JSEvents.wheelEvent)+(72))>>3)]=e["deltaX"];
HEAPF64[(((JSEvents.wheelEvent)+(80))>>3)]=e["deltaY"];
HEAPF64[(((JSEvents.wheelEvent)+(88))>>3)]=e["deltaZ"];
HEAP32[(((JSEvents.wheelEvent)+(96))>>2)]=e["deltaMode"];
var shouldCancel = Module['dynCall_iiii'](callbackfunc, eventTypeId, JSEvents.wheelEvent, userData);
if (shouldCancel) {
e.preventDefault();
}
} | javascript | function(event) {
var e = event || window.event;
JSEvents.fillMouseEventData(JSEvents.wheelEvent, e, target);
HEAPF64[(((JSEvents.wheelEvent)+(72))>>3)]=e["deltaX"];
HEAPF64[(((JSEvents.wheelEvent)+(80))>>3)]=e["deltaY"];
HEAPF64[(((JSEvents.wheelEvent)+(88))>>3)]=e["deltaZ"];
HEAP32[(((JSEvents.wheelEvent)+(96))>>2)]=e["deltaMode"];
var shouldCancel = Module['dynCall_iiii'](callbackfunc, eventTypeId, JSEvents.wheelEvent, userData);
if (shouldCancel) {
e.preventDefault();
}
} | [
"function",
"(",
"event",
")",
"{",
"var",
"e",
"=",
"event",
"||",
"window",
".",
"event",
";",
"JSEvents",
".",
"fillMouseEventData",
"(",
"JSEvents",
".",
"wheelEvent",
",",
"e",
",",
"target",
")",
";",
"HEAPF64",
"[",
"(",
"(",
"(",
"JSEvents",
".",
"wheelEvent",
")",
"+",
"(",
"72",
")",
")",
">>",
"3",
")",
"]",
"=",
"e",
"[",
"\"deltaX\"",
"]",
";",
"HEAPF64",
"[",
"(",
"(",
"(",
"JSEvents",
".",
"wheelEvent",
")",
"+",
"(",
"80",
")",
")",
">>",
"3",
")",
"]",
"=",
"e",
"[",
"\"deltaY\"",
"]",
";",
"HEAPF64",
"[",
"(",
"(",
"(",
"JSEvents",
".",
"wheelEvent",
")",
"+",
"(",
"88",
")",
")",
">>",
"3",
")",
"]",
"=",
"e",
"[",
"\"deltaZ\"",
"]",
";",
"HEAP32",
"[",
"(",
"(",
"(",
"JSEvents",
".",
"wheelEvent",
")",
"+",
"(",
"96",
")",
")",
">>",
"2",
")",
"]",
"=",
"e",
"[",
"\"deltaMode\"",
"]",
";",
"var",
"shouldCancel",
"=",
"Module",
"[",
"'dynCall_iiii'",
"]",
"(",
"callbackfunc",
",",
"eventTypeId",
",",
"JSEvents",
".",
"wheelEvent",
",",
"userData",
")",
";",
"if",
"(",
"shouldCancel",
")",
"{",
"e",
".",
"preventDefault",
"(",
")",
";",
"}",
"}"
] | The DOM Level 3 events spec event 'wheel' | [
"The",
"DOM",
"Level",
"3",
"events",
"spec",
"event",
"wheel"
] | 37cd769a029cec5dcd75c43e1e0dba4737fa011a | https://github.com/stormcolor/grel/blob/37cd769a029cec5dcd75c43e1e0dba4737fa011a/dist/grel/nclgl.js#L5527-L5538 |
|
48,049 | ceoaliongroo/angular-weather | src/angular-weather.js | get | function get(city, _options) {
extend(options, _options, {city: city});
getWeather = $q.when(getWeather || angular.copy(getCache()) || getWeatherFromServer(city));
// Clear the promise cached, after resolve or reject the promise. Permit access to the cache data, when
// the promise excecution is done (finally).
getWeather.finally(function getWeatherFinally() {
getWeather = undefined;
});
return getWeather;
} | javascript | function get(city, _options) {
extend(options, _options, {city: city});
getWeather = $q.when(getWeather || angular.copy(getCache()) || getWeatherFromServer(city));
// Clear the promise cached, after resolve or reject the promise. Permit access to the cache data, when
// the promise excecution is done (finally).
getWeather.finally(function getWeatherFinally() {
getWeather = undefined;
});
return getWeather;
} | [
"function",
"get",
"(",
"city",
",",
"_options",
")",
"{",
"extend",
"(",
"options",
",",
"_options",
",",
"{",
"city",
":",
"city",
"}",
")",
";",
"getWeather",
"=",
"$q",
".",
"when",
"(",
"getWeather",
"||",
"angular",
".",
"copy",
"(",
"getCache",
"(",
")",
")",
"||",
"getWeatherFromServer",
"(",
"city",
")",
")",
";",
"// Clear the promise cached, after resolve or reject the promise. Permit access to the cache data, when",
"// the promise excecution is done (finally).",
"getWeather",
".",
"finally",
"(",
"function",
"getWeatherFinally",
"(",
")",
"{",
"getWeather",
"=",
"undefined",
";",
"}",
")",
";",
"return",
"getWeather",
";",
"}"
] | Return the promise with the category list, from cache or the server.
@param city - string
The city name. Ex: Houston
@param _options - object
The options to handle.
refresh: activate to get new weather information in interval
of delay time.
delay: interval of time in miliseconds.
@returns {Promise} | [
"Return",
"the",
"promise",
"with",
"the",
"category",
"list",
"from",
"cache",
"or",
"the",
"server",
"."
] | 4f8e4206c67c254549f5afdbeb10d6d694824144 | https://github.com/ceoaliongroo/angular-weather/blob/4f8e4206c67c254549f5afdbeb10d6d694824144/src/angular-weather.js#L62-L74 |
48,050 | ceoaliongroo/angular-weather | src/angular-weather.js | getWeatherFromServer | function getWeatherFromServer(city) {
var deferred = $q.defer();
var url = openweatherEndpoint;
var params = {
q: city,
units: 'metric',
APPID: Config.openweather.apikey || ''
};
$http({
method: 'GET',
url: url,
params: params,
withoutToken: true,
cache: true
}).success(function(data) {
// Prepare the Weather object.
var weatherData = prepareWeather(data);
setCache(weatherData);
// Start refresh automatic the weather, according the interval of time.
options.refresh && startRefreshWeather();
deferred.resolve(weatherData);
});
return deferred.promise;
} | javascript | function getWeatherFromServer(city) {
var deferred = $q.defer();
var url = openweatherEndpoint;
var params = {
q: city,
units: 'metric',
APPID: Config.openweather.apikey || ''
};
$http({
method: 'GET',
url: url,
params: params,
withoutToken: true,
cache: true
}).success(function(data) {
// Prepare the Weather object.
var weatherData = prepareWeather(data);
setCache(weatherData);
// Start refresh automatic the weather, according the interval of time.
options.refresh && startRefreshWeather();
deferred.resolve(weatherData);
});
return deferred.promise;
} | [
"function",
"getWeatherFromServer",
"(",
"city",
")",
"{",
"var",
"deferred",
"=",
"$q",
".",
"defer",
"(",
")",
";",
"var",
"url",
"=",
"openweatherEndpoint",
";",
"var",
"params",
"=",
"{",
"q",
":",
"city",
",",
"units",
":",
"'metric'",
",",
"APPID",
":",
"Config",
".",
"openweather",
".",
"apikey",
"||",
"''",
"}",
";",
"$http",
"(",
"{",
"method",
":",
"'GET'",
",",
"url",
":",
"url",
",",
"params",
":",
"params",
",",
"withoutToken",
":",
"true",
",",
"cache",
":",
"true",
"}",
")",
".",
"success",
"(",
"function",
"(",
"data",
")",
"{",
"// Prepare the Weather object.",
"var",
"weatherData",
"=",
"prepareWeather",
"(",
"data",
")",
";",
"setCache",
"(",
"weatherData",
")",
";",
"// Start refresh automatic the weather, according the interval of time.",
"options",
".",
"refresh",
"&&",
"startRefreshWeather",
"(",
")",
";",
"deferred",
".",
"resolve",
"(",
"weatherData",
")",
";",
"}",
")",
";",
"return",
"deferred",
".",
"promise",
";",
"}"
] | Return Weather array from the server.
@returns {$q.promise} | [
"Return",
"Weather",
"array",
"from",
"the",
"server",
"."
] | 4f8e4206c67c254549f5afdbeb10d6d694824144 | https://github.com/ceoaliongroo/angular-weather/blob/4f8e4206c67c254549f5afdbeb10d6d694824144/src/angular-weather.js#L81-L107 |
48,051 | ceoaliongroo/angular-weather | src/angular-weather.js | startRefreshWeather | function startRefreshWeather() {
interval = $interval(getWeatherFromServer(options.city), options.delay);
localforage.setItem('aw.refreshing', true);
} | javascript | function startRefreshWeather() {
interval = $interval(getWeatherFromServer(options.city), options.delay);
localforage.setItem('aw.refreshing', true);
} | [
"function",
"startRefreshWeather",
"(",
")",
"{",
"interval",
"=",
"$interval",
"(",
"getWeatherFromServer",
"(",
"options",
".",
"city",
")",
",",
"options",
".",
"delay",
")",
";",
"localforage",
".",
"setItem",
"(",
"'aw.refreshing'",
",",
"true",
")",
";",
"}"
] | Start an interval to refresh the weather cache data with new server data. | [
"Start",
"an",
"interval",
"to",
"refresh",
"the",
"weather",
"cache",
"data",
"with",
"new",
"server",
"data",
"."
] | 4f8e4206c67c254549f5afdbeb10d6d694824144 | https://github.com/ceoaliongroo/angular-weather/blob/4f8e4206c67c254549f5afdbeb10d6d694824144/src/angular-weather.js#L131-L134 |
48,052 | ceoaliongroo/angular-weather | src/angular-weather.js | prepareWeather | function prepareWeather(weatherData) {
return {
temperature: weatherData.main.temp,
icon: (angular.isDefined(weatherIcons[weatherData.weather[0].icon])) ? weatherData.weather[0].icon : weatherData.weather[0].id,
description: weatherData.weather[0].description
}
} | javascript | function prepareWeather(weatherData) {
return {
temperature: weatherData.main.temp,
icon: (angular.isDefined(weatherIcons[weatherData.weather[0].icon])) ? weatherData.weather[0].icon : weatherData.weather[0].id,
description: weatherData.weather[0].description
}
} | [
"function",
"prepareWeather",
"(",
"weatherData",
")",
"{",
"return",
"{",
"temperature",
":",
"weatherData",
".",
"main",
".",
"temp",
",",
"icon",
":",
"(",
"angular",
".",
"isDefined",
"(",
"weatherIcons",
"[",
"weatherData",
".",
"weather",
"[",
"0",
"]",
".",
"icon",
"]",
")",
")",
"?",
"weatherData",
".",
"weather",
"[",
"0",
"]",
".",
"icon",
":",
"weatherData",
".",
"weather",
"[",
"0",
"]",
".",
"id",
",",
"description",
":",
"weatherData",
".",
"weather",
"[",
"0",
"]",
".",
"description",
"}",
"}"
] | Prepare Weather object with order by list, tree and collection indexed by id.
Return the Weather object into a promises.
@param weatherData - {$q.promise)
Promise of list of Weather, comming from cache or the server. | [
"Prepare",
"Weather",
"object",
"with",
"order",
"by",
"list",
"tree",
"and",
"collection",
"indexed",
"by",
"id",
"."
] | 4f8e4206c67c254549f5afdbeb10d6d694824144 | https://github.com/ceoaliongroo/angular-weather/blob/4f8e4206c67c254549f5afdbeb10d6d694824144/src/angular-weather.js#L154-L160 |
48,053 | BlackDice/lill | src/lill.js | func$withContext | function func$withContext(fn, item, i, ctx) { // eslint-disable-line max-params
return fn.call(ctx, item, i)
} | javascript | function func$withContext(fn, item, i, ctx) { // eslint-disable-line max-params
return fn.call(ctx, item, i)
} | [
"function",
"func$withContext",
"(",
"fn",
",",
"item",
",",
"i",
",",
"ctx",
")",
"{",
"// eslint-disable-line max-params",
"return",
"fn",
".",
"call",
"(",
"ctx",
",",
"item",
",",
"i",
")",
"}"
] | bit slower to use call when changing context | [
"bit",
"slower",
"to",
"use",
"call",
"when",
"changing",
"context"
] | 8bd52b904b9ecbc1d3eec262af8a4734e356188a | https://github.com/BlackDice/lill/blob/8bd52b904b9ecbc1d3eec262af8a4734e356188a/src/lill.js#L352-L354 |
48,054 | BlackDice/lill | src/lill.js | getNeighbor | function getNeighbor(owner, item, dataPropertyName) {
const data = validateAttached(owner)
return obtainTrueValue(item[data[dataPropertyName]])
} | javascript | function getNeighbor(owner, item, dataPropertyName) {
const data = validateAttached(owner)
return obtainTrueValue(item[data[dataPropertyName]])
} | [
"function",
"getNeighbor",
"(",
"owner",
",",
"item",
",",
"dataPropertyName",
")",
"{",
"const",
"data",
"=",
"validateAttached",
"(",
"owner",
")",
"return",
"obtainTrueValue",
"(",
"item",
"[",
"data",
"[",
"dataPropertyName",
"]",
"]",
")",
"}"
] | just wrapper to minimize duplicate code | [
"just",
"wrapper",
"to",
"minimize",
"duplicate",
"code"
] | 8bd52b904b9ecbc1d3eec262af8a4734e356188a | https://github.com/BlackDice/lill/blob/8bd52b904b9ecbc1d3eec262af8a4734e356188a/src/lill.js#L365-L368 |
48,055 | smartface/sf-component-calendar | scripts/components/__Calendar_List.js | CalendarList | function CalendarList(_super) {
_super(this, {
flexGrow: 1,
alignSelf: FlexLayout.AlignSelf.STRETCH,
backgroundColor: Color.GREEN,
});
this.init();
} | javascript | function CalendarList(_super) {
_super(this, {
flexGrow: 1,
alignSelf: FlexLayout.AlignSelf.STRETCH,
backgroundColor: Color.GREEN,
});
this.init();
} | [
"function",
"CalendarList",
"(",
"_super",
")",
"{",
"_super",
"(",
"this",
",",
"{",
"flexGrow",
":",
"1",
",",
"alignSelf",
":",
"FlexLayout",
".",
"AlignSelf",
".",
"STRETCH",
",",
"backgroundColor",
":",
"Color",
".",
"GREEN",
",",
"}",
")",
";",
"this",
".",
"init",
"(",
")",
";",
"}"
] | CalendarList Component constructor
@constructor | [
"CalendarList",
"Component",
"constructor"
] | d6c8310564ff551b9424ac6955efa5e8cf5f8dff | https://github.com/smartface/sf-component-calendar/blob/d6c8310564ff551b9424ac6955efa5e8cf5f8dff/scripts/components/__Calendar_List.js#L10-L18 |
48,056 | Ragnarokkr/chrome-i18n | lib/commons.js | validateMeta | function validateMeta( meta, errBuf ) {
var supportedLocales =
'ar,am,bg,bn,ca,cs,da,de,el,en,en_GB,en_US,es,es_419,et,' +
'fa,fi,fil,fr,gu,he,hi,hr,hu,id,it,ja,kn,ko,lt,lv,ml,mr,' +
'ms,nl,no,pl,pt_BR,pt_PT,ro,ru,sk,sl,sr,sv,sw,ta,te,th,' +
'tr,uk,vi,zh_CN,zh_TW'.split(','),
isFormatValid = true,
isImportsValid = true,
isDestValid = true,
isLocalesValid = true,
isDefintionsValid = true;
// `format` MUST BE a string of value: monolith|category|language
if ( typeof meta.format !== 'string' ) {
errBuf.push(
'Error (META): `format` field is not defined or in wrong format'
);
isFormatValid = false;
} else {
if ( !/^(monolith|category|language)$/.test( meta.format ) ) {
errBuf.push(
'Error (META): "' + meta.format + '" value in `format` field not supported'
);
isFormatValid = false;
} // if
} // if..else
// `imports` MUST BE defined if `format` is != monolith
if ( isFormatValid ) {
if ( meta.format === 'category' ) {
if ( typeof meta.imports !== 'string' && !Array.isArray( meta.imports ) ) {
errBuf.push(
'Error (META): when in "category" mode, `imports` field can' +
' be either a string or an array'
);
isImportsValid = false;
} // if
} else {
if ( meta.format === 'language' ) {
if ( typeof meta.imports !== 'string' ) {
errBuf.push(
'Error (META): when in "language" mode, `imports` field' +
' can be only a string pointing to a directory'
);
isImportsValid = false;
} else {
if ( meta.imports.lastIndexOf( path.sep ) !== meta.imports.length-1 ) {
errBuf.push( 'Error: (META): `imports` field is not a directory' );
isImportsValid = false;
} // if
} // if
} // if
} // if..else
} // if
// `dest` MUST BE ALWAYS defined as string pointing to a directory
if ( typeof meta.dest !== 'string' ) {
errBuf.push( 'Error (META): `dest` field MUST be a string' );
isDestValid = false;
} else {
if ( meta.dest.lastIndexOf( path.sep ) !== meta.dest.length-1 ) {
errBuf.push( 'Error (META): `dest` is not a directory' );
isDestValid = false;
} // if
} // if..else
// `locales` MUST BE ALWAYS defined as array with a minimum of one
// country code
if ( !Array.isArray( meta.locales ) ) {
errBuf.push( 'Error (META): `locales` field MUST be an array' );
isLocalesValid = false;
} else {
meta.locales.forEach( function( locale ){
if ( !~supportedLocales.indexOf( locale ) ) {
errBuf.push(
'Error (META): `locales` field\'s country-code "' +
locale + '" is not supported'
);
} // if
});
} // if..else
// `definitions` MUST BE ALWAYS defined as literal object when in
// `language` mode.
if ( meta.format === 'language' ) {
if ( typeof meta.definitions !== 'object' ) {
errBuf.push( 'Error (definitions): in `language` mode, ' +
'`definitions` field MUST be an object' );
isDefintionsValid = false;
} // if
} // if
return isFormatValid && isImportsValid && isDestValid &&
isLocalesValid && isDefintionsValid;
} | javascript | function validateMeta( meta, errBuf ) {
var supportedLocales =
'ar,am,bg,bn,ca,cs,da,de,el,en,en_GB,en_US,es,es_419,et,' +
'fa,fi,fil,fr,gu,he,hi,hr,hu,id,it,ja,kn,ko,lt,lv,ml,mr,' +
'ms,nl,no,pl,pt_BR,pt_PT,ro,ru,sk,sl,sr,sv,sw,ta,te,th,' +
'tr,uk,vi,zh_CN,zh_TW'.split(','),
isFormatValid = true,
isImportsValid = true,
isDestValid = true,
isLocalesValid = true,
isDefintionsValid = true;
// `format` MUST BE a string of value: monolith|category|language
if ( typeof meta.format !== 'string' ) {
errBuf.push(
'Error (META): `format` field is not defined or in wrong format'
);
isFormatValid = false;
} else {
if ( !/^(monolith|category|language)$/.test( meta.format ) ) {
errBuf.push(
'Error (META): "' + meta.format + '" value in `format` field not supported'
);
isFormatValid = false;
} // if
} // if..else
// `imports` MUST BE defined if `format` is != monolith
if ( isFormatValid ) {
if ( meta.format === 'category' ) {
if ( typeof meta.imports !== 'string' && !Array.isArray( meta.imports ) ) {
errBuf.push(
'Error (META): when in "category" mode, `imports` field can' +
' be either a string or an array'
);
isImportsValid = false;
} // if
} else {
if ( meta.format === 'language' ) {
if ( typeof meta.imports !== 'string' ) {
errBuf.push(
'Error (META): when in "language" mode, `imports` field' +
' can be only a string pointing to a directory'
);
isImportsValid = false;
} else {
if ( meta.imports.lastIndexOf( path.sep ) !== meta.imports.length-1 ) {
errBuf.push( 'Error: (META): `imports` field is not a directory' );
isImportsValid = false;
} // if
} // if
} // if
} // if..else
} // if
// `dest` MUST BE ALWAYS defined as string pointing to a directory
if ( typeof meta.dest !== 'string' ) {
errBuf.push( 'Error (META): `dest` field MUST be a string' );
isDestValid = false;
} else {
if ( meta.dest.lastIndexOf( path.sep ) !== meta.dest.length-1 ) {
errBuf.push( 'Error (META): `dest` is not a directory' );
isDestValid = false;
} // if
} // if..else
// `locales` MUST BE ALWAYS defined as array with a minimum of one
// country code
if ( !Array.isArray( meta.locales ) ) {
errBuf.push( 'Error (META): `locales` field MUST be an array' );
isLocalesValid = false;
} else {
meta.locales.forEach( function( locale ){
if ( !~supportedLocales.indexOf( locale ) ) {
errBuf.push(
'Error (META): `locales` field\'s country-code "' +
locale + '" is not supported'
);
} // if
});
} // if..else
// `definitions` MUST BE ALWAYS defined as literal object when in
// `language` mode.
if ( meta.format === 'language' ) {
if ( typeof meta.definitions !== 'object' ) {
errBuf.push( 'Error (definitions): in `language` mode, ' +
'`definitions` field MUST be an object' );
isDefintionsValid = false;
} // if
} // if
return isFormatValid && isImportsValid && isDestValid &&
isLocalesValid && isDefintionsValid;
} | [
"function",
"validateMeta",
"(",
"meta",
",",
"errBuf",
")",
"{",
"var",
"supportedLocales",
"=",
"'ar,am,bg,bn,ca,cs,da,de,el,en,en_GB,en_US,es,es_419,et,'",
"+",
"'fa,fi,fil,fr,gu,he,hi,hr,hu,id,it,ja,kn,ko,lt,lv,ml,mr,'",
"+",
"'ms,nl,no,pl,pt_BR,pt_PT,ro,ru,sk,sl,sr,sv,sw,ta,te,th,'",
"+",
"'tr,uk,vi,zh_CN,zh_TW'",
".",
"split",
"(",
"','",
")",
",",
"isFormatValid",
"=",
"true",
",",
"isImportsValid",
"=",
"true",
",",
"isDestValid",
"=",
"true",
",",
"isLocalesValid",
"=",
"true",
",",
"isDefintionsValid",
"=",
"true",
";",
"// `format` MUST BE a string of value: monolith|category|language",
"if",
"(",
"typeof",
"meta",
".",
"format",
"!==",
"'string'",
")",
"{",
"errBuf",
".",
"push",
"(",
"'Error (META): `format` field is not defined or in wrong format'",
")",
";",
"isFormatValid",
"=",
"false",
";",
"}",
"else",
"{",
"if",
"(",
"!",
"/",
"^(monolith|category|language)$",
"/",
".",
"test",
"(",
"meta",
".",
"format",
")",
")",
"{",
"errBuf",
".",
"push",
"(",
"'Error (META): \"'",
"+",
"meta",
".",
"format",
"+",
"'\" value in `format` field not supported'",
")",
";",
"isFormatValid",
"=",
"false",
";",
"}",
"// if",
"}",
"// if..else",
"// `imports` MUST BE defined if `format` is != monolith",
"if",
"(",
"isFormatValid",
")",
"{",
"if",
"(",
"meta",
".",
"format",
"===",
"'category'",
")",
"{",
"if",
"(",
"typeof",
"meta",
".",
"imports",
"!==",
"'string'",
"&&",
"!",
"Array",
".",
"isArray",
"(",
"meta",
".",
"imports",
")",
")",
"{",
"errBuf",
".",
"push",
"(",
"'Error (META): when in \"category\" mode, `imports` field can'",
"+",
"' be either a string or an array'",
")",
";",
"isImportsValid",
"=",
"false",
";",
"}",
"// if",
"}",
"else",
"{",
"if",
"(",
"meta",
".",
"format",
"===",
"'language'",
")",
"{",
"if",
"(",
"typeof",
"meta",
".",
"imports",
"!==",
"'string'",
")",
"{",
"errBuf",
".",
"push",
"(",
"'Error (META): when in \"language\" mode, `imports` field'",
"+",
"' can be only a string pointing to a directory'",
")",
";",
"isImportsValid",
"=",
"false",
";",
"}",
"else",
"{",
"if",
"(",
"meta",
".",
"imports",
".",
"lastIndexOf",
"(",
"path",
".",
"sep",
")",
"!==",
"meta",
".",
"imports",
".",
"length",
"-",
"1",
")",
"{",
"errBuf",
".",
"push",
"(",
"'Error: (META): `imports` field is not a directory'",
")",
";",
"isImportsValid",
"=",
"false",
";",
"}",
"// if",
"}",
"// if",
"}",
"// if",
"}",
"// if..else",
"}",
"// if",
"// `dest` MUST BE ALWAYS defined as string pointing to a directory",
"if",
"(",
"typeof",
"meta",
".",
"dest",
"!==",
"'string'",
")",
"{",
"errBuf",
".",
"push",
"(",
"'Error (META): `dest` field MUST be a string'",
")",
";",
"isDestValid",
"=",
"false",
";",
"}",
"else",
"{",
"if",
"(",
"meta",
".",
"dest",
".",
"lastIndexOf",
"(",
"path",
".",
"sep",
")",
"!==",
"meta",
".",
"dest",
".",
"length",
"-",
"1",
")",
"{",
"errBuf",
".",
"push",
"(",
"'Error (META): `dest` is not a directory'",
")",
";",
"isDestValid",
"=",
"false",
";",
"}",
"// if",
"}",
"// if..else",
"// `locales` MUST BE ALWAYS defined as array with a minimum of one",
"// country code",
"if",
"(",
"!",
"Array",
".",
"isArray",
"(",
"meta",
".",
"locales",
")",
")",
"{",
"errBuf",
".",
"push",
"(",
"'Error (META): `locales` field MUST be an array'",
")",
";",
"isLocalesValid",
"=",
"false",
";",
"}",
"else",
"{",
"meta",
".",
"locales",
".",
"forEach",
"(",
"function",
"(",
"locale",
")",
"{",
"if",
"(",
"!",
"~",
"supportedLocales",
".",
"indexOf",
"(",
"locale",
")",
")",
"{",
"errBuf",
".",
"push",
"(",
"'Error (META): `locales` field\\'s country-code \"'",
"+",
"locale",
"+",
"'\" is not supported'",
")",
";",
"}",
"// if",
"}",
")",
";",
"}",
"// if..else",
"// `definitions` MUST BE ALWAYS defined as literal object when in",
"// `language` mode.",
"if",
"(",
"meta",
".",
"format",
"===",
"'language'",
")",
"{",
"if",
"(",
"typeof",
"meta",
".",
"definitions",
"!==",
"'object'",
")",
"{",
"errBuf",
".",
"push",
"(",
"'Error (definitions): in `language` mode, '",
"+",
"'`definitions` field MUST be an object'",
")",
";",
"isDefintionsValid",
"=",
"false",
";",
"}",
"// if",
"}",
"// if",
"return",
"isFormatValid",
"&&",
"isImportsValid",
"&&",
"isDestValid",
"&&",
"isLocalesValid",
"&&",
"isDefintionsValid",
";",
"}"
] | Checks the integrity of the META descriptor.
The locales codes are compared to those supported by the Chrome
Store (https://developers.google.com/chrome/web-store/docs/i18n?hl=it#localeTable),
so any unsupported locale code will invalidate the field.
@param {object} meta a valid JSON object
@param {array} errBuf buffer for generated errors
@return {boolean} `true` if members are available | [
"Checks",
"the",
"integrity",
"of",
"the",
"META",
"descriptor",
"."
] | e7660533fc6846f89bdf5cb6f3745a1b8930f4b9 | https://github.com/Ragnarokkr/chrome-i18n/blob/e7660533fc6846f89bdf5cb6f3745a1b8930f4b9/lib/commons.js#L26-L120 |
48,057 | camme/zonar | lib/zonar.js | listen | function listen(next) {
listenSocket = dgram.createSocket({ type: 'udp4', reuseAddr: true });
listenSocket.on('message', function(payload, rinfo) {
var message = parseMessage(payload, rinfo);
if (message) {
if (message.id != id) {
if (message.status == "ONE") {
updateNodeList(message);
} else if (message.name != listenNameIdentifier && message.status == "NAMETAKEN") {
stop(function() {
//throw new Error('name already taken "' + name + '"');
self.emit("error", {cause: "Name already taken"});
});
}
} else {
//self.emit('error', id + " already exists in network");
throw new Error(id + ' already exits in network');
stop();
}
}
});
listenSocket.bind(function(err) {
var info = listenSocket.address();
self.port = info.port;
next(err);
});
} | javascript | function listen(next) {
listenSocket = dgram.createSocket({ type: 'udp4', reuseAddr: true });
listenSocket.on('message', function(payload, rinfo) {
var message = parseMessage(payload, rinfo);
if (message) {
if (message.id != id) {
if (message.status == "ONE") {
updateNodeList(message);
} else if (message.name != listenNameIdentifier && message.status == "NAMETAKEN") {
stop(function() {
//throw new Error('name already taken "' + name + '"');
self.emit("error", {cause: "Name already taken"});
});
}
} else {
//self.emit('error', id + " already exists in network");
throw new Error(id + ' already exits in network');
stop();
}
}
});
listenSocket.bind(function(err) {
var info = listenSocket.address();
self.port = info.port;
next(err);
});
} | [
"function",
"listen",
"(",
"next",
")",
"{",
"listenSocket",
"=",
"dgram",
".",
"createSocket",
"(",
"{",
"type",
":",
"'udp4'",
",",
"reuseAddr",
":",
"true",
"}",
")",
";",
"listenSocket",
".",
"on",
"(",
"'message'",
",",
"function",
"(",
"payload",
",",
"rinfo",
")",
"{",
"var",
"message",
"=",
"parseMessage",
"(",
"payload",
",",
"rinfo",
")",
";",
"if",
"(",
"message",
")",
"{",
"if",
"(",
"message",
".",
"id",
"!=",
"id",
")",
"{",
"if",
"(",
"message",
".",
"status",
"==",
"\"ONE\"",
")",
"{",
"updateNodeList",
"(",
"message",
")",
";",
"}",
"else",
"if",
"(",
"message",
".",
"name",
"!=",
"listenNameIdentifier",
"&&",
"message",
".",
"status",
"==",
"\"NAMETAKEN\"",
")",
"{",
"stop",
"(",
"function",
"(",
")",
"{",
"//throw new Error('name already taken \"' + name + '\"');",
"self",
".",
"emit",
"(",
"\"error\"",
",",
"{",
"cause",
":",
"\"Name already taken\"",
"}",
")",
";",
"}",
")",
";",
"}",
"}",
"else",
"{",
"//self.emit('error', id + \" already exists in network\");",
"throw",
"new",
"Error",
"(",
"id",
"+",
"' already exits in network'",
")",
";",
"stop",
"(",
")",
";",
"}",
"}",
"}",
")",
";",
"listenSocket",
".",
"bind",
"(",
"function",
"(",
"err",
")",
"{",
"var",
"info",
"=",
"listenSocket",
".",
"address",
"(",
")",
";",
"self",
".",
"port",
"=",
"info",
".",
"port",
";",
"next",
"(",
"err",
")",
";",
"}",
")",
";",
"}"
] | Listen for incoming single messages | [
"Listen",
"for",
"incoming",
"single",
"messages"
] | 9a2c9a355a885f68cbbf21cb170d3763abb0f458 | https://github.com/camme/zonar/blob/9a2c9a355a885f68cbbf21cb170d3763abb0f458/lib/zonar.js#L185-L215 |
48,058 | camme/zonar | lib/zonar.js | createMessage | function createMessage(status) {
var message = [];
message.push(broadcastIdentifier);
message.push(compabilityVersion);
message.push(netId);
message.push(id);
message.push(name);
message.push(self.port);
message.push(status);
//message.push(mode);
payloadLength = payload.length;
message.push(payloadLength + ':' + payload);
var messageString = message.join(" ");
return new Buffer(messageString);
} | javascript | function createMessage(status) {
var message = [];
message.push(broadcastIdentifier);
message.push(compabilityVersion);
message.push(netId);
message.push(id);
message.push(name);
message.push(self.port);
message.push(status);
//message.push(mode);
payloadLength = payload.length;
message.push(payloadLength + ':' + payload);
var messageString = message.join(" ");
return new Buffer(messageString);
} | [
"function",
"createMessage",
"(",
"status",
")",
"{",
"var",
"message",
"=",
"[",
"]",
";",
"message",
".",
"push",
"(",
"broadcastIdentifier",
")",
";",
"message",
".",
"push",
"(",
"compabilityVersion",
")",
";",
"message",
".",
"push",
"(",
"netId",
")",
";",
"message",
".",
"push",
"(",
"id",
")",
";",
"message",
".",
"push",
"(",
"name",
")",
";",
"message",
".",
"push",
"(",
"self",
".",
"port",
")",
";",
"message",
".",
"push",
"(",
"status",
")",
";",
"//message.push(mode);",
"payloadLength",
"=",
"payload",
".",
"length",
";",
"message",
".",
"push",
"(",
"payloadLength",
"+",
"':'",
"+",
"payload",
")",
";",
"var",
"messageString",
"=",
"message",
".",
"join",
"(",
"\" \"",
")",
";",
"return",
"new",
"Buffer",
"(",
"messageString",
")",
";",
"}"
] | Creates the broadcast string, and returns a buffer | [
"Creates",
"the",
"broadcast",
"string",
"and",
"returns",
"a",
"buffer"
] | 9a2c9a355a885f68cbbf21cb170d3763abb0f458 | https://github.com/camme/zonar/blob/9a2c9a355a885f68cbbf21cb170d3763abb0f458/lib/zonar.js#L487-L506 |
48,059 | eblanshey/safenet | src/request.js | Request | function Request(Safe, uri, method) {
if (!this)
return new Request(Safe, uri, method);
this.Safe = Safe;
this.uri = uri;
this.method = method;
this._needAuth = false;
this._returnMeta = false;
} | javascript | function Request(Safe, uri, method) {
if (!this)
return new Request(Safe, uri, method);
this.Safe = Safe;
this.uri = uri;
this.method = method;
this._needAuth = false;
this._returnMeta = false;
} | [
"function",
"Request",
"(",
"Safe",
",",
"uri",
",",
"method",
")",
"{",
"if",
"(",
"!",
"this",
")",
"return",
"new",
"Request",
"(",
"Safe",
",",
"uri",
",",
"method",
")",
";",
"this",
".",
"Safe",
"=",
"Safe",
";",
"this",
".",
"uri",
"=",
"uri",
";",
"this",
".",
"method",
"=",
"method",
";",
"this",
".",
"_needAuth",
"=",
"false",
";",
"this",
".",
"_returnMeta",
"=",
"false",
";",
"}"
] | The main function for creating new Requests to SAFE
@param Safe
@param uri
@param method
@returns {Request}
@constructor | [
"The",
"main",
"function",
"for",
"creating",
"new",
"Requests",
"to",
"SAFE"
] | 8438251bf0999b43f39c231df299b05d01dd4618 | https://github.com/eblanshey/safenet/blob/8438251bf0999b43f39c231df299b05d01dd4618/src/request.js#L47-L56 |
48,060 | eblanshey/safenet | src/request.js | prepareResponse | function prepareResponse(response) {
Safe.log('Received response: ', response);
return response.text().then(function(text) {
// If we get a 2xx...
Safe.log('Launcher returned status '+response.status);
if (response.ok) {
// If not an authorized request, or not encrypted, no decryption necessary
if (!this._needAuth || doNotDecrypt.indexOf(text) > -1)
var body = utils.parseJson(text);
// Otherwise, decrypt response
else
var body = utils.decrypt(text, this.Safe.getAuth('symNonce'), this.Safe.getAuth('symKey'));
// Lastly, if any meta data was requested (e.g. the headers), then return an object
if (this._returnMeta) {
return {body: body, meta: response.headers.entries()};
} else {
// No need to return 'OK' for responses that return that.
return (typeof body === 'string' && body.toUpperCase() === 'OK') ? undefined : body;
}
} else {
// If authentication was requested, then decrypt the error message received.
if (this._needAuth && doNotDecrypt.indexOf(text) === -1) {
var message = utils.decrypt(text, this.Safe.getAuth('symNonce'), this.Safe.getAuth('symKey')),
parsed = parseSafeMessage(message, response.status);
// Throw a "launcher" error type, which is an error from the launcher.
throw new SafeError('launcher', parsed.message, parsed.status, response);
} else {
// If no message received, it's a standard http response error
var parsed = parseSafeMessage(utils.parseJson(text), response.status);
throw new SafeError('http', parsed.message, parsed.status, response);
}
}
}.bind(this));
} | javascript | function prepareResponse(response) {
Safe.log('Received response: ', response);
return response.text().then(function(text) {
// If we get a 2xx...
Safe.log('Launcher returned status '+response.status);
if (response.ok) {
// If not an authorized request, or not encrypted, no decryption necessary
if (!this._needAuth || doNotDecrypt.indexOf(text) > -1)
var body = utils.parseJson(text);
// Otherwise, decrypt response
else
var body = utils.decrypt(text, this.Safe.getAuth('symNonce'), this.Safe.getAuth('symKey'));
// Lastly, if any meta data was requested (e.g. the headers), then return an object
if (this._returnMeta) {
return {body: body, meta: response.headers.entries()};
} else {
// No need to return 'OK' for responses that return that.
return (typeof body === 'string' && body.toUpperCase() === 'OK') ? undefined : body;
}
} else {
// If authentication was requested, then decrypt the error message received.
if (this._needAuth && doNotDecrypt.indexOf(text) === -1) {
var message = utils.decrypt(text, this.Safe.getAuth('symNonce'), this.Safe.getAuth('symKey')),
parsed = parseSafeMessage(message, response.status);
// Throw a "launcher" error type, which is an error from the launcher.
throw new SafeError('launcher', parsed.message, parsed.status, response);
} else {
// If no message received, it's a standard http response error
var parsed = parseSafeMessage(utils.parseJson(text), response.status);
throw new SafeError('http', parsed.message, parsed.status, response);
}
}
}.bind(this));
} | [
"function",
"prepareResponse",
"(",
"response",
")",
"{",
"Safe",
".",
"log",
"(",
"'Received response: '",
",",
"response",
")",
";",
"return",
"response",
".",
"text",
"(",
")",
".",
"then",
"(",
"function",
"(",
"text",
")",
"{",
"// If we get a 2xx...",
"Safe",
".",
"log",
"(",
"'Launcher returned status '",
"+",
"response",
".",
"status",
")",
";",
"if",
"(",
"response",
".",
"ok",
")",
"{",
"// If not an authorized request, or not encrypted, no decryption necessary",
"if",
"(",
"!",
"this",
".",
"_needAuth",
"||",
"doNotDecrypt",
".",
"indexOf",
"(",
"text",
")",
">",
"-",
"1",
")",
"var",
"body",
"=",
"utils",
".",
"parseJson",
"(",
"text",
")",
";",
"// Otherwise, decrypt response",
"else",
"var",
"body",
"=",
"utils",
".",
"decrypt",
"(",
"text",
",",
"this",
".",
"Safe",
".",
"getAuth",
"(",
"'symNonce'",
")",
",",
"this",
".",
"Safe",
".",
"getAuth",
"(",
"'symKey'",
")",
")",
";",
"// Lastly, if any meta data was requested (e.g. the headers), then return an object",
"if",
"(",
"this",
".",
"_returnMeta",
")",
"{",
"return",
"{",
"body",
":",
"body",
",",
"meta",
":",
"response",
".",
"headers",
".",
"entries",
"(",
")",
"}",
";",
"}",
"else",
"{",
"// No need to return 'OK' for responses that return that.",
"return",
"(",
"typeof",
"body",
"===",
"'string'",
"&&",
"body",
".",
"toUpperCase",
"(",
")",
"===",
"'OK'",
")",
"?",
"undefined",
":",
"body",
";",
"}",
"}",
"else",
"{",
"// If authentication was requested, then decrypt the error message received.",
"if",
"(",
"this",
".",
"_needAuth",
"&&",
"doNotDecrypt",
".",
"indexOf",
"(",
"text",
")",
"===",
"-",
"1",
")",
"{",
"var",
"message",
"=",
"utils",
".",
"decrypt",
"(",
"text",
",",
"this",
".",
"Safe",
".",
"getAuth",
"(",
"'symNonce'",
")",
",",
"this",
".",
"Safe",
".",
"getAuth",
"(",
"'symKey'",
")",
")",
",",
"parsed",
"=",
"parseSafeMessage",
"(",
"message",
",",
"response",
".",
"status",
")",
";",
"// Throw a \"launcher\" error type, which is an error from the launcher.",
"throw",
"new",
"SafeError",
"(",
"'launcher'",
",",
"parsed",
".",
"message",
",",
"parsed",
".",
"status",
",",
"response",
")",
";",
"}",
"else",
"{",
"// If no message received, it's a standard http response error",
"var",
"parsed",
"=",
"parseSafeMessage",
"(",
"utils",
".",
"parseJson",
"(",
"text",
")",
",",
"response",
".",
"status",
")",
";",
"throw",
"new",
"SafeError",
"(",
"'http'",
",",
"parsed",
".",
"message",
",",
"parsed",
".",
"status",
",",
"response",
")",
";",
"}",
"}",
"}",
".",
"bind",
"(",
"this",
")",
")",
";",
"}"
] | If request was with auth token, returned data is encrypted, otherwise it's plain ol' json | [
"If",
"request",
"was",
"with",
"auth",
"token",
"returned",
"data",
"is",
"encrypted",
"otherwise",
"it",
"s",
"plain",
"ol",
"json"
] | 8438251bf0999b43f39c231df299b05d01dd4618 | https://github.com/eblanshey/safenet/blob/8438251bf0999b43f39c231df299b05d01dd4618/src/request.js#L130-L166 |
48,061 | eblanshey/safenet | src/request.js | parseSafeMessage | function parseSafeMessage(message, status) {
if (typeof message === 'object') {
return {status: message.errorCode, message: message.description};
} else {
return {status: status, message: message};
}
} | javascript | function parseSafeMessage(message, status) {
if (typeof message === 'object') {
return {status: message.errorCode, message: message.description};
} else {
return {status: status, message: message};
}
} | [
"function",
"parseSafeMessage",
"(",
"message",
",",
"status",
")",
"{",
"if",
"(",
"typeof",
"message",
"===",
"'object'",
")",
"{",
"return",
"{",
"status",
":",
"message",
".",
"errorCode",
",",
"message",
":",
"message",
".",
"description",
"}",
";",
"}",
"else",
"{",
"return",
"{",
"status",
":",
"status",
",",
"message",
":",
"message",
"}",
";",
"}",
"}"
] | Sometimes the message returns is an object with a 'description' and 'errorCode' property
@param message | [
"Sometimes",
"the",
"message",
"returns",
"is",
"an",
"object",
"with",
"a",
"description",
"and",
"errorCode",
"property"
] | 8438251bf0999b43f39c231df299b05d01dd4618 | https://github.com/eblanshey/safenet/blob/8438251bf0999b43f39c231df299b05d01dd4618/src/request.js#L214-L220 |
48,062 | recidive/prana | prana.js | function(next) {
if (!extension[type] || typeof extension[type] !== 'function') {
return next();
}
// Invoke type hook implemetation.
extension[type](result, function(error, newItems) {
if (error) {
return next(error);
}
utils.extend(result, newItems || {});
next();
});
} | javascript | function(next) {
if (!extension[type] || typeof extension[type] !== 'function') {
return next();
}
// Invoke type hook implemetation.
extension[type](result, function(error, newItems) {
if (error) {
return next(error);
}
utils.extend(result, newItems || {});
next();
});
} | [
"function",
"(",
"next",
")",
"{",
"if",
"(",
"!",
"extension",
"[",
"type",
"]",
"||",
"typeof",
"extension",
"[",
"type",
"]",
"!==",
"'function'",
")",
"{",
"return",
"next",
"(",
")",
";",
"}",
"// Invoke type hook implemetation.",
"extension",
"[",
"type",
"]",
"(",
"result",
",",
"function",
"(",
"error",
",",
"newItems",
")",
"{",
"if",
"(",
"error",
")",
"{",
"return",
"next",
"(",
"error",
")",
";",
"}",
"utils",
".",
"extend",
"(",
"result",
",",
"newItems",
"||",
"{",
"}",
")",
";",
"next",
"(",
")",
";",
"}",
")",
";",
"}"
] | The callback that will receive and process. | [
"The",
"callback",
"that",
"will",
"receive",
"and",
"process",
"."
] | e2900c01d3c8ea73bbb8f8f4155cf76ad3c95b63 | https://github.com/recidive/prana/blob/e2900c01d3c8ea73bbb8f8f4155cf76ad3c95b63/prana.js#L320-L335 |
|
48,063 | jhermsmeier/node-chs | lib/chs.js | CHS | function CHS( cylinder, head, sector ) {
if( !(this instanceof CHS) )
return new CHS( cylinder, head, sector )
if( Buffer.isBuffer( cylinder ) )
return CHS.fromBuffer( cylinder )
/** @type {Number} Cylinder */
this.cylinder = cylinder & 0x03FF
/** @type {Number} Head */
this.head = head & 0xFF
/** @type {Number} Sector */
this.sector = sector & 0x3F
} | javascript | function CHS( cylinder, head, sector ) {
if( !(this instanceof CHS) )
return new CHS( cylinder, head, sector )
if( Buffer.isBuffer( cylinder ) )
return CHS.fromBuffer( cylinder )
/** @type {Number} Cylinder */
this.cylinder = cylinder & 0x03FF
/** @type {Number} Head */
this.head = head & 0xFF
/** @type {Number} Sector */
this.sector = sector & 0x3F
} | [
"function",
"CHS",
"(",
"cylinder",
",",
"head",
",",
"sector",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"CHS",
")",
")",
"return",
"new",
"CHS",
"(",
"cylinder",
",",
"head",
",",
"sector",
")",
"if",
"(",
"Buffer",
".",
"isBuffer",
"(",
"cylinder",
")",
")",
"return",
"CHS",
".",
"fromBuffer",
"(",
"cylinder",
")",
"/** @type {Number} Cylinder */",
"this",
".",
"cylinder",
"=",
"cylinder",
"&",
"0x03FF",
"/** @type {Number} Head */",
"this",
".",
"head",
"=",
"head",
"&",
"0xFF",
"/** @type {Number} Sector */",
"this",
".",
"sector",
"=",
"sector",
"&",
"0x3F",
"}"
] | Cylinder-Head-Sector Address
@constructor
@param {(Number|Buffer)} [cylinder=1023]
@param {Number} [head=254]
@param {Number} [sector=63] | [
"Cylinder",
"-",
"Head",
"-",
"Sector",
"Address"
] | f6fd45d01beb5e19890c287e206ba75ff4e18084 | https://github.com/jhermsmeier/node-chs/blob/f6fd45d01beb5e19890c287e206ba75ff4e18084/lib/chs.js#L8-L23 |
48,064 | jhermsmeier/node-chs | lib/chs.js | function( target ) {
target.cylinder = this.cylinder
target.head = this.head
target.sector = this.sector
return target
} | javascript | function( target ) {
target.cylinder = this.cylinder
target.head = this.head
target.sector = this.sector
return target
} | [
"function",
"(",
"target",
")",
"{",
"target",
".",
"cylinder",
"=",
"this",
".",
"cylinder",
"target",
".",
"head",
"=",
"this",
".",
"head",
"target",
".",
"sector",
"=",
"this",
".",
"sector",
"return",
"target",
"}"
] | Copy this address to a target address
@param {CHS} target
@return {CHS} | [
"Copy",
"this",
"address",
"to",
"a",
"target",
"address"
] | f6fd45d01beb5e19890c287e206ba75ff4e18084 | https://github.com/jhermsmeier/node-chs/blob/f6fd45d01beb5e19890c287e206ba75ff4e18084/lib/chs.js#L108-L116 |
|
48,065 | jhermsmeier/node-chs | lib/chs.js | function( buffer, offset ) {
if( !Buffer.isBuffer( buffer ) )
throw new TypeError( 'Value must be a buffer' )
offset = offset || 0
return this.fromNumber( buffer.readUIntLE( offset, 3 ) )
} | javascript | function( buffer, offset ) {
if( !Buffer.isBuffer( buffer ) )
throw new TypeError( 'Value must be a buffer' )
offset = offset || 0
return this.fromNumber( buffer.readUIntLE( offset, 3 ) )
} | [
"function",
"(",
"buffer",
",",
"offset",
")",
"{",
"if",
"(",
"!",
"Buffer",
".",
"isBuffer",
"(",
"buffer",
")",
")",
"throw",
"new",
"TypeError",
"(",
"'Value must be a buffer'",
")",
"offset",
"=",
"offset",
"||",
"0",
"return",
"this",
".",
"fromNumber",
"(",
"buffer",
".",
"readUIntLE",
"(",
"offset",
",",
"3",
")",
")",
"}"
] | Parse a given Buffer
@param {Buffer} buffer
@param {Number} [offset=0]
@return {CHS} | [
"Parse",
"a",
"given",
"Buffer"
] | f6fd45d01beb5e19890c287e206ba75ff4e18084 | https://github.com/jhermsmeier/node-chs/blob/f6fd45d01beb5e19890c287e206ba75ff4e18084/lib/chs.js#L124-L133 |
|
48,066 | rtm/upward | src/Ify.js | compose | function compose(...fns) {
return function(x) {
return fns.reduceRight((result, val) => val(result), x);
};
} | javascript | function compose(...fns) {
return function(x) {
return fns.reduceRight((result, val) => val(result), x);
};
} | [
"function",
"compose",
"(",
"...",
"fns",
")",
"{",
"return",
"function",
"(",
"x",
")",
"{",
"return",
"fns",
".",
"reduceRight",
"(",
"(",
"result",
",",
"val",
")",
"=>",
"val",
"(",
"result",
")",
",",
"x",
")",
";",
"}",
";",
"}"
] | Compose functions, calling from right to left. | [
"Compose",
"functions",
"calling",
"from",
"right",
"to",
"left",
"."
] | 82495c34f70c9a4336a3b34cc6781e5662324c03 | https://github.com/rtm/upward/blob/82495c34f70c9a4336a3b34cc6781e5662324c03/src/Ify.js#L13-L17 |
48,067 | rtm/upward | src/Ify.js | tickify | function tickify(fn, {delay} = {}) {
delay = delay || 10;
return function() {
return setTimeout(() => fn.apply(this, arguments), delay);
};
} | javascript | function tickify(fn, {delay} = {}) {
delay = delay || 10;
return function() {
return setTimeout(() => fn.apply(this, arguments), delay);
};
} | [
"function",
"tickify",
"(",
"fn",
",",
"{",
"delay",
"}",
"=",
"{",
"}",
")",
"{",
"delay",
"=",
"delay",
"||",
"10",
";",
"return",
"function",
"(",
")",
"{",
"return",
"setTimeout",
"(",
"(",
")",
"=>",
"fn",
".",
"apply",
"(",
"this",
",",
"arguments",
")",
",",
"delay",
")",
";",
"}",
";",
"}"
] | Create a function which runs on next tick. | [
"Create",
"a",
"function",
"which",
"runs",
"on",
"next",
"tick",
"."
] | 82495c34f70c9a4336a3b34cc6781e5662324c03 | https://github.com/rtm/upward/blob/82495c34f70c9a4336a3b34cc6781e5662324c03/src/Ify.js#L20-L25 |
48,068 | rtm/upward | src/Ify.js | memoify | function memoify(fn, {hash, cache} = {}) {
hash = hash || identify;
cache = cache = {};
function memoified(...args) {
var key = hash(...args);
return key in cache ? cache[key] : cache[key] = fn.call(this, ...args);
}
memoified.clear = () => cache = {};
return memoified;
} | javascript | function memoify(fn, {hash, cache} = {}) {
hash = hash || identify;
cache = cache = {};
function memoified(...args) {
var key = hash(...args);
return key in cache ? cache[key] : cache[key] = fn.call(this, ...args);
}
memoified.clear = () => cache = {};
return memoified;
} | [
"function",
"memoify",
"(",
"fn",
",",
"{",
"hash",
",",
"cache",
"}",
"=",
"{",
"}",
")",
"{",
"hash",
"=",
"hash",
"||",
"identify",
";",
"cache",
"=",
"cache",
"=",
"{",
"}",
";",
"function",
"memoified",
"(",
"...",
"args",
")",
"{",
"var",
"key",
"=",
"hash",
"(",
"...",
"args",
")",
";",
"return",
"key",
"in",
"cache",
"?",
"cache",
"[",
"key",
"]",
":",
"cache",
"[",
"key",
"]",
"=",
"fn",
".",
"call",
"(",
"this",
",",
"...",
"args",
")",
";",
"}",
"memoified",
".",
"clear",
"=",
"(",
")",
"=>",
"cache",
"=",
"{",
"}",
";",
"return",
"memoified",
";",
"}"
] | Make a function which memozies its result. | [
"Make",
"a",
"function",
"which",
"memozies",
"its",
"result",
"."
] | 82495c34f70c9a4336a3b34cc6781e5662324c03 | https://github.com/rtm/upward/blob/82495c34f70c9a4336a3b34cc6781e5662324c03/src/Ify.js#L58-L67 |
48,069 | rtm/upward | src/Ify.js | logify | function logify(fn) {
return function() {
console.log("entering", fn.name);
var ret = fn.apply(this, arguments);
console.log("leaving", fn.name);
return ret;
};
} | javascript | function logify(fn) {
return function() {
console.log("entering", fn.name);
var ret = fn.apply(this, arguments);
console.log("leaving", fn.name);
return ret;
};
} | [
"function",
"logify",
"(",
"fn",
")",
"{",
"return",
"function",
"(",
")",
"{",
"console",
".",
"log",
"(",
"\"entering\"",
",",
"fn",
".",
"name",
")",
";",
"var",
"ret",
"=",
"fn",
".",
"apply",
"(",
"this",
",",
"arguments",
")",
";",
"console",
".",
"log",
"(",
"\"leaving\"",
",",
"fn",
".",
"name",
")",
";",
"return",
"ret",
";",
"}",
";",
"}"
] | Make a version of the function which logs entry and exit. | [
"Make",
"a",
"version",
"of",
"the",
"function",
"which",
"logs",
"entry",
"and",
"exit",
"."
] | 82495c34f70c9a4336a3b34cc6781e5662324c03 | https://github.com/rtm/upward/blob/82495c34f70c9a4336a3b34cc6781e5662324c03/src/Ify.js#L103-L110 |
48,070 | rtm/upward | src/Ify.js | onceify | function onceify(f) {
var ran, ret;
return function() {
return ran ? ret : (ran=true, ret=f.apply(this,arguments));
};
} | javascript | function onceify(f) {
var ran, ret;
return function() {
return ran ? ret : (ran=true, ret=f.apply(this,arguments));
};
} | [
"function",
"onceify",
"(",
"f",
")",
"{",
"var",
"ran",
",",
"ret",
";",
"return",
"function",
"(",
")",
"{",
"return",
"ran",
"?",
"ret",
":",
"(",
"ran",
"=",
"true",
",",
"ret",
"=",
"f",
".",
"apply",
"(",
"this",
",",
"arguments",
")",
")",
";",
"}",
";",
"}"
] | Make create a version of a function which runs just once on first call. Returns same value on succeeding calls. | [
"Make",
"create",
"a",
"version",
"of",
"a",
"function",
"which",
"runs",
"just",
"once",
"on",
"first",
"call",
".",
"Returns",
"same",
"value",
"on",
"succeeding",
"calls",
"."
] | 82495c34f70c9a4336a3b34cc6781e5662324c03 | https://github.com/rtm/upward/blob/82495c34f70c9a4336a3b34cc6781e5662324c03/src/Ify.js#L126-L131 |
48,071 | rtm/upward | src/Ify.js | wrapify | function wrapify(fn, before = noop, after = noop) {
return function(...args) {
before.call(this);
var ret = fn.call(this, ...args);
after.call(this);
return ret;
};
} | javascript | function wrapify(fn, before = noop, after = noop) {
return function(...args) {
before.call(this);
var ret = fn.call(this, ...args);
after.call(this);
return ret;
};
} | [
"function",
"wrapify",
"(",
"fn",
",",
"before",
"=",
"noop",
",",
"after",
"=",
"noop",
")",
"{",
"return",
"function",
"(",
"...",
"args",
")",
"{",
"before",
".",
"call",
"(",
"this",
")",
";",
"var",
"ret",
"=",
"fn",
".",
"call",
"(",
"this",
",",
"...",
"args",
")",
";",
"after",
".",
"call",
"(",
"this",
")",
";",
"return",
"ret",
";",
"}",
";",
"}"
] | Create a function with a prelude and postlude. | [
"Create",
"a",
"function",
"with",
"a",
"prelude",
"and",
"postlude",
"."
] | 82495c34f70c9a4336a3b34cc6781e5662324c03 | https://github.com/rtm/upward/blob/82495c34f70c9a4336a3b34cc6781e5662324c03/src/Ify.js#L148-L155 |
48,072 | rtm/upward | src/Ify.js | parseBody | function parseBody(fn){
//get arguments to function as array of strings
var body=fn.body=fn.body|| //cache result in `body` property of function
fn.toString() //get string version of function
.replace(/\/\/.*$|\/\*[\s\S]*?\*\//mg, '') //strip comments
.replace(/^\s*$/mg, '') // kill empty lines
.replace(/^.*?\)\s*\{\s*(return)?\s*/, '') // kill argument list and leading curly
.replace(/\s*\}\s*$/, '') // kill trailing curly
;
return body; // or fn?
} | javascript | function parseBody(fn){
//get arguments to function as array of strings
var body=fn.body=fn.body|| //cache result in `body` property of function
fn.toString() //get string version of function
.replace(/\/\/.*$|\/\*[\s\S]*?\*\//mg, '') //strip comments
.replace(/^\s*$/mg, '') // kill empty lines
.replace(/^.*?\)\s*\{\s*(return)?\s*/, '') // kill argument list and leading curly
.replace(/\s*\}\s*$/, '') // kill trailing curly
;
return body; // or fn?
} | [
"function",
"parseBody",
"(",
"fn",
")",
"{",
"//get arguments to function as array of strings",
"var",
"body",
"=",
"fn",
".",
"body",
"=",
"fn",
".",
"body",
"||",
"//cache result in `body` property of function",
"fn",
".",
"toString",
"(",
")",
"//get string version of function",
".",
"replace",
"(",
"/",
"\\/\\/.*$|\\/\\*[\\s\\S]*?\\*\\/",
"/",
"mg",
",",
"''",
")",
"//strip comments",
".",
"replace",
"(",
"/",
"^\\s*$",
"/",
"mg",
",",
"''",
")",
"// kill empty lines",
".",
"replace",
"(",
"/",
"^.*?\\)\\s*\\{\\s*(return)?\\s*",
"/",
",",
"''",
")",
"// kill argument list and leading curly",
".",
"replace",
"(",
"/",
"\\s*\\}\\s*$",
"/",
",",
"''",
")",
"// kill trailing curly",
";",
"return",
"body",
";",
"// or fn?",
"}"
] | Return function body. | [
"Return",
"function",
"body",
"."
] | 82495c34f70c9a4336a3b34cc6781e5662324c03 | https://github.com/rtm/upward/blob/82495c34f70c9a4336a3b34cc6781e5662324c03/src/Ify.js#L182-L192 |
48,073 | gwicke/nodegrind | nodegrind.js | convertProfNode | function convertProfNode (node) {
var res = {
functionName: node.functionName,
lineNumber: node.lineNumber,
callUID: node.callUid,
hitCount: node.selfSamplesCount,
url: node.scriptName,
children: []
};
for (var i = 0; i < node.childrenCount; i++) {
res.children.push(convertProfNode(node.getChild(i)));
}
return res;
} | javascript | function convertProfNode (node) {
var res = {
functionName: node.functionName,
lineNumber: node.lineNumber,
callUID: node.callUid,
hitCount: node.selfSamplesCount,
url: node.scriptName,
children: []
};
for (var i = 0; i < node.childrenCount; i++) {
res.children.push(convertProfNode(node.getChild(i)));
}
return res;
} | [
"function",
"convertProfNode",
"(",
"node",
")",
"{",
"var",
"res",
"=",
"{",
"functionName",
":",
"node",
".",
"functionName",
",",
"lineNumber",
":",
"node",
".",
"lineNumber",
",",
"callUID",
":",
"node",
".",
"callUid",
",",
"hitCount",
":",
"node",
".",
"selfSamplesCount",
",",
"url",
":",
"node",
".",
"scriptName",
",",
"children",
":",
"[",
"]",
"}",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"node",
".",
"childrenCount",
";",
"i",
"++",
")",
"{",
"res",
".",
"children",
".",
"push",
"(",
"convertProfNode",
"(",
"node",
".",
"getChild",
"(",
"i",
")",
")",
")",
";",
"}",
"return",
"res",
";",
"}"
] | Simplistic V8 CPU profiler wrapper, WIP
Usage:
npm install v8-profiler
var profiler = require('./profiler');
profiler.start('parse');
<some computation>
var prof = profiler.stop('parse');
fs.writeFileSync('parse.cpuprofile', JSON.stringify(prof));
Now you can load parse.cpuprofile into chrome, or (much nicer) convert it
to calltree format using https://github.com/phleet/chrome2calltree:
chrome2calltree -i parse.cpuprofile -o parse.calltree
kcachegrind parse.calltree
Then use kcachegrind to visualize the callgrind file.
V8 prof node structure:
{ childrenCount: 3,
callUid: 3550382514,
selfSamplesCount: 0,
totalSamplesCount: 7706,
selfTime: 0,
totalTime: 7960.497092032271,
lineNumber: 0,
scriptName: '',
functionName: '(root)',
getChild: [Function: getChild] }
sample cpuprofile (from Chrome):
{
"functionName":"(root)",
"scriptId":"0",
"url":"",
"lineNumber":0,
"columnNumber":0,
"hitCount":0,
"callUID":4142747341,
"children":[{"functionName":"(program)","scriptId":"0","url":"","lineNumber":0,"columnNumber":0,"hitCount":3,"callUID":912934196,"children":[],"deoptReason":"","id":2},{"functionName":"(idle)","scriptId":"0","url":"","lineNumber":0,"columnNumber":0,"hitCount":27741,"callUID":176593847,"children":[],"deoptReason":"","id":3}],"deoptReason":"","id":1} | [
"Simplistic",
"V8",
"CPU",
"profiler",
"wrapper",
"WIP"
] | de40c14eda8f81c345519a805e9e3c3a5ebc4e61 | https://github.com/gwicke/nodegrind/blob/de40c14eda8f81c345519a805e9e3c3a5ebc4e61/nodegrind.js#L55-L68 |
48,074 | gwicke/nodegrind | nodegrind.js | writeProfile | function writeProfile() {
var format;
if (/\.cpuprofile$/.test(argv.o)) {
format = 'cpuprofile';
}
var prof = stopCPU('global', format);
fs.writeFileSync(argv.o, prof);
var fname = JSON.stringify(argv.o);
console.warn('Profile written to', fname + '\nTry `kcachegrind', fname + '`');
process.removeAllListeners('exit');
process.exit(0);
} | javascript | function writeProfile() {
var format;
if (/\.cpuprofile$/.test(argv.o)) {
format = 'cpuprofile';
}
var prof = stopCPU('global', format);
fs.writeFileSync(argv.o, prof);
var fname = JSON.stringify(argv.o);
console.warn('Profile written to', fname + '\nTry `kcachegrind', fname + '`');
process.removeAllListeners('exit');
process.exit(0);
} | [
"function",
"writeProfile",
"(",
")",
"{",
"var",
"format",
";",
"if",
"(",
"/",
"\\.cpuprofile$",
"/",
".",
"test",
"(",
"argv",
".",
"o",
")",
")",
"{",
"format",
"=",
"'cpuprofile'",
";",
"}",
"var",
"prof",
"=",
"stopCPU",
"(",
"'global'",
",",
"format",
")",
";",
"fs",
".",
"writeFileSync",
"(",
"argv",
".",
"o",
",",
"prof",
")",
";",
"var",
"fname",
"=",
"JSON",
".",
"stringify",
"(",
"argv",
".",
"o",
")",
";",
"console",
".",
"warn",
"(",
"'Profile written to'",
",",
"fname",
"+",
"'\\nTry `kcachegrind'",
",",
"fname",
"+",
"'`'",
")",
";",
"process",
".",
"removeAllListeners",
"(",
"'exit'",
")",
";",
"process",
".",
"exit",
"(",
"0",
")",
";",
"}"
] | Stop profiling in an exit handler so that we properly handle async code | [
"Stop",
"profiling",
"in",
"an",
"exit",
"handler",
"so",
"that",
"we",
"properly",
"handle",
"async",
"code"
] | de40c14eda8f81c345519a805e9e3c3a5ebc4e61 | https://github.com/gwicke/nodegrind/blob/de40c14eda8f81c345519a805e9e3c3a5ebc4e61/nodegrind.js#L115-L127 |
48,075 | intervolga/bembh-loader | lib/walk-bemjson.js | walkBemJson | function walkBemJson(bemJson, cb) {
let result;
if (Array.isArray(bemJson)) {
result = [];
bemJson.forEach((childBemJson, i) => {
result[i] = walkBemJson(childBemJson, cb);
});
} else if (bemJson instanceof Object) {
result = {};
Object.keys(bemJson).forEach((key) => {
result[key] = walkBemJson(bemJson[key], cb);
});
} else if (typeof bemJson === 'string') {
result = cb(bemJson);
}
return result;
} | javascript | function walkBemJson(bemJson, cb) {
let result;
if (Array.isArray(bemJson)) {
result = [];
bemJson.forEach((childBemJson, i) => {
result[i] = walkBemJson(childBemJson, cb);
});
} else if (bemJson instanceof Object) {
result = {};
Object.keys(bemJson).forEach((key) => {
result[key] = walkBemJson(bemJson[key], cb);
});
} else if (typeof bemJson === 'string') {
result = cb(bemJson);
}
return result;
} | [
"function",
"walkBemJson",
"(",
"bemJson",
",",
"cb",
")",
"{",
"let",
"result",
";",
"if",
"(",
"Array",
".",
"isArray",
"(",
"bemJson",
")",
")",
"{",
"result",
"=",
"[",
"]",
";",
"bemJson",
".",
"forEach",
"(",
"(",
"childBemJson",
",",
"i",
")",
"=>",
"{",
"result",
"[",
"i",
"]",
"=",
"walkBemJson",
"(",
"childBemJson",
",",
"cb",
")",
";",
"}",
")",
";",
"}",
"else",
"if",
"(",
"bemJson",
"instanceof",
"Object",
")",
"{",
"result",
"=",
"{",
"}",
";",
"Object",
".",
"keys",
"(",
"bemJson",
")",
".",
"forEach",
"(",
"(",
"key",
")",
"=>",
"{",
"result",
"[",
"key",
"]",
"=",
"walkBemJson",
"(",
"bemJson",
"[",
"key",
"]",
",",
"cb",
")",
";",
"}",
")",
";",
"}",
"else",
"if",
"(",
"typeof",
"bemJson",
"===",
"'string'",
")",
"{",
"result",
"=",
"cb",
"(",
"bemJson",
")",
";",
"}",
"return",
"result",
";",
"}"
] | Walks thru BemJson recursively and invokes callback on each string value
@param {Object|Array|String} bemJson
@param {Function} cb
@return {Object|Array|String} | [
"Walks",
"thru",
"BemJson",
"recursively",
"and",
"invokes",
"callback",
"on",
"each",
"string",
"value"
] | 24d599ccdb395fa2d9f70a205676134e48fc4f12 | https://github.com/intervolga/bembh-loader/blob/24d599ccdb395fa2d9f70a205676134e48fc4f12/lib/walk-bemjson.js#L8-L26 |
48,076 | nicktindall/cyclon.p2p-rtc-client | lib/AdapterJsRTCObjectFactory.js | AdapterJsRTCObjectFactory | function AdapterJsRTCObjectFactory(logger) {
Utils.checkArguments(arguments, 1);
this.createIceServers = function (urls, username, password) {
if (typeof(createIceServers) !== "undefined") {
return createIceServers(urls, username, password);
}
else {
logger.error("adapter.js not present or unsupported browser!");
return null;
}
};
this.createRTCSessionDescription = function (sessionDescriptionString) {
if (typeof(RTCSessionDescription) !== "undefined") {
return new RTCSessionDescription(sessionDescriptionString);
}
else {
logger.error("adapter.js not present or unsupported browser!");
return null;
}
};
this.createRTCIceCandidate = function (rtcIceCandidateString) {
if (typeof(RTCIceCandidate) !== "undefined") {
return new RTCIceCandidate(rtcIceCandidateString);
}
else {
logger.error("adapter.js not present or unsupported browser!");
return null;
}
};
this.createRTCPeerConnection = function (config) {
if (typeof(RTCPeerConnection) !== "undefined") {
return new RTCPeerConnection(config);
}
else {
logger.error("adapter.js not present or unsupported browser!");
return null;
}
};
} | javascript | function AdapterJsRTCObjectFactory(logger) {
Utils.checkArguments(arguments, 1);
this.createIceServers = function (urls, username, password) {
if (typeof(createIceServers) !== "undefined") {
return createIceServers(urls, username, password);
}
else {
logger.error("adapter.js not present or unsupported browser!");
return null;
}
};
this.createRTCSessionDescription = function (sessionDescriptionString) {
if (typeof(RTCSessionDescription) !== "undefined") {
return new RTCSessionDescription(sessionDescriptionString);
}
else {
logger.error("adapter.js not present or unsupported browser!");
return null;
}
};
this.createRTCIceCandidate = function (rtcIceCandidateString) {
if (typeof(RTCIceCandidate) !== "undefined") {
return new RTCIceCandidate(rtcIceCandidateString);
}
else {
logger.error("adapter.js not present or unsupported browser!");
return null;
}
};
this.createRTCPeerConnection = function (config) {
if (typeof(RTCPeerConnection) !== "undefined") {
return new RTCPeerConnection(config);
}
else {
logger.error("adapter.js not present or unsupported browser!");
return null;
}
};
} | [
"function",
"AdapterJsRTCObjectFactory",
"(",
"logger",
")",
"{",
"Utils",
".",
"checkArguments",
"(",
"arguments",
",",
"1",
")",
";",
"this",
".",
"createIceServers",
"=",
"function",
"(",
"urls",
",",
"username",
",",
"password",
")",
"{",
"if",
"(",
"typeof",
"(",
"createIceServers",
")",
"!==",
"\"undefined\"",
")",
"{",
"return",
"createIceServers",
"(",
"urls",
",",
"username",
",",
"password",
")",
";",
"}",
"else",
"{",
"logger",
".",
"error",
"(",
"\"adapter.js not present or unsupported browser!\"",
")",
";",
"return",
"null",
";",
"}",
"}",
";",
"this",
".",
"createRTCSessionDescription",
"=",
"function",
"(",
"sessionDescriptionString",
")",
"{",
"if",
"(",
"typeof",
"(",
"RTCSessionDescription",
")",
"!==",
"\"undefined\"",
")",
"{",
"return",
"new",
"RTCSessionDescription",
"(",
"sessionDescriptionString",
")",
";",
"}",
"else",
"{",
"logger",
".",
"error",
"(",
"\"adapter.js not present or unsupported browser!\"",
")",
";",
"return",
"null",
";",
"}",
"}",
";",
"this",
".",
"createRTCIceCandidate",
"=",
"function",
"(",
"rtcIceCandidateString",
")",
"{",
"if",
"(",
"typeof",
"(",
"RTCIceCandidate",
")",
"!==",
"\"undefined\"",
")",
"{",
"return",
"new",
"RTCIceCandidate",
"(",
"rtcIceCandidateString",
")",
";",
"}",
"else",
"{",
"logger",
".",
"error",
"(",
"\"adapter.js not present or unsupported browser!\"",
")",
";",
"return",
"null",
";",
"}",
"}",
";",
"this",
".",
"createRTCPeerConnection",
"=",
"function",
"(",
"config",
")",
"{",
"if",
"(",
"typeof",
"(",
"RTCPeerConnection",
")",
"!==",
"\"undefined\"",
")",
"{",
"return",
"new",
"RTCPeerConnection",
"(",
"config",
")",
";",
"}",
"else",
"{",
"logger",
".",
"error",
"(",
"\"adapter.js not present or unsupported browser!\"",
")",
";",
"return",
"null",
";",
"}",
"}",
";",
"}"
] | An RTC Object factory that works in Firefox and Chrome when adapter.js is present
adapter.js can be downloaded from:
https://github.com/GoogleChrome/webrtc/blob/master/samples/web/js/adapter.js | [
"An",
"RTC",
"Object",
"factory",
"that",
"works",
"in",
"Firefox",
"and",
"Chrome",
"when",
"adapter",
".",
"js",
"is",
"present"
] | eb586ce288a6ad7e1b221280825037e855b03904 | https://github.com/nicktindall/cyclon.p2p-rtc-client/blob/eb586ce288a6ad7e1b221280825037e855b03904/lib/AdapterJsRTCObjectFactory.js#L11-L54 |
48,077 | YYago/summarybuilder | builder.js | onlySmHere | function onlySmHere(jsonFileName,isIndent,outFileName){
if (fs.existsSync(jsonFileName)) {
var fcount = JSON.parse(fs.readFileSync(jsonFileName));
var foooo = [];
if(fs.existsSync('SUMMARY.md')){
fcount = lodash.without(fcount,...haslisted.hasListed('SUMMARY.md'));
}
if (fcount[0] !== undefined) {
for (var i = 0; i < fcount.length; i++) {
var CFpath = fcount[i];
var CFtitle = gH1.getFirstH1(fcount[i],"both");
if ( isIndent == true) {
var prefix = '\ \ ';
var spsign = CFpath.match(/\//g);
if (spsign !== null) {
var spsignCount = spsign.length;
var prefixRep = prefix.repeat(spsignCount);
var foo_item = prefixRep + '* [' + CFtitle + '](' + CFpath + ')';
foooo.push(foo_item);
} else {
var foo_item = '* [' + CFtitle + '](' + CFpath + ')';
foooo.push(foo_item);
}
} else {
var foo_item = '* [' + CFtitle + '](' + CFpath + ')';
foooo.push(foo_item);
}
}
var datas = foooo.join('\n');
fs.writeFile(outFileName, datas, { encoding: 'utf8', flag: 'w' }, function (err) {
if (err) {
throw err;
}
});
console.log(`${chalk.yellow('summarybuilder: ')}`+outFileName+"......ok");
}
}else if(typeof(jsonFileName)=="object"){
var fcount = jsonFileName;
var foooo = [];
if(fs.existsSync('SUMMARY.md')){
fcount = lodash.without(fcount,...haslisted.hasListed('SUMMARY.md'));
}
if (fcount[0] !== undefined) {
for (var i = 0; i < fcount.length; i++) {
var CFpath = fcount[i];
var CFtitle = gH1.getFirstH1(fcount[i],"both");
if ( isIndent == true) {
var prefix = '\ \ ';
var spsign = CFpath.match(/\//g);
if (spsign !== null) {
var spsignCount = spsign.length;
var prefixRep = prefix.repeat(spsignCount);
var foo_item = prefixRep + '* [' + CFtitle + '](' + CFpath + ')';
foooo.push(foo_item);
} else {
var foo_item = '* [' + CFtitle + '](' + CFpath + ')';
foooo.push(foo_item);
}
} else {
var foo_item = '* [' + CFtitle + '](' + CFpath + ')';
foooo.push(foo_item);
}
}
var datas = foooo.join('\n');
fs.writeFile(outFileName, datas, { encoding: 'utf8', flag: 'w' }, function (err) {
if (err) {
throw err;
}
});
console.log(`${chalk.yellow('summarybuilder: ')}`+outFileName+" ....... ok");
}
}else{
console.log(`${chalk.yellow('summarybuilder: ')}`+"No such a file names:"+jsonFileName+'. It is better to be created by the plugin: gulp-filelist.And sure all path of the list in '+jsonFileName+' are existent.');
console.log(`${chalk.yellow('summarybuilder: ')}`+' You can use an array type variable ,or like this: SBer_summary(["a.md","b/a.md"],true,"mySummary.md"). ')
}
} | javascript | function onlySmHere(jsonFileName,isIndent,outFileName){
if (fs.existsSync(jsonFileName)) {
var fcount = JSON.parse(fs.readFileSync(jsonFileName));
var foooo = [];
if(fs.existsSync('SUMMARY.md')){
fcount = lodash.without(fcount,...haslisted.hasListed('SUMMARY.md'));
}
if (fcount[0] !== undefined) {
for (var i = 0; i < fcount.length; i++) {
var CFpath = fcount[i];
var CFtitle = gH1.getFirstH1(fcount[i],"both");
if ( isIndent == true) {
var prefix = '\ \ ';
var spsign = CFpath.match(/\//g);
if (spsign !== null) {
var spsignCount = spsign.length;
var prefixRep = prefix.repeat(spsignCount);
var foo_item = prefixRep + '* [' + CFtitle + '](' + CFpath + ')';
foooo.push(foo_item);
} else {
var foo_item = '* [' + CFtitle + '](' + CFpath + ')';
foooo.push(foo_item);
}
} else {
var foo_item = '* [' + CFtitle + '](' + CFpath + ')';
foooo.push(foo_item);
}
}
var datas = foooo.join('\n');
fs.writeFile(outFileName, datas, { encoding: 'utf8', flag: 'w' }, function (err) {
if (err) {
throw err;
}
});
console.log(`${chalk.yellow('summarybuilder: ')}`+outFileName+"......ok");
}
}else if(typeof(jsonFileName)=="object"){
var fcount = jsonFileName;
var foooo = [];
if(fs.existsSync('SUMMARY.md')){
fcount = lodash.without(fcount,...haslisted.hasListed('SUMMARY.md'));
}
if (fcount[0] !== undefined) {
for (var i = 0; i < fcount.length; i++) {
var CFpath = fcount[i];
var CFtitle = gH1.getFirstH1(fcount[i],"both");
if ( isIndent == true) {
var prefix = '\ \ ';
var spsign = CFpath.match(/\//g);
if (spsign !== null) {
var spsignCount = spsign.length;
var prefixRep = prefix.repeat(spsignCount);
var foo_item = prefixRep + '* [' + CFtitle + '](' + CFpath + ')';
foooo.push(foo_item);
} else {
var foo_item = '* [' + CFtitle + '](' + CFpath + ')';
foooo.push(foo_item);
}
} else {
var foo_item = '* [' + CFtitle + '](' + CFpath + ')';
foooo.push(foo_item);
}
}
var datas = foooo.join('\n');
fs.writeFile(outFileName, datas, { encoding: 'utf8', flag: 'w' }, function (err) {
if (err) {
throw err;
}
});
console.log(`${chalk.yellow('summarybuilder: ')}`+outFileName+" ....... ok");
}
}else{
console.log(`${chalk.yellow('summarybuilder: ')}`+"No such a file names:"+jsonFileName+'. It is better to be created by the plugin: gulp-filelist.And sure all path of the list in '+jsonFileName+' are existent.');
console.log(`${chalk.yellow('summarybuilder: ')}`+' You can use an array type variable ,or like this: SBer_summary(["a.md","b/a.md"],true,"mySummary.md"). ')
}
} | [
"function",
"onlySmHere",
"(",
"jsonFileName",
",",
"isIndent",
",",
"outFileName",
")",
"{",
"if",
"(",
"fs",
".",
"existsSync",
"(",
"jsonFileName",
")",
")",
"{",
"var",
"fcount",
"=",
"JSON",
".",
"parse",
"(",
"fs",
".",
"readFileSync",
"(",
"jsonFileName",
")",
")",
";",
"var",
"foooo",
"=",
"[",
"]",
";",
"if",
"(",
"fs",
".",
"existsSync",
"(",
"'SUMMARY.md'",
")",
")",
"{",
"fcount",
"=",
"lodash",
".",
"without",
"(",
"fcount",
",",
"...",
"haslisted",
".",
"hasListed",
"(",
"'SUMMARY.md'",
")",
")",
";",
"}",
"if",
"(",
"fcount",
"[",
"0",
"]",
"!==",
"undefined",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"fcount",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"CFpath",
"=",
"fcount",
"[",
"i",
"]",
";",
"var",
"CFtitle",
"=",
"gH1",
".",
"getFirstH1",
"(",
"fcount",
"[",
"i",
"]",
",",
"\"both\"",
")",
";",
"if",
"(",
"isIndent",
"==",
"true",
")",
"{",
"var",
"prefix",
"=",
"'\\ \\ '",
";",
"var",
"spsign",
"=",
"CFpath",
".",
"match",
"(",
"/",
"\\/",
"/",
"g",
")",
";",
"if",
"(",
"spsign",
"!==",
"null",
")",
"{",
"var",
"spsignCount",
"=",
"spsign",
".",
"length",
";",
"var",
"prefixRep",
"=",
"prefix",
".",
"repeat",
"(",
"spsignCount",
")",
";",
"var",
"foo_item",
"=",
"prefixRep",
"+",
"'* ['",
"+",
"CFtitle",
"+",
"']('",
"+",
"CFpath",
"+",
"')'",
";",
"foooo",
".",
"push",
"(",
"foo_item",
")",
";",
"}",
"else",
"{",
"var",
"foo_item",
"=",
"'* ['",
"+",
"CFtitle",
"+",
"']('",
"+",
"CFpath",
"+",
"')'",
";",
"foooo",
".",
"push",
"(",
"foo_item",
")",
";",
"}",
"}",
"else",
"{",
"var",
"foo_item",
"=",
"'* ['",
"+",
"CFtitle",
"+",
"']('",
"+",
"CFpath",
"+",
"')'",
";",
"foooo",
".",
"push",
"(",
"foo_item",
")",
";",
"}",
"}",
"var",
"datas",
"=",
"foooo",
".",
"join",
"(",
"'\\n'",
")",
";",
"fs",
".",
"writeFile",
"(",
"outFileName",
",",
"datas",
",",
"{",
"encoding",
":",
"'utf8'",
",",
"flag",
":",
"'w'",
"}",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"throw",
"err",
";",
"}",
"}",
")",
";",
"console",
".",
"log",
"(",
"`",
"${",
"chalk",
".",
"yellow",
"(",
"'summarybuilder: '",
")",
"}",
"`",
"+",
"outFileName",
"+",
"\"......ok\"",
")",
";",
"}",
"}",
"else",
"if",
"(",
"typeof",
"(",
"jsonFileName",
")",
"==",
"\"object\"",
")",
"{",
"var",
"fcount",
"=",
"jsonFileName",
";",
"var",
"foooo",
"=",
"[",
"]",
";",
"if",
"(",
"fs",
".",
"existsSync",
"(",
"'SUMMARY.md'",
")",
")",
"{",
"fcount",
"=",
"lodash",
".",
"without",
"(",
"fcount",
",",
"...",
"haslisted",
".",
"hasListed",
"(",
"'SUMMARY.md'",
")",
")",
";",
"}",
"if",
"(",
"fcount",
"[",
"0",
"]",
"!==",
"undefined",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"fcount",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"CFpath",
"=",
"fcount",
"[",
"i",
"]",
";",
"var",
"CFtitle",
"=",
"gH1",
".",
"getFirstH1",
"(",
"fcount",
"[",
"i",
"]",
",",
"\"both\"",
")",
";",
"if",
"(",
"isIndent",
"==",
"true",
")",
"{",
"var",
"prefix",
"=",
"'\\ \\ '",
";",
"var",
"spsign",
"=",
"CFpath",
".",
"match",
"(",
"/",
"\\/",
"/",
"g",
")",
";",
"if",
"(",
"spsign",
"!==",
"null",
")",
"{",
"var",
"spsignCount",
"=",
"spsign",
".",
"length",
";",
"var",
"prefixRep",
"=",
"prefix",
".",
"repeat",
"(",
"spsignCount",
")",
";",
"var",
"foo_item",
"=",
"prefixRep",
"+",
"'* ['",
"+",
"CFtitle",
"+",
"']('",
"+",
"CFpath",
"+",
"')'",
";",
"foooo",
".",
"push",
"(",
"foo_item",
")",
";",
"}",
"else",
"{",
"var",
"foo_item",
"=",
"'* ['",
"+",
"CFtitle",
"+",
"']('",
"+",
"CFpath",
"+",
"')'",
";",
"foooo",
".",
"push",
"(",
"foo_item",
")",
";",
"}",
"}",
"else",
"{",
"var",
"foo_item",
"=",
"'* ['",
"+",
"CFtitle",
"+",
"']('",
"+",
"CFpath",
"+",
"')'",
";",
"foooo",
".",
"push",
"(",
"foo_item",
")",
";",
"}",
"}",
"var",
"datas",
"=",
"foooo",
".",
"join",
"(",
"'\\n'",
")",
";",
"fs",
".",
"writeFile",
"(",
"outFileName",
",",
"datas",
",",
"{",
"encoding",
":",
"'utf8'",
",",
"flag",
":",
"'w'",
"}",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"throw",
"err",
";",
"}",
"}",
")",
";",
"console",
".",
"log",
"(",
"`",
"${",
"chalk",
".",
"yellow",
"(",
"'summarybuilder: '",
")",
"}",
"`",
"+",
"outFileName",
"+",
"\" ....... ok\"",
")",
";",
"}",
"}",
"else",
"{",
"console",
".",
"log",
"(",
"`",
"${",
"chalk",
".",
"yellow",
"(",
"'summarybuilder: '",
")",
"}",
"`",
"+",
"\"No such a file names:\"",
"+",
"jsonFileName",
"+",
"'. It is better to be created by the plugin: gulp-filelist.And sure all path of the list in '",
"+",
"jsonFileName",
"+",
"' are existent.'",
")",
";",
"console",
".",
"log",
"(",
"`",
"${",
"chalk",
".",
"yellow",
"(",
"'summarybuilder: '",
")",
"}",
"`",
"+",
"' You can use an array type variable ,or like this: SBer_summary([\"a.md\",\"b/a.md\"],true,\"mySummary.md\"). '",
")",
"}",
"}"
] | for gulp
Run only in the specified folder
@param {string} jsonFileName The path of the JSON file.It's better to be created by the plugin: gulp-filelist.
@param {boolean} isIndent indent? If'true'will be indented.
@param {string} outFileName Like this: 'a.md',Any you wanted if you sure it can be read. | [
"for",
"gulp",
"Run",
"only",
"in",
"the",
"specified",
"folder"
] | 0fa24d478cd9fff6a8fb638b7ffbb5fc4bd0c704 | https://github.com/YYago/summarybuilder/blob/0fa24d478cd9fff6a8fb638b7ffbb5fc4bd0c704/builder.js#L79-L155 |
48,078 | loverly/awesome-automata | lib/State.js | State | function State(config) {
this._ = require('lodash');
this._name = config.name;
this._isInitial = config.isInitial;
this._isTerminal = config.isTerminal;
this._outgoingTransitions = config.outgoingTransitions;
this.accept = config.accept;
this._validateConfig(config);
// Transform any value-based transition criteria to be a function
this._.forEach(this._outgoingTransitions, function (transition) {
var criteria = transition.criteria;
// Replace the value-based criteria with a simple comparison function
if (typeof criteria !== 'function') {
transition.criteria = function (input) {
return (input === criteria);
}
}
});
} | javascript | function State(config) {
this._ = require('lodash');
this._name = config.name;
this._isInitial = config.isInitial;
this._isTerminal = config.isTerminal;
this._outgoingTransitions = config.outgoingTransitions;
this.accept = config.accept;
this._validateConfig(config);
// Transform any value-based transition criteria to be a function
this._.forEach(this._outgoingTransitions, function (transition) {
var criteria = transition.criteria;
// Replace the value-based criteria with a simple comparison function
if (typeof criteria !== 'function') {
transition.criteria = function (input) {
return (input === criteria);
}
}
});
} | [
"function",
"State",
"(",
"config",
")",
"{",
"this",
".",
"_",
"=",
"require",
"(",
"'lodash'",
")",
";",
"this",
".",
"_name",
"=",
"config",
".",
"name",
";",
"this",
".",
"_isInitial",
"=",
"config",
".",
"isInitial",
";",
"this",
".",
"_isTerminal",
"=",
"config",
".",
"isTerminal",
";",
"this",
".",
"_outgoingTransitions",
"=",
"config",
".",
"outgoingTransitions",
";",
"this",
".",
"accept",
"=",
"config",
".",
"accept",
";",
"this",
".",
"_validateConfig",
"(",
"config",
")",
";",
"// Transform any value-based transition criteria to be a function",
"this",
".",
"_",
".",
"forEach",
"(",
"this",
".",
"_outgoingTransitions",
",",
"function",
"(",
"transition",
")",
"{",
"var",
"criteria",
"=",
"transition",
".",
"criteria",
";",
"// Replace the value-based criteria with a simple comparison function",
"if",
"(",
"typeof",
"criteria",
"!==",
"'function'",
")",
"{",
"transition",
".",
"criteria",
"=",
"function",
"(",
"input",
")",
"{",
"return",
"(",
"input",
"===",
"criteria",
")",
";",
"}",
"}",
"}",
")",
";",
"}"
] | Represents an automata or state within a Finite State Machine.
Provides mechanisms for | [
"Represents",
"an",
"automata",
"or",
"state",
"within",
"a",
"Finite",
"State",
"Machine",
"."
] | 06ad9b26da9025a1cb1754a4eaa0277d728968e4 | https://github.com/loverly/awesome-automata/blob/06ad9b26da9025a1cb1754a4eaa0277d728968e4/lib/State.js#L6-L29 |
48,079 | bumbu/website-visual-diff | src/index.js | removeDir | function removeDir(dirPath, cleanOnly) {
var files;
try {
files = fs.readdirSync(dirPath);
} catch(e) {
return;
}
if (files.length > 0) {
for (var i = 0; i < files.length; i++) {
var filePath = path.join(dirPath, files[i]);
if (fs.statSync(filePath).isFile())
fs.unlinkSync(filePath);
else
rmDir(filePath);
}
}
!cleanOnly && fs.rmdirSync(dirPath);
} | javascript | function removeDir(dirPath, cleanOnly) {
var files;
try {
files = fs.readdirSync(dirPath);
} catch(e) {
return;
}
if (files.length > 0) {
for (var i = 0; i < files.length; i++) {
var filePath = path.join(dirPath, files[i]);
if (fs.statSync(filePath).isFile())
fs.unlinkSync(filePath);
else
rmDir(filePath);
}
}
!cleanOnly && fs.rmdirSync(dirPath);
} | [
"function",
"removeDir",
"(",
"dirPath",
",",
"cleanOnly",
")",
"{",
"var",
"files",
";",
"try",
"{",
"files",
"=",
"fs",
".",
"readdirSync",
"(",
"dirPath",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"return",
";",
"}",
"if",
"(",
"files",
".",
"length",
">",
"0",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"files",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"filePath",
"=",
"path",
".",
"join",
"(",
"dirPath",
",",
"files",
"[",
"i",
"]",
")",
";",
"if",
"(",
"fs",
".",
"statSync",
"(",
"filePath",
")",
".",
"isFile",
"(",
")",
")",
"fs",
".",
"unlinkSync",
"(",
"filePath",
")",
";",
"else",
"rmDir",
"(",
"filePath",
")",
";",
"}",
"}",
"!",
"cleanOnly",
"&&",
"fs",
".",
"rmdirSync",
"(",
"dirPath",
")",
";",
"}"
] | Removes a directory and its cotents
If cleanOnly is true then only the contents are removed
@param {String} dirPath
@param {boolean} cleanOnly | [
"Removes",
"a",
"directory",
"and",
"its",
"cotents",
"If",
"cleanOnly",
"is",
"true",
"then",
"only",
"the",
"contents",
"are",
"removed"
] | b0903bcf55117f3903e69058b4e42f6b2b025e0d | https://github.com/bumbu/website-visual-diff/blob/b0903bcf55117f3903e69058b4e42f6b2b025e0d/src/index.js#L86-L106 |
48,080 | bumbu/website-visual-diff | src/index.js | loadAndSaveShoots | function loadAndSaveShoots(settings, folderPath) {
var promisesPool = [];
var semaphore = new Semaphore({rooms: 6});
settings.pages.forEach((page) => {
settings.sizes.forEach((size) => {
promisesPool.push(semaphore.add(() => {
return new Promise((resolve, reject) => {
console.log(`Start ${page.name} for ${size.width}x${size.height}`);
screenshot({
url : settings.urlBase + page.url,
width : size.width,
height : size.height,
page: size.page === undefined ? true : size.page,
cookies: settings.cookies,
auth: settings.auth,
delay: settings.delay,
})
.then(function(img){
var fileName = getFileName(page, size);
fs.writeFile(path.join(folderPath, fileName), img.data, function(err){
if (err) {
console.info(`Failed to save ${fileName}`, err)
}
resolve();
});
})
.catch((err) => {
console.info(`Failed to retrieve ${page.url}`, err)
resolve();
})
})
}))
})
})
var promise = Promise.all(promisesPool);
// Close screenshot service
promise = promise.then(() => {
console.log(`Done`)
screenshot.close();
}).catch(() => {
console.log(`Done with errors`)
screenshot.close();
})
return promise
} | javascript | function loadAndSaveShoots(settings, folderPath) {
var promisesPool = [];
var semaphore = new Semaphore({rooms: 6});
settings.pages.forEach((page) => {
settings.sizes.forEach((size) => {
promisesPool.push(semaphore.add(() => {
return new Promise((resolve, reject) => {
console.log(`Start ${page.name} for ${size.width}x${size.height}`);
screenshot({
url : settings.urlBase + page.url,
width : size.width,
height : size.height,
page: size.page === undefined ? true : size.page,
cookies: settings.cookies,
auth: settings.auth,
delay: settings.delay,
})
.then(function(img){
var fileName = getFileName(page, size);
fs.writeFile(path.join(folderPath, fileName), img.data, function(err){
if (err) {
console.info(`Failed to save ${fileName}`, err)
}
resolve();
});
})
.catch((err) => {
console.info(`Failed to retrieve ${page.url}`, err)
resolve();
})
})
}))
})
})
var promise = Promise.all(promisesPool);
// Close screenshot service
promise = promise.then(() => {
console.log(`Done`)
screenshot.close();
}).catch(() => {
console.log(`Done with errors`)
screenshot.close();
})
return promise
} | [
"function",
"loadAndSaveShoots",
"(",
"settings",
",",
"folderPath",
")",
"{",
"var",
"promisesPool",
"=",
"[",
"]",
";",
"var",
"semaphore",
"=",
"new",
"Semaphore",
"(",
"{",
"rooms",
":",
"6",
"}",
")",
";",
"settings",
".",
"pages",
".",
"forEach",
"(",
"(",
"page",
")",
"=>",
"{",
"settings",
".",
"sizes",
".",
"forEach",
"(",
"(",
"size",
")",
"=>",
"{",
"promisesPool",
".",
"push",
"(",
"semaphore",
".",
"add",
"(",
"(",
")",
"=>",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"console",
".",
"log",
"(",
"`",
"${",
"page",
".",
"name",
"}",
"${",
"size",
".",
"width",
"}",
"${",
"size",
".",
"height",
"}",
"`",
")",
";",
"screenshot",
"(",
"{",
"url",
":",
"settings",
".",
"urlBase",
"+",
"page",
".",
"url",
",",
"width",
":",
"size",
".",
"width",
",",
"height",
":",
"size",
".",
"height",
",",
"page",
":",
"size",
".",
"page",
"===",
"undefined",
"?",
"true",
":",
"size",
".",
"page",
",",
"cookies",
":",
"settings",
".",
"cookies",
",",
"auth",
":",
"settings",
".",
"auth",
",",
"delay",
":",
"settings",
".",
"delay",
",",
"}",
")",
".",
"then",
"(",
"function",
"(",
"img",
")",
"{",
"var",
"fileName",
"=",
"getFileName",
"(",
"page",
",",
"size",
")",
";",
"fs",
".",
"writeFile",
"(",
"path",
".",
"join",
"(",
"folderPath",
",",
"fileName",
")",
",",
"img",
".",
"data",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"console",
".",
"info",
"(",
"`",
"${",
"fileName",
"}",
"`",
",",
"err",
")",
"}",
"resolve",
"(",
")",
";",
"}",
")",
";",
"}",
")",
".",
"catch",
"(",
"(",
"err",
")",
"=>",
"{",
"console",
".",
"info",
"(",
"`",
"${",
"page",
".",
"url",
"}",
"`",
",",
"err",
")",
"resolve",
"(",
")",
";",
"}",
")",
"}",
")",
"}",
")",
")",
"}",
")",
"}",
")",
"var",
"promise",
"=",
"Promise",
".",
"all",
"(",
"promisesPool",
")",
";",
"// Close screenshot service",
"promise",
"=",
"promise",
".",
"then",
"(",
"(",
")",
"=>",
"{",
"console",
".",
"log",
"(",
"`",
"`",
")",
"screenshot",
".",
"close",
"(",
")",
";",
"}",
")",
".",
"catch",
"(",
"(",
")",
"=>",
"{",
"console",
".",
"log",
"(",
"`",
"`",
")",
"screenshot",
".",
"close",
"(",
")",
";",
"}",
")",
"return",
"promise",
"}"
] | Creates screenshots based on provided settings and saves them into provided folder
@param {Object} settings
@param {String} folderPath
@return {Promise} | [
"Creates",
"screenshots",
"based",
"on",
"provided",
"settings",
"and",
"saves",
"them",
"into",
"provided",
"folder"
] | b0903bcf55117f3903e69058b4e42f6b2b025e0d | https://github.com/bumbu/website-visual-diff/blob/b0903bcf55117f3903e69058b4e42f6b2b025e0d/src/index.js#L151-L206 |
48,081 | sosout/vssr | lib/app/store.js | getModule | function getModule (filename) {
const file = files(filename)
const module = file.default || file
if (module.commit) {
throw new Error('[vssr] <%= dir.store %>/' + filename.replace('./', '') + ' should export a method which returns a Vuex instance.')
}
if (module.state && typeof module.state !== 'function') {
throw new Error('[vssr] state should be a function in <%= dir.store %>/' + filename.replace('./', ''))
}
return module
} | javascript | function getModule (filename) {
const file = files(filename)
const module = file.default || file
if (module.commit) {
throw new Error('[vssr] <%= dir.store %>/' + filename.replace('./', '') + ' should export a method which returns a Vuex instance.')
}
if (module.state && typeof module.state !== 'function') {
throw new Error('[vssr] state should be a function in <%= dir.store %>/' + filename.replace('./', ''))
}
return module
} | [
"function",
"getModule",
"(",
"filename",
")",
"{",
"const",
"file",
"=",
"files",
"(",
"filename",
")",
"const",
"module",
"=",
"file",
".",
"default",
"||",
"file",
"if",
"(",
"module",
".",
"commit",
")",
"{",
"throw",
"new",
"Error",
"(",
"'[vssr] <%= dir.store %>/'",
"+",
"filename",
".",
"replace",
"(",
"'./'",
",",
"''",
")",
"+",
"' should export a method which returns a Vuex instance.'",
")",
"}",
"if",
"(",
"module",
".",
"state",
"&&",
"typeof",
"module",
".",
"state",
"!==",
"'function'",
")",
"{",
"throw",
"new",
"Error",
"(",
"'[vssr] state should be a function in <%= dir.store %>/'",
"+",
"filename",
".",
"replace",
"(",
"'./'",
",",
"''",
")",
")",
"}",
"return",
"module",
"}"
] | Dynamically require module | [
"Dynamically",
"require",
"module"
] | 1cb1e21b15aa6aa761356fe0eb8618a099c9e215 | https://github.com/sosout/vssr/blob/1cb1e21b15aa6aa761356fe0eb8618a099c9e215/lib/app/store.js#L89-L99 |
48,082 | tidoust/fetch-filecache-for-crawling | fetch-filecache.js | filenamify | function filenamify(url) {
let res = filenamifyUrl(url);
if (res.length >= 60) {
res = res.substr(0, 60) +
'-md5-' +
crypto.createHash('md5').update(url, 'utf8').digest('hex');
}
return res;
} | javascript | function filenamify(url) {
let res = filenamifyUrl(url);
if (res.length >= 60) {
res = res.substr(0, 60) +
'-md5-' +
crypto.createHash('md5').update(url, 'utf8').digest('hex');
}
return res;
} | [
"function",
"filenamify",
"(",
"url",
")",
"{",
"let",
"res",
"=",
"filenamifyUrl",
"(",
"url",
")",
";",
"if",
"(",
"res",
".",
"length",
">=",
"60",
")",
"{",
"res",
"=",
"res",
".",
"substr",
"(",
"0",
",",
"60",
")",
"+",
"'-md5-'",
"+",
"crypto",
".",
"createHash",
"(",
"'md5'",
")",
".",
"update",
"(",
"url",
",",
"'utf8'",
")",
".",
"digest",
"(",
"'hex'",
")",
";",
"}",
"return",
"res",
";",
"}"
] | Wrapper around the filenamify library to handle lengthy URLs.
By default filenamify truncates the result to 100 characters, but that may
not be enough to distinguish between cache entries. When string is too long,
replace the end by an MD5 checksum.
Note we keep the beginning from filenamify because it remains somewhat human
friendly.
@function
@param {String} url The URL to convert to a filename
@return {String} A safe filename that is less than 100 characters long | [
"Wrapper",
"around",
"the",
"filenamify",
"library",
"to",
"handle",
"lengthy",
"URLs",
"."
] | f93106df67421dcb6d169e1c7ea4338eb01b4a11 | https://github.com/tidoust/fetch-filecache-for-crawling/blob/f93106df67421dcb6d169e1c7ea4338eb01b4a11/fetch-filecache.js#L55-L63 |
48,083 | tidoust/fetch-filecache-for-crawling | fetch-filecache.js | hasExpired | function hasExpired(headers, refresh) {
if (!headers) {
log('response is not in cache');
return true;
}
if (refresh === 'force') {
log('response in cache but refresh requested');
return true;
}
if (refresh === 'never') {
log('response in cache and considered to be always valid');
return false;
}
let received = new Date(
headers.received || headers.date || 'Jan 1, 1970, 00:00:00.000 GMT');
received = received.getTime();
if (refresh === 'once') {
if (received < launchTime) {
log('response in cache but one refresh requested');
return true;
}
else {
log('response in cache and already refreshed once')
return false;
}
}
let now = Date.now();
if (Number.isInteger(refresh)) {
if (received + refresh * 1000 < now) {
log('response in cache is older than requested duration');
return true;
}
else {
log('response in cache is fresh enough for requested duration');
return false;
}
}
// Apply HTTP expiration rules otherwise
if (headers.expires) {
try {
let expires = (new Date(headers.expires)).getTime();
if (expires < now) {
log('response in cache has expired');
return true;
}
else {
log('response in cache is still valid');
return false;
}
}
catch (err) {}
}
if (headers['cache-control']) {
try {
let tokens = headers['cache-control'].split(',')
.map(token => token.split('='));
for (token of tokens) {
let param = token[0].trim();
if (param === 'no-cache') {
log('response in cache but no-cache directive');
return true;
}
else if (param === 'max-age') {
let maxAge = parseInt(token[1], 10);
if (received + maxAge * 1000 < now) {
log('response in cache has expired');
return true;
}
else {
log('response in cache is still valid');
return false;
}
}
}
}
catch (err) {}
}
// Cannot tell? Let's refresh the cache
log('response in cache has expired (no explicit directive)');
return true;
} | javascript | function hasExpired(headers, refresh) {
if (!headers) {
log('response is not in cache');
return true;
}
if (refresh === 'force') {
log('response in cache but refresh requested');
return true;
}
if (refresh === 'never') {
log('response in cache and considered to be always valid');
return false;
}
let received = new Date(
headers.received || headers.date || 'Jan 1, 1970, 00:00:00.000 GMT');
received = received.getTime();
if (refresh === 'once') {
if (received < launchTime) {
log('response in cache but one refresh requested');
return true;
}
else {
log('response in cache and already refreshed once')
return false;
}
}
let now = Date.now();
if (Number.isInteger(refresh)) {
if (received + refresh * 1000 < now) {
log('response in cache is older than requested duration');
return true;
}
else {
log('response in cache is fresh enough for requested duration');
return false;
}
}
// Apply HTTP expiration rules otherwise
if (headers.expires) {
try {
let expires = (new Date(headers.expires)).getTime();
if (expires < now) {
log('response in cache has expired');
return true;
}
else {
log('response in cache is still valid');
return false;
}
}
catch (err) {}
}
if (headers['cache-control']) {
try {
let tokens = headers['cache-control'].split(',')
.map(token => token.split('='));
for (token of tokens) {
let param = token[0].trim();
if (param === 'no-cache') {
log('response in cache but no-cache directive');
return true;
}
else if (param === 'max-age') {
let maxAge = parseInt(token[1], 10);
if (received + maxAge * 1000 < now) {
log('response in cache has expired');
return true;
}
else {
log('response in cache is still valid');
return false;
}
}
}
}
catch (err) {}
}
// Cannot tell? Let's refresh the cache
log('response in cache has expired (no explicit directive)');
return true;
} | [
"function",
"hasExpired",
"(",
"headers",
",",
"refresh",
")",
"{",
"if",
"(",
"!",
"headers",
")",
"{",
"log",
"(",
"'response is not in cache'",
")",
";",
"return",
"true",
";",
"}",
"if",
"(",
"refresh",
"===",
"'force'",
")",
"{",
"log",
"(",
"'response in cache but refresh requested'",
")",
";",
"return",
"true",
";",
"}",
"if",
"(",
"refresh",
"===",
"'never'",
")",
"{",
"log",
"(",
"'response in cache and considered to be always valid'",
")",
";",
"return",
"false",
";",
"}",
"let",
"received",
"=",
"new",
"Date",
"(",
"headers",
".",
"received",
"||",
"headers",
".",
"date",
"||",
"'Jan 1, 1970, 00:00:00.000 GMT'",
")",
";",
"received",
"=",
"received",
".",
"getTime",
"(",
")",
";",
"if",
"(",
"refresh",
"===",
"'once'",
")",
"{",
"if",
"(",
"received",
"<",
"launchTime",
")",
"{",
"log",
"(",
"'response in cache but one refresh requested'",
")",
";",
"return",
"true",
";",
"}",
"else",
"{",
"log",
"(",
"'response in cache and already refreshed once'",
")",
"return",
"false",
";",
"}",
"}",
"let",
"now",
"=",
"Date",
".",
"now",
"(",
")",
";",
"if",
"(",
"Number",
".",
"isInteger",
"(",
"refresh",
")",
")",
"{",
"if",
"(",
"received",
"+",
"refresh",
"*",
"1000",
"<",
"now",
")",
"{",
"log",
"(",
"'response in cache is older than requested duration'",
")",
";",
"return",
"true",
";",
"}",
"else",
"{",
"log",
"(",
"'response in cache is fresh enough for requested duration'",
")",
";",
"return",
"false",
";",
"}",
"}",
"// Apply HTTP expiration rules otherwise",
"if",
"(",
"headers",
".",
"expires",
")",
"{",
"try",
"{",
"let",
"expires",
"=",
"(",
"new",
"Date",
"(",
"headers",
".",
"expires",
")",
")",
".",
"getTime",
"(",
")",
";",
"if",
"(",
"expires",
"<",
"now",
")",
"{",
"log",
"(",
"'response in cache has expired'",
")",
";",
"return",
"true",
";",
"}",
"else",
"{",
"log",
"(",
"'response in cache is still valid'",
")",
";",
"return",
"false",
";",
"}",
"}",
"catch",
"(",
"err",
")",
"{",
"}",
"}",
"if",
"(",
"headers",
"[",
"'cache-control'",
"]",
")",
"{",
"try",
"{",
"let",
"tokens",
"=",
"headers",
"[",
"'cache-control'",
"]",
".",
"split",
"(",
"','",
")",
".",
"map",
"(",
"token",
"=>",
"token",
".",
"split",
"(",
"'='",
")",
")",
";",
"for",
"(",
"token",
"of",
"tokens",
")",
"{",
"let",
"param",
"=",
"token",
"[",
"0",
"]",
".",
"trim",
"(",
")",
";",
"if",
"(",
"param",
"===",
"'no-cache'",
")",
"{",
"log",
"(",
"'response in cache but no-cache directive'",
")",
";",
"return",
"true",
";",
"}",
"else",
"if",
"(",
"param",
"===",
"'max-age'",
")",
"{",
"let",
"maxAge",
"=",
"parseInt",
"(",
"token",
"[",
"1",
"]",
",",
"10",
")",
";",
"if",
"(",
"received",
"+",
"maxAge",
"*",
"1000",
"<",
"now",
")",
"{",
"log",
"(",
"'response in cache has expired'",
")",
";",
"return",
"true",
";",
"}",
"else",
"{",
"log",
"(",
"'response in cache is still valid'",
")",
";",
"return",
"false",
";",
"}",
"}",
"}",
"}",
"catch",
"(",
"err",
")",
"{",
"}",
"}",
"// Cannot tell? Let's refresh the cache",
"log",
"(",
"'response in cache has expired (no explicit directive)'",
")",
";",
"return",
"true",
";",
"}"
] | Look at HTTP headers, current time and refresh strategy to determine whether
cached content has expired
@function
@param {Object} headers HTTP headers received last time
@param {String|Integer} refresh Refresh strategy
@return {Boolean} true if cached content has expired (or does not exist),
false when it can still be returned. | [
"Look",
"at",
"HTTP",
"headers",
"current",
"time",
"and",
"refresh",
"strategy",
"to",
"determine",
"whether",
"cached",
"content",
"has",
"expired"
] | f93106df67421dcb6d169e1c7ea4338eb01b4a11 | https://github.com/tidoust/fetch-filecache-for-crawling/blob/f93106df67421dcb6d169e1c7ea4338eb01b4a11/fetch-filecache.js#L146-L231 |
48,084 | tidoust/fetch-filecache-for-crawling | fetch-filecache.js | addPendingFetch | function addPendingFetch(url) {
let resolve = null;
let reject = null;
let promise = new Promise((innerResolve, innerReject) => {
resolve = innerResolve;
reject = innerReject;
});
pendingFetches[url] = { promise, resolve, reject };
} | javascript | function addPendingFetch(url) {
let resolve = null;
let reject = null;
let promise = new Promise((innerResolve, innerReject) => {
resolve = innerResolve;
reject = innerReject;
});
pendingFetches[url] = { promise, resolve, reject };
} | [
"function",
"addPendingFetch",
"(",
"url",
")",
"{",
"let",
"resolve",
"=",
"null",
";",
"let",
"reject",
"=",
"null",
";",
"let",
"promise",
"=",
"new",
"Promise",
"(",
"(",
"innerResolve",
",",
"innerReject",
")",
"=>",
"{",
"resolve",
"=",
"innerResolve",
";",
"reject",
"=",
"innerReject",
";",
"}",
")",
";",
"pendingFetches",
"[",
"url",
"]",
"=",
"{",
"promise",
",",
"resolve",
",",
"reject",
"}",
";",
"}"
] | Create a pending fetch promise and keep controls over that promise so that
the code may resolve or reject it through calls to resolvePendingFetch and
rejectPendingFetch functions | [
"Create",
"a",
"pending",
"fetch",
"promise",
"and",
"keep",
"controls",
"over",
"that",
"promise",
"so",
"that",
"the",
"code",
"may",
"resolve",
"or",
"reject",
"it",
"through",
"calls",
"to",
"resolvePendingFetch",
"and",
"rejectPendingFetch",
"functions"
] | f93106df67421dcb6d169e1c7ea4338eb01b4a11 | https://github.com/tidoust/fetch-filecache-for-crawling/blob/f93106df67421dcb6d169e1c7ea4338eb01b4a11/fetch-filecache.js#L273-L281 |
48,085 | tidoust/fetch-filecache-for-crawling | fetch-filecache.js | fetchWithRetry | async function fetchWithRetry(url, options, remainingAttempts) {
try {
return await baseFetch(url, options);
}
catch (err) {
if (remainingAttempts <= 0) throw err;
log('fetch attempt failed, sleep and try again');
await sleep(2000 + Math.floor(Math.random() * 8000));
return fetchWithRetry(url, options, remainingAttempts - 1);
}
} | javascript | async function fetchWithRetry(url, options, remainingAttempts) {
try {
return await baseFetch(url, options);
}
catch (err) {
if (remainingAttempts <= 0) throw err;
log('fetch attempt failed, sleep and try again');
await sleep(2000 + Math.floor(Math.random() * 8000));
return fetchWithRetry(url, options, remainingAttempts - 1);
}
} | [
"async",
"function",
"fetchWithRetry",
"(",
"url",
",",
"options",
",",
"remainingAttempts",
")",
"{",
"try",
"{",
"return",
"await",
"baseFetch",
"(",
"url",
",",
"options",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"if",
"(",
"remainingAttempts",
"<=",
"0",
")",
"throw",
"err",
";",
"log",
"(",
"'fetch attempt failed, sleep and try again'",
")",
";",
"await",
"sleep",
"(",
"2000",
"+",
"Math",
".",
"floor",
"(",
"Math",
".",
"random",
"(",
")",
"*",
"8000",
")",
")",
";",
"return",
"fetchWithRetry",
"(",
"url",
",",
"options",
",",
"remainingAttempts",
"-",
"1",
")",
";",
"}",
"}"
] | To overcome transient network errors, we'll fetch the same URL again a few times before we surrender when a network error occurs, letting a few seconds elapse between attempts | [
"To",
"overcome",
"transient",
"network",
"errors",
"we",
"ll",
"fetch",
"the",
"same",
"URL",
"again",
"a",
"few",
"times",
"before",
"we",
"surrender",
"when",
"a",
"network",
"error",
"occurs",
"letting",
"a",
"few",
"seconds",
"elapse",
"between",
"attempts"
] | f93106df67421dcb6d169e1c7ea4338eb01b4a11 | https://github.com/tidoust/fetch-filecache-for-crawling/blob/f93106df67421dcb6d169e1c7ea4338eb01b4a11/fetch-filecache.js#L375-L385 |
48,086 | stevenvelozo/stricture | source/Stricture-Run-Prepare.js | function(pModel)
{
// First create a "lookup" of primary keys that point back to tables
console.log('--> ... creating contextual Index ==> Table lookups ...');
var tmpIndices = {};
for(var tmpTable in pModel.Tables)
{
for (var j = 0; j < pModel.Tables[tmpTable].Columns.length; j++)
{
if (pModel.Tables[tmpTable].Columns[j].DataType == "ID")
{
console.log(' > Adding the table '+pModel.Tables[tmpTable].TableName+' to the lookup cache with the key '+pModel.Tables[tmpTable].Columns[j].Column);
tmpIndices[pModel.Tables[tmpTable].Columns[j].Column] = pModel.Tables[tmpTable].TableName;
}
}
}
console.log(' > indices built successfully.');
return tmpIndices;
} | javascript | function(pModel)
{
// First create a "lookup" of primary keys that point back to tables
console.log('--> ... creating contextual Index ==> Table lookups ...');
var tmpIndices = {};
for(var tmpTable in pModel.Tables)
{
for (var j = 0; j < pModel.Tables[tmpTable].Columns.length; j++)
{
if (pModel.Tables[tmpTable].Columns[j].DataType == "ID")
{
console.log(' > Adding the table '+pModel.Tables[tmpTable].TableName+' to the lookup cache with the key '+pModel.Tables[tmpTable].Columns[j].Column);
tmpIndices[pModel.Tables[tmpTable].Columns[j].Column] = pModel.Tables[tmpTable].TableName;
}
}
}
console.log(' > indices built successfully.');
return tmpIndices;
} | [
"function",
"(",
"pModel",
")",
"{",
"// First create a \"lookup\" of primary keys that point back to tables",
"console",
".",
"log",
"(",
"'--> ... creating contextual Index ==> Table lookups ...'",
")",
";",
"var",
"tmpIndices",
"=",
"{",
"}",
";",
"for",
"(",
"var",
"tmpTable",
"in",
"pModel",
".",
"Tables",
")",
"{",
"for",
"(",
"var",
"j",
"=",
"0",
";",
"j",
"<",
"pModel",
".",
"Tables",
"[",
"tmpTable",
"]",
".",
"Columns",
".",
"length",
";",
"j",
"++",
")",
"{",
"if",
"(",
"pModel",
".",
"Tables",
"[",
"tmpTable",
"]",
".",
"Columns",
"[",
"j",
"]",
".",
"DataType",
"==",
"\"ID\"",
")",
"{",
"console",
".",
"log",
"(",
"' > Adding the table '",
"+",
"pModel",
".",
"Tables",
"[",
"tmpTable",
"]",
".",
"TableName",
"+",
"' to the lookup cache with the key '",
"+",
"pModel",
".",
"Tables",
"[",
"tmpTable",
"]",
".",
"Columns",
"[",
"j",
"]",
".",
"Column",
")",
";",
"tmpIndices",
"[",
"pModel",
".",
"Tables",
"[",
"tmpTable",
"]",
".",
"Columns",
"[",
"j",
"]",
".",
"Column",
"]",
"=",
"pModel",
".",
"Tables",
"[",
"tmpTable",
"]",
".",
"TableName",
";",
"}",
"}",
"}",
"console",
".",
"log",
"(",
"' > indices built successfully.'",
")",
";",
"return",
"tmpIndices",
";",
"}"
] | Generate a lookup object that contains the identity key pointing to a table name | [
"Generate",
"a",
"lookup",
"object",
"that",
"contains",
"the",
"identity",
"key",
"pointing",
"to",
"a",
"table",
"name"
] | 467610baee0551881a8a453f7e496148b9304706 | https://github.com/stevenvelozo/stricture/blob/467610baee0551881a8a453f7e496148b9304706/source/Stricture-Run-Prepare.js#L13-L31 |
|
48,087 | rtm/upward | src/Obj.js | _delete | function _delete(name) {
observers[name].unobserve();
delete observers[name];
delete u [name];
delete shadow [name];
} | javascript | function _delete(name) {
observers[name].unobserve();
delete observers[name];
delete u [name];
delete shadow [name];
} | [
"function",
"_delete",
"(",
"name",
")",
"{",
"observers",
"[",
"name",
"]",
".",
"unobserve",
"(",
")",
";",
"delete",
"observers",
"[",
"name",
"]",
";",
"delete",
"u",
"[",
"name",
"]",
";",
"delete",
"shadow",
"[",
"name",
"]",
";",
"}"
] | Delete a property. Unobserve it, delete shadow and proxy entries. | [
"Delete",
"a",
"property",
".",
"Unobserve",
"it",
"delete",
"shadow",
"and",
"proxy",
"entries",
"."
] | 82495c34f70c9a4336a3b34cc6781e5662324c03 | https://github.com/rtm/upward/blob/82495c34f70c9a4336a3b34cc6781e5662324c03/src/Obj.js#L74-L79 |
48,088 | rtm/upward | src/Obj.js | add | function add(name) {
function set(v) {
var oldValue = shadow[name];
if (oldValue === v) return;
o[name] = v;
notifier.notify({type: 'update', object: u, name, oldValue});
shadow[name] = oldValue.change(v);
}
// When property on upwardable object is accessed, report it and return shadow value.
function get() {
accessNotifier.notify({type: 'access', object: u, name});
return shadow[name];
}
function observe(changes) {
// changes.forEach(change => shadow[name] = shadow[name].change(change.newValue));
// observers[name].reobserve(shadow[name]);
}
shadow[name] = makeUpwardable(o[name]);
observers[name] = Observer(shadow[name], observe, ['upward']).observe();
defineProperty(u, name, {set: set, get: get, enumerable: true});
} | javascript | function add(name) {
function set(v) {
var oldValue = shadow[name];
if (oldValue === v) return;
o[name] = v;
notifier.notify({type: 'update', object: u, name, oldValue});
shadow[name] = oldValue.change(v);
}
// When property on upwardable object is accessed, report it and return shadow value.
function get() {
accessNotifier.notify({type: 'access', object: u, name});
return shadow[name];
}
function observe(changes) {
// changes.forEach(change => shadow[name] = shadow[name].change(change.newValue));
// observers[name].reobserve(shadow[name]);
}
shadow[name] = makeUpwardable(o[name]);
observers[name] = Observer(shadow[name], observe, ['upward']).observe();
defineProperty(u, name, {set: set, get: get, enumerable: true});
} | [
"function",
"add",
"(",
"name",
")",
"{",
"function",
"set",
"(",
"v",
")",
"{",
"var",
"oldValue",
"=",
"shadow",
"[",
"name",
"]",
";",
"if",
"(",
"oldValue",
"===",
"v",
")",
"return",
";",
"o",
"[",
"name",
"]",
"=",
"v",
";",
"notifier",
".",
"notify",
"(",
"{",
"type",
":",
"'update'",
",",
"object",
":",
"u",
",",
"name",
",",
"oldValue",
"}",
")",
";",
"shadow",
"[",
"name",
"]",
"=",
"oldValue",
".",
"change",
"(",
"v",
")",
";",
"}",
"// When property on upwardable object is accessed, report it and return shadow value.",
"function",
"get",
"(",
")",
"{",
"accessNotifier",
".",
"notify",
"(",
"{",
"type",
":",
"'access'",
",",
"object",
":",
"u",
",",
"name",
"}",
")",
";",
"return",
"shadow",
"[",
"name",
"]",
";",
"}",
"function",
"observe",
"(",
"changes",
")",
"{",
"// changes.forEach(change => shadow[name] = shadow[name].change(change.newValue));",
"// observers[name].reobserve(shadow[name]);",
"}",
"shadow",
"[",
"name",
"]",
"=",
"makeUpwardable",
"(",
"o",
"[",
"name",
"]",
")",
";",
"observers",
"[",
"name",
"]",
"=",
"Observer",
"(",
"shadow",
"[",
"name",
"]",
",",
"observe",
",",
"[",
"'upward'",
"]",
")",
".",
"observe",
"(",
")",
";",
"defineProperty",
"(",
"u",
",",
"name",
",",
"{",
"set",
":",
"set",
",",
"get",
":",
"get",
",",
"enumerable",
":",
"true",
"}",
")",
";",
"}"
] | Add a property. Set up getter and setter, Observe. Populate shadow. | [
"Add",
"a",
"property",
".",
"Set",
"up",
"getter",
"and",
"setter",
"Observe",
".",
"Populate",
"shadow",
"."
] | 82495c34f70c9a4336a3b34cc6781e5662324c03 | https://github.com/rtm/upward/blob/82495c34f70c9a4336a3b34cc6781e5662324c03/src/Obj.js#L87-L111 |
48,089 | rtm/upward | src/Obj.js | objectObserver | function objectObserver(changes) {
changes.forEach(({type, name}) => {
switch (type) {
case 'add': o[name] = u[name]; break;
case 'delete': delete o[name]; break;
}
});
} | javascript | function objectObserver(changes) {
changes.forEach(({type, name}) => {
switch (type) {
case 'add': o[name] = u[name]; break;
case 'delete': delete o[name]; break;
}
});
} | [
"function",
"objectObserver",
"(",
"changes",
")",
"{",
"changes",
".",
"forEach",
"(",
"(",
"{",
"type",
",",
"name",
"}",
")",
"=>",
"{",
"switch",
"(",
"type",
")",
"{",
"case",
"'add'",
":",
"o",
"[",
"name",
"]",
"=",
"u",
"[",
"name",
"]",
";",
"break",
";",
"case",
"'delete'",
":",
"delete",
"o",
"[",
"name",
"]",
";",
"break",
";",
"}",
"}",
")",
";",
"}"
] | Observer to handle new or deleted properties on the object. Pass through to underlying object, which will cause the right things to happen. | [
"Observer",
"to",
"handle",
"new",
"or",
"deleted",
"properties",
"on",
"the",
"object",
".",
"Pass",
"through",
"to",
"underlying",
"object",
"which",
"will",
"cause",
"the",
"right",
"things",
"to",
"happen",
"."
] | 82495c34f70c9a4336a3b34cc6781e5662324c03 | https://github.com/rtm/upward/blob/82495c34f70c9a4336a3b34cc6781e5662324c03/src/Obj.js#L115-L122 |
48,090 | boylesoftware/x2node-common | index.js | buildMessageBuilder | function buildMessageBuilder(section) {
const logOptions = process.env.X2_LOG || '';
const msgBuilder = new Array();
if (!/(^|,)nots(,|$)/i.test(logOptions))
msgBuilder.push(() => (new Date()).toISOString());
if (!/(^|,)nopid(,|$)/i.test(logOptions))
msgBuilder.push(() => String(process.pid));
let m;
const envRE = new RegExp('(?:^|,)env:([^,]+)', 'gi');
while ((m = envRE.exec(logOptions)) !== null) {
const envName = m[1];
msgBuilder.push(() => process.env[envName]);
}
if (section && !/(^|,)nosec(,|$)/i.test(logOptions))
msgBuilder.push(() => section);
return msgBuilder;
} | javascript | function buildMessageBuilder(section) {
const logOptions = process.env.X2_LOG || '';
const msgBuilder = new Array();
if (!/(^|,)nots(,|$)/i.test(logOptions))
msgBuilder.push(() => (new Date()).toISOString());
if (!/(^|,)nopid(,|$)/i.test(logOptions))
msgBuilder.push(() => String(process.pid));
let m;
const envRE = new RegExp('(?:^|,)env:([^,]+)', 'gi');
while ((m = envRE.exec(logOptions)) !== null) {
const envName = m[1];
msgBuilder.push(() => process.env[envName]);
}
if (section && !/(^|,)nosec(,|$)/i.test(logOptions))
msgBuilder.push(() => section);
return msgBuilder;
} | [
"function",
"buildMessageBuilder",
"(",
"section",
")",
"{",
"const",
"logOptions",
"=",
"process",
".",
"env",
".",
"X2_LOG",
"||",
"''",
";",
"const",
"msgBuilder",
"=",
"new",
"Array",
"(",
")",
";",
"if",
"(",
"!",
"/",
"(^|,)nots(,|$)",
"/",
"i",
".",
"test",
"(",
"logOptions",
")",
")",
"msgBuilder",
".",
"push",
"(",
"(",
")",
"=>",
"(",
"new",
"Date",
"(",
")",
")",
".",
"toISOString",
"(",
")",
")",
";",
"if",
"(",
"!",
"/",
"(^|,)nopid(,|$)",
"/",
"i",
".",
"test",
"(",
"logOptions",
")",
")",
"msgBuilder",
".",
"push",
"(",
"(",
")",
"=>",
"String",
"(",
"process",
".",
"pid",
")",
")",
";",
"let",
"m",
";",
"const",
"envRE",
"=",
"new",
"RegExp",
"(",
"'(?:^|,)env:([^,]+)'",
",",
"'gi'",
")",
";",
"while",
"(",
"(",
"m",
"=",
"envRE",
".",
"exec",
"(",
"logOptions",
")",
")",
"!==",
"null",
")",
"{",
"const",
"envName",
"=",
"m",
"[",
"1",
"]",
";",
"msgBuilder",
".",
"push",
"(",
"(",
")",
"=>",
"process",
".",
"env",
"[",
"envName",
"]",
")",
";",
"}",
"if",
"(",
"section",
"&&",
"!",
"/",
"(^|,)nosec(,|$)",
"/",
"i",
".",
"test",
"(",
"logOptions",
")",
")",
"msgBuilder",
".",
"push",
"(",
"(",
")",
"=>",
"section",
")",
";",
"return",
"msgBuilder",
";",
"}"
] | Build message build functions list.
@private
@param {string} [section] Debug log section, nothing if error log.
@returns {Array.<function>} Message builder functions. | [
"Build",
"message",
"build",
"functions",
"list",
"."
] | 2ddb0672b4294395ddbdc60bff13263db9f0beae | https://github.com/boylesoftware/x2node-common/blob/2ddb0672b4294395ddbdc60bff13263db9f0beae/index.js#L133-L156 |
48,091 | rtm/upward | src/Css.js | makeSheet | function makeSheet(scope) {
var style = document.createElement('style');
document.head.appendChild(style);
var sheet = style.sheet;
if (scope) {
style.setAttribute('scoped', "scoped");
if (!scopedSupported) {
scope.dataset[scopedStyleIdsProp] = (scope.dataset[scopedStyleIdsProp] || "") + " " +
(sheet.scopedStyleId = makeScopedStyleId(scopedStyleId++));
}
}
return sheet;
} | javascript | function makeSheet(scope) {
var style = document.createElement('style');
document.head.appendChild(style);
var sheet = style.sheet;
if (scope) {
style.setAttribute('scoped', "scoped");
if (!scopedSupported) {
scope.dataset[scopedStyleIdsProp] = (scope.dataset[scopedStyleIdsProp] || "") + " " +
(sheet.scopedStyleId = makeScopedStyleId(scopedStyleId++));
}
}
return sheet;
} | [
"function",
"makeSheet",
"(",
"scope",
")",
"{",
"var",
"style",
"=",
"document",
".",
"createElement",
"(",
"'style'",
")",
";",
"document",
".",
"head",
".",
"appendChild",
"(",
"style",
")",
";",
"var",
"sheet",
"=",
"style",
".",
"sheet",
";",
"if",
"(",
"scope",
")",
"{",
"style",
".",
"setAttribute",
"(",
"'scoped'",
",",
"\"scoped\"",
")",
";",
"if",
"(",
"!",
"scopedSupported",
")",
"{",
"scope",
".",
"dataset",
"[",
"scopedStyleIdsProp",
"]",
"=",
"(",
"scope",
".",
"dataset",
"[",
"scopedStyleIdsProp",
"]",
"||",
"\"\"",
")",
"+",
"\" \"",
"+",
"(",
"sheet",
".",
"scopedStyleId",
"=",
"makeScopedStyleId",
"(",
"scopedStyleId",
"++",
")",
")",
";",
"}",
"}",
"return",
"sheet",
";",
"}"
] | Create a new stylesheet, optionally scoped to a DOM element. | [
"Create",
"a",
"new",
"stylesheet",
"optionally",
"scoped",
"to",
"a",
"DOM",
"element",
"."
] | 82495c34f70c9a4336a3b34cc6781e5662324c03 | https://github.com/rtm/upward/blob/82495c34f70c9a4336a3b34cc6781e5662324c03/src/Css.js#L38-L52 |
48,092 | openactive/skos.js | src/skos.js | Concept | function Concept(concept) {
if (!(concept.prefLabel && concept.id && concept.type === 'Concept')) {
throw new Error('Invalid concept: "' + concept.id + '"');
}
this.id = concept.id;
this.prefLabel = concept.prefLabel;
this.altLabel = concept.altLabel;
this.hiddenLabel = concept.hiddenLabel;
this.definition = concept.definition;
this._topConceptOf = concept.topConceptOf;
this._partOfScheme = false;
this._originalConcept = concept;
this._broaderConcepts = [];
this._narrowerConcepts = [];
this._relatedConcepts = [];
} | javascript | function Concept(concept) {
if (!(concept.prefLabel && concept.id && concept.type === 'Concept')) {
throw new Error('Invalid concept: "' + concept.id + '"');
}
this.id = concept.id;
this.prefLabel = concept.prefLabel;
this.altLabel = concept.altLabel;
this.hiddenLabel = concept.hiddenLabel;
this.definition = concept.definition;
this._topConceptOf = concept.topConceptOf;
this._partOfScheme = false;
this._originalConcept = concept;
this._broaderConcepts = [];
this._narrowerConcepts = [];
this._relatedConcepts = [];
} | [
"function",
"Concept",
"(",
"concept",
")",
"{",
"if",
"(",
"!",
"(",
"concept",
".",
"prefLabel",
"&&",
"concept",
".",
"id",
"&&",
"concept",
".",
"type",
"===",
"'Concept'",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Invalid concept: \"'",
"+",
"concept",
".",
"id",
"+",
"'\"'",
")",
";",
"}",
"this",
".",
"id",
"=",
"concept",
".",
"id",
";",
"this",
".",
"prefLabel",
"=",
"concept",
".",
"prefLabel",
";",
"this",
".",
"altLabel",
"=",
"concept",
".",
"altLabel",
";",
"this",
".",
"hiddenLabel",
"=",
"concept",
".",
"hiddenLabel",
";",
"this",
".",
"definition",
"=",
"concept",
".",
"definition",
";",
"this",
".",
"_topConceptOf",
"=",
"concept",
".",
"topConceptOf",
";",
"this",
".",
"_partOfScheme",
"=",
"false",
";",
"this",
".",
"_originalConcept",
"=",
"concept",
";",
"this",
".",
"_broaderConcepts",
"=",
"[",
"]",
";",
"this",
".",
"_narrowerConcepts",
"=",
"[",
"]",
";",
"this",
".",
"_relatedConcepts",
"=",
"[",
"]",
";",
"}"
] | Concept class.
A wrapper for the SKOS Concept JSON object
@constructor
@param {Object} concept - A Concept JSON object | [
"Concept",
"class",
"."
] | 1bdc88eb004924f8279dac541af0374fa692fda9 | https://github.com/openactive/skos.js/blob/1bdc88eb004924f8279dac541af0374fa692fda9/src/skos.js#L316-L331 |
48,093 | eblanshey/safenet | src/api/auth.js | function () {
// Get stored auth data.
var stored = this.storage.get();
// If nothing stored, proceed with new authorization
if (!stored) {
this.log('No auth data stored, starting authorization from scratch...');
return this.auth.authorize();
}
// Otherwise, set the auth data on the Request object so that it can be used for requests
this.log('Auth data stored, checking validity...');
this._auth = utils.unserialize(stored);
// Use the saved auth data to check if we're already authorized. If not, it will clear the stored
// data, then proceed with new authorization.
return this.auth.isAuth()
.then(function(result) {
if (result === false)
return this.auth.authorize();
}.bind(this));
} | javascript | function () {
// Get stored auth data.
var stored = this.storage.get();
// If nothing stored, proceed with new authorization
if (!stored) {
this.log('No auth data stored, starting authorization from scratch...');
return this.auth.authorize();
}
// Otherwise, set the auth data on the Request object so that it can be used for requests
this.log('Auth data stored, checking validity...');
this._auth = utils.unserialize(stored);
// Use the saved auth data to check if we're already authorized. If not, it will clear the stored
// data, then proceed with new authorization.
return this.auth.isAuth()
.then(function(result) {
if (result === false)
return this.auth.authorize();
}.bind(this));
} | [
"function",
"(",
")",
"{",
"// Get stored auth data.",
"var",
"stored",
"=",
"this",
".",
"storage",
".",
"get",
"(",
")",
";",
"// If nothing stored, proceed with new authorization",
"if",
"(",
"!",
"stored",
")",
"{",
"this",
".",
"log",
"(",
"'No auth data stored, starting authorization from scratch...'",
")",
";",
"return",
"this",
".",
"auth",
".",
"authorize",
"(",
")",
";",
"}",
"// Otherwise, set the auth data on the Request object so that it can be used for requests",
"this",
".",
"log",
"(",
"'Auth data stored, checking validity...'",
")",
";",
"this",
".",
"_auth",
"=",
"utils",
".",
"unserialize",
"(",
"stored",
")",
";",
"// Use the saved auth data to check if we're already authorized. If not, it will clear the stored",
"// data, then proceed with new authorization.",
"return",
"this",
".",
"auth",
".",
"isAuth",
"(",
")",
".",
"then",
"(",
"function",
"(",
"result",
")",
"{",
"if",
"(",
"result",
"===",
"false",
")",
"return",
"this",
".",
"auth",
".",
"authorize",
"(",
")",
";",
"}",
".",
"bind",
"(",
"this",
")",
")",
";",
"}"
] | Call this method in order to authenticate with SAFE, using either previous authentication
or new.
@returns {Promise} | [
"Call",
"this",
"method",
"in",
"order",
"to",
"authenticate",
"with",
"SAFE",
"using",
"either",
"previous",
"authentication",
"or",
"new",
"."
] | 8438251bf0999b43f39c231df299b05d01dd4618 | https://github.com/eblanshey/safenet/blob/8438251bf0999b43f39c231df299b05d01dd4618/src/api/auth.js#L12-L33 |
|
48,094 | eblanshey/safenet | src/api/auth.js | function () {
this.log('Authorizing...');
// Generate new asymmetric key pair and nonce, e.g. public-key encryption
var asymKeys = nacl.box.keyPair(),
asymNonce = nacl.randomBytes(nacl.box.nonceLength);
// The payload for the request
var authPayload = {
app: this.app,
publicKey: base64.fromByteArray(asymKeys.publicKey),
nonce: base64.fromByteArray(asymNonce),
permissions: this.permissions
};
// Proceed with request
return this.Request
.post('/auth')
.body(authPayload)
.execute()
.then(function (json) {
// We received the launcher's private key + encrypted symmetrical keys (i.e. private key encryption)
var launcherPubKey = base64.toByteArray(json.publicKey);
var messageWithSymKeys = base64.toByteArray(json.encryptedKey);
// Decrypt the private key/nonce
var key = nacl.box.open(messageWithSymKeys, asymNonce, launcherPubKey, asymKeys.secretKey);
// Save auth data for future requests
this._auth = {
token: json.token,
symKey: key.slice(0, nacl.secretbox.keyLength),
symNonce: key.slice(nacl.secretbox.keyLength)
};
// Set the auth data for future requests
this.storage.set(utils.serialize(this._auth));
this.log('Authorized');
}.bind(this), function(res) {
this.log('Could not authorize.');
this.storage.clear();
}.bind(this));
} | javascript | function () {
this.log('Authorizing...');
// Generate new asymmetric key pair and nonce, e.g. public-key encryption
var asymKeys = nacl.box.keyPair(),
asymNonce = nacl.randomBytes(nacl.box.nonceLength);
// The payload for the request
var authPayload = {
app: this.app,
publicKey: base64.fromByteArray(asymKeys.publicKey),
nonce: base64.fromByteArray(asymNonce),
permissions: this.permissions
};
// Proceed with request
return this.Request
.post('/auth')
.body(authPayload)
.execute()
.then(function (json) {
// We received the launcher's private key + encrypted symmetrical keys (i.e. private key encryption)
var launcherPubKey = base64.toByteArray(json.publicKey);
var messageWithSymKeys = base64.toByteArray(json.encryptedKey);
// Decrypt the private key/nonce
var key = nacl.box.open(messageWithSymKeys, asymNonce, launcherPubKey, asymKeys.secretKey);
// Save auth data for future requests
this._auth = {
token: json.token,
symKey: key.slice(0, nacl.secretbox.keyLength),
symNonce: key.slice(nacl.secretbox.keyLength)
};
// Set the auth data for future requests
this.storage.set(utils.serialize(this._auth));
this.log('Authorized');
}.bind(this), function(res) {
this.log('Could not authorize.');
this.storage.clear();
}.bind(this));
} | [
"function",
"(",
")",
"{",
"this",
".",
"log",
"(",
"'Authorizing...'",
")",
";",
"// Generate new asymmetric key pair and nonce, e.g. public-key encryption",
"var",
"asymKeys",
"=",
"nacl",
".",
"box",
".",
"keyPair",
"(",
")",
",",
"asymNonce",
"=",
"nacl",
".",
"randomBytes",
"(",
"nacl",
".",
"box",
".",
"nonceLength",
")",
";",
"// The payload for the request",
"var",
"authPayload",
"=",
"{",
"app",
":",
"this",
".",
"app",
",",
"publicKey",
":",
"base64",
".",
"fromByteArray",
"(",
"asymKeys",
".",
"publicKey",
")",
",",
"nonce",
":",
"base64",
".",
"fromByteArray",
"(",
"asymNonce",
")",
",",
"permissions",
":",
"this",
".",
"permissions",
"}",
";",
"// Proceed with request",
"return",
"this",
".",
"Request",
".",
"post",
"(",
"'/auth'",
")",
".",
"body",
"(",
"authPayload",
")",
".",
"execute",
"(",
")",
".",
"then",
"(",
"function",
"(",
"json",
")",
"{",
"// We received the launcher's private key + encrypted symmetrical keys (i.e. private key encryption)",
"var",
"launcherPubKey",
"=",
"base64",
".",
"toByteArray",
"(",
"json",
".",
"publicKey",
")",
";",
"var",
"messageWithSymKeys",
"=",
"base64",
".",
"toByteArray",
"(",
"json",
".",
"encryptedKey",
")",
";",
"// Decrypt the private key/nonce",
"var",
"key",
"=",
"nacl",
".",
"box",
".",
"open",
"(",
"messageWithSymKeys",
",",
"asymNonce",
",",
"launcherPubKey",
",",
"asymKeys",
".",
"secretKey",
")",
";",
"// Save auth data for future requests",
"this",
".",
"_auth",
"=",
"{",
"token",
":",
"json",
".",
"token",
",",
"symKey",
":",
"key",
".",
"slice",
"(",
"0",
",",
"nacl",
".",
"secretbox",
".",
"keyLength",
")",
",",
"symNonce",
":",
"key",
".",
"slice",
"(",
"nacl",
".",
"secretbox",
".",
"keyLength",
")",
"}",
";",
"// Set the auth data for future requests",
"this",
".",
"storage",
".",
"set",
"(",
"utils",
".",
"serialize",
"(",
"this",
".",
"_auth",
")",
")",
";",
"this",
".",
"log",
"(",
"'Authorized'",
")",
";",
"}",
".",
"bind",
"(",
"this",
")",
",",
"function",
"(",
"res",
")",
"{",
"this",
".",
"log",
"(",
"'Could not authorize.'",
")",
";",
"this",
".",
"storage",
".",
"clear",
"(",
")",
";",
"}",
".",
"bind",
"(",
"this",
")",
")",
";",
"}"
] | Requests authorization from the safe launcher.
@returns {*} | [
"Requests",
"authorization",
"from",
"the",
"safe",
"launcher",
"."
] | 8438251bf0999b43f39c231df299b05d01dd4618 | https://github.com/eblanshey/safenet/blob/8438251bf0999b43f39c231df299b05d01dd4618/src/api/auth.js#L39-L80 |
|
48,095 | eblanshey/safenet | src/api/auth.js | function () {
this.log('Checking if authorized...');
return this.Request.get('/auth').auth().execute()
// let's use our own function here, that resolve true or false,
// rather than throwing an error if invalid token
.then(function () {
this.log('Authorized');
return true;
}.bind(this), function (response) {
this.log('Not authorized, or received error.', response);
if (response.status === 401) {
// Remove any auth from storage and Request class
this.log('Not authorized, removing any stored auth data.');
clearAuthData.call(this);
// Return false
return false;
} else {
// Any other status is another error, throw the response
throw response;
}
}.bind(this));
} | javascript | function () {
this.log('Checking if authorized...');
return this.Request.get('/auth').auth().execute()
// let's use our own function here, that resolve true or false,
// rather than throwing an error if invalid token
.then(function () {
this.log('Authorized');
return true;
}.bind(this), function (response) {
this.log('Not authorized, or received error.', response);
if (response.status === 401) {
// Remove any auth from storage and Request class
this.log('Not authorized, removing any stored auth data.');
clearAuthData.call(this);
// Return false
return false;
} else {
// Any other status is another error, throw the response
throw response;
}
}.bind(this));
} | [
"function",
"(",
")",
"{",
"this",
".",
"log",
"(",
"'Checking if authorized...'",
")",
";",
"return",
"this",
".",
"Request",
".",
"get",
"(",
"'/auth'",
")",
".",
"auth",
"(",
")",
".",
"execute",
"(",
")",
"// let's use our own function here, that resolve true or false,",
"// rather than throwing an error if invalid token",
".",
"then",
"(",
"function",
"(",
")",
"{",
"this",
".",
"log",
"(",
"'Authorized'",
")",
";",
"return",
"true",
";",
"}",
".",
"bind",
"(",
"this",
")",
",",
"function",
"(",
"response",
")",
"{",
"this",
".",
"log",
"(",
"'Not authorized, or received error.'",
",",
"response",
")",
";",
"if",
"(",
"response",
".",
"status",
"===",
"401",
")",
"{",
"// Remove any auth from storage and Request class",
"this",
".",
"log",
"(",
"'Not authorized, removing any stored auth data.'",
")",
";",
"clearAuthData",
".",
"call",
"(",
"this",
")",
";",
"// Return false",
"return",
"false",
";",
"}",
"else",
"{",
"// Any other status is another error, throw the response",
"throw",
"response",
";",
"}",
"}",
".",
"bind",
"(",
"this",
")",
")",
";",
"}"
] | Checks if we're authenticated on the SAFE network
@returns {*} | [
"Checks",
"if",
"we",
"re",
"authenticated",
"on",
"the",
"SAFE",
"network"
] | 8438251bf0999b43f39c231df299b05d01dd4618 | https://github.com/eblanshey/safenet/blob/8438251bf0999b43f39c231df299b05d01dd4618/src/api/auth.js#L86-L108 |
|
48,096 | eblanshey/safenet | src/api/auth.js | function () {
this.log('Deauthorizing...');
return this.Request.delete('/auth').auth().execute()
.then(function (response) {
// Clear auth data from storage upon deauthorization
this.storage.clear();
clearAuthData.call(this);
this.log('Deauthorized and cleared from storage.');
return response;
}.bind(this));
} | javascript | function () {
this.log('Deauthorizing...');
return this.Request.delete('/auth').auth().execute()
.then(function (response) {
// Clear auth data from storage upon deauthorization
this.storage.clear();
clearAuthData.call(this);
this.log('Deauthorized and cleared from storage.');
return response;
}.bind(this));
} | [
"function",
"(",
")",
"{",
"this",
".",
"log",
"(",
"'Deauthorizing...'",
")",
";",
"return",
"this",
".",
"Request",
".",
"delete",
"(",
"'/auth'",
")",
".",
"auth",
"(",
")",
".",
"execute",
"(",
")",
".",
"then",
"(",
"function",
"(",
"response",
")",
"{",
"// Clear auth data from storage upon deauthorization",
"this",
".",
"storage",
".",
"clear",
"(",
")",
";",
"clearAuthData",
".",
"call",
"(",
"this",
")",
";",
"this",
".",
"log",
"(",
"'Deauthorized and cleared from storage.'",
")",
";",
"return",
"response",
";",
"}",
".",
"bind",
"(",
"this",
")",
")",
";",
"}"
] | Deauthorizes you from the launcher, and removed saved auth data from storage.
@returns {*} | [
"Deauthorizes",
"you",
"from",
"the",
"launcher",
"and",
"removed",
"saved",
"auth",
"data",
"from",
"storage",
"."
] | 8438251bf0999b43f39c231df299b05d01dd4618 | https://github.com/eblanshey/safenet/blob/8438251bf0999b43f39c231df299b05d01dd4618/src/api/auth.js#L114-L126 |
|
48,097 | milankinen/stanga | examples/04-bmi-counter/index.js | model | function model(M, prop) {
const bmiLens = L(
prop,
// if we don't have <prop> property yet, then use these default values
L.defaults({weight: 80, height: 180}),
// add "read-only" bmi property to our BMI model that is derived from weight and height
L.augment({bmi: ({weight: w, height: h}) => Math.round(w / (h * h * 0.0001))})
)
return M.lens(bmiLens)
} | javascript | function model(M, prop) {
const bmiLens = L(
prop,
// if we don't have <prop> property yet, then use these default values
L.defaults({weight: 80, height: 180}),
// add "read-only" bmi property to our BMI model that is derived from weight and height
L.augment({bmi: ({weight: w, height: h}) => Math.round(w / (h * h * 0.0001))})
)
return M.lens(bmiLens)
} | [
"function",
"model",
"(",
"M",
",",
"prop",
")",
"{",
"const",
"bmiLens",
"=",
"L",
"(",
"prop",
",",
"// if we don't have <prop> property yet, then use these default values",
"L",
".",
"defaults",
"(",
"{",
"weight",
":",
"80",
",",
"height",
":",
"180",
"}",
")",
",",
"// add \"read-only\" bmi property to our BMI model that is derived from weight and height",
"L",
".",
"augment",
"(",
"{",
"bmi",
":",
"(",
"{",
"weight",
":",
"w",
",",
"height",
":",
"h",
"}",
")",
"=>",
"Math",
".",
"round",
"(",
"w",
"/",
"(",
"h",
"*",
"h",
"*",
"0.0001",
")",
")",
"}",
")",
")",
"return",
"M",
".",
"lens",
"(",
"bmiLens",
")",
"}"
] | Let's define the model function so that it takes the parent state and property containing the BMI counter state. We are making this BMI model as a separate function so that we could re-use it if needed | [
"Let",
"s",
"define",
"the",
"model",
"function",
"so",
"that",
"it",
"takes",
"the",
"parent",
"state",
"and",
"property",
"containing",
"the",
"BMI",
"counter",
"state",
".",
"We",
"are",
"making",
"this",
"BMI",
"model",
"as",
"a",
"separate",
"function",
"so",
"that",
"we",
"could",
"re",
"-",
"use",
"it",
"if",
"needed"
] | 82f293c73162c997d138cb468992699df0c74180 | https://github.com/milankinen/stanga/blob/82f293c73162c997d138cb468992699df0c74180/examples/04-bmi-counter/index.js#L11-L20 |
48,098 | pjdietz/rester-client | src/parser.js | beginsWith | function beginsWith(haystack, needles) {
let needle;
for (let i = 0, u = needles.length; i < u; ++i) {
needle = needles[i];
if (haystack.substr(0, needle.length) === needle) {
return true;
}
}
return false;
} | javascript | function beginsWith(haystack, needles) {
let needle;
for (let i = 0, u = needles.length; i < u; ++i) {
needle = needles[i];
if (haystack.substr(0, needle.length) === needle) {
return true;
}
}
return false;
} | [
"function",
"beginsWith",
"(",
"haystack",
",",
"needles",
")",
"{",
"let",
"needle",
";",
"for",
"(",
"let",
"i",
"=",
"0",
",",
"u",
"=",
"needles",
".",
"length",
";",
"i",
"<",
"u",
";",
"++",
"i",
")",
"{",
"needle",
"=",
"needles",
"[",
"i",
"]",
";",
"if",
"(",
"haystack",
".",
"substr",
"(",
"0",
",",
"needle",
".",
"length",
")",
"===",
"needle",
")",
"{",
"return",
"true",
";",
"}",
"}",
"return",
"false",
";",
"}"
] | Tests if a string begins with any of the string in the array of needles.
@param {string} haystack String to test
@param {string[]} needles Array of string to look for
@return {boolean} True indicates the string begins with one of the needles. | [
"Tests",
"if",
"a",
"string",
"begins",
"with",
"any",
"of",
"the",
"string",
"in",
"the",
"array",
"of",
"needles",
"."
] | 00ffcedffc858fcc0cfd3fa7f55aeab3d11e13c9 | https://github.com/pjdietz/rester-client/blob/00ffcedffc858fcc0cfd3fa7f55aeab3d11e13c9/src/parser.js#L374-L383 |
48,099 | pjdietz/rester-client | src/parser.js | mergeQuery | function mergeQuery(path, newQuery) {
let parsed, properties, query, queryString;
// Return the original path if the query to merge is empty.
if (Object.keys(newQuery).length === 0) {
return path;
}
// Parse the original path.
parsed = url.parse(path, true);
// Merge the queries to form a new query.
query = parsed.query;
properties = Object.keys(newQuery);
for (let i = 0, u = properties.length; i < u; ++i) {
let property = properties[i];
query[property] = newQuery[property];
}
queryString = querystring.stringify(query);
path = parsed.pathname + '?' + queryString;
return path;
} | javascript | function mergeQuery(path, newQuery) {
let parsed, properties, query, queryString;
// Return the original path if the query to merge is empty.
if (Object.keys(newQuery).length === 0) {
return path;
}
// Parse the original path.
parsed = url.parse(path, true);
// Merge the queries to form a new query.
query = parsed.query;
properties = Object.keys(newQuery);
for (let i = 0, u = properties.length; i < u; ++i) {
let property = properties[i];
query[property] = newQuery[property];
}
queryString = querystring.stringify(query);
path = parsed.pathname + '?' + queryString;
return path;
} | [
"function",
"mergeQuery",
"(",
"path",
",",
"newQuery",
")",
"{",
"let",
"parsed",
",",
"properties",
",",
"query",
",",
"queryString",
";",
"// Return the original path if the query to merge is empty.",
"if",
"(",
"Object",
".",
"keys",
"(",
"newQuery",
")",
".",
"length",
"===",
"0",
")",
"{",
"return",
"path",
";",
"}",
"// Parse the original path.",
"parsed",
"=",
"url",
".",
"parse",
"(",
"path",
",",
"true",
")",
";",
"// Merge the queries to form a new query.",
"query",
"=",
"parsed",
".",
"query",
";",
"properties",
"=",
"Object",
".",
"keys",
"(",
"newQuery",
")",
";",
"for",
"(",
"let",
"i",
"=",
"0",
",",
"u",
"=",
"properties",
".",
"length",
";",
"i",
"<",
"u",
";",
"++",
"i",
")",
"{",
"let",
"property",
"=",
"properties",
"[",
"i",
"]",
";",
"query",
"[",
"property",
"]",
"=",
"newQuery",
"[",
"property",
"]",
";",
"}",
"queryString",
"=",
"querystring",
".",
"stringify",
"(",
"query",
")",
";",
"path",
"=",
"parsed",
".",
"pathname",
"+",
"'?'",
"+",
"queryString",
";",
"return",
"path",
";",
"}"
] | Merge additional query parameters onto an existing request path and return
the combined path + query
@param {string} path Request path, with or without a query
@param {Object} newQuery Query parameters to merge
@return {string} New path with query parameters merged | [
"Merge",
"additional",
"query",
"parameters",
"onto",
"an",
"existing",
"request",
"path",
"and",
"return",
"the",
"combined",
"path",
"+",
"query"
] | 00ffcedffc858fcc0cfd3fa7f55aeab3d11e13c9 | https://github.com/pjdietz/rester-client/blob/00ffcedffc858fcc0cfd3fa7f55aeab3d11e13c9/src/parser.js#L417-L435 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.