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
sequence | docstring
stringlengths 4
11.8k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 86
226
|
---|---|---|---|---|---|---|---|---|---|---|---|
5,300 | HospitalRun/hospitalrun-frontend | prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js | utf8Text | function utf8Text(buf, i) {
var total = utf8CheckIncomplete(this, buf, i);
if (!this.lastNeed) return buf.toString('utf8', i);
this.lastTotal = total;
var end = buf.length - (total - this.lastNeed);
buf.copy(this.lastChar, 0, end);
return buf.toString('utf8', i, end);
} | javascript | function utf8Text(buf, i) {
var total = utf8CheckIncomplete(this, buf, i);
if (!this.lastNeed) return buf.toString('utf8', i);
this.lastTotal = total;
var end = buf.length - (total - this.lastNeed);
buf.copy(this.lastChar, 0, end);
return buf.toString('utf8', i, end);
} | [
"function",
"utf8Text",
"(",
"buf",
",",
"i",
")",
"{",
"var",
"total",
"=",
"utf8CheckIncomplete",
"(",
"this",
",",
"buf",
",",
"i",
")",
";",
"if",
"(",
"!",
"this",
".",
"lastNeed",
")",
"return",
"buf",
".",
"toString",
"(",
"'utf8'",
",",
"i",
")",
";",
"this",
".",
"lastTotal",
"=",
"total",
";",
"var",
"end",
"=",
"buf",
".",
"length",
"-",
"(",
"total",
"-",
"this",
".",
"lastNeed",
")",
";",
"buf",
".",
"copy",
"(",
"this",
".",
"lastChar",
",",
"0",
",",
"end",
")",
";",
"return",
"buf",
".",
"toString",
"(",
"'utf8'",
",",
"i",
",",
"end",
")",
";",
"}"
] | Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a partial character, the character's bytes are buffered until the required number of bytes are available. | [
"Returns",
"all",
"complete",
"UTF",
"-",
"8",
"characters",
"in",
"a",
"Buffer",
".",
"If",
"the",
"Buffer",
"ended",
"on",
"a",
"partial",
"character",
"the",
"character",
"s",
"bytes",
"are",
"buffered",
"until",
"the",
"required",
"number",
"of",
"bytes",
"are",
"available",
"."
] | 60b692a1b7aa6f2ef007c28717e76582014e07ad | https://github.com/HospitalRun/hospitalrun-frontend/blob/60b692a1b7aa6f2ef007c28717e76582014e07ad/prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js#L13714-L13721 |
5,301 | HospitalRun/hospitalrun-frontend | prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js | utf16End | function utf16End(buf) {
var r = buf && buf.length ? this.write(buf) : '';
if (this.lastNeed) {
var end = this.lastTotal - this.lastNeed;
return r + this.lastChar.toString('utf16le', 0, end);
}
return r;
} | javascript | function utf16End(buf) {
var r = buf && buf.length ? this.write(buf) : '';
if (this.lastNeed) {
var end = this.lastTotal - this.lastNeed;
return r + this.lastChar.toString('utf16le', 0, end);
}
return r;
} | [
"function",
"utf16End",
"(",
"buf",
")",
"{",
"var",
"r",
"=",
"buf",
"&&",
"buf",
".",
"length",
"?",
"this",
".",
"write",
"(",
"buf",
")",
":",
"''",
";",
"if",
"(",
"this",
".",
"lastNeed",
")",
"{",
"var",
"end",
"=",
"this",
".",
"lastTotal",
"-",
"this",
".",
"lastNeed",
";",
"return",
"r",
"+",
"this",
".",
"lastChar",
".",
"toString",
"(",
"'utf16le'",
",",
"0",
",",
"end",
")",
";",
"}",
"return",
"r",
";",
"}"
] | For UTF-16LE we do not explicitly append special replacement characters if we end on a partial character, we simply let v8 handle that. | [
"For",
"UTF",
"-",
"16LE",
"we",
"do",
"not",
"explicitly",
"append",
"special",
"replacement",
"characters",
"if",
"we",
"end",
"on",
"a",
"partial",
"character",
"we",
"simply",
"let",
"v8",
"handle",
"that",
"."
] | 60b692a1b7aa6f2ef007c28717e76582014e07ad | https://github.com/HospitalRun/hospitalrun-frontend/blob/60b692a1b7aa6f2ef007c28717e76582014e07ad/prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js#L13758-L13765 |
5,302 | HospitalRun/hospitalrun-frontend | prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js | through2 | function through2 (construct) {
return function (options, transform, flush) {
if (typeof options == 'function') {
flush = transform
transform = options
options = {}
}
if (typeof transform != 'function')
transform = noop
if (typeof flush != 'function')
flush = null
return construct(options, transform, flush)
}
} | javascript | function through2 (construct) {
return function (options, transform, flush) {
if (typeof options == 'function') {
flush = transform
transform = options
options = {}
}
if (typeof transform != 'function')
transform = noop
if (typeof flush != 'function')
flush = null
return construct(options, transform, flush)
}
} | [
"function",
"through2",
"(",
"construct",
")",
"{",
"return",
"function",
"(",
"options",
",",
"transform",
",",
"flush",
")",
"{",
"if",
"(",
"typeof",
"options",
"==",
"'function'",
")",
"{",
"flush",
"=",
"transform",
"transform",
"=",
"options",
"options",
"=",
"{",
"}",
"}",
"if",
"(",
"typeof",
"transform",
"!=",
"'function'",
")",
"transform",
"=",
"noop",
"if",
"(",
"typeof",
"flush",
"!=",
"'function'",
")",
"flush",
"=",
"null",
"return",
"construct",
"(",
"options",
",",
"transform",
",",
"flush",
")",
"}",
"}"
] | create a new export function, used by both the main export and the .ctor export, contains common logic for dealing with arguments | [
"create",
"a",
"new",
"export",
"function",
"used",
"by",
"both",
"the",
"main",
"export",
"and",
"the",
".",
"ctor",
"export",
"contains",
"common",
"logic",
"for",
"dealing",
"with",
"arguments"
] | 60b692a1b7aa6f2ef007c28717e76582014e07ad | https://github.com/HospitalRun/hospitalrun-frontend/blob/60b692a1b7aa6f2ef007c28717e76582014e07ad/prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js#L13828-L13844 |
5,303 | HospitalRun/hospitalrun-frontend | prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js | parseDoc | function parseDoc(doc, newEdits) {
var nRevNum;
var newRevId;
var revInfo;
var opts = {status: 'available'};
if (doc._deleted) {
opts.deleted = true;
}
if (newEdits) {
if (!doc._id) {
doc._id = pouchdbUtils.uuid();
}
newRevId = pouchdbUtils.uuid(32, 16).toLowerCase();
if (doc._rev) {
revInfo = parseRevisionInfo(doc._rev);
if (revInfo.error) {
return revInfo;
}
doc._rev_tree = [{
pos: revInfo.prefix,
ids: [revInfo.id, {status: 'missing'}, [[newRevId, opts, []]]]
}];
nRevNum = revInfo.prefix + 1;
} else {
doc._rev_tree = [{
pos: 1,
ids : [newRevId, opts, []]
}];
nRevNum = 1;
}
} else {
if (doc._revisions) {
doc._rev_tree = makeRevTreeFromRevisions(doc._revisions, opts);
nRevNum = doc._revisions.start;
newRevId = doc._revisions.ids[0];
}
if (!doc._rev_tree) {
revInfo = parseRevisionInfo(doc._rev);
if (revInfo.error) {
return revInfo;
}
nRevNum = revInfo.prefix;
newRevId = revInfo.id;
doc._rev_tree = [{
pos: nRevNum,
ids: [newRevId, opts, []]
}];
}
}
pouchdbUtils.invalidIdError(doc._id);
doc._rev = nRevNum + '-' + newRevId;
var result = {metadata : {}, data : {}};
for (var key in doc) {
/* istanbul ignore else */
if (Object.prototype.hasOwnProperty.call(doc, key)) {
var specialKey = key[0] === '_';
if (specialKey && !reservedWords[key]) {
var error = pouchdbErrors.createError(pouchdbErrors.DOC_VALIDATION, key);
error.message = pouchdbErrors.DOC_VALIDATION.message + ': ' + key;
throw error;
} else if (specialKey && !dataWords[key]) {
result.metadata[key.slice(1)] = doc[key];
} else {
result.data[key] = doc[key];
}
}
}
return result;
} | javascript | function parseDoc(doc, newEdits) {
var nRevNum;
var newRevId;
var revInfo;
var opts = {status: 'available'};
if (doc._deleted) {
opts.deleted = true;
}
if (newEdits) {
if (!doc._id) {
doc._id = pouchdbUtils.uuid();
}
newRevId = pouchdbUtils.uuid(32, 16).toLowerCase();
if (doc._rev) {
revInfo = parseRevisionInfo(doc._rev);
if (revInfo.error) {
return revInfo;
}
doc._rev_tree = [{
pos: revInfo.prefix,
ids: [revInfo.id, {status: 'missing'}, [[newRevId, opts, []]]]
}];
nRevNum = revInfo.prefix + 1;
} else {
doc._rev_tree = [{
pos: 1,
ids : [newRevId, opts, []]
}];
nRevNum = 1;
}
} else {
if (doc._revisions) {
doc._rev_tree = makeRevTreeFromRevisions(doc._revisions, opts);
nRevNum = doc._revisions.start;
newRevId = doc._revisions.ids[0];
}
if (!doc._rev_tree) {
revInfo = parseRevisionInfo(doc._rev);
if (revInfo.error) {
return revInfo;
}
nRevNum = revInfo.prefix;
newRevId = revInfo.id;
doc._rev_tree = [{
pos: nRevNum,
ids: [newRevId, opts, []]
}];
}
}
pouchdbUtils.invalidIdError(doc._id);
doc._rev = nRevNum + '-' + newRevId;
var result = {metadata : {}, data : {}};
for (var key in doc) {
/* istanbul ignore else */
if (Object.prototype.hasOwnProperty.call(doc, key)) {
var specialKey = key[0] === '_';
if (specialKey && !reservedWords[key]) {
var error = pouchdbErrors.createError(pouchdbErrors.DOC_VALIDATION, key);
error.message = pouchdbErrors.DOC_VALIDATION.message + ': ' + key;
throw error;
} else if (specialKey && !dataWords[key]) {
result.metadata[key.slice(1)] = doc[key];
} else {
result.data[key] = doc[key];
}
}
}
return result;
} | [
"function",
"parseDoc",
"(",
"doc",
",",
"newEdits",
")",
"{",
"var",
"nRevNum",
";",
"var",
"newRevId",
";",
"var",
"revInfo",
";",
"var",
"opts",
"=",
"{",
"status",
":",
"'available'",
"}",
";",
"if",
"(",
"doc",
".",
"_deleted",
")",
"{",
"opts",
".",
"deleted",
"=",
"true",
";",
"}",
"if",
"(",
"newEdits",
")",
"{",
"if",
"(",
"!",
"doc",
".",
"_id",
")",
"{",
"doc",
".",
"_id",
"=",
"pouchdbUtils",
".",
"uuid",
"(",
")",
";",
"}",
"newRevId",
"=",
"pouchdbUtils",
".",
"uuid",
"(",
"32",
",",
"16",
")",
".",
"toLowerCase",
"(",
")",
";",
"if",
"(",
"doc",
".",
"_rev",
")",
"{",
"revInfo",
"=",
"parseRevisionInfo",
"(",
"doc",
".",
"_rev",
")",
";",
"if",
"(",
"revInfo",
".",
"error",
")",
"{",
"return",
"revInfo",
";",
"}",
"doc",
".",
"_rev_tree",
"=",
"[",
"{",
"pos",
":",
"revInfo",
".",
"prefix",
",",
"ids",
":",
"[",
"revInfo",
".",
"id",
",",
"{",
"status",
":",
"'missing'",
"}",
",",
"[",
"[",
"newRevId",
",",
"opts",
",",
"[",
"]",
"]",
"]",
"]",
"}",
"]",
";",
"nRevNum",
"=",
"revInfo",
".",
"prefix",
"+",
"1",
";",
"}",
"else",
"{",
"doc",
".",
"_rev_tree",
"=",
"[",
"{",
"pos",
":",
"1",
",",
"ids",
":",
"[",
"newRevId",
",",
"opts",
",",
"[",
"]",
"]",
"}",
"]",
";",
"nRevNum",
"=",
"1",
";",
"}",
"}",
"else",
"{",
"if",
"(",
"doc",
".",
"_revisions",
")",
"{",
"doc",
".",
"_rev_tree",
"=",
"makeRevTreeFromRevisions",
"(",
"doc",
".",
"_revisions",
",",
"opts",
")",
";",
"nRevNum",
"=",
"doc",
".",
"_revisions",
".",
"start",
";",
"newRevId",
"=",
"doc",
".",
"_revisions",
".",
"ids",
"[",
"0",
"]",
";",
"}",
"if",
"(",
"!",
"doc",
".",
"_rev_tree",
")",
"{",
"revInfo",
"=",
"parseRevisionInfo",
"(",
"doc",
".",
"_rev",
")",
";",
"if",
"(",
"revInfo",
".",
"error",
")",
"{",
"return",
"revInfo",
";",
"}",
"nRevNum",
"=",
"revInfo",
".",
"prefix",
";",
"newRevId",
"=",
"revInfo",
".",
"id",
";",
"doc",
".",
"_rev_tree",
"=",
"[",
"{",
"pos",
":",
"nRevNum",
",",
"ids",
":",
"[",
"newRevId",
",",
"opts",
",",
"[",
"]",
"]",
"}",
"]",
";",
"}",
"}",
"pouchdbUtils",
".",
"invalidIdError",
"(",
"doc",
".",
"_id",
")",
";",
"doc",
".",
"_rev",
"=",
"nRevNum",
"+",
"'-'",
"+",
"newRevId",
";",
"var",
"result",
"=",
"{",
"metadata",
":",
"{",
"}",
",",
"data",
":",
"{",
"}",
"}",
";",
"for",
"(",
"var",
"key",
"in",
"doc",
")",
"{",
"/* istanbul ignore else */",
"if",
"(",
"Object",
".",
"prototype",
".",
"hasOwnProperty",
".",
"call",
"(",
"doc",
",",
"key",
")",
")",
"{",
"var",
"specialKey",
"=",
"key",
"[",
"0",
"]",
"===",
"'_'",
";",
"if",
"(",
"specialKey",
"&&",
"!",
"reservedWords",
"[",
"key",
"]",
")",
"{",
"var",
"error",
"=",
"pouchdbErrors",
".",
"createError",
"(",
"pouchdbErrors",
".",
"DOC_VALIDATION",
",",
"key",
")",
";",
"error",
".",
"message",
"=",
"pouchdbErrors",
".",
"DOC_VALIDATION",
".",
"message",
"+",
"': '",
"+",
"key",
";",
"throw",
"error",
";",
"}",
"else",
"if",
"(",
"specialKey",
"&&",
"!",
"dataWords",
"[",
"key",
"]",
")",
"{",
"result",
".",
"metadata",
"[",
"key",
".",
"slice",
"(",
"1",
")",
"]",
"=",
"doc",
"[",
"key",
"]",
";",
"}",
"else",
"{",
"result",
".",
"data",
"[",
"key",
"]",
"=",
"doc",
"[",
"key",
"]",
";",
"}",
"}",
"}",
"return",
"result",
";",
"}"
] | Preprocess documents, parse their revisions, assign an id and a revision for new writes that are missing them, etc | [
"Preprocess",
"documents",
"parse",
"their",
"revisions",
"assign",
"an",
"id",
"and",
"a",
"revision",
"for",
"new",
"writes",
"that",
"are",
"missing",
"them",
"etc"
] | 60b692a1b7aa6f2ef007c28717e76582014e07ad | https://github.com/HospitalRun/hospitalrun-frontend/blob/60b692a1b7aa6f2ef007c28717e76582014e07ad/prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js#L14006-L14079 |
5,304 | HospitalRun/hospitalrun-frontend | prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js | readAsBinaryString | function readAsBinaryString(blob, callback) {
if (typeof FileReader === 'undefined') {
// fix for Firefox in a web worker
// https://bugzilla.mozilla.org/show_bug.cgi?id=901097
return callback(arrayBufferToBinaryString(
new FileReaderSync().readAsArrayBuffer(blob)));
}
var reader = new FileReader();
var hasBinaryString = typeof reader.readAsBinaryString === 'function';
reader.onloadend = function (e) {
var result = e.target.result || '';
if (hasBinaryString) {
return callback(result);
}
callback(arrayBufferToBinaryString(result));
};
if (hasBinaryString) {
reader.readAsBinaryString(blob);
} else {
reader.readAsArrayBuffer(blob);
}
} | javascript | function readAsBinaryString(blob, callback) {
if (typeof FileReader === 'undefined') {
// fix for Firefox in a web worker
// https://bugzilla.mozilla.org/show_bug.cgi?id=901097
return callback(arrayBufferToBinaryString(
new FileReaderSync().readAsArrayBuffer(blob)));
}
var reader = new FileReader();
var hasBinaryString = typeof reader.readAsBinaryString === 'function';
reader.onloadend = function (e) {
var result = e.target.result || '';
if (hasBinaryString) {
return callback(result);
}
callback(arrayBufferToBinaryString(result));
};
if (hasBinaryString) {
reader.readAsBinaryString(blob);
} else {
reader.readAsArrayBuffer(blob);
}
} | [
"function",
"readAsBinaryString",
"(",
"blob",
",",
"callback",
")",
"{",
"if",
"(",
"typeof",
"FileReader",
"===",
"'undefined'",
")",
"{",
"// fix for Firefox in a web worker",
"// https://bugzilla.mozilla.org/show_bug.cgi?id=901097",
"return",
"callback",
"(",
"arrayBufferToBinaryString",
"(",
"new",
"FileReaderSync",
"(",
")",
".",
"readAsArrayBuffer",
"(",
"blob",
")",
")",
")",
";",
"}",
"var",
"reader",
"=",
"new",
"FileReader",
"(",
")",
";",
"var",
"hasBinaryString",
"=",
"typeof",
"reader",
".",
"readAsBinaryString",
"===",
"'function'",
";",
"reader",
".",
"onloadend",
"=",
"function",
"(",
"e",
")",
"{",
"var",
"result",
"=",
"e",
".",
"target",
".",
"result",
"||",
"''",
";",
"if",
"(",
"hasBinaryString",
")",
"{",
"return",
"callback",
"(",
"result",
")",
";",
"}",
"callback",
"(",
"arrayBufferToBinaryString",
"(",
"result",
")",
")",
";",
"}",
";",
"if",
"(",
"hasBinaryString",
")",
"{",
"reader",
".",
"readAsBinaryString",
"(",
"blob",
")",
";",
"}",
"else",
"{",
"reader",
".",
"readAsArrayBuffer",
"(",
"blob",
")",
";",
"}",
"}"
] | shim for browsers that don't support it | [
"shim",
"for",
"browsers",
"that",
"don",
"t",
"support",
"it"
] | 60b692a1b7aa6f2ef007c28717e76582014e07ad | https://github.com/HospitalRun/hospitalrun-frontend/blob/60b692a1b7aa6f2ef007c28717e76582014e07ad/prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js#L14827-L14849 |
5,305 | HospitalRun/hospitalrun-frontend | prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js | yankError | function yankError(callback) {
return function (err, results) {
if (err || (results[0] && results[0].error)) {
callback(err || results[0]);
} else {
callback(null, results.length ? results[0] : results);
}
};
} | javascript | function yankError(callback) {
return function (err, results) {
if (err || (results[0] && results[0].error)) {
callback(err || results[0]);
} else {
callback(null, results.length ? results[0] : results);
}
};
} | [
"function",
"yankError",
"(",
"callback",
")",
"{",
"return",
"function",
"(",
"err",
",",
"results",
")",
"{",
"if",
"(",
"err",
"||",
"(",
"results",
"[",
"0",
"]",
"&&",
"results",
"[",
"0",
"]",
".",
"error",
")",
")",
"{",
"callback",
"(",
"err",
"||",
"results",
"[",
"0",
"]",
")",
";",
"}",
"else",
"{",
"callback",
"(",
"null",
",",
"results",
".",
"length",
"?",
"results",
"[",
"0",
"]",
":",
"results",
")",
";",
"}",
"}",
";",
"}"
] | Wrapper for functions that call the bulkdocs api with a single doc, if the first result is an error, return an error | [
"Wrapper",
"for",
"functions",
"that",
"call",
"the",
"bulkdocs",
"api",
"with",
"a",
"single",
"doc",
"if",
"the",
"first",
"result",
"is",
"an",
"error",
"return",
"an",
"error"
] | 60b692a1b7aa6f2ef007c28717e76582014e07ad | https://github.com/HospitalRun/hospitalrun-frontend/blob/60b692a1b7aa6f2ef007c28717e76582014e07ad/prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js#L16030-L16038 |
5,306 | HospitalRun/hospitalrun-frontend | prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js | cleanDocs | function cleanDocs(docs) {
for (var i = 0; i < docs.length; i++) {
var doc = docs[i];
if (doc._deleted) {
delete doc._attachments; // ignore atts for deleted docs
} else if (doc._attachments) {
// filter out extraneous keys from _attachments
var atts = Object.keys(doc._attachments);
for (var j = 0; j < atts.length; j++) {
var att = atts[j];
doc._attachments[att] = pouchdbUtils.pick(doc._attachments[att],
['data', 'digest', 'content_type', 'length', 'revpos', 'stub']);
}
}
}
} | javascript | function cleanDocs(docs) {
for (var i = 0; i < docs.length; i++) {
var doc = docs[i];
if (doc._deleted) {
delete doc._attachments; // ignore atts for deleted docs
} else if (doc._attachments) {
// filter out extraneous keys from _attachments
var atts = Object.keys(doc._attachments);
for (var j = 0; j < atts.length; j++) {
var att = atts[j];
doc._attachments[att] = pouchdbUtils.pick(doc._attachments[att],
['data', 'digest', 'content_type', 'length', 'revpos', 'stub']);
}
}
}
} | [
"function",
"cleanDocs",
"(",
"docs",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"docs",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"doc",
"=",
"docs",
"[",
"i",
"]",
";",
"if",
"(",
"doc",
".",
"_deleted",
")",
"{",
"delete",
"doc",
".",
"_attachments",
";",
"// ignore atts for deleted docs",
"}",
"else",
"if",
"(",
"doc",
".",
"_attachments",
")",
"{",
"// filter out extraneous keys from _attachments",
"var",
"atts",
"=",
"Object",
".",
"keys",
"(",
"doc",
".",
"_attachments",
")",
";",
"for",
"(",
"var",
"j",
"=",
"0",
";",
"j",
"<",
"atts",
".",
"length",
";",
"j",
"++",
")",
"{",
"var",
"att",
"=",
"atts",
"[",
"j",
"]",
";",
"doc",
".",
"_attachments",
"[",
"att",
"]",
"=",
"pouchdbUtils",
".",
"pick",
"(",
"doc",
".",
"_attachments",
"[",
"att",
"]",
",",
"[",
"'data'",
",",
"'digest'",
",",
"'content_type'",
",",
"'length'",
",",
"'revpos'",
",",
"'stub'",
"]",
")",
";",
"}",
"}",
"}",
"}"
] | clean docs given to us by the user | [
"clean",
"docs",
"given",
"to",
"us",
"by",
"the",
"user"
] | 60b692a1b7aa6f2ef007c28717e76582014e07ad | https://github.com/HospitalRun/hospitalrun-frontend/blob/60b692a1b7aa6f2ef007c28717e76582014e07ad/prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js#L16041-L16056 |
5,307 | HospitalRun/hospitalrun-frontend | prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js | compareByIdThenRev | function compareByIdThenRev(a, b) {
var idCompare = compare(a._id, b._id);
if (idCompare !== 0) {
return idCompare;
}
var aStart = a._revisions ? a._revisions.start : 0;
var bStart = b._revisions ? b._revisions.start : 0;
return compare(aStart, bStart);
} | javascript | function compareByIdThenRev(a, b) {
var idCompare = compare(a._id, b._id);
if (idCompare !== 0) {
return idCompare;
}
var aStart = a._revisions ? a._revisions.start : 0;
var bStart = b._revisions ? b._revisions.start : 0;
return compare(aStart, bStart);
} | [
"function",
"compareByIdThenRev",
"(",
"a",
",",
"b",
")",
"{",
"var",
"idCompare",
"=",
"compare",
"(",
"a",
".",
"_id",
",",
"b",
".",
"_id",
")",
";",
"if",
"(",
"idCompare",
"!==",
"0",
")",
"{",
"return",
"idCompare",
";",
"}",
"var",
"aStart",
"=",
"a",
".",
"_revisions",
"?",
"a",
".",
"_revisions",
".",
"start",
":",
"0",
";",
"var",
"bStart",
"=",
"b",
".",
"_revisions",
"?",
"b",
".",
"_revisions",
".",
"start",
":",
"0",
";",
"return",
"compare",
"(",
"aStart",
",",
"bStart",
")",
";",
"}"
] | compare two docs, first by _id then by _rev | [
"compare",
"two",
"docs",
"first",
"by",
"_id",
"then",
"by",
"_rev"
] | 60b692a1b7aa6f2ef007c28717e76582014e07ad | https://github.com/HospitalRun/hospitalrun-frontend/blob/60b692a1b7aa6f2ef007c28717e76582014e07ad/prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js#L16059-L16067 |
5,308 | HospitalRun/hospitalrun-frontend | prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js | computeHeight | function computeHeight(revs) {
var height = {};
var edges = [];
pouchdbMerge.traverseRevTree(revs, function (isLeaf, pos, id, prnt) {
var rev = pos + "-" + id;
if (isLeaf) {
height[rev] = 0;
}
if (prnt !== undefined) {
edges.push({from: prnt, to: rev});
}
return rev;
});
edges.reverse();
edges.forEach(function (edge) {
if (height[edge.from] === undefined) {
height[edge.from] = 1 + height[edge.to];
} else {
height[edge.from] = Math.min(height[edge.from], 1 + height[edge.to]);
}
});
return height;
} | javascript | function computeHeight(revs) {
var height = {};
var edges = [];
pouchdbMerge.traverseRevTree(revs, function (isLeaf, pos, id, prnt) {
var rev = pos + "-" + id;
if (isLeaf) {
height[rev] = 0;
}
if (prnt !== undefined) {
edges.push({from: prnt, to: rev});
}
return rev;
});
edges.reverse();
edges.forEach(function (edge) {
if (height[edge.from] === undefined) {
height[edge.from] = 1 + height[edge.to];
} else {
height[edge.from] = Math.min(height[edge.from], 1 + height[edge.to]);
}
});
return height;
} | [
"function",
"computeHeight",
"(",
"revs",
")",
"{",
"var",
"height",
"=",
"{",
"}",
";",
"var",
"edges",
"=",
"[",
"]",
";",
"pouchdbMerge",
".",
"traverseRevTree",
"(",
"revs",
",",
"function",
"(",
"isLeaf",
",",
"pos",
",",
"id",
",",
"prnt",
")",
"{",
"var",
"rev",
"=",
"pos",
"+",
"\"-\"",
"+",
"id",
";",
"if",
"(",
"isLeaf",
")",
"{",
"height",
"[",
"rev",
"]",
"=",
"0",
";",
"}",
"if",
"(",
"prnt",
"!==",
"undefined",
")",
"{",
"edges",
".",
"push",
"(",
"{",
"from",
":",
"prnt",
",",
"to",
":",
"rev",
"}",
")",
";",
"}",
"return",
"rev",
";",
"}",
")",
";",
"edges",
".",
"reverse",
"(",
")",
";",
"edges",
".",
"forEach",
"(",
"function",
"(",
"edge",
")",
"{",
"if",
"(",
"height",
"[",
"edge",
".",
"from",
"]",
"===",
"undefined",
")",
"{",
"height",
"[",
"edge",
".",
"from",
"]",
"=",
"1",
"+",
"height",
"[",
"edge",
".",
"to",
"]",
";",
"}",
"else",
"{",
"height",
"[",
"edge",
".",
"from",
"]",
"=",
"Math",
".",
"min",
"(",
"height",
"[",
"edge",
".",
"from",
"]",
",",
"1",
"+",
"height",
"[",
"edge",
".",
"to",
"]",
")",
";",
"}",
"}",
")",
";",
"return",
"height",
";",
"}"
] | for every node in a revision tree computes its distance from the closest leaf | [
"for",
"every",
"node",
"in",
"a",
"revision",
"tree",
"computes",
"its",
"distance",
"from",
"the",
"closest",
"leaf"
] | 60b692a1b7aa6f2ef007c28717e76582014e07ad | https://github.com/HospitalRun/hospitalrun-frontend/blob/60b692a1b7aa6f2ef007c28717e76582014e07ad/prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js#L16071-L16094 |
5,309 | HospitalRun/hospitalrun-frontend | prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js | doNextCompaction | function doNextCompaction(self) {
var task = self._compactionQueue[0];
var opts = task.opts;
var callback = task.callback;
self.get('_local/compaction').catch(function () {
return false;
}).then(function (doc) {
if (doc && doc.last_seq) {
opts.last_seq = doc.last_seq;
}
self._compact(opts, function (err, res) {
/* istanbul ignore if */
if (err) {
callback(err);
} else {
callback(null, res);
}
pouchdbUtils.nextTick(function () {
self._compactionQueue.shift();
if (self._compactionQueue.length) {
doNextCompaction(self);
}
});
});
});
} | javascript | function doNextCompaction(self) {
var task = self._compactionQueue[0];
var opts = task.opts;
var callback = task.callback;
self.get('_local/compaction').catch(function () {
return false;
}).then(function (doc) {
if (doc && doc.last_seq) {
opts.last_seq = doc.last_seq;
}
self._compact(opts, function (err, res) {
/* istanbul ignore if */
if (err) {
callback(err);
} else {
callback(null, res);
}
pouchdbUtils.nextTick(function () {
self._compactionQueue.shift();
if (self._compactionQueue.length) {
doNextCompaction(self);
}
});
});
});
} | [
"function",
"doNextCompaction",
"(",
"self",
")",
"{",
"var",
"task",
"=",
"self",
".",
"_compactionQueue",
"[",
"0",
"]",
";",
"var",
"opts",
"=",
"task",
".",
"opts",
";",
"var",
"callback",
"=",
"task",
".",
"callback",
";",
"self",
".",
"get",
"(",
"'_local/compaction'",
")",
".",
"catch",
"(",
"function",
"(",
")",
"{",
"return",
"false",
";",
"}",
")",
".",
"then",
"(",
"function",
"(",
"doc",
")",
"{",
"if",
"(",
"doc",
"&&",
"doc",
".",
"last_seq",
")",
"{",
"opts",
".",
"last_seq",
"=",
"doc",
".",
"last_seq",
";",
"}",
"self",
".",
"_compact",
"(",
"opts",
",",
"function",
"(",
"err",
",",
"res",
")",
"{",
"/* istanbul ignore if */",
"if",
"(",
"err",
")",
"{",
"callback",
"(",
"err",
")",
";",
"}",
"else",
"{",
"callback",
"(",
"null",
",",
"res",
")",
";",
"}",
"pouchdbUtils",
".",
"nextTick",
"(",
"function",
"(",
")",
"{",
"self",
".",
"_compactionQueue",
".",
"shift",
"(",
")",
";",
"if",
"(",
"self",
".",
"_compactionQueue",
".",
"length",
")",
"{",
"doNextCompaction",
"(",
"self",
")",
";",
"}",
"}",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | all compaction is done in a queue, to avoid attaching too many listeners at once | [
"all",
"compaction",
"is",
"done",
"in",
"a",
"queue",
"to",
"avoid",
"attaching",
"too",
"many",
"listeners",
"at",
"once"
] | 60b692a1b7aa6f2ef007c28717e76582014e07ad | https://github.com/HospitalRun/hospitalrun-frontend/blob/60b692a1b7aa6f2ef007c28717e76582014e07ad/prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js#L16132-L16157 |
5,310 | HospitalRun/hospitalrun-frontend | prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js | createFieldSorter | function createFieldSorter(sort) {
function getFieldValuesAsArray(doc) {
return sort.map(function (sorting) {
var fieldName = getKey(sorting);
var parsedField = parseField(fieldName);
var docFieldValue = getFieldFromDoc(doc, parsedField);
return docFieldValue;
});
}
return function (aRow, bRow) {
var aFieldValues = getFieldValuesAsArray(aRow.doc);
var bFieldValues = getFieldValuesAsArray(bRow.doc);
var collation = collate(aFieldValues, bFieldValues);
if (collation !== 0) {
return collation;
}
// this is what mango seems to do
return utils.compare(aRow.doc._id, bRow.doc._id);
};
} | javascript | function createFieldSorter(sort) {
function getFieldValuesAsArray(doc) {
return sort.map(function (sorting) {
var fieldName = getKey(sorting);
var parsedField = parseField(fieldName);
var docFieldValue = getFieldFromDoc(doc, parsedField);
return docFieldValue;
});
}
return function (aRow, bRow) {
var aFieldValues = getFieldValuesAsArray(aRow.doc);
var bFieldValues = getFieldValuesAsArray(bRow.doc);
var collation = collate(aFieldValues, bFieldValues);
if (collation !== 0) {
return collation;
}
// this is what mango seems to do
return utils.compare(aRow.doc._id, bRow.doc._id);
};
} | [
"function",
"createFieldSorter",
"(",
"sort",
")",
"{",
"function",
"getFieldValuesAsArray",
"(",
"doc",
")",
"{",
"return",
"sort",
".",
"map",
"(",
"function",
"(",
"sorting",
")",
"{",
"var",
"fieldName",
"=",
"getKey",
"(",
"sorting",
")",
";",
"var",
"parsedField",
"=",
"parseField",
"(",
"fieldName",
")",
";",
"var",
"docFieldValue",
"=",
"getFieldFromDoc",
"(",
"doc",
",",
"parsedField",
")",
";",
"return",
"docFieldValue",
";",
"}",
")",
";",
"}",
"return",
"function",
"(",
"aRow",
",",
"bRow",
")",
"{",
"var",
"aFieldValues",
"=",
"getFieldValuesAsArray",
"(",
"aRow",
".",
"doc",
")",
";",
"var",
"bFieldValues",
"=",
"getFieldValuesAsArray",
"(",
"bRow",
".",
"doc",
")",
";",
"var",
"collation",
"=",
"collate",
"(",
"aFieldValues",
",",
"bFieldValues",
")",
";",
"if",
"(",
"collation",
"!==",
"0",
")",
"{",
"return",
"collation",
";",
"}",
"// this is what mango seems to do",
"return",
"utils",
".",
"compare",
"(",
"aRow",
".",
"doc",
".",
"_id",
",",
"bRow",
".",
"doc",
".",
"_id",
")",
";",
"}",
";",
"}"
] | create a comparator based on the sort object | [
"create",
"a",
"comparator",
"based",
"on",
"the",
"sort",
"object"
] | 60b692a1b7aa6f2ef007c28717e76582014e07ad | https://github.com/HospitalRun/hospitalrun-frontend/blob/60b692a1b7aa6f2ef007c28717e76582014e07ad/prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js#L19347-L19368 |
5,311 | HospitalRun/hospitalrun-frontend | prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js | checkFieldInIndex | function checkFieldInIndex(index, field) {
var indexFields = index.def.fields.map(getKey);
for (var i = 0, len = indexFields.length; i < len; i++) {
var indexField = indexFields[i];
if (field === indexField) {
return true;
}
}
return false;
} | javascript | function checkFieldInIndex(index, field) {
var indexFields = index.def.fields.map(getKey);
for (var i = 0, len = indexFields.length; i < len; i++) {
var indexField = indexFields[i];
if (field === indexField) {
return true;
}
}
return false;
} | [
"function",
"checkFieldInIndex",
"(",
"index",
",",
"field",
")",
"{",
"var",
"indexFields",
"=",
"index",
".",
"def",
".",
"fields",
".",
"map",
"(",
"getKey",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"len",
"=",
"indexFields",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"var",
"indexField",
"=",
"indexFields",
"[",
"i",
"]",
";",
"if",
"(",
"field",
"===",
"indexField",
")",
"{",
"return",
"true",
";",
"}",
"}",
"return",
"false",
";",
"}"
] | couchdb second-lowest collation value | [
"couchdb",
"second",
"-",
"lowest",
"collation",
"value"
] | 60b692a1b7aa6f2ef007c28717e76582014e07ad | https://github.com/HospitalRun/hospitalrun-frontend/blob/60b692a1b7aa6f2ef007c28717e76582014e07ad/prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js#L19780-L19789 |
5,312 | HospitalRun/hospitalrun-frontend | prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js | sortFieldsByIndex | function sortFieldsByIndex(userFields, index) {
var indexFields = index.def.fields.map(getKey);
return userFields.slice().sort(function (a, b) {
var aIdx = indexFields.indexOf(a);
var bIdx = indexFields.indexOf(b);
if (aIdx === -1) {
aIdx = Number.MAX_VALUE;
}
if (bIdx === -1) {
bIdx = Number.MAX_VALUE;
}
return utils.compare(aIdx, bIdx);
});
} | javascript | function sortFieldsByIndex(userFields, index) {
var indexFields = index.def.fields.map(getKey);
return userFields.slice().sort(function (a, b) {
var aIdx = indexFields.indexOf(a);
var bIdx = indexFields.indexOf(b);
if (aIdx === -1) {
aIdx = Number.MAX_VALUE;
}
if (bIdx === -1) {
bIdx = Number.MAX_VALUE;
}
return utils.compare(aIdx, bIdx);
});
} | [
"function",
"sortFieldsByIndex",
"(",
"userFields",
",",
"index",
")",
"{",
"var",
"indexFields",
"=",
"index",
".",
"def",
".",
"fields",
".",
"map",
"(",
"getKey",
")",
";",
"return",
"userFields",
".",
"slice",
"(",
")",
".",
"sort",
"(",
"function",
"(",
"a",
",",
"b",
")",
"{",
"var",
"aIdx",
"=",
"indexFields",
".",
"indexOf",
"(",
"a",
")",
";",
"var",
"bIdx",
"=",
"indexFields",
".",
"indexOf",
"(",
"b",
")",
";",
"if",
"(",
"aIdx",
"===",
"-",
"1",
")",
"{",
"aIdx",
"=",
"Number",
".",
"MAX_VALUE",
";",
"}",
"if",
"(",
"bIdx",
"===",
"-",
"1",
")",
"{",
"bIdx",
"=",
"Number",
".",
"MAX_VALUE",
";",
"}",
"return",
"utils",
".",
"compare",
"(",
"aIdx",
",",
"bIdx",
")",
";",
"}",
")",
";",
"}"
] | sort the user fields by their position in the index, if they're in the index | [
"sort",
"the",
"user",
"fields",
"by",
"their",
"position",
"in",
"the",
"index",
"if",
"they",
"re",
"in",
"the",
"index"
] | 60b692a1b7aa6f2ef007c28717e76582014e07ad | https://github.com/HospitalRun/hospitalrun-frontend/blob/60b692a1b7aa6f2ef007c28717e76582014e07ad/prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js#L19805-L19819 |
5,313 | HospitalRun/hospitalrun-frontend | prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js | getBasicInMemoryFields | function getBasicInMemoryFields(index, selector, userFields) {
userFields = sortFieldsByIndex(userFields, index);
// check if any of the user selectors lose precision
var needToFilterInMemory = false;
for (var i = 0, len = userFields.length; i < len; i++) {
var field = userFields[i];
if (needToFilterInMemory || !checkFieldInIndex(index, field)) {
return userFields.slice(i);
}
if (i < len - 1 && userOperatorLosesPrecision(selector, field)) {
needToFilterInMemory = true;
}
}
return [];
} | javascript | function getBasicInMemoryFields(index, selector, userFields) {
userFields = sortFieldsByIndex(userFields, index);
// check if any of the user selectors lose precision
var needToFilterInMemory = false;
for (var i = 0, len = userFields.length; i < len; i++) {
var field = userFields[i];
if (needToFilterInMemory || !checkFieldInIndex(index, field)) {
return userFields.slice(i);
}
if (i < len - 1 && userOperatorLosesPrecision(selector, field)) {
needToFilterInMemory = true;
}
}
return [];
} | [
"function",
"getBasicInMemoryFields",
"(",
"index",
",",
"selector",
",",
"userFields",
")",
"{",
"userFields",
"=",
"sortFieldsByIndex",
"(",
"userFields",
",",
"index",
")",
";",
"// check if any of the user selectors lose precision",
"var",
"needToFilterInMemory",
"=",
"false",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"len",
"=",
"userFields",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"var",
"field",
"=",
"userFields",
"[",
"i",
"]",
";",
"if",
"(",
"needToFilterInMemory",
"||",
"!",
"checkFieldInIndex",
"(",
"index",
",",
"field",
")",
")",
"{",
"return",
"userFields",
".",
"slice",
"(",
"i",
")",
";",
"}",
"if",
"(",
"i",
"<",
"len",
"-",
"1",
"&&",
"userOperatorLosesPrecision",
"(",
"selector",
",",
"field",
")",
")",
"{",
"needToFilterInMemory",
"=",
"true",
";",
"}",
"}",
"return",
"[",
"]",
";",
"}"
] | first pass to try to find fields that will need to be sorted in-memory | [
"first",
"pass",
"to",
"try",
"to",
"find",
"fields",
"that",
"will",
"need",
"to",
"be",
"sorted",
"in",
"-",
"memory"
] | 60b692a1b7aa6f2ef007c28717e76582014e07ad | https://github.com/HospitalRun/hospitalrun-frontend/blob/60b692a1b7aa6f2ef007c28717e76582014e07ad/prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js#L19822-L19838 |
5,314 | HospitalRun/hospitalrun-frontend | prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js | checkIndexFieldsMatch | function checkIndexFieldsMatch(indexFields, sortOrder, fields) {
if (sortOrder) {
// array has to be a strict subarray of index array. furthermore,
// the sortOrder fields need to all be represented in the index
var sortMatches = utils.oneArrayIsStrictSubArrayOfOther(sortOrder, indexFields);
var selectorMatches = utils.oneArrayIsSubArrayOfOther(fields, indexFields);
return sortMatches && selectorMatches;
}
// all of the user's specified fields still need to be
// on the left side of the index array, although the order
// doesn't matter
return utils.oneSetIsSubArrayOfOther(fields, indexFields);
} | javascript | function checkIndexFieldsMatch(indexFields, sortOrder, fields) {
if (sortOrder) {
// array has to be a strict subarray of index array. furthermore,
// the sortOrder fields need to all be represented in the index
var sortMatches = utils.oneArrayIsStrictSubArrayOfOther(sortOrder, indexFields);
var selectorMatches = utils.oneArrayIsSubArrayOfOther(fields, indexFields);
return sortMatches && selectorMatches;
}
// all of the user's specified fields still need to be
// on the left side of the index array, although the order
// doesn't matter
return utils.oneSetIsSubArrayOfOther(fields, indexFields);
} | [
"function",
"checkIndexFieldsMatch",
"(",
"indexFields",
",",
"sortOrder",
",",
"fields",
")",
"{",
"if",
"(",
"sortOrder",
")",
"{",
"// array has to be a strict subarray of index array. furthermore,",
"// the sortOrder fields need to all be represented in the index",
"var",
"sortMatches",
"=",
"utils",
".",
"oneArrayIsStrictSubArrayOfOther",
"(",
"sortOrder",
",",
"indexFields",
")",
";",
"var",
"selectorMatches",
"=",
"utils",
".",
"oneArrayIsSubArrayOfOther",
"(",
"fields",
",",
"indexFields",
")",
";",
"return",
"sortMatches",
"&&",
"selectorMatches",
";",
"}",
"// all of the user's specified fields still need to be",
"// on the left side of the index array, although the order",
"// doesn't matter",
"return",
"utils",
".",
"oneSetIsSubArrayOfOther",
"(",
"fields",
",",
"indexFields",
")",
";",
"}"
] | check that at least one field in the user's query is represented in the index. order matters in the case of sorts | [
"check",
"that",
"at",
"least",
"one",
"field",
"in",
"the",
"user",
"s",
"query",
"is",
"represented",
"in",
"the",
"index",
".",
"order",
"matters",
"in",
"the",
"case",
"of",
"sorts"
] | 60b692a1b7aa6f2ef007c28717e76582014e07ad | https://github.com/HospitalRun/hospitalrun-frontend/blob/60b692a1b7aa6f2ef007c28717e76582014e07ad/prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js#L19868-L19882 |
5,315 | HospitalRun/hospitalrun-frontend | prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js | findBestMatchingIndex | function findBestMatchingIndex(selector, userFields, sortOrder, indexes) {
var matchingIndexes = findMatchingIndexes(selector, userFields, sortOrder, indexes);
if (matchingIndexes.length === 0) {
//return `all_docs` as a default index;
//I'm assuming that _all_docs is always first
var defaultIndex = indexes[0];
defaultIndex.defaultUsed = true;
return defaultIndex;
}
if (matchingIndexes.length === 1) {
return matchingIndexes[0];
}
var userFieldsMap = utils.arrayToObject(userFields);
function scoreIndex(index) {
var indexFields = index.def.fields.map(getKey);
var score = 0;
for (var i = 0, len = indexFields.length; i < len; i++) {
var indexField = indexFields[i];
if (userFieldsMap[indexField]) {
score++;
}
}
return score;
}
return utils.max(matchingIndexes, scoreIndex);
} | javascript | function findBestMatchingIndex(selector, userFields, sortOrder, indexes) {
var matchingIndexes = findMatchingIndexes(selector, userFields, sortOrder, indexes);
if (matchingIndexes.length === 0) {
//return `all_docs` as a default index;
//I'm assuming that _all_docs is always first
var defaultIndex = indexes[0];
defaultIndex.defaultUsed = true;
return defaultIndex;
}
if (matchingIndexes.length === 1) {
return matchingIndexes[0];
}
var userFieldsMap = utils.arrayToObject(userFields);
function scoreIndex(index) {
var indexFields = index.def.fields.map(getKey);
var score = 0;
for (var i = 0, len = indexFields.length; i < len; i++) {
var indexField = indexFields[i];
if (userFieldsMap[indexField]) {
score++;
}
}
return score;
}
return utils.max(matchingIndexes, scoreIndex);
} | [
"function",
"findBestMatchingIndex",
"(",
"selector",
",",
"userFields",
",",
"sortOrder",
",",
"indexes",
")",
"{",
"var",
"matchingIndexes",
"=",
"findMatchingIndexes",
"(",
"selector",
",",
"userFields",
",",
"sortOrder",
",",
"indexes",
")",
";",
"if",
"(",
"matchingIndexes",
".",
"length",
"===",
"0",
")",
"{",
"//return `all_docs` as a default index;",
"//I'm assuming that _all_docs is always first",
"var",
"defaultIndex",
"=",
"indexes",
"[",
"0",
"]",
";",
"defaultIndex",
".",
"defaultUsed",
"=",
"true",
";",
"return",
"defaultIndex",
";",
"}",
"if",
"(",
"matchingIndexes",
".",
"length",
"===",
"1",
")",
"{",
"return",
"matchingIndexes",
"[",
"0",
"]",
";",
"}",
"var",
"userFieldsMap",
"=",
"utils",
".",
"arrayToObject",
"(",
"userFields",
")",
";",
"function",
"scoreIndex",
"(",
"index",
")",
"{",
"var",
"indexFields",
"=",
"index",
".",
"def",
".",
"fields",
".",
"map",
"(",
"getKey",
")",
";",
"var",
"score",
"=",
"0",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"len",
"=",
"indexFields",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"var",
"indexField",
"=",
"indexFields",
"[",
"i",
"]",
";",
"if",
"(",
"userFieldsMap",
"[",
"indexField",
"]",
")",
"{",
"score",
"++",
";",
"}",
"}",
"return",
"score",
";",
"}",
"return",
"utils",
".",
"max",
"(",
"matchingIndexes",
",",
"scoreIndex",
")",
";",
"}"
] | find the best index, i.e. the one that matches the most fields in the user's query | [
"find",
"the",
"best",
"index",
"i",
".",
"e",
".",
"the",
"one",
"that",
"matches",
"the",
"most",
"fields",
"in",
"the",
"user",
"s",
"query"
] | 60b692a1b7aa6f2ef007c28717e76582014e07ad | https://github.com/HospitalRun/hospitalrun-frontend/blob/60b692a1b7aa6f2ef007c28717e76582014e07ad/prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js#L19948-L19978 |
5,316 | HospitalRun/hospitalrun-frontend | prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js | massageSort | function massageSort(sort) {
if (!Array.isArray(sort)) {
throw new Error('invalid sort json - should be an array');
}
return sort.map(function (sorting) {
if (typeof sorting === 'string') {
var obj = {};
obj[sorting] = 'asc';
return obj;
} else {
return sorting;
}
});
} | javascript | function massageSort(sort) {
if (!Array.isArray(sort)) {
throw new Error('invalid sort json - should be an array');
}
return sort.map(function (sorting) {
if (typeof sorting === 'string') {
var obj = {};
obj[sorting] = 'asc';
return obj;
} else {
return sorting;
}
});
} | [
"function",
"massageSort",
"(",
"sort",
")",
"{",
"if",
"(",
"!",
"Array",
".",
"isArray",
"(",
"sort",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'invalid sort json - should be an array'",
")",
";",
"}",
"return",
"sort",
".",
"map",
"(",
"function",
"(",
"sorting",
")",
"{",
"if",
"(",
"typeof",
"sorting",
"===",
"'string'",
")",
"{",
"var",
"obj",
"=",
"{",
"}",
";",
"obj",
"[",
"sorting",
"]",
"=",
"'asc'",
";",
"return",
"obj",
";",
"}",
"else",
"{",
"return",
"sorting",
";",
"}",
"}",
")",
";",
"}"
] | normalize the "sort" value | [
"normalize",
"the",
"sort",
"value"
] | 60b692a1b7aa6f2ef007c28717e76582014e07ad | https://github.com/HospitalRun/hospitalrun-frontend/blob/60b692a1b7aa6f2ef007c28717e76582014e07ad/prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js#L20289-L20302 |
5,317 | HospitalRun/hospitalrun-frontend | prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js | filterInclusiveStart | function filterInclusiveStart(rows, targetValue, index) {
var indexFields = index.def.fields;
for (var i = 0, len = rows.length; i < len; i++) {
var row = rows[i];
// shave off any docs at the beginning that are <= the
// target value
var docKey = getKeyFromDoc(row.doc, index);
if (indexFields.length === 1) {
docKey = docKey[0]; // only one field, not multi-field
} else { // more than one field in index
// in the case where e.g. the user is searching {$gt: {a: 1}}
// but the index is [a, b], then we need to shorten the doc key
while (docKey.length > targetValue.length) {
docKey.pop();
}
}
//ABS as we just looking for values that don't match
if (Math.abs(collate.collate(docKey, targetValue)) > 0) {
// no need to filter any further; we're past the key
break;
}
}
return i > 0 ? rows.slice(i) : rows;
} | javascript | function filterInclusiveStart(rows, targetValue, index) {
var indexFields = index.def.fields;
for (var i = 0, len = rows.length; i < len; i++) {
var row = rows[i];
// shave off any docs at the beginning that are <= the
// target value
var docKey = getKeyFromDoc(row.doc, index);
if (indexFields.length === 1) {
docKey = docKey[0]; // only one field, not multi-field
} else { // more than one field in index
// in the case where e.g. the user is searching {$gt: {a: 1}}
// but the index is [a, b], then we need to shorten the doc key
while (docKey.length > targetValue.length) {
docKey.pop();
}
}
//ABS as we just looking for values that don't match
if (Math.abs(collate.collate(docKey, targetValue)) > 0) {
// no need to filter any further; we're past the key
break;
}
}
return i > 0 ? rows.slice(i) : rows;
} | [
"function",
"filterInclusiveStart",
"(",
"rows",
",",
"targetValue",
",",
"index",
")",
"{",
"var",
"indexFields",
"=",
"index",
".",
"def",
".",
"fields",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"len",
"=",
"rows",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"var",
"row",
"=",
"rows",
"[",
"i",
"]",
";",
"// shave off any docs at the beginning that are <= the",
"// target value",
"var",
"docKey",
"=",
"getKeyFromDoc",
"(",
"row",
".",
"doc",
",",
"index",
")",
";",
"if",
"(",
"indexFields",
".",
"length",
"===",
"1",
")",
"{",
"docKey",
"=",
"docKey",
"[",
"0",
"]",
";",
"// only one field, not multi-field",
"}",
"else",
"{",
"// more than one field in index",
"// in the case where e.g. the user is searching {$gt: {a: 1}}",
"// but the index is [a, b], then we need to shorten the doc key",
"while",
"(",
"docKey",
".",
"length",
">",
"targetValue",
".",
"length",
")",
"{",
"docKey",
".",
"pop",
"(",
")",
";",
"}",
"}",
"//ABS as we just looking for values that don't match",
"if",
"(",
"Math",
".",
"abs",
"(",
"collate",
".",
"collate",
"(",
"docKey",
",",
"targetValue",
")",
")",
">",
"0",
")",
"{",
"// no need to filter any further; we're past the key",
"break",
";",
"}",
"}",
"return",
"i",
">",
"0",
"?",
"rows",
".",
"slice",
"(",
"i",
")",
":",
"rows",
";",
"}"
] | have to do this manually because REASONS. I don't know why CouchDB didn't implement inclusive_start | [
"have",
"to",
"do",
"this",
"manually",
"because",
"REASONS",
".",
"I",
"don",
"t",
"know",
"why",
"CouchDB",
"didn",
"t",
"implement",
"inclusive_start"
] | 60b692a1b7aa6f2ef007c28717e76582014e07ad | https://github.com/HospitalRun/hospitalrun-frontend/blob/60b692a1b7aa6f2ef007c28717e76582014e07ad/prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js#L20501-L20526 |
5,318 | HospitalRun/hospitalrun-frontend | prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js | generateReplicationId | function generateReplicationId(src, target, opts) {
var docIds = opts.doc_ids ? opts.doc_ids.sort(pouchdbCollate.collate) : '';
var filterFun = opts.filter ? opts.filter.toString() : '';
var queryParams = '';
var filterViewName = '';
var selector = '';
// possibility for checkpoints to be lost here as behaviour of
// JSON.stringify is not stable (see #6226)
/* istanbul ignore if */
if (opts.selector) {
selector = JSON.stringify(opts.selector);
}
if (opts.filter && opts.query_params) {
queryParams = JSON.stringify(sortObjectPropertiesByKey(opts.query_params));
}
if (opts.filter && opts.filter === '_view') {
filterViewName = opts.view.toString();
}
return Promise.all([src.id(), target.id()]).then(function (res) {
var queryData = res[0] + res[1] + filterFun + filterViewName +
queryParams + docIds + selector;
return new Promise(function (resolve) {
pouchdbMd5.binaryMd5(queryData, resolve);
});
}).then(function (md5sum) {
// can't use straight-up md5 alphabet, because
// the char '/' is interpreted as being for attachments,
// and + is also not url-safe
md5sum = md5sum.replace(/\//g, '.').replace(/\+/g, '_');
return '_local/' + md5sum;
});
} | javascript | function generateReplicationId(src, target, opts) {
var docIds = opts.doc_ids ? opts.doc_ids.sort(pouchdbCollate.collate) : '';
var filterFun = opts.filter ? opts.filter.toString() : '';
var queryParams = '';
var filterViewName = '';
var selector = '';
// possibility for checkpoints to be lost here as behaviour of
// JSON.stringify is not stable (see #6226)
/* istanbul ignore if */
if (opts.selector) {
selector = JSON.stringify(opts.selector);
}
if (opts.filter && opts.query_params) {
queryParams = JSON.stringify(sortObjectPropertiesByKey(opts.query_params));
}
if (opts.filter && opts.filter === '_view') {
filterViewName = opts.view.toString();
}
return Promise.all([src.id(), target.id()]).then(function (res) {
var queryData = res[0] + res[1] + filterFun + filterViewName +
queryParams + docIds + selector;
return new Promise(function (resolve) {
pouchdbMd5.binaryMd5(queryData, resolve);
});
}).then(function (md5sum) {
// can't use straight-up md5 alphabet, because
// the char '/' is interpreted as being for attachments,
// and + is also not url-safe
md5sum = md5sum.replace(/\//g, '.').replace(/\+/g, '_');
return '_local/' + md5sum;
});
} | [
"function",
"generateReplicationId",
"(",
"src",
",",
"target",
",",
"opts",
")",
"{",
"var",
"docIds",
"=",
"opts",
".",
"doc_ids",
"?",
"opts",
".",
"doc_ids",
".",
"sort",
"(",
"pouchdbCollate",
".",
"collate",
")",
":",
"''",
";",
"var",
"filterFun",
"=",
"opts",
".",
"filter",
"?",
"opts",
".",
"filter",
".",
"toString",
"(",
")",
":",
"''",
";",
"var",
"queryParams",
"=",
"''",
";",
"var",
"filterViewName",
"=",
"''",
";",
"var",
"selector",
"=",
"''",
";",
"// possibility for checkpoints to be lost here as behaviour of",
"// JSON.stringify is not stable (see #6226)",
"/* istanbul ignore if */",
"if",
"(",
"opts",
".",
"selector",
")",
"{",
"selector",
"=",
"JSON",
".",
"stringify",
"(",
"opts",
".",
"selector",
")",
";",
"}",
"if",
"(",
"opts",
".",
"filter",
"&&",
"opts",
".",
"query_params",
")",
"{",
"queryParams",
"=",
"JSON",
".",
"stringify",
"(",
"sortObjectPropertiesByKey",
"(",
"opts",
".",
"query_params",
")",
")",
";",
"}",
"if",
"(",
"opts",
".",
"filter",
"&&",
"opts",
".",
"filter",
"===",
"'_view'",
")",
"{",
"filterViewName",
"=",
"opts",
".",
"view",
".",
"toString",
"(",
")",
";",
"}",
"return",
"Promise",
".",
"all",
"(",
"[",
"src",
".",
"id",
"(",
")",
",",
"target",
".",
"id",
"(",
")",
"]",
")",
".",
"then",
"(",
"function",
"(",
"res",
")",
"{",
"var",
"queryData",
"=",
"res",
"[",
"0",
"]",
"+",
"res",
"[",
"1",
"]",
"+",
"filterFun",
"+",
"filterViewName",
"+",
"queryParams",
"+",
"docIds",
"+",
"selector",
";",
"return",
"new",
"Promise",
"(",
"function",
"(",
"resolve",
")",
"{",
"pouchdbMd5",
".",
"binaryMd5",
"(",
"queryData",
",",
"resolve",
")",
";",
"}",
")",
";",
"}",
")",
".",
"then",
"(",
"function",
"(",
"md5sum",
")",
"{",
"// can't use straight-up md5 alphabet, because",
"// the char '/' is interpreted as being for attachments,",
"// and + is also not url-safe",
"md5sum",
"=",
"md5sum",
".",
"replace",
"(",
"/",
"\\/",
"/",
"g",
",",
"'.'",
")",
".",
"replace",
"(",
"/",
"\\+",
"/",
"g",
",",
"'_'",
")",
";",
"return",
"'_local/'",
"+",
"md5sum",
";",
"}",
")",
";",
"}"
] | Generate a unique id particular to this replication. Not guaranteed to align perfectly with CouchDB's rep ids. | [
"Generate",
"a",
"unique",
"id",
"particular",
"to",
"this",
"replication",
".",
"Not",
"guaranteed",
"to",
"align",
"perfectly",
"with",
"CouchDB",
"s",
"rep",
"ids",
"."
] | 60b692a1b7aa6f2ef007c28717e76582014e07ad | https://github.com/HospitalRun/hospitalrun-frontend/blob/60b692a1b7aa6f2ef007c28717e76582014e07ad/prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js#L21762-L21797 |
5,319 | HospitalRun/hospitalrun-frontend | prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js | fin | function fin(promise, finalPromiseFactory) {
return promise.then(function (res) {
return finalPromiseFactory().then(function () {
return res;
});
}, function (reason) {
return finalPromiseFactory().then(function () {
throw reason;
});
});
} | javascript | function fin(promise, finalPromiseFactory) {
return promise.then(function (res) {
return finalPromiseFactory().then(function () {
return res;
});
}, function (reason) {
return finalPromiseFactory().then(function () {
throw reason;
});
});
} | [
"function",
"fin",
"(",
"promise",
",",
"finalPromiseFactory",
")",
"{",
"return",
"promise",
".",
"then",
"(",
"function",
"(",
"res",
")",
"{",
"return",
"finalPromiseFactory",
"(",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"return",
"res",
";",
"}",
")",
";",
"}",
",",
"function",
"(",
"reason",
")",
"{",
"return",
"finalPromiseFactory",
"(",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"throw",
"reason",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | Promise finally util similar to Q.finally | [
"Promise",
"finally",
"util",
"similar",
"to",
"Q",
".",
"finally"
] | 60b692a1b7aa6f2ef007c28717e76582014e07ad | https://github.com/HospitalRun/hospitalrun-frontend/blob/60b692a1b7aa6f2ef007c28717e76582014e07ad/prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js#L21913-L21923 |
5,320 | HospitalRun/hospitalrun-frontend | prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js | sumsqr | function sumsqr(values) {
var _sumsqr = 0;
for (var i = 0, len = values.length; i < len; i++) {
var num = values[i];
_sumsqr += (num * num);
}
return _sumsqr;
} | javascript | function sumsqr(values) {
var _sumsqr = 0;
for (var i = 0, len = values.length; i < len; i++) {
var num = values[i];
_sumsqr += (num * num);
}
return _sumsqr;
} | [
"function",
"sumsqr",
"(",
"values",
")",
"{",
"var",
"_sumsqr",
"=",
"0",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"len",
"=",
"values",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"var",
"num",
"=",
"values",
"[",
"i",
"]",
";",
"_sumsqr",
"+=",
"(",
"num",
"*",
"num",
")",
";",
"}",
"return",
"_sumsqr",
";",
"}"
] | no need to implement rereduce=true, because Pouch will never call it | [
"no",
"need",
"to",
"implement",
"rereduce",
"=",
"true",
"because",
"Pouch",
"will",
"never",
"call",
"it"
] | 60b692a1b7aa6f2ef007c28717e76582014e07ad | https://github.com/HospitalRun/hospitalrun-frontend/blob/60b692a1b7aa6f2ef007c28717e76582014e07ad/prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js#L22041-L22048 |
5,321 | HospitalRun/hospitalrun-frontend | prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js | traverseRevTree | function traverseRevTree(revs, callback) {
var toVisit = revs.slice();
var node;
while ((node = toVisit.pop())) {
var pos = node.pos;
var tree = node.ids;
var branches = tree[2];
var newCtx =
callback(branches.length === 0, pos, tree[0], node.ctx, tree[1]);
for (var i = 0, len = branches.length; i < len; i++) {
toVisit.push({pos: pos + 1, ids: branches[i], ctx: newCtx});
}
}
} | javascript | function traverseRevTree(revs, callback) {
var toVisit = revs.slice();
var node;
while ((node = toVisit.pop())) {
var pos = node.pos;
var tree = node.ids;
var branches = tree[2];
var newCtx =
callback(branches.length === 0, pos, tree[0], node.ctx, tree[1]);
for (var i = 0, len = branches.length; i < len; i++) {
toVisit.push({pos: pos + 1, ids: branches[i], ctx: newCtx});
}
}
} | [
"function",
"traverseRevTree",
"(",
"revs",
",",
"callback",
")",
"{",
"var",
"toVisit",
"=",
"revs",
".",
"slice",
"(",
")",
";",
"var",
"node",
";",
"while",
"(",
"(",
"node",
"=",
"toVisit",
".",
"pop",
"(",
")",
")",
")",
"{",
"var",
"pos",
"=",
"node",
".",
"pos",
";",
"var",
"tree",
"=",
"node",
".",
"ids",
";",
"var",
"branches",
"=",
"tree",
"[",
"2",
"]",
";",
"var",
"newCtx",
"=",
"callback",
"(",
"branches",
".",
"length",
"===",
"0",
",",
"pos",
",",
"tree",
"[",
"0",
"]",
",",
"node",
".",
"ctx",
",",
"tree",
"[",
"1",
"]",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"len",
"=",
"branches",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"toVisit",
".",
"push",
"(",
"{",
"pos",
":",
"pos",
"+",
"1",
",",
"ids",
":",
"branches",
"[",
"i",
"]",
",",
"ctx",
":",
"newCtx",
"}",
")",
";",
"}",
"}",
"}"
] | Pretty much all below can be combined into a higher order function to traverse revisions The return value from the callback will be passed as context to all children of that node | [
"Pretty",
"much",
"all",
"below",
"can",
"be",
"combined",
"into",
"a",
"higher",
"order",
"function",
"to",
"traverse",
"revisions",
"The",
"return",
"value",
"from",
"the",
"callback",
"will",
"be",
"passed",
"as",
"context",
"to",
"all",
"children",
"of",
"that",
"node"
] | 60b692a1b7aa6f2ef007c28717e76582014e07ad | https://github.com/HospitalRun/hospitalrun-frontend/blob/60b692a1b7aa6f2ef007c28717e76582014e07ad/prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js#L22236-L22250 |
5,322 | HospitalRun/hospitalrun-frontend | prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js | collectConflicts | function collectConflicts(metadata) {
var win = winningRev(metadata);
var leaves = collectLeaves(metadata.rev_tree);
var conflicts = [];
for (var i = 0, len = leaves.length; i < len; i++) {
var leaf = leaves[i];
if (leaf.rev !== win && !leaf.opts.deleted) {
conflicts.push(leaf.rev);
}
}
return conflicts;
} | javascript | function collectConflicts(metadata) {
var win = winningRev(metadata);
var leaves = collectLeaves(metadata.rev_tree);
var conflicts = [];
for (var i = 0, len = leaves.length; i < len; i++) {
var leaf = leaves[i];
if (leaf.rev !== win && !leaf.opts.deleted) {
conflicts.push(leaf.rev);
}
}
return conflicts;
} | [
"function",
"collectConflicts",
"(",
"metadata",
")",
"{",
"var",
"win",
"=",
"winningRev",
"(",
"metadata",
")",
";",
"var",
"leaves",
"=",
"collectLeaves",
"(",
"metadata",
".",
"rev_tree",
")",
";",
"var",
"conflicts",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"len",
"=",
"leaves",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"var",
"leaf",
"=",
"leaves",
"[",
"i",
"]",
";",
"if",
"(",
"leaf",
".",
"rev",
"!==",
"win",
"&&",
"!",
"leaf",
".",
"opts",
".",
"deleted",
")",
"{",
"conflicts",
".",
"push",
"(",
"leaf",
".",
"rev",
")",
";",
"}",
"}",
"return",
"conflicts",
";",
"}"
] | returns revs of all conflicts that is leaves such that 1. are not deleted and 2. are different than winning revision | [
"returns",
"revs",
"of",
"all",
"conflicts",
"that",
"is",
"leaves",
"such",
"that",
"1",
".",
"are",
"not",
"deleted",
"and",
"2",
".",
"are",
"different",
"than",
"winning",
"revision"
] | 60b692a1b7aa6f2ef007c28717e76582014e07ad | https://github.com/HospitalRun/hospitalrun-frontend/blob/60b692a1b7aa6f2ef007c28717e76582014e07ad/prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js#L22273-L22284 |
5,323 | HospitalRun/hospitalrun-frontend | prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js | compactTree | function compactTree(metadata) {
var revs = [];
traverseRevTree(metadata.rev_tree, function (isLeaf, pos,
revHash, ctx, opts) {
if (opts.status === 'available' && !isLeaf) {
revs.push(pos + '-' + revHash);
opts.status = 'missing';
}
});
return revs;
} | javascript | function compactTree(metadata) {
var revs = [];
traverseRevTree(metadata.rev_tree, function (isLeaf, pos,
revHash, ctx, opts) {
if (opts.status === 'available' && !isLeaf) {
revs.push(pos + '-' + revHash);
opts.status = 'missing';
}
});
return revs;
} | [
"function",
"compactTree",
"(",
"metadata",
")",
"{",
"var",
"revs",
"=",
"[",
"]",
";",
"traverseRevTree",
"(",
"metadata",
".",
"rev_tree",
",",
"function",
"(",
"isLeaf",
",",
"pos",
",",
"revHash",
",",
"ctx",
",",
"opts",
")",
"{",
"if",
"(",
"opts",
".",
"status",
"===",
"'available'",
"&&",
"!",
"isLeaf",
")",
"{",
"revs",
".",
"push",
"(",
"pos",
"+",
"'-'",
"+",
"revHash",
")",
";",
"opts",
".",
"status",
"=",
"'missing'",
";",
"}",
"}",
")",
";",
"return",
"revs",
";",
"}"
] | compact a tree by marking its non-leafs as missing, and return a list of revs to delete | [
"compact",
"a",
"tree",
"by",
"marking",
"its",
"non",
"-",
"leafs",
"as",
"missing",
"and",
"return",
"a",
"list",
"of",
"revs",
"to",
"delete"
] | 60b692a1b7aa6f2ef007c28717e76582014e07ad | https://github.com/HospitalRun/hospitalrun-frontend/blob/60b692a1b7aa6f2ef007c28717e76582014e07ad/prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js#L22288-L22298 |
5,324 | HospitalRun/hospitalrun-frontend | prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js | rootToLeaf | function rootToLeaf(revs) {
var paths = [];
var toVisit = revs.slice();
var node;
while ((node = toVisit.pop())) {
var pos = node.pos;
var tree = node.ids;
var id = tree[0];
var opts = tree[1];
var branches = tree[2];
var isLeaf = branches.length === 0;
var history = node.history ? node.history.slice() : [];
history.push({id: id, opts: opts});
if (isLeaf) {
paths.push({pos: (pos + 1 - history.length), ids: history});
}
for (var i = 0, len = branches.length; i < len; i++) {
toVisit.push({pos: pos + 1, ids: branches[i], history: history});
}
}
return paths.reverse();
} | javascript | function rootToLeaf(revs) {
var paths = [];
var toVisit = revs.slice();
var node;
while ((node = toVisit.pop())) {
var pos = node.pos;
var tree = node.ids;
var id = tree[0];
var opts = tree[1];
var branches = tree[2];
var isLeaf = branches.length === 0;
var history = node.history ? node.history.slice() : [];
history.push({id: id, opts: opts});
if (isLeaf) {
paths.push({pos: (pos + 1 - history.length), ids: history});
}
for (var i = 0, len = branches.length; i < len; i++) {
toVisit.push({pos: pos + 1, ids: branches[i], history: history});
}
}
return paths.reverse();
} | [
"function",
"rootToLeaf",
"(",
"revs",
")",
"{",
"var",
"paths",
"=",
"[",
"]",
";",
"var",
"toVisit",
"=",
"revs",
".",
"slice",
"(",
")",
";",
"var",
"node",
";",
"while",
"(",
"(",
"node",
"=",
"toVisit",
".",
"pop",
"(",
")",
")",
")",
"{",
"var",
"pos",
"=",
"node",
".",
"pos",
";",
"var",
"tree",
"=",
"node",
".",
"ids",
";",
"var",
"id",
"=",
"tree",
"[",
"0",
"]",
";",
"var",
"opts",
"=",
"tree",
"[",
"1",
"]",
";",
"var",
"branches",
"=",
"tree",
"[",
"2",
"]",
";",
"var",
"isLeaf",
"=",
"branches",
".",
"length",
"===",
"0",
";",
"var",
"history",
"=",
"node",
".",
"history",
"?",
"node",
".",
"history",
".",
"slice",
"(",
")",
":",
"[",
"]",
";",
"history",
".",
"push",
"(",
"{",
"id",
":",
"id",
",",
"opts",
":",
"opts",
"}",
")",
";",
"if",
"(",
"isLeaf",
")",
"{",
"paths",
".",
"push",
"(",
"{",
"pos",
":",
"(",
"pos",
"+",
"1",
"-",
"history",
".",
"length",
")",
",",
"ids",
":",
"history",
"}",
")",
";",
"}",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"len",
"=",
"branches",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"toVisit",
".",
"push",
"(",
"{",
"pos",
":",
"pos",
"+",
"1",
",",
"ids",
":",
"branches",
"[",
"i",
"]",
",",
"history",
":",
"history",
"}",
")",
";",
"}",
"}",
"return",
"paths",
".",
"reverse",
"(",
")",
";",
"}"
] | build up a list of all the paths to the leafs in this revision tree | [
"build",
"up",
"a",
"list",
"of",
"all",
"the",
"paths",
"to",
"the",
"leafs",
"in",
"this",
"revision",
"tree"
] | 60b692a1b7aa6f2ef007c28717e76582014e07ad | https://github.com/HospitalRun/hospitalrun-frontend/blob/60b692a1b7aa6f2ef007c28717e76582014e07ad/prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js#L22301-L22323 |
5,325 | HospitalRun/hospitalrun-frontend | prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js | binarySearch | function binarySearch(arr, item, comparator) {
var low = 0;
var high = arr.length;
var mid;
while (low < high) {
mid = (low + high) >>> 1;
if (comparator(arr[mid], item) < 0) {
low = mid + 1;
} else {
high = mid;
}
}
return low;
} | javascript | function binarySearch(arr, item, comparator) {
var low = 0;
var high = arr.length;
var mid;
while (low < high) {
mid = (low + high) >>> 1;
if (comparator(arr[mid], item) < 0) {
low = mid + 1;
} else {
high = mid;
}
}
return low;
} | [
"function",
"binarySearch",
"(",
"arr",
",",
"item",
",",
"comparator",
")",
"{",
"var",
"low",
"=",
"0",
";",
"var",
"high",
"=",
"arr",
".",
"length",
";",
"var",
"mid",
";",
"while",
"(",
"low",
"<",
"high",
")",
"{",
"mid",
"=",
"(",
"low",
"+",
"high",
")",
">>>",
"1",
";",
"if",
"(",
"comparator",
"(",
"arr",
"[",
"mid",
"]",
",",
"item",
")",
"<",
"0",
")",
"{",
"low",
"=",
"mid",
"+",
"1",
";",
"}",
"else",
"{",
"high",
"=",
"mid",
";",
"}",
"}",
"return",
"low",
";",
"}"
] | classic binary search | [
"classic",
"binary",
"search"
] | 60b692a1b7aa6f2ef007c28717e76582014e07ad | https://github.com/HospitalRun/hospitalrun-frontend/blob/60b692a1b7aa6f2ef007c28717e76582014e07ad/prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js#L22341-L22354 |
5,326 | HospitalRun/hospitalrun-frontend | prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js | insertSorted | function insertSorted(arr, item, comparator) {
var idx = binarySearch(arr, item, comparator);
arr.splice(idx, 0, item);
} | javascript | function insertSorted(arr, item, comparator) {
var idx = binarySearch(arr, item, comparator);
arr.splice(idx, 0, item);
} | [
"function",
"insertSorted",
"(",
"arr",
",",
"item",
",",
"comparator",
")",
"{",
"var",
"idx",
"=",
"binarySearch",
"(",
"arr",
",",
"item",
",",
"comparator",
")",
";",
"arr",
".",
"splice",
"(",
"idx",
",",
"0",
",",
"item",
")",
";",
"}"
] | assuming the arr is sorted, insert the item in the proper place | [
"assuming",
"the",
"arr",
"is",
"sorted",
"insert",
"the",
"item",
"in",
"the",
"proper",
"place"
] | 60b692a1b7aa6f2ef007c28717e76582014e07ad | https://github.com/HospitalRun/hospitalrun-frontend/blob/60b692a1b7aa6f2ef007c28717e76582014e07ad/prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js#L22357-L22360 |
5,327 | HospitalRun/hospitalrun-frontend | prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js | pathToTree | function pathToTree(path, numStemmed) {
var root;
var leaf;
for (var i = numStemmed, len = path.length; i < len; i++) {
var node = path[i];
var currentLeaf = [node.id, node.opts, []];
if (leaf) {
leaf[2].push(currentLeaf);
leaf = currentLeaf;
} else {
root = leaf = currentLeaf;
}
}
return root;
} | javascript | function pathToTree(path, numStemmed) {
var root;
var leaf;
for (var i = numStemmed, len = path.length; i < len; i++) {
var node = path[i];
var currentLeaf = [node.id, node.opts, []];
if (leaf) {
leaf[2].push(currentLeaf);
leaf = currentLeaf;
} else {
root = leaf = currentLeaf;
}
}
return root;
} | [
"function",
"pathToTree",
"(",
"path",
",",
"numStemmed",
")",
"{",
"var",
"root",
";",
"var",
"leaf",
";",
"for",
"(",
"var",
"i",
"=",
"numStemmed",
",",
"len",
"=",
"path",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"var",
"node",
"=",
"path",
"[",
"i",
"]",
";",
"var",
"currentLeaf",
"=",
"[",
"node",
".",
"id",
",",
"node",
".",
"opts",
",",
"[",
"]",
"]",
";",
"if",
"(",
"leaf",
")",
"{",
"leaf",
"[",
"2",
"]",
".",
"push",
"(",
"currentLeaf",
")",
";",
"leaf",
"=",
"currentLeaf",
";",
"}",
"else",
"{",
"root",
"=",
"leaf",
"=",
"currentLeaf",
";",
"}",
"}",
"return",
"root",
";",
"}"
] | Turn a path as a flat array into a tree with a single branch. If any should be stemmed from the beginning of the array, that's passed in as the second argument | [
"Turn",
"a",
"path",
"as",
"a",
"flat",
"array",
"into",
"a",
"tree",
"with",
"a",
"single",
"branch",
".",
"If",
"any",
"should",
"be",
"stemmed",
"from",
"the",
"beginning",
"of",
"the",
"array",
"that",
"s",
"passed",
"in",
"as",
"the",
"second",
"argument"
] | 60b692a1b7aa6f2ef007c28717e76582014e07ad | https://github.com/HospitalRun/hospitalrun-frontend/blob/60b692a1b7aa6f2ef007c28717e76582014e07ad/prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js#L22365-L22379 |
5,328 | HospitalRun/hospitalrun-frontend | prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js | mergeTree | function mergeTree(in_tree1, in_tree2) {
var queue = [{tree1: in_tree1, tree2: in_tree2}];
var conflicts = false;
while (queue.length > 0) {
var item = queue.pop();
var tree1 = item.tree1;
var tree2 = item.tree2;
if (tree1[1].status || tree2[1].status) {
tree1[1].status =
(tree1[1].status === 'available' ||
tree2[1].status === 'available') ? 'available' : 'missing';
}
for (var i = 0; i < tree2[2].length; i++) {
if (!tree1[2][0]) {
conflicts = 'new_leaf';
tree1[2][0] = tree2[2][i];
continue;
}
var merged = false;
for (var j = 0; j < tree1[2].length; j++) {
if (tree1[2][j][0] === tree2[2][i][0]) {
queue.push({tree1: tree1[2][j], tree2: tree2[2][i]});
merged = true;
}
}
if (!merged) {
conflicts = 'new_branch';
insertSorted(tree1[2], tree2[2][i], compareTree);
}
}
}
return {conflicts: conflicts, tree: in_tree1};
} | javascript | function mergeTree(in_tree1, in_tree2) {
var queue = [{tree1: in_tree1, tree2: in_tree2}];
var conflicts = false;
while (queue.length > 0) {
var item = queue.pop();
var tree1 = item.tree1;
var tree2 = item.tree2;
if (tree1[1].status || tree2[1].status) {
tree1[1].status =
(tree1[1].status === 'available' ||
tree2[1].status === 'available') ? 'available' : 'missing';
}
for (var i = 0; i < tree2[2].length; i++) {
if (!tree1[2][0]) {
conflicts = 'new_leaf';
tree1[2][0] = tree2[2][i];
continue;
}
var merged = false;
for (var j = 0; j < tree1[2].length; j++) {
if (tree1[2][j][0] === tree2[2][i][0]) {
queue.push({tree1: tree1[2][j], tree2: tree2[2][i]});
merged = true;
}
}
if (!merged) {
conflicts = 'new_branch';
insertSorted(tree1[2], tree2[2][i], compareTree);
}
}
}
return {conflicts: conflicts, tree: in_tree1};
} | [
"function",
"mergeTree",
"(",
"in_tree1",
",",
"in_tree2",
")",
"{",
"var",
"queue",
"=",
"[",
"{",
"tree1",
":",
"in_tree1",
",",
"tree2",
":",
"in_tree2",
"}",
"]",
";",
"var",
"conflicts",
"=",
"false",
";",
"while",
"(",
"queue",
".",
"length",
">",
"0",
")",
"{",
"var",
"item",
"=",
"queue",
".",
"pop",
"(",
")",
";",
"var",
"tree1",
"=",
"item",
".",
"tree1",
";",
"var",
"tree2",
"=",
"item",
".",
"tree2",
";",
"if",
"(",
"tree1",
"[",
"1",
"]",
".",
"status",
"||",
"tree2",
"[",
"1",
"]",
".",
"status",
")",
"{",
"tree1",
"[",
"1",
"]",
".",
"status",
"=",
"(",
"tree1",
"[",
"1",
"]",
".",
"status",
"===",
"'available'",
"||",
"tree2",
"[",
"1",
"]",
".",
"status",
"===",
"'available'",
")",
"?",
"'available'",
":",
"'missing'",
";",
"}",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"tree2",
"[",
"2",
"]",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"!",
"tree1",
"[",
"2",
"]",
"[",
"0",
"]",
")",
"{",
"conflicts",
"=",
"'new_leaf'",
";",
"tree1",
"[",
"2",
"]",
"[",
"0",
"]",
"=",
"tree2",
"[",
"2",
"]",
"[",
"i",
"]",
";",
"continue",
";",
"}",
"var",
"merged",
"=",
"false",
";",
"for",
"(",
"var",
"j",
"=",
"0",
";",
"j",
"<",
"tree1",
"[",
"2",
"]",
".",
"length",
";",
"j",
"++",
")",
"{",
"if",
"(",
"tree1",
"[",
"2",
"]",
"[",
"j",
"]",
"[",
"0",
"]",
"===",
"tree2",
"[",
"2",
"]",
"[",
"i",
"]",
"[",
"0",
"]",
")",
"{",
"queue",
".",
"push",
"(",
"{",
"tree1",
":",
"tree1",
"[",
"2",
"]",
"[",
"j",
"]",
",",
"tree2",
":",
"tree2",
"[",
"2",
"]",
"[",
"i",
"]",
"}",
")",
";",
"merged",
"=",
"true",
";",
"}",
"}",
"if",
"(",
"!",
"merged",
")",
"{",
"conflicts",
"=",
"'new_branch'",
";",
"insertSorted",
"(",
"tree1",
"[",
"2",
"]",
",",
"tree2",
"[",
"2",
"]",
"[",
"i",
"]",
",",
"compareTree",
")",
";",
"}",
"}",
"}",
"return",
"{",
"conflicts",
":",
"conflicts",
",",
"tree",
":",
"in_tree1",
"}",
";",
"}"
] | Merge two trees together The roots of tree1 and tree2 must be the same revision | [
"Merge",
"two",
"trees",
"together",
"The",
"roots",
"of",
"tree1",
"and",
"tree2",
"must",
"be",
"the",
"same",
"revision"
] | 60b692a1b7aa6f2ef007c28717e76582014e07ad | https://github.com/HospitalRun/hospitalrun-frontend/blob/60b692a1b7aa6f2ef007c28717e76582014e07ad/prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js#L22388-L22423 |
5,329 | HospitalRun/hospitalrun-frontend | prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js | stem | function stem(tree, depth) {
// First we break out the tree into a complete list of root to leaf paths
var paths = rootToLeaf(tree);
var stemmedRevs;
var result;
for (var i = 0, len = paths.length; i < len; i++) {
// Then for each path, we cut off the start of the path based on the
// `depth` to stem to, and generate a new set of flat trees
var path = paths[i];
var stemmed = path.ids;
var node;
if (stemmed.length > depth) {
// only do the stemming work if we actually need to stem
if (!stemmedRevs) {
stemmedRevs = {}; // avoid allocating this object unnecessarily
}
var numStemmed = stemmed.length - depth;
node = {
pos: path.pos + numStemmed,
ids: pathToTree(stemmed, numStemmed)
};
for (var s = 0; s < numStemmed; s++) {
var rev = (path.pos + s) + '-' + stemmed[s].id;
stemmedRevs[rev] = true;
}
} else { // no need to actually stem
node = {
pos: path.pos,
ids: pathToTree(stemmed, 0)
};
}
// Then we remerge all those flat trees together, ensuring that we dont
// connect trees that would go beyond the depth limit
if (result) {
result = doMerge(result, node, true).tree;
} else {
result = [node];
}
}
// this is memory-heavy per Chrome profiler, avoid unless we actually stemmed
if (stemmedRevs) {
traverseRevTree(result, function (isLeaf, pos, revHash) {
// some revisions may have been removed in a branch but not in another
delete stemmedRevs[pos + '-' + revHash];
});
}
return {
tree: result,
revs: stemmedRevs ? Object.keys(stemmedRevs) : []
};
} | javascript | function stem(tree, depth) {
// First we break out the tree into a complete list of root to leaf paths
var paths = rootToLeaf(tree);
var stemmedRevs;
var result;
for (var i = 0, len = paths.length; i < len; i++) {
// Then for each path, we cut off the start of the path based on the
// `depth` to stem to, and generate a new set of flat trees
var path = paths[i];
var stemmed = path.ids;
var node;
if (stemmed.length > depth) {
// only do the stemming work if we actually need to stem
if (!stemmedRevs) {
stemmedRevs = {}; // avoid allocating this object unnecessarily
}
var numStemmed = stemmed.length - depth;
node = {
pos: path.pos + numStemmed,
ids: pathToTree(stemmed, numStemmed)
};
for (var s = 0; s < numStemmed; s++) {
var rev = (path.pos + s) + '-' + stemmed[s].id;
stemmedRevs[rev] = true;
}
} else { // no need to actually stem
node = {
pos: path.pos,
ids: pathToTree(stemmed, 0)
};
}
// Then we remerge all those flat trees together, ensuring that we dont
// connect trees that would go beyond the depth limit
if (result) {
result = doMerge(result, node, true).tree;
} else {
result = [node];
}
}
// this is memory-heavy per Chrome profiler, avoid unless we actually stemmed
if (stemmedRevs) {
traverseRevTree(result, function (isLeaf, pos, revHash) {
// some revisions may have been removed in a branch but not in another
delete stemmedRevs[pos + '-' + revHash];
});
}
return {
tree: result,
revs: stemmedRevs ? Object.keys(stemmedRevs) : []
};
} | [
"function",
"stem",
"(",
"tree",
",",
"depth",
")",
"{",
"// First we break out the tree into a complete list of root to leaf paths",
"var",
"paths",
"=",
"rootToLeaf",
"(",
"tree",
")",
";",
"var",
"stemmedRevs",
";",
"var",
"result",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"len",
"=",
"paths",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"// Then for each path, we cut off the start of the path based on the",
"// `depth` to stem to, and generate a new set of flat trees",
"var",
"path",
"=",
"paths",
"[",
"i",
"]",
";",
"var",
"stemmed",
"=",
"path",
".",
"ids",
";",
"var",
"node",
";",
"if",
"(",
"stemmed",
".",
"length",
">",
"depth",
")",
"{",
"// only do the stemming work if we actually need to stem",
"if",
"(",
"!",
"stemmedRevs",
")",
"{",
"stemmedRevs",
"=",
"{",
"}",
";",
"// avoid allocating this object unnecessarily",
"}",
"var",
"numStemmed",
"=",
"stemmed",
".",
"length",
"-",
"depth",
";",
"node",
"=",
"{",
"pos",
":",
"path",
".",
"pos",
"+",
"numStemmed",
",",
"ids",
":",
"pathToTree",
"(",
"stemmed",
",",
"numStemmed",
")",
"}",
";",
"for",
"(",
"var",
"s",
"=",
"0",
";",
"s",
"<",
"numStemmed",
";",
"s",
"++",
")",
"{",
"var",
"rev",
"=",
"(",
"path",
".",
"pos",
"+",
"s",
")",
"+",
"'-'",
"+",
"stemmed",
"[",
"s",
"]",
".",
"id",
";",
"stemmedRevs",
"[",
"rev",
"]",
"=",
"true",
";",
"}",
"}",
"else",
"{",
"// no need to actually stem",
"node",
"=",
"{",
"pos",
":",
"path",
".",
"pos",
",",
"ids",
":",
"pathToTree",
"(",
"stemmed",
",",
"0",
")",
"}",
";",
"}",
"// Then we remerge all those flat trees together, ensuring that we dont",
"// connect trees that would go beyond the depth limit",
"if",
"(",
"result",
")",
"{",
"result",
"=",
"doMerge",
"(",
"result",
",",
"node",
",",
"true",
")",
".",
"tree",
";",
"}",
"else",
"{",
"result",
"=",
"[",
"node",
"]",
";",
"}",
"}",
"// this is memory-heavy per Chrome profiler, avoid unless we actually stemmed",
"if",
"(",
"stemmedRevs",
")",
"{",
"traverseRevTree",
"(",
"result",
",",
"function",
"(",
"isLeaf",
",",
"pos",
",",
"revHash",
")",
"{",
"// some revisions may have been removed in a branch but not in another",
"delete",
"stemmedRevs",
"[",
"pos",
"+",
"'-'",
"+",
"revHash",
"]",
";",
"}",
")",
";",
"}",
"return",
"{",
"tree",
":",
"result",
",",
"revs",
":",
"stemmedRevs",
"?",
"Object",
".",
"keys",
"(",
"stemmedRevs",
")",
":",
"[",
"]",
"}",
";",
"}"
] | To ensure we dont grow the revision tree infinitely, we stem old revisions | [
"To",
"ensure",
"we",
"dont",
"grow",
"the",
"revision",
"tree",
"infinitely",
"we",
"stem",
"old",
"revisions"
] | 60b692a1b7aa6f2ef007c28717e76582014e07ad | https://github.com/HospitalRun/hospitalrun-frontend/blob/60b692a1b7aa6f2ef007c28717e76582014e07ad/prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js#L22507-L22562 |
5,330 | HospitalRun/hospitalrun-frontend | prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js | revExists | function revExists(revs, rev) {
var toVisit = revs.slice();
var splitRev = rev.split('-');
var targetPos = parseInt(splitRev[0], 10);
var targetId = splitRev[1];
var node;
while ((node = toVisit.pop())) {
if (node.pos === targetPos && node.ids[0] === targetId) {
return true;
}
var branches = node.ids[2];
for (var i = 0, len = branches.length; i < len; i++) {
toVisit.push({pos: node.pos + 1, ids: branches[i]});
}
}
return false;
} | javascript | function revExists(revs, rev) {
var toVisit = revs.slice();
var splitRev = rev.split('-');
var targetPos = parseInt(splitRev[0], 10);
var targetId = splitRev[1];
var node;
while ((node = toVisit.pop())) {
if (node.pos === targetPos && node.ids[0] === targetId) {
return true;
}
var branches = node.ids[2];
for (var i = 0, len = branches.length; i < len; i++) {
toVisit.push({pos: node.pos + 1, ids: branches[i]});
}
}
return false;
} | [
"function",
"revExists",
"(",
"revs",
",",
"rev",
")",
"{",
"var",
"toVisit",
"=",
"revs",
".",
"slice",
"(",
")",
";",
"var",
"splitRev",
"=",
"rev",
".",
"split",
"(",
"'-'",
")",
";",
"var",
"targetPos",
"=",
"parseInt",
"(",
"splitRev",
"[",
"0",
"]",
",",
"10",
")",
";",
"var",
"targetId",
"=",
"splitRev",
"[",
"1",
"]",
";",
"var",
"node",
";",
"while",
"(",
"(",
"node",
"=",
"toVisit",
".",
"pop",
"(",
")",
")",
")",
"{",
"if",
"(",
"node",
".",
"pos",
"===",
"targetPos",
"&&",
"node",
".",
"ids",
"[",
"0",
"]",
"===",
"targetId",
")",
"{",
"return",
"true",
";",
"}",
"var",
"branches",
"=",
"node",
".",
"ids",
"[",
"2",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"len",
"=",
"branches",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"toVisit",
".",
"push",
"(",
"{",
"pos",
":",
"node",
".",
"pos",
"+",
"1",
",",
"ids",
":",
"branches",
"[",
"i",
"]",
"}",
")",
";",
"}",
"}",
"return",
"false",
";",
"}"
] | return true if a rev exists in the rev tree, false otherwise | [
"return",
"true",
"if",
"a",
"rev",
"exists",
"in",
"the",
"rev",
"tree",
"false",
"otherwise"
] | 60b692a1b7aa6f2ef007c28717e76582014e07ad | https://github.com/HospitalRun/hospitalrun-frontend/blob/60b692a1b7aa6f2ef007c28717e76582014e07ad/prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js#L22575-L22592 |
5,331 | HospitalRun/hospitalrun-frontend | prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js | matchesSelector | function matchesSelector(doc, selector) {
/* istanbul ignore if */
if (typeof selector !== 'object') {
// match the CouchDB error message
throw 'Selector error: expected a JSON object';
}
selector = massageSelector(selector);
var row = {
'doc': doc
};
var rowsMatched = filterInMemoryFields([row], { 'selector': selector }, Object.keys(selector));
return rowsMatched && rowsMatched.length === 1;
} | javascript | function matchesSelector(doc, selector) {
/* istanbul ignore if */
if (typeof selector !== 'object') {
// match the CouchDB error message
throw 'Selector error: expected a JSON object';
}
selector = massageSelector(selector);
var row = {
'doc': doc
};
var rowsMatched = filterInMemoryFields([row], { 'selector': selector }, Object.keys(selector));
return rowsMatched && rowsMatched.length === 1;
} | [
"function",
"matchesSelector",
"(",
"doc",
",",
"selector",
")",
"{",
"/* istanbul ignore if */",
"if",
"(",
"typeof",
"selector",
"!==",
"'object'",
")",
"{",
"// match the CouchDB error message",
"throw",
"'Selector error: expected a JSON object'",
";",
"}",
"selector",
"=",
"massageSelector",
"(",
"selector",
")",
";",
"var",
"row",
"=",
"{",
"'doc'",
":",
"doc",
"}",
";",
"var",
"rowsMatched",
"=",
"filterInMemoryFields",
"(",
"[",
"row",
"]",
",",
"{",
"'selector'",
":",
"selector",
"}",
",",
"Object",
".",
"keys",
"(",
"selector",
")",
")",
";",
"return",
"rowsMatched",
"&&",
"rowsMatched",
".",
"length",
"===",
"1",
";",
"}"
] | return true if the given doc matches the supplied selector | [
"return",
"true",
"if",
"the",
"given",
"doc",
"matches",
"the",
"supplied",
"selector"
] | 60b692a1b7aa6f2ef007c28717e76582014e07ad | https://github.com/HospitalRun/hospitalrun-frontend/blob/60b692a1b7aa6f2ef007c28717e76582014e07ad/prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js#L24468-L24482 |
5,332 | HospitalRun/hospitalrun-frontend | prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js | invalidIdError | function invalidIdError(id) {
var err;
if (!id) {
err = pouchdbErrors.createError(pouchdbErrors.MISSING_ID);
} else if (typeof id !== 'string') {
err = pouchdbErrors.createError(pouchdbErrors.INVALID_ID);
} else if (/^_/.test(id) && !(/^_(design|local)/).test(id)) {
err = pouchdbErrors.createError(pouchdbErrors.RESERVED_ID);
}
if (err) {
throw err;
}
} | javascript | function invalidIdError(id) {
var err;
if (!id) {
err = pouchdbErrors.createError(pouchdbErrors.MISSING_ID);
} else if (typeof id !== 'string') {
err = pouchdbErrors.createError(pouchdbErrors.INVALID_ID);
} else if (/^_/.test(id) && !(/^_(design|local)/).test(id)) {
err = pouchdbErrors.createError(pouchdbErrors.RESERVED_ID);
}
if (err) {
throw err;
}
} | [
"function",
"invalidIdError",
"(",
"id",
")",
"{",
"var",
"err",
";",
"if",
"(",
"!",
"id",
")",
"{",
"err",
"=",
"pouchdbErrors",
".",
"createError",
"(",
"pouchdbErrors",
".",
"MISSING_ID",
")",
";",
"}",
"else",
"if",
"(",
"typeof",
"id",
"!==",
"'string'",
")",
"{",
"err",
"=",
"pouchdbErrors",
".",
"createError",
"(",
"pouchdbErrors",
".",
"INVALID_ID",
")",
";",
"}",
"else",
"if",
"(",
"/",
"^_",
"/",
".",
"test",
"(",
"id",
")",
"&&",
"!",
"(",
"/",
"^_(design|local)",
"/",
")",
".",
"test",
"(",
"id",
")",
")",
"{",
"err",
"=",
"pouchdbErrors",
".",
"createError",
"(",
"pouchdbErrors",
".",
"RESERVED_ID",
")",
";",
"}",
"if",
"(",
"err",
")",
"{",
"throw",
"err",
";",
"}",
"}"
] | Determine id an ID is valid - invalid IDs begin with an underescore that does not begin '_design' or '_local' - any other string value is a valid id Returns the specific error object for each case | [
"Determine",
"id",
"an",
"ID",
"is",
"valid",
"-",
"invalid",
"IDs",
"begin",
"with",
"an",
"underescore",
"that",
"does",
"not",
"begin",
"_design",
"or",
"_local",
"-",
"any",
"other",
"string",
"value",
"is",
"a",
"valid",
"id",
"Returns",
"the",
"specific",
"error",
"object",
"for",
"each",
"case"
] | 60b692a1b7aa6f2ef007c28717e76582014e07ad | https://github.com/HospitalRun/hospitalrun-frontend/blob/60b692a1b7aa6f2ef007c28717e76582014e07ad/prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js#L25237-L25249 |
5,333 | HospitalRun/hospitalrun-frontend | prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js | deprecate | function deprecate (fn, msg) {
if (config('noDeprecation')) {
return fn;
}
var warned = false;
function deprecated() {
if (!warned) {
if (config('throwDeprecation')) {
throw new Error(msg);
} else if (config('traceDeprecation')) {
console.trace(msg);
} else {
console.warn(msg);
}
warned = true;
}
return fn.apply(this, arguments);
}
return deprecated;
} | javascript | function deprecate (fn, msg) {
if (config('noDeprecation')) {
return fn;
}
var warned = false;
function deprecated() {
if (!warned) {
if (config('throwDeprecation')) {
throw new Error(msg);
} else if (config('traceDeprecation')) {
console.trace(msg);
} else {
console.warn(msg);
}
warned = true;
}
return fn.apply(this, arguments);
}
return deprecated;
} | [
"function",
"deprecate",
"(",
"fn",
",",
"msg",
")",
"{",
"if",
"(",
"config",
"(",
"'noDeprecation'",
")",
")",
"{",
"return",
"fn",
";",
"}",
"var",
"warned",
"=",
"false",
";",
"function",
"deprecated",
"(",
")",
"{",
"if",
"(",
"!",
"warned",
")",
"{",
"if",
"(",
"config",
"(",
"'throwDeprecation'",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"msg",
")",
";",
"}",
"else",
"if",
"(",
"config",
"(",
"'traceDeprecation'",
")",
")",
"{",
"console",
".",
"trace",
"(",
"msg",
")",
";",
"}",
"else",
"{",
"console",
".",
"warn",
"(",
"msg",
")",
";",
"}",
"warned",
"=",
"true",
";",
"}",
"return",
"fn",
".",
"apply",
"(",
"this",
",",
"arguments",
")",
";",
"}",
"return",
"deprecated",
";",
"}"
] | Mark that a method should not be used.
Returns a modified function which warns once by default.
If `localStorage.noDeprecation = true` is set, then it is a no-op.
If `localStorage.throwDeprecation = true` is set, then deprecated functions
will throw an Error when invoked.
If `localStorage.traceDeprecation = true` is set, then deprecated functions
will invoke `console.trace()` instead of `console.error()`.
@param {Function} fn - the function to deprecate
@param {String} msg - the string to print to the console when `fn` is invoked
@returns {Function} a new "deprecated" version of `fn`
@api public | [
"Mark",
"that",
"a",
"method",
"should",
"not",
"be",
"used",
".",
"Returns",
"a",
"modified",
"function",
"which",
"warns",
"once",
"by",
"default",
"."
] | 60b692a1b7aa6f2ef007c28717e76582014e07ad | https://github.com/HospitalRun/hospitalrun-frontend/blob/60b692a1b7aa6f2ef007c28717e76582014e07ad/prod/service-worker-28ddbc7ef7a575da0539a0f05f4bfdae.js#L30439-L30460 |
5,334 | impress/impress.js | js/impress.js | function( el, props ) {
var key, pkey;
for ( key in props ) {
if ( props.hasOwnProperty( key ) ) {
pkey = pfx( key );
if ( pkey !== null ) {
el.style[ pkey ] = props[ key ];
}
}
}
return el;
} | javascript | function( el, props ) {
var key, pkey;
for ( key in props ) {
if ( props.hasOwnProperty( key ) ) {
pkey = pfx( key );
if ( pkey !== null ) {
el.style[ pkey ] = props[ key ];
}
}
}
return el;
} | [
"function",
"(",
"el",
",",
"props",
")",
"{",
"var",
"key",
",",
"pkey",
";",
"for",
"(",
"key",
"in",
"props",
")",
"{",
"if",
"(",
"props",
".",
"hasOwnProperty",
"(",
"key",
")",
")",
"{",
"pkey",
"=",
"pfx",
"(",
"key",
")",
";",
"if",
"(",
"pkey",
"!==",
"null",
")",
"{",
"el",
".",
"style",
"[",
"pkey",
"]",
"=",
"props",
"[",
"key",
"]",
";",
"}",
"}",
"}",
"return",
"el",
";",
"}"
] | `css` function applies the styles given in `props` object to the element given as `el`. It runs all property names through `pfx` function to make sure proper prefixed version of the property is used. | [
"css",
"function",
"applies",
"the",
"styles",
"given",
"in",
"props",
"object",
"to",
"the",
"element",
"given",
"as",
"el",
".",
"It",
"runs",
"all",
"property",
"names",
"through",
"pfx",
"function",
"to",
"make",
"sure",
"proper",
"prefixed",
"version",
"of",
"the",
"property",
"is",
"used",
"."
] | c61403d57ad4603a45117d893e99877d58530604 | https://github.com/impress/impress.js/blob/c61403d57ad4603a45117d893e99877d58530604/js/impress.js#L85-L96 |
|
5,335 | impress/impress.js | js/impress.js | function( currentStep, nextStep ) {
if ( lastEntered === currentStep ) {
lib.util.triggerEvent( currentStep, "impress:stepleave", { next: nextStep } );
lastEntered = null;
}
} | javascript | function( currentStep, nextStep ) {
if ( lastEntered === currentStep ) {
lib.util.triggerEvent( currentStep, "impress:stepleave", { next: nextStep } );
lastEntered = null;
}
} | [
"function",
"(",
"currentStep",
",",
"nextStep",
")",
"{",
"if",
"(",
"lastEntered",
"===",
"currentStep",
")",
"{",
"lib",
".",
"util",
".",
"triggerEvent",
"(",
"currentStep",
",",
"\"impress:stepleave\"",
",",
"{",
"next",
":",
"nextStep",
"}",
")",
";",
"lastEntered",
"=",
"null",
";",
"}",
"}"
] | `onStepLeave` is called whenever the currentStep element is left but the event is triggered only if the currentStep is the same as lastEntered step. | [
"onStepLeave",
"is",
"called",
"whenever",
"the",
"currentStep",
"element",
"is",
"left",
"but",
"the",
"event",
"is",
"triggered",
"only",
"if",
"the",
"currentStep",
"is",
"the",
"same",
"as",
"lastEntered",
"step",
"."
] | c61403d57ad4603a45117d893e99877d58530604 | https://github.com/impress/impress.js/blob/c61403d57ad4603a45117d893e99877d58530604/js/impress.js#L273-L278 |
|
5,336 | impress/impress.js | js/impress.js | function( rootId ) { //jshint ignore:line
var lib = {};
for ( var libname in libraryFactories ) {
if ( libraryFactories.hasOwnProperty( libname ) ) {
if ( lib[ libname ] !== undefined ) {
throw "impress.js ERROR: Two libraries both tried to use libname: " + libname;
}
lib[ libname ] = libraryFactories[ libname ]( rootId );
}
}
return lib;
} | javascript | function( rootId ) { //jshint ignore:line
var lib = {};
for ( var libname in libraryFactories ) {
if ( libraryFactories.hasOwnProperty( libname ) ) {
if ( lib[ libname ] !== undefined ) {
throw "impress.js ERROR: Two libraries both tried to use libname: " + libname;
}
lib[ libname ] = libraryFactories[ libname ]( rootId );
}
}
return lib;
} | [
"function",
"(",
"rootId",
")",
"{",
"//jshint ignore:line",
"var",
"lib",
"=",
"{",
"}",
";",
"for",
"(",
"var",
"libname",
"in",
"libraryFactories",
")",
"{",
"if",
"(",
"libraryFactories",
".",
"hasOwnProperty",
"(",
"libname",
")",
")",
"{",
"if",
"(",
"lib",
"[",
"libname",
"]",
"!==",
"undefined",
")",
"{",
"throw",
"\"impress.js ERROR: Two libraries both tried to use libname: \"",
"+",
"libname",
";",
"}",
"lib",
"[",
"libname",
"]",
"=",
"libraryFactories",
"[",
"libname",
"]",
"(",
"rootId",
")",
";",
"}",
"}",
"return",
"lib",
";",
"}"
] | Call each library factory, and return the lib object that is added to the api. | [
"Call",
"each",
"library",
"factory",
"and",
"return",
"the",
"lib",
"object",
"that",
"is",
"added",
"to",
"the",
"api",
"."
] | c61403d57ad4603a45117d893e99877d58530604 | https://github.com/impress/impress.js/blob/c61403d57ad4603a45117d893e99877d58530604/js/impress.js#L839-L850 |
|
5,337 | impress/impress.js | js/impress.js | function( root ) { //jshint ignore:line
for ( var i = 0; i < preInitPlugins.length; i++ ) {
var thisLevel = preInitPlugins[ i ];
if ( thisLevel !== undefined ) {
for ( var j = 0; j < thisLevel.length; j++ ) {
thisLevel[ j ]( root );
}
}
}
} | javascript | function( root ) { //jshint ignore:line
for ( var i = 0; i < preInitPlugins.length; i++ ) {
var thisLevel = preInitPlugins[ i ];
if ( thisLevel !== undefined ) {
for ( var j = 0; j < thisLevel.length; j++ ) {
thisLevel[ j ]( root );
}
}
}
} | [
"function",
"(",
"root",
")",
"{",
"//jshint ignore:line",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"preInitPlugins",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"thisLevel",
"=",
"preInitPlugins",
"[",
"i",
"]",
";",
"if",
"(",
"thisLevel",
"!==",
"undefined",
")",
"{",
"for",
"(",
"var",
"j",
"=",
"0",
";",
"j",
"<",
"thisLevel",
".",
"length",
";",
"j",
"++",
")",
"{",
"thisLevel",
"[",
"j",
"]",
"(",
"root",
")",
";",
"}",
"}",
"}",
"}"
] | Called at beginning of init, to execute all pre-init plugins. | [
"Called",
"at",
"beginning",
"of",
"init",
"to",
"execute",
"all",
"pre",
"-",
"init",
"plugins",
"."
] | c61403d57ad4603a45117d893e99877d58530604 | https://github.com/impress/impress.js/blob/c61403d57ad4603a45117d893e99877d58530604/js/impress.js#L868-L877 |
|
5,338 | impress/impress.js | js/impress.js | function( target, type, listenerFunction ) {
eventListenerList.push( { target:target, type:type, listener:listenerFunction } );
} | javascript | function( target, type, listenerFunction ) {
eventListenerList.push( { target:target, type:type, listener:listenerFunction } );
} | [
"function",
"(",
"target",
",",
"type",
",",
"listenerFunction",
")",
"{",
"eventListenerList",
".",
"push",
"(",
"{",
"target",
":",
"target",
",",
"type",
":",
"type",
",",
"listener",
":",
"listenerFunction",
"}",
")",
";",
"}"
] | `pushEventListener` adds an event listener to the gc stack | [
"pushEventListener",
"adds",
"an",
"event",
"listener",
"to",
"the",
"gc",
"stack"
] | c61403d57ad4603a45117d893e99877d58530604 | https://github.com/impress/impress.js/blob/c61403d57ad4603a45117d893e99877d58530604/js/impress.js#L967-L969 |
|
5,339 | impress/impress.js | js/impress.js | function( target, type, listenerFunction ) {
target.addEventListener( type, listenerFunction );
pushEventListener( target, type, listenerFunction );
} | javascript | function( target, type, listenerFunction ) {
target.addEventListener( type, listenerFunction );
pushEventListener( target, type, listenerFunction );
} | [
"function",
"(",
"target",
",",
"type",
",",
"listenerFunction",
")",
"{",
"target",
".",
"addEventListener",
"(",
"type",
",",
"listenerFunction",
")",
";",
"pushEventListener",
"(",
"target",
",",
"type",
",",
"listenerFunction",
")",
";",
"}"
] | `addEventListener` combines DOM addEventListener with gc.pushEventListener | [
"addEventListener",
"combines",
"DOM",
"addEventListener",
"with",
"gc",
".",
"pushEventListener"
] | c61403d57ad4603a45117d893e99877d58530604 | https://github.com/impress/impress.js/blob/c61403d57ad4603a45117d893e99877d58530604/js/impress.js#L972-L975 |
|
5,340 | impress/impress.js | js/impress.js | function( el, eventName, detail ) {
var event = document.createEvent( "CustomEvent" );
event.initCustomEvent( eventName, true, true, detail );
el.dispatchEvent( event );
} | javascript | function( el, eventName, detail ) {
var event = document.createEvent( "CustomEvent" );
event.initCustomEvent( eventName, true, true, detail );
el.dispatchEvent( event );
} | [
"function",
"(",
"el",
",",
"eventName",
",",
"detail",
")",
"{",
"var",
"event",
"=",
"document",
".",
"createEvent",
"(",
"\"CustomEvent\"",
")",
";",
"event",
".",
"initCustomEvent",
"(",
"eventName",
",",
"true",
",",
"true",
",",
"detail",
")",
";",
"el",
".",
"dispatchEvent",
"(",
"event",
")",
";",
"}"
] | `triggerEvent` builds a custom DOM event with given `eventName` and `detail` data and triggers it on element given as `el`. | [
"triggerEvent",
"builds",
"a",
"custom",
"DOM",
"event",
"with",
"given",
"eventName",
"and",
"detail",
"data",
"and",
"triggers",
"it",
"on",
"element",
"given",
"as",
"el",
"."
] | c61403d57ad4603a45117d893e99877d58530604 | https://github.com/impress/impress.js/blob/c61403d57ad4603a45117d893e99877d58530604/js/impress.js#L1232-L1236 |
|
5,341 | impress/impress.js | js/impress.js | function( event ) {
var step = event.target;
currentStepTimeout = util.toNumber( step.dataset.autoplay, autoplayDefault );
if ( status === "paused" ) {
setAutoplayTimeout( 0 );
} else {
setAutoplayTimeout( currentStepTimeout );
}
} | javascript | function( event ) {
var step = event.target;
currentStepTimeout = util.toNumber( step.dataset.autoplay, autoplayDefault );
if ( status === "paused" ) {
setAutoplayTimeout( 0 );
} else {
setAutoplayTimeout( currentStepTimeout );
}
} | [
"function",
"(",
"event",
")",
"{",
"var",
"step",
"=",
"event",
".",
"target",
";",
"currentStepTimeout",
"=",
"util",
".",
"toNumber",
"(",
"step",
".",
"dataset",
".",
"autoplay",
",",
"autoplayDefault",
")",
";",
"if",
"(",
"status",
"===",
"\"paused\"",
")",
"{",
"setAutoplayTimeout",
"(",
"0",
")",
";",
"}",
"else",
"{",
"setAutoplayTimeout",
"(",
"currentStepTimeout",
")",
";",
"}",
"}"
] | If default autoplay time was defined in the presentation root, or in this step, set timeout. | [
"If",
"default",
"autoplay",
"time",
"was",
"defined",
"in",
"the",
"presentation",
"root",
"or",
"in",
"this",
"step",
"set",
"timeout",
"."
] | c61403d57ad4603a45117d893e99877d58530604 | https://github.com/impress/impress.js/blob/c61403d57ad4603a45117d893e99877d58530604/js/impress.js#L1320-L1328 |
|
5,342 | impress/impress.js | js/impress.js | function() {
if ( consoleWindow ) {
// Set notes to next steps notes.
var newNotes = document.querySelector( '.active' ).querySelector( '.notes' );
if ( newNotes ) {
newNotes = newNotes.innerHTML;
} else {
newNotes = lang.noNotes;
}
consoleWindow.document.getElementById( 'notes' ).innerHTML = newNotes;
// Set the views
var baseURL = document.URL.substring( 0, document.URL.search( '#/' ) );
var slideSrc = baseURL + '#' + document.querySelector( '.active' ).id;
var preSrc = baseURL + '#' + nextStep().id;
var slideView = consoleWindow.document.getElementById( 'slideView' );
// Setting them when they are already set causes glithes in Firefox, so check first:
if ( slideView.src !== slideSrc ) {
slideView.src = slideSrc;
}
var preView = consoleWindow.document.getElementById( 'preView' );
if ( preView.src !== preSrc ) {
preView.src = preSrc;
}
consoleWindow.document.getElementById( 'status' ).innerHTML =
'<span class="moving">' + lang.moving + '</span>';
}
} | javascript | function() {
if ( consoleWindow ) {
// Set notes to next steps notes.
var newNotes = document.querySelector( '.active' ).querySelector( '.notes' );
if ( newNotes ) {
newNotes = newNotes.innerHTML;
} else {
newNotes = lang.noNotes;
}
consoleWindow.document.getElementById( 'notes' ).innerHTML = newNotes;
// Set the views
var baseURL = document.URL.substring( 0, document.URL.search( '#/' ) );
var slideSrc = baseURL + '#' + document.querySelector( '.active' ).id;
var preSrc = baseURL + '#' + nextStep().id;
var slideView = consoleWindow.document.getElementById( 'slideView' );
// Setting them when they are already set causes glithes in Firefox, so check first:
if ( slideView.src !== slideSrc ) {
slideView.src = slideSrc;
}
var preView = consoleWindow.document.getElementById( 'preView' );
if ( preView.src !== preSrc ) {
preView.src = preSrc;
}
consoleWindow.document.getElementById( 'status' ).innerHTML =
'<span class="moving">' + lang.moving + '</span>';
}
} | [
"function",
"(",
")",
"{",
"if",
"(",
"consoleWindow",
")",
"{",
"// Set notes to next steps notes.",
"var",
"newNotes",
"=",
"document",
".",
"querySelector",
"(",
"'.active'",
")",
".",
"querySelector",
"(",
"'.notes'",
")",
";",
"if",
"(",
"newNotes",
")",
"{",
"newNotes",
"=",
"newNotes",
".",
"innerHTML",
";",
"}",
"else",
"{",
"newNotes",
"=",
"lang",
".",
"noNotes",
";",
"}",
"consoleWindow",
".",
"document",
".",
"getElementById",
"(",
"'notes'",
")",
".",
"innerHTML",
"=",
"newNotes",
";",
"// Set the views",
"var",
"baseURL",
"=",
"document",
".",
"URL",
".",
"substring",
"(",
"0",
",",
"document",
".",
"URL",
".",
"search",
"(",
"'#/'",
")",
")",
";",
"var",
"slideSrc",
"=",
"baseURL",
"+",
"'#'",
"+",
"document",
".",
"querySelector",
"(",
"'.active'",
")",
".",
"id",
";",
"var",
"preSrc",
"=",
"baseURL",
"+",
"'#'",
"+",
"nextStep",
"(",
")",
".",
"id",
";",
"var",
"slideView",
"=",
"consoleWindow",
".",
"document",
".",
"getElementById",
"(",
"'slideView'",
")",
";",
"// Setting them when they are already set causes glithes in Firefox, so check first:",
"if",
"(",
"slideView",
".",
"src",
"!==",
"slideSrc",
")",
"{",
"slideView",
".",
"src",
"=",
"slideSrc",
";",
"}",
"var",
"preView",
"=",
"consoleWindow",
".",
"document",
".",
"getElementById",
"(",
"'preView'",
")",
";",
"if",
"(",
"preView",
".",
"src",
"!==",
"preSrc",
")",
"{",
"preView",
".",
"src",
"=",
"preSrc",
";",
"}",
"consoleWindow",
".",
"document",
".",
"getElementById",
"(",
"'status'",
")",
".",
"innerHTML",
"=",
"'<span class=\"moving\">'",
"+",
"lang",
".",
"moving",
"+",
"'</span>'",
";",
"}",
"}"
] | Sync the notes to the step | [
"Sync",
"the",
"notes",
"to",
"the",
"step"
] | c61403d57ad4603a45117d893e99877d58530604 | https://github.com/impress/impress.js/blob/c61403d57ad4603a45117d893e99877d58530604/js/impress.js#L2182-L2212 |
|
5,343 | impress/impress.js | js/impress.js | function() {
var now = new Date();
var hours = now.getHours();
var minutes = now.getMinutes();
var seconds = now.getSeconds();
var ampm = '';
if ( lang.useAMPM ) {
ampm = ( hours < 12 ) ? 'AM' : 'PM';
hours = ( hours > 12 ) ? hours - 12 : hours;
hours = ( hours === 0 ) ? 12 : hours;
}
// Clock
var clockStr = zeroPad( hours ) + ':' + zeroPad( minutes ) + ':' + zeroPad( seconds ) +
' ' + ampm;
consoleWindow.document.getElementById( 'clock' ).firstChild.nodeValue = clockStr;
// Timer
seconds = Math.floor( ( now - consoleWindow.timerStart ) / 1000 );
minutes = Math.floor( seconds / 60 );
seconds = Math.floor( seconds % 60 );
consoleWindow.document.getElementById( 'timer' ).firstChild.nodeValue =
zeroPad( minutes ) + 'm ' + zeroPad( seconds ) + 's';
if ( !consoleWindow.initialized ) {
// Nudge the slide windows after load, or they will scrolled wrong on Firefox.
consoleWindow.document.getElementById( 'slideView' ).contentWindow.scrollTo( 0, 0 );
consoleWindow.document.getElementById( 'preView' ).contentWindow.scrollTo( 0, 0 );
consoleWindow.initialized = true;
}
} | javascript | function() {
var now = new Date();
var hours = now.getHours();
var minutes = now.getMinutes();
var seconds = now.getSeconds();
var ampm = '';
if ( lang.useAMPM ) {
ampm = ( hours < 12 ) ? 'AM' : 'PM';
hours = ( hours > 12 ) ? hours - 12 : hours;
hours = ( hours === 0 ) ? 12 : hours;
}
// Clock
var clockStr = zeroPad( hours ) + ':' + zeroPad( minutes ) + ':' + zeroPad( seconds ) +
' ' + ampm;
consoleWindow.document.getElementById( 'clock' ).firstChild.nodeValue = clockStr;
// Timer
seconds = Math.floor( ( now - consoleWindow.timerStart ) / 1000 );
minutes = Math.floor( seconds / 60 );
seconds = Math.floor( seconds % 60 );
consoleWindow.document.getElementById( 'timer' ).firstChild.nodeValue =
zeroPad( minutes ) + 'm ' + zeroPad( seconds ) + 's';
if ( !consoleWindow.initialized ) {
// Nudge the slide windows after load, or they will scrolled wrong on Firefox.
consoleWindow.document.getElementById( 'slideView' ).contentWindow.scrollTo( 0, 0 );
consoleWindow.document.getElementById( 'preView' ).contentWindow.scrollTo( 0, 0 );
consoleWindow.initialized = true;
}
} | [
"function",
"(",
")",
"{",
"var",
"now",
"=",
"new",
"Date",
"(",
")",
";",
"var",
"hours",
"=",
"now",
".",
"getHours",
"(",
")",
";",
"var",
"minutes",
"=",
"now",
".",
"getMinutes",
"(",
")",
";",
"var",
"seconds",
"=",
"now",
".",
"getSeconds",
"(",
")",
";",
"var",
"ampm",
"=",
"''",
";",
"if",
"(",
"lang",
".",
"useAMPM",
")",
"{",
"ampm",
"=",
"(",
"hours",
"<",
"12",
")",
"?",
"'AM'",
":",
"'PM'",
";",
"hours",
"=",
"(",
"hours",
">",
"12",
")",
"?",
"hours",
"-",
"12",
":",
"hours",
";",
"hours",
"=",
"(",
"hours",
"===",
"0",
")",
"?",
"12",
":",
"hours",
";",
"}",
"// Clock",
"var",
"clockStr",
"=",
"zeroPad",
"(",
"hours",
")",
"+",
"':'",
"+",
"zeroPad",
"(",
"minutes",
")",
"+",
"':'",
"+",
"zeroPad",
"(",
"seconds",
")",
"+",
"' '",
"+",
"ampm",
";",
"consoleWindow",
".",
"document",
".",
"getElementById",
"(",
"'clock'",
")",
".",
"firstChild",
".",
"nodeValue",
"=",
"clockStr",
";",
"// Timer",
"seconds",
"=",
"Math",
".",
"floor",
"(",
"(",
"now",
"-",
"consoleWindow",
".",
"timerStart",
")",
"/",
"1000",
")",
";",
"minutes",
"=",
"Math",
".",
"floor",
"(",
"seconds",
"/",
"60",
")",
";",
"seconds",
"=",
"Math",
".",
"floor",
"(",
"seconds",
"%",
"60",
")",
";",
"consoleWindow",
".",
"document",
".",
"getElementById",
"(",
"'timer'",
")",
".",
"firstChild",
".",
"nodeValue",
"=",
"zeroPad",
"(",
"minutes",
")",
"+",
"'m '",
"+",
"zeroPad",
"(",
"seconds",
")",
"+",
"'s'",
";",
"if",
"(",
"!",
"consoleWindow",
".",
"initialized",
")",
"{",
"// Nudge the slide windows after load, or they will scrolled wrong on Firefox.",
"consoleWindow",
".",
"document",
".",
"getElementById",
"(",
"'slideView'",
")",
".",
"contentWindow",
".",
"scrollTo",
"(",
"0",
",",
"0",
")",
";",
"consoleWindow",
".",
"document",
".",
"getElementById",
"(",
"'preView'",
")",
".",
"contentWindow",
".",
"scrollTo",
"(",
"0",
",",
"0",
")",
";",
"consoleWindow",
".",
"initialized",
"=",
"true",
";",
"}",
"}"
] | Show a clock | [
"Show",
"a",
"clock"
] | c61403d57ad4603a45117d893e99877d58530604 | https://github.com/impress/impress.js/blob/c61403d57ad4603a45117d893e99877d58530604/js/impress.js#L2297-L2329 |
|
5,344 | impress/impress.js | js/impress.js | function() {
stepids = [];
var steps = root.querySelectorAll( ".step" );
for ( var i = 0; i < steps.length; i++ )
{
stepids[ i + 1 ] = steps[ i ].id;
}
} | javascript | function() {
stepids = [];
var steps = root.querySelectorAll( ".step" );
for ( var i = 0; i < steps.length; i++ )
{
stepids[ i + 1 ] = steps[ i ].id;
}
} | [
"function",
"(",
")",
"{",
"stepids",
"=",
"[",
"]",
";",
"var",
"steps",
"=",
"root",
".",
"querySelectorAll",
"(",
"\".step\"",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"steps",
".",
"length",
";",
"i",
"++",
")",
"{",
"stepids",
"[",
"i",
"+",
"1",
"]",
"=",
"steps",
"[",
"i",
"]",
".",
"id",
";",
"}",
"}"
] | Get stepids from the steps under impress root | [
"Get",
"stepids",
"from",
"the",
"steps",
"under",
"impress",
"root"
] | c61403d57ad4603a45117d893e99877d58530604 | https://github.com/impress/impress.js/blob/c61403d57ad4603a45117d893e99877d58530604/js/impress.js#L3511-L3518 |
|
5,345 | impress/impress.js | js/impress.js | function( index ) {
var id = "impress-toolbar-group-" + index;
if ( !groups[ index ] ) {
groups[ index ] = document.createElement( "span" );
groups[ index ].id = id;
var nextIndex = getNextGroupIndex( index );
if ( nextIndex === undefined ) {
toolbar.appendChild( groups[ index ] );
} else {
toolbar.insertBefore( groups[ index ], groups[ nextIndex ] );
}
}
return groups[ index ];
} | javascript | function( index ) {
var id = "impress-toolbar-group-" + index;
if ( !groups[ index ] ) {
groups[ index ] = document.createElement( "span" );
groups[ index ].id = id;
var nextIndex = getNextGroupIndex( index );
if ( nextIndex === undefined ) {
toolbar.appendChild( groups[ index ] );
} else {
toolbar.insertBefore( groups[ index ], groups[ nextIndex ] );
}
}
return groups[ index ];
} | [
"function",
"(",
"index",
")",
"{",
"var",
"id",
"=",
"\"impress-toolbar-group-\"",
"+",
"index",
";",
"if",
"(",
"!",
"groups",
"[",
"index",
"]",
")",
"{",
"groups",
"[",
"index",
"]",
"=",
"document",
".",
"createElement",
"(",
"\"span\"",
")",
";",
"groups",
"[",
"index",
"]",
".",
"id",
"=",
"id",
";",
"var",
"nextIndex",
"=",
"getNextGroupIndex",
"(",
"index",
")",
";",
"if",
"(",
"nextIndex",
"===",
"undefined",
")",
"{",
"toolbar",
".",
"appendChild",
"(",
"groups",
"[",
"index",
"]",
")",
";",
"}",
"else",
"{",
"toolbar",
".",
"insertBefore",
"(",
"groups",
"[",
"index",
"]",
",",
"groups",
"[",
"nextIndex",
"]",
")",
";",
"}",
"}",
"return",
"groups",
"[",
"index",
"]",
";",
"}"
] | Get the span element that is a child of toolbar, identified by index.
If span element doesn't exist yet, it is created.
Note: Because of Run-to-completion, this is not a race condition.
https://developer.mozilla.org/en/docs/Web/JavaScript/EventLoop#Run-to-completion
:param: index Method will return the element <span id="impress-toolbar-group-{index}"> | [
"Get",
"the",
"span",
"element",
"that",
"is",
"a",
"child",
"of",
"toolbar",
"identified",
"by",
"index",
"."
] | c61403d57ad4603a45117d893e99877d58530604 | https://github.com/impress/impress.js/blob/c61403d57ad4603a45117d893e99877d58530604/js/impress.js#L4192-L4205 |
|
5,346 | webpack/webpack-dev-server | client-src/default/index.js | sendMsg | function sendMsg(type, data) {
if (
typeof self !== 'undefined' &&
(typeof WorkerGlobalScope === 'undefined' ||
!(self instanceof WorkerGlobalScope))
) {
self.postMessage(
{
type: `webpack${type}`,
data,
},
'*'
);
}
} | javascript | function sendMsg(type, data) {
if (
typeof self !== 'undefined' &&
(typeof WorkerGlobalScope === 'undefined' ||
!(self instanceof WorkerGlobalScope))
) {
self.postMessage(
{
type: `webpack${type}`,
data,
},
'*'
);
}
} | [
"function",
"sendMsg",
"(",
"type",
",",
"data",
")",
"{",
"if",
"(",
"typeof",
"self",
"!==",
"'undefined'",
"&&",
"(",
"typeof",
"WorkerGlobalScope",
"===",
"'undefined'",
"||",
"!",
"(",
"self",
"instanceof",
"WorkerGlobalScope",
")",
")",
")",
"{",
"self",
".",
"postMessage",
"(",
"{",
"type",
":",
"`",
"${",
"type",
"}",
"`",
",",
"data",
",",
"}",
",",
"'*'",
")",
";",
"}",
"}"
] | Send messages to the outside, so plugins can consume it. | [
"Send",
"messages",
"to",
"the",
"outside",
"so",
"plugins",
"can",
"consume",
"it",
"."
] | efe850b6d32791cf2f8da3bd8e43b3f62b15ed96 | https://github.com/webpack/webpack-dev-server/blob/efe850b6d32791cf2f8da3bd8e43b3f62b15ed96/client-src/default/index.js#L67-L81 |
5,347 | google/shaka-player | build/generateExterns.js | removeExportAnnotationsFromComment | function removeExportAnnotationsFromComment(comment) {
// Remove @export annotations.
comment = comment.replace(EXPORT_REGEX, '')
// Split into lines, remove empty comment lines, then recombine.
comment = comment.split('\n')
.filter(function(line) { return !/^ *\*? *$/.test(line); })
.join('\n');
return comment;
} | javascript | function removeExportAnnotationsFromComment(comment) {
// Remove @export annotations.
comment = comment.replace(EXPORT_REGEX, '')
// Split into lines, remove empty comment lines, then recombine.
comment = comment.split('\n')
.filter(function(line) { return !/^ *\*? *$/.test(line); })
.join('\n');
return comment;
} | [
"function",
"removeExportAnnotationsFromComment",
"(",
"comment",
")",
"{",
"// Remove @export annotations.",
"comment",
"=",
"comment",
".",
"replace",
"(",
"EXPORT_REGEX",
",",
"''",
")",
"// Split into lines, remove empty comment lines, then recombine.",
"comment",
"=",
"comment",
".",
"split",
"(",
"'\\n'",
")",
".",
"filter",
"(",
"function",
"(",
"line",
")",
"{",
"return",
"!",
"/",
"^ *\\*? *$",
"/",
".",
"test",
"(",
"line",
")",
";",
"}",
")",
".",
"join",
"(",
"'\\n'",
")",
";",
"return",
"comment",
";",
"}"
] | Take the original block comment and prep it for the externs by removing
export annotations and blank lines.
@param {string}
@return {string} | [
"Take",
"the",
"original",
"block",
"comment",
"and",
"prep",
"it",
"for",
"the",
"externs",
"by",
"removing",
"export",
"annotations",
"and",
"blank",
"lines",
"."
] | 01f7af9d4ee3eeb712719480cb55b7573a2b41fd | https://github.com/google/shaka-player/blob/01f7af9d4ee3eeb712719480cb55b7573a2b41fd/build/generateExterns.js#L286-L296 |
5,348 | google/shaka-player | build/generateExterns.js | getAllExpressionStatements | function getAllExpressionStatements(node) {
console.assert(node.body && node.body.body);
var expressionStatements = [];
node.body.body.forEach(function(childNode) {
if (childNode.type == 'ExpressionStatement') {
expressionStatements.push(childNode);
} else if (childNode.body) {
var childExpressions = getAllExpressionStatements(childNode);
expressionStatements.push.apply(expressionStatements, childExpressions);
}
});
return expressionStatements;
} | javascript | function getAllExpressionStatements(node) {
console.assert(node.body && node.body.body);
var expressionStatements = [];
node.body.body.forEach(function(childNode) {
if (childNode.type == 'ExpressionStatement') {
expressionStatements.push(childNode);
} else if (childNode.body) {
var childExpressions = getAllExpressionStatements(childNode);
expressionStatements.push.apply(expressionStatements, childExpressions);
}
});
return expressionStatements;
} | [
"function",
"getAllExpressionStatements",
"(",
"node",
")",
"{",
"console",
".",
"assert",
"(",
"node",
".",
"body",
"&&",
"node",
".",
"body",
".",
"body",
")",
";",
"var",
"expressionStatements",
"=",
"[",
"]",
";",
"node",
".",
"body",
".",
"body",
".",
"forEach",
"(",
"function",
"(",
"childNode",
")",
"{",
"if",
"(",
"childNode",
".",
"type",
"==",
"'ExpressionStatement'",
")",
"{",
"expressionStatements",
".",
"push",
"(",
"childNode",
")",
";",
"}",
"else",
"if",
"(",
"childNode",
".",
"body",
")",
"{",
"var",
"childExpressions",
"=",
"getAllExpressionStatements",
"(",
"childNode",
")",
";",
"expressionStatements",
".",
"push",
".",
"apply",
"(",
"expressionStatements",
",",
"childExpressions",
")",
";",
"}",
"}",
")",
";",
"return",
"expressionStatements",
";",
"}"
] | Recursively find all expression statements in all block nodes.
@param {ASTNode} node
@return {!Array.<ASTNode>} | [
"Recursively",
"find",
"all",
"expression",
"statements",
"in",
"all",
"block",
"nodes",
"."
] | 01f7af9d4ee3eeb712719480cb55b7573a2b41fd | https://github.com/google/shaka-player/blob/01f7af9d4ee3eeb712719480cb55b7573a2b41fd/build/generateExterns.js#L304-L316 |
5,349 | google/shaka-player | build/generateExterns.js | createExternsFromConstructor | function createExternsFromConstructor(className, constructorNode) {
// Example code:
//
// /** @interface @exportInterface */
// FooLike = function() {};
//
// /** @exportInterface @type {number} */
// FooLike.prototype.bar;
//
// /** @constructor @export @implements {FooLike} */
// Foo = function() {
// /** @override @exportInterface */
// this.bar = 10;
// };
//
// Example externs:
//
// /**
// * Generated by createExternFromExportNode:
// * @constructor @implements {FooLike}
// */
// Foo = function() {}
//
// /**
// * Generated by createExternsFromConstructor:
// * @override
// */
// Foo.prototype.bar;
var expressionStatements = getAllExpressionStatements(constructorNode);
var externString = '';
expressionStatements.forEach(function(statement) {
var left = statement.expression.left;
var right = statement.expression.right;
// Skip anything that isn't an assignment to a member of "this".
if (statement.expression.type != 'AssignmentExpression' ||
left.type != 'MemberExpression' ||
left.object.type != 'ThisExpression')
return;
console.assert(left);
console.assert(right);
// Skip anything that isn't exported.
var comment = getLeadingBlockComment(statement);
if (!EXPORT_REGEX.test(comment))
return;
comment = removeExportAnnotationsFromComment(comment);
console.assert(left.property.type == 'Identifier');
var name = className + '.prototype.' + left.property.name;
externString += comment + '\n' + name + ';\n';
});
return externString;
} | javascript | function createExternsFromConstructor(className, constructorNode) {
// Example code:
//
// /** @interface @exportInterface */
// FooLike = function() {};
//
// /** @exportInterface @type {number} */
// FooLike.prototype.bar;
//
// /** @constructor @export @implements {FooLike} */
// Foo = function() {
// /** @override @exportInterface */
// this.bar = 10;
// };
//
// Example externs:
//
// /**
// * Generated by createExternFromExportNode:
// * @constructor @implements {FooLike}
// */
// Foo = function() {}
//
// /**
// * Generated by createExternsFromConstructor:
// * @override
// */
// Foo.prototype.bar;
var expressionStatements = getAllExpressionStatements(constructorNode);
var externString = '';
expressionStatements.forEach(function(statement) {
var left = statement.expression.left;
var right = statement.expression.right;
// Skip anything that isn't an assignment to a member of "this".
if (statement.expression.type != 'AssignmentExpression' ||
left.type != 'MemberExpression' ||
left.object.type != 'ThisExpression')
return;
console.assert(left);
console.assert(right);
// Skip anything that isn't exported.
var comment = getLeadingBlockComment(statement);
if (!EXPORT_REGEX.test(comment))
return;
comment = removeExportAnnotationsFromComment(comment);
console.assert(left.property.type == 'Identifier');
var name = className + '.prototype.' + left.property.name;
externString += comment + '\n' + name + ';\n';
});
return externString;
} | [
"function",
"createExternsFromConstructor",
"(",
"className",
",",
"constructorNode",
")",
"{",
"// Example code:",
"//",
"// /** @interface @exportInterface */",
"// FooLike = function() {};",
"//",
"// /** @exportInterface @type {number} */",
"// FooLike.prototype.bar;",
"//",
"// /** @constructor @export @implements {FooLike} */",
"// Foo = function() {",
"// /** @override @exportInterface */",
"// this.bar = 10;",
"// };",
"//",
"// Example externs:",
"//",
"// /**",
"// * Generated by createExternFromExportNode:",
"// * @constructor @implements {FooLike}",
"// */",
"// Foo = function() {}",
"//",
"// /**",
"// * Generated by createExternsFromConstructor:",
"// * @override",
"// */",
"// Foo.prototype.bar;",
"var",
"expressionStatements",
"=",
"getAllExpressionStatements",
"(",
"constructorNode",
")",
";",
"var",
"externString",
"=",
"''",
";",
"expressionStatements",
".",
"forEach",
"(",
"function",
"(",
"statement",
")",
"{",
"var",
"left",
"=",
"statement",
".",
"expression",
".",
"left",
";",
"var",
"right",
"=",
"statement",
".",
"expression",
".",
"right",
";",
"// Skip anything that isn't an assignment to a member of \"this\".",
"if",
"(",
"statement",
".",
"expression",
".",
"type",
"!=",
"'AssignmentExpression'",
"||",
"left",
".",
"type",
"!=",
"'MemberExpression'",
"||",
"left",
".",
"object",
".",
"type",
"!=",
"'ThisExpression'",
")",
"return",
";",
"console",
".",
"assert",
"(",
"left",
")",
";",
"console",
".",
"assert",
"(",
"right",
")",
";",
"// Skip anything that isn't exported.",
"var",
"comment",
"=",
"getLeadingBlockComment",
"(",
"statement",
")",
";",
"if",
"(",
"!",
"EXPORT_REGEX",
".",
"test",
"(",
"comment",
")",
")",
"return",
";",
"comment",
"=",
"removeExportAnnotationsFromComment",
"(",
"comment",
")",
";",
"console",
".",
"assert",
"(",
"left",
".",
"property",
".",
"type",
"==",
"'Identifier'",
")",
";",
"var",
"name",
"=",
"className",
"+",
"'.prototype.'",
"+",
"left",
".",
"property",
".",
"name",
";",
"externString",
"+=",
"comment",
"+",
"'\\n'",
"+",
"name",
"+",
"';\\n'",
";",
"}",
")",
";",
"return",
"externString",
";",
"}"
] | Look for exports in a constructor body. If we don't do this, we may end up
with errors about classes not fully implementing their interfaces. In
reality, the interface is implemented by assigning members on "this".
@param {string} className
@param {ASTNode} constructorNode
@return {string} | [
"Look",
"for",
"exports",
"in",
"a",
"constructor",
"body",
".",
"If",
"we",
"don",
"t",
"do",
"this",
"we",
"may",
"end",
"up",
"with",
"errors",
"about",
"classes",
"not",
"fully",
"implementing",
"their",
"interfaces",
".",
"In",
"reality",
"the",
"interface",
"is",
"implemented",
"by",
"assigning",
"members",
"on",
"this",
"."
] | 01f7af9d4ee3eeb712719480cb55b7573a2b41fd | https://github.com/google/shaka-player/blob/01f7af9d4ee3eeb712719480cb55b7573a2b41fd/build/generateExterns.js#L502-L560 |
5,350 | google/shaka-player | lib/util/object_utils.js | function(val) {
switch (typeof val) {
case 'undefined':
case 'boolean':
case 'number':
case 'string':
case 'symbol':
case 'function':
return val;
case 'object':
default: {
// typeof null === 'object'
if (!val) return val;
// This covers Uint8Array and friends, even without a TypedArray
// base-class constructor.
const isTypedArray =
val.buffer && val.buffer.constructor == ArrayBuffer;
if (isTypedArray) {
return val;
}
if (seenObjects.has(val)) {
return null;
}
const isArray = val.constructor == Array;
if (val.constructor != Object && !isArray) {
return null;
}
seenObjects.add(val);
const ret = isArray ? [] : {};
// Note |name| will equal a number for arrays.
for (const name in val) {
ret[name] = clone(val[name]);
}
// Length is a non-enumerable property, but we should copy it over in
// case it is not the default.
if (isArray) {
ret.length = val.length;
}
return ret;
}
}
} | javascript | function(val) {
switch (typeof val) {
case 'undefined':
case 'boolean':
case 'number':
case 'string':
case 'symbol':
case 'function':
return val;
case 'object':
default: {
// typeof null === 'object'
if (!val) return val;
// This covers Uint8Array and friends, even without a TypedArray
// base-class constructor.
const isTypedArray =
val.buffer && val.buffer.constructor == ArrayBuffer;
if (isTypedArray) {
return val;
}
if (seenObjects.has(val)) {
return null;
}
const isArray = val.constructor == Array;
if (val.constructor != Object && !isArray) {
return null;
}
seenObjects.add(val);
const ret = isArray ? [] : {};
// Note |name| will equal a number for arrays.
for (const name in val) {
ret[name] = clone(val[name]);
}
// Length is a non-enumerable property, but we should copy it over in
// case it is not the default.
if (isArray) {
ret.length = val.length;
}
return ret;
}
}
} | [
"function",
"(",
"val",
")",
"{",
"switch",
"(",
"typeof",
"val",
")",
"{",
"case",
"'undefined'",
":",
"case",
"'boolean'",
":",
"case",
"'number'",
":",
"case",
"'string'",
":",
"case",
"'symbol'",
":",
"case",
"'function'",
":",
"return",
"val",
";",
"case",
"'object'",
":",
"default",
":",
"{",
"// typeof null === 'object'",
"if",
"(",
"!",
"val",
")",
"return",
"val",
";",
"// This covers Uint8Array and friends, even without a TypedArray",
"// base-class constructor.",
"const",
"isTypedArray",
"=",
"val",
".",
"buffer",
"&&",
"val",
".",
"buffer",
".",
"constructor",
"==",
"ArrayBuffer",
";",
"if",
"(",
"isTypedArray",
")",
"{",
"return",
"val",
";",
"}",
"if",
"(",
"seenObjects",
".",
"has",
"(",
"val",
")",
")",
"{",
"return",
"null",
";",
"}",
"const",
"isArray",
"=",
"val",
".",
"constructor",
"==",
"Array",
";",
"if",
"(",
"val",
".",
"constructor",
"!=",
"Object",
"&&",
"!",
"isArray",
")",
"{",
"return",
"null",
";",
"}",
"seenObjects",
".",
"add",
"(",
"val",
")",
";",
"const",
"ret",
"=",
"isArray",
"?",
"[",
"]",
":",
"{",
"}",
";",
"// Note |name| will equal a number for arrays.",
"for",
"(",
"const",
"name",
"in",
"val",
")",
"{",
"ret",
"[",
"name",
"]",
"=",
"clone",
"(",
"val",
"[",
"name",
"]",
")",
";",
"}",
"// Length is a non-enumerable property, but we should copy it over in",
"// case it is not the default.",
"if",
"(",
"isArray",
")",
"{",
"ret",
".",
"length",
"=",
"val",
".",
"length",
";",
"}",
"return",
"ret",
";",
"}",
"}",
"}"
] | This recursively clones the value |val|, using the captured variable |seenObjects| to track the objects we have already cloned. | [
"This",
"recursively",
"clones",
"the",
"value",
"|val|",
"using",
"the",
"captured",
"variable",
"|seenObjects|",
"to",
"track",
"the",
"objects",
"we",
"have",
"already",
"cloned",
"."
] | 01f7af9d4ee3eeb712719480cb55b7573a2b41fd | https://github.com/google/shaka-player/blob/01f7af9d4ee3eeb712719480cb55b7573a2b41fd/lib/util/object_utils.js#L36-L82 |
|
5,351 | google/shaka-player | lib/player.js | getAdjustedTime | function getAdjustedTime(stream, time) {
if (!stream) return null;
const idx = stream.findSegmentPosition(time - period.startTime);
if (idx == null) return null;
const ref = stream.getSegmentReference(idx);
if (!ref) return null;
const refTime = ref.startTime + period.startTime;
goog.asserts.assert(refTime <= time, 'Segment should start before time');
return refTime;
} | javascript | function getAdjustedTime(stream, time) {
if (!stream) return null;
const idx = stream.findSegmentPosition(time - period.startTime);
if (idx == null) return null;
const ref = stream.getSegmentReference(idx);
if (!ref) return null;
const refTime = ref.startTime + period.startTime;
goog.asserts.assert(refTime <= time, 'Segment should start before time');
return refTime;
} | [
"function",
"getAdjustedTime",
"(",
"stream",
",",
"time",
")",
"{",
"if",
"(",
"!",
"stream",
")",
"return",
"null",
";",
"const",
"idx",
"=",
"stream",
".",
"findSegmentPosition",
"(",
"time",
"-",
"period",
".",
"startTime",
")",
";",
"if",
"(",
"idx",
"==",
"null",
")",
"return",
"null",
";",
"const",
"ref",
"=",
"stream",
".",
"getSegmentReference",
"(",
"idx",
")",
";",
"if",
"(",
"!",
"ref",
")",
"return",
"null",
";",
"const",
"refTime",
"=",
"ref",
".",
"startTime",
"+",
"period",
".",
"startTime",
";",
"goog",
".",
"asserts",
".",
"assert",
"(",
"refTime",
"<=",
"time",
",",
"'Segment should start before time'",
")",
";",
"return",
"refTime",
";",
"}"
] | This method is called after StreamingEngine.init resolves, which means that all the active streams have had createSegmentIndex called. | [
"This",
"method",
"is",
"called",
"after",
"StreamingEngine",
".",
"init",
"resolves",
"which",
"means",
"that",
"all",
"the",
"active",
"streams",
"have",
"had",
"createSegmentIndex",
"called",
"."
] | 01f7af9d4ee3eeb712719480cb55b7573a2b41fd | https://github.com/google/shaka-player/blob/01f7af9d4ee3eeb712719480cb55b7573a2b41fd/lib/player.js#L3905-L3914 |
5,352 | google/shaka-player | karma.conf.js | allUsableBrowserLaunchers | function allUsableBrowserLaunchers(config) {
var browsers = [];
// Load all launcher plugins.
// The format of the items in this list is something like:
// {
// 'launcher:foo1': ['type', Function],
// 'launcher:foo2': ['type', Function],
// }
// Where the launchers grouped together into one item were defined by a single
// plugin, and the Functions in the inner array are the constructors for those
// launchers.
var plugins = require('karma/lib/plugin').resolve(['karma-*-launcher']);
plugins.forEach(function(map) {
Object.keys(map).forEach(function(name) {
// Launchers should all start with 'launcher:', but occasionally we also
// see 'test' come up for some reason.
if (!name.startsWith('launcher:')) return;
var browserName = name.split(':')[1];
var pluginConstructor = map[name][1];
// Most launchers requiring configuration through customLaunchers have
// no DEFAULT_CMD. Some launchers have DEFAULT_CMD, but not for this
// platform. Finally, WebDriver has DEFAULT_CMD, but still requires
// configuration, so we simply blacklist it by name.
var DEFAULT_CMD = pluginConstructor.prototype.DEFAULT_CMD;
if (!DEFAULT_CMD || !DEFAULT_CMD[process.platform]) return;
if (browserName == 'WebDriver') return;
// Now that we've filtered out the browsers that can't be launched without
// custom config or that can't be launched on this platform, we filter out
// the browsers you don't have installed.
var ENV_CMD = pluginConstructor.prototype.ENV_CMD;
var browserPath = process.env[ENV_CMD] || DEFAULT_CMD[process.platform];
if (!fs.existsSync(browserPath) &&
!which.sync(browserPath, {nothrow: true})) return;
browsers.push(browserName);
});
});
// Once we've found the names of all the standard launchers, add to that list
// the names of any custom launcher configurations.
if (config.customLaunchers) {
browsers.push.apply(browsers, Object.keys(config.customLaunchers));
}
return browsers;
} | javascript | function allUsableBrowserLaunchers(config) {
var browsers = [];
// Load all launcher plugins.
// The format of the items in this list is something like:
// {
// 'launcher:foo1': ['type', Function],
// 'launcher:foo2': ['type', Function],
// }
// Where the launchers grouped together into one item were defined by a single
// plugin, and the Functions in the inner array are the constructors for those
// launchers.
var plugins = require('karma/lib/plugin').resolve(['karma-*-launcher']);
plugins.forEach(function(map) {
Object.keys(map).forEach(function(name) {
// Launchers should all start with 'launcher:', but occasionally we also
// see 'test' come up for some reason.
if (!name.startsWith('launcher:')) return;
var browserName = name.split(':')[1];
var pluginConstructor = map[name][1];
// Most launchers requiring configuration through customLaunchers have
// no DEFAULT_CMD. Some launchers have DEFAULT_CMD, but not for this
// platform. Finally, WebDriver has DEFAULT_CMD, but still requires
// configuration, so we simply blacklist it by name.
var DEFAULT_CMD = pluginConstructor.prototype.DEFAULT_CMD;
if (!DEFAULT_CMD || !DEFAULT_CMD[process.platform]) return;
if (browserName == 'WebDriver') return;
// Now that we've filtered out the browsers that can't be launched without
// custom config or that can't be launched on this platform, we filter out
// the browsers you don't have installed.
var ENV_CMD = pluginConstructor.prototype.ENV_CMD;
var browserPath = process.env[ENV_CMD] || DEFAULT_CMD[process.platform];
if (!fs.existsSync(browserPath) &&
!which.sync(browserPath, {nothrow: true})) return;
browsers.push(browserName);
});
});
// Once we've found the names of all the standard launchers, add to that list
// the names of any custom launcher configurations.
if (config.customLaunchers) {
browsers.push.apply(browsers, Object.keys(config.customLaunchers));
}
return browsers;
} | [
"function",
"allUsableBrowserLaunchers",
"(",
"config",
")",
"{",
"var",
"browsers",
"=",
"[",
"]",
";",
"// Load all launcher plugins.",
"// The format of the items in this list is something like:",
"// {",
"// 'launcher:foo1': ['type', Function],",
"// 'launcher:foo2': ['type', Function],",
"// }",
"// Where the launchers grouped together into one item were defined by a single",
"// plugin, and the Functions in the inner array are the constructors for those",
"// launchers.",
"var",
"plugins",
"=",
"require",
"(",
"'karma/lib/plugin'",
")",
".",
"resolve",
"(",
"[",
"'karma-*-launcher'",
"]",
")",
";",
"plugins",
".",
"forEach",
"(",
"function",
"(",
"map",
")",
"{",
"Object",
".",
"keys",
"(",
"map",
")",
".",
"forEach",
"(",
"function",
"(",
"name",
")",
"{",
"// Launchers should all start with 'launcher:', but occasionally we also",
"// see 'test' come up for some reason.",
"if",
"(",
"!",
"name",
".",
"startsWith",
"(",
"'launcher:'",
")",
")",
"return",
";",
"var",
"browserName",
"=",
"name",
".",
"split",
"(",
"':'",
")",
"[",
"1",
"]",
";",
"var",
"pluginConstructor",
"=",
"map",
"[",
"name",
"]",
"[",
"1",
"]",
";",
"// Most launchers requiring configuration through customLaunchers have",
"// no DEFAULT_CMD. Some launchers have DEFAULT_CMD, but not for this",
"// platform. Finally, WebDriver has DEFAULT_CMD, but still requires",
"// configuration, so we simply blacklist it by name.",
"var",
"DEFAULT_CMD",
"=",
"pluginConstructor",
".",
"prototype",
".",
"DEFAULT_CMD",
";",
"if",
"(",
"!",
"DEFAULT_CMD",
"||",
"!",
"DEFAULT_CMD",
"[",
"process",
".",
"platform",
"]",
")",
"return",
";",
"if",
"(",
"browserName",
"==",
"'WebDriver'",
")",
"return",
";",
"// Now that we've filtered out the browsers that can't be launched without",
"// custom config or that can't be launched on this platform, we filter out",
"// the browsers you don't have installed.",
"var",
"ENV_CMD",
"=",
"pluginConstructor",
".",
"prototype",
".",
"ENV_CMD",
";",
"var",
"browserPath",
"=",
"process",
".",
"env",
"[",
"ENV_CMD",
"]",
"||",
"DEFAULT_CMD",
"[",
"process",
".",
"platform",
"]",
";",
"if",
"(",
"!",
"fs",
".",
"existsSync",
"(",
"browserPath",
")",
"&&",
"!",
"which",
".",
"sync",
"(",
"browserPath",
",",
"{",
"nothrow",
":",
"true",
"}",
")",
")",
"return",
";",
"browsers",
".",
"push",
"(",
"browserName",
")",
";",
"}",
")",
";",
"}",
")",
";",
"// Once we've found the names of all the standard launchers, add to that list",
"// the names of any custom launcher configurations.",
"if",
"(",
"config",
".",
"customLaunchers",
")",
"{",
"browsers",
".",
"push",
".",
"apply",
"(",
"browsers",
",",
"Object",
".",
"keys",
"(",
"config",
".",
"customLaunchers",
")",
")",
";",
"}",
"return",
"browsers",
";",
"}"
] | Determines which launchers and customLaunchers can be used and returns an array of strings. | [
"Determines",
"which",
"launchers",
"and",
"customLaunchers",
"can",
"be",
"used",
"and",
"returns",
"an",
"array",
"of",
"strings",
"."
] | 01f7af9d4ee3eeb712719480cb55b7573a2b41fd | https://github.com/google/shaka-player/blob/01f7af9d4ee3eeb712719480cb55b7573a2b41fd/karma.conf.js#L315-L365 |
5,353 | google/shaka-player | demo/service_worker.js | onInstall | function onInstall(event) {
const preCacheApplication = async () => {
const cache = await caches.open(CACHE_NAME);
// Fetching these with addAll fails for CORS-restricted content, so we use
// fetchAndCache with no-cors mode to work around it.
// Optional resources: failure on these will NOT fail the Promise chain.
// We will also not wait for them to be installed.
for (const url of OPTIONAL_RESOURCES) {
const request = new Request(url, {mode: 'no-cors'});
fetchAndCache(cache, request).catch(() => {});
}
// Critical resources: failure on these will fail the Promise chain.
// The installation will not be complete until these are all cached.
const criticalFetches = [];
for (const url of CRITICAL_RESOURCES) {
const request = new Request(url, {mode: 'no-cors'});
criticalFetches.push(fetchAndCache(cache, request));
}
return Promise.all(criticalFetches);
};
event.waitUntil(preCacheApplication());
} | javascript | function onInstall(event) {
const preCacheApplication = async () => {
const cache = await caches.open(CACHE_NAME);
// Fetching these with addAll fails for CORS-restricted content, so we use
// fetchAndCache with no-cors mode to work around it.
// Optional resources: failure on these will NOT fail the Promise chain.
// We will also not wait for them to be installed.
for (const url of OPTIONAL_RESOURCES) {
const request = new Request(url, {mode: 'no-cors'});
fetchAndCache(cache, request).catch(() => {});
}
// Critical resources: failure on these will fail the Promise chain.
// The installation will not be complete until these are all cached.
const criticalFetches = [];
for (const url of CRITICAL_RESOURCES) {
const request = new Request(url, {mode: 'no-cors'});
criticalFetches.push(fetchAndCache(cache, request));
}
return Promise.all(criticalFetches);
};
event.waitUntil(preCacheApplication());
} | [
"function",
"onInstall",
"(",
"event",
")",
"{",
"const",
"preCacheApplication",
"=",
"async",
"(",
")",
"=>",
"{",
"const",
"cache",
"=",
"await",
"caches",
".",
"open",
"(",
"CACHE_NAME",
")",
";",
"// Fetching these with addAll fails for CORS-restricted content, so we use",
"// fetchAndCache with no-cors mode to work around it.",
"// Optional resources: failure on these will NOT fail the Promise chain.",
"// We will also not wait for them to be installed.",
"for",
"(",
"const",
"url",
"of",
"OPTIONAL_RESOURCES",
")",
"{",
"const",
"request",
"=",
"new",
"Request",
"(",
"url",
",",
"{",
"mode",
":",
"'no-cors'",
"}",
")",
";",
"fetchAndCache",
"(",
"cache",
",",
"request",
")",
".",
"catch",
"(",
"(",
")",
"=>",
"{",
"}",
")",
";",
"}",
"// Critical resources: failure on these will fail the Promise chain.",
"// The installation will not be complete until these are all cached.",
"const",
"criticalFetches",
"=",
"[",
"]",
";",
"for",
"(",
"const",
"url",
"of",
"CRITICAL_RESOURCES",
")",
"{",
"const",
"request",
"=",
"new",
"Request",
"(",
"url",
",",
"{",
"mode",
":",
"'no-cors'",
"}",
")",
";",
"criticalFetches",
".",
"push",
"(",
"fetchAndCache",
"(",
"cache",
",",
"request",
")",
")",
";",
"}",
"return",
"Promise",
".",
"all",
"(",
"criticalFetches",
")",
";",
"}",
";",
"event",
".",
"waitUntil",
"(",
"preCacheApplication",
"(",
")",
")",
";",
"}"
] | This event fires when the service worker is installed.
@param {!InstallEvent} event | [
"This",
"event",
"fires",
"when",
"the",
"service",
"worker",
"is",
"installed",
"."
] | 01f7af9d4ee3eeb712719480cb55b7573a2b41fd | https://github.com/google/shaka-player/blob/01f7af9d4ee3eeb712719480cb55b7573a2b41fd/demo/service_worker.js#L144-L168 |
5,354 | google/shaka-player | demo/service_worker.js | onActivate | function onActivate(event) {
// Delete old caches to save space.
const dropOldCaches = async () => {
const cacheNames = await caches.keys();
// Return true on all the caches we want to clean up.
// Note that caches are shared across the origin, so only remove
// caches we are sure we created.
const cleanTheseUp = cacheNames.filter((cacheName) =>
cacheName.startsWith(CACHE_NAME_PREFIX) && cacheName != CACHE_NAME);
const cleanUpPromises =
cleanTheseUp.map((cacheName) => caches.delete(cacheName));
await Promise.all(cleanUpPromises);
};
event.waitUntil(dropOldCaches());
} | javascript | function onActivate(event) {
// Delete old caches to save space.
const dropOldCaches = async () => {
const cacheNames = await caches.keys();
// Return true on all the caches we want to clean up.
// Note that caches are shared across the origin, so only remove
// caches we are sure we created.
const cleanTheseUp = cacheNames.filter((cacheName) =>
cacheName.startsWith(CACHE_NAME_PREFIX) && cacheName != CACHE_NAME);
const cleanUpPromises =
cleanTheseUp.map((cacheName) => caches.delete(cacheName));
await Promise.all(cleanUpPromises);
};
event.waitUntil(dropOldCaches());
} | [
"function",
"onActivate",
"(",
"event",
")",
"{",
"// Delete old caches to save space.",
"const",
"dropOldCaches",
"=",
"async",
"(",
")",
"=>",
"{",
"const",
"cacheNames",
"=",
"await",
"caches",
".",
"keys",
"(",
")",
";",
"// Return true on all the caches we want to clean up.",
"// Note that caches are shared across the origin, so only remove",
"// caches we are sure we created.",
"const",
"cleanTheseUp",
"=",
"cacheNames",
".",
"filter",
"(",
"(",
"cacheName",
")",
"=>",
"cacheName",
".",
"startsWith",
"(",
"CACHE_NAME_PREFIX",
")",
"&&",
"cacheName",
"!=",
"CACHE_NAME",
")",
";",
"const",
"cleanUpPromises",
"=",
"cleanTheseUp",
".",
"map",
"(",
"(",
"cacheName",
")",
"=>",
"caches",
".",
"delete",
"(",
"cacheName",
")",
")",
";",
"await",
"Promise",
".",
"all",
"(",
"cleanUpPromises",
")",
";",
"}",
";",
"event",
".",
"waitUntil",
"(",
"dropOldCaches",
"(",
")",
")",
";",
"}"
] | This event fires when the service worker is activated.
This can be after installation or upgrade.
@param {!ExtendableEvent} event | [
"This",
"event",
"fires",
"when",
"the",
"service",
"worker",
"is",
"activated",
".",
"This",
"can",
"be",
"after",
"installation",
"or",
"upgrade",
"."
] | 01f7af9d4ee3eeb712719480cb55b7573a2b41fd | https://github.com/google/shaka-player/blob/01f7af9d4ee3eeb712719480cb55b7573a2b41fd/demo/service_worker.js#L176-L194 |
5,355 | google/shaka-player | demo/service_worker.js | onFetch | function onFetch(event) {
// Make sure this is a request we should be handling in the first place.
// If it's not, it's important to leave it alone and not call respondWith.
let useCache = false;
for (const prefix of CACHEABLE_URL_PREFIXES) {
if (event.request.url.startsWith(prefix)) {
useCache = true;
break;
}
}
// Now we need to check our resource lists. The list of prefixes above won't
// cover everything that was installed initially, and those things still need
// to be read from cache. So we check if this request URL matches one of
// those lists.
// The resource lists contain some relative URLs and some absolute URLs. The
// check here will only be able to match the absolute ones, but that's enough,
// because the relative ones are covered by the loop above.
if (!useCache) {
if (CRITICAL_RESOURCES.includes(event.request.url) ||
OPTIONAL_RESOURCES.includes(event.request.url)) {
useCache = true;
}
}
if (useCache) {
event.respondWith(fetchCacheableResource(event.request));
}
} | javascript | function onFetch(event) {
// Make sure this is a request we should be handling in the first place.
// If it's not, it's important to leave it alone and not call respondWith.
let useCache = false;
for (const prefix of CACHEABLE_URL_PREFIXES) {
if (event.request.url.startsWith(prefix)) {
useCache = true;
break;
}
}
// Now we need to check our resource lists. The list of prefixes above won't
// cover everything that was installed initially, and those things still need
// to be read from cache. So we check if this request URL matches one of
// those lists.
// The resource lists contain some relative URLs and some absolute URLs. The
// check here will only be able to match the absolute ones, but that's enough,
// because the relative ones are covered by the loop above.
if (!useCache) {
if (CRITICAL_RESOURCES.includes(event.request.url) ||
OPTIONAL_RESOURCES.includes(event.request.url)) {
useCache = true;
}
}
if (useCache) {
event.respondWith(fetchCacheableResource(event.request));
}
} | [
"function",
"onFetch",
"(",
"event",
")",
"{",
"// Make sure this is a request we should be handling in the first place.",
"// If it's not, it's important to leave it alone and not call respondWith.",
"let",
"useCache",
"=",
"false",
";",
"for",
"(",
"const",
"prefix",
"of",
"CACHEABLE_URL_PREFIXES",
")",
"{",
"if",
"(",
"event",
".",
"request",
".",
"url",
".",
"startsWith",
"(",
"prefix",
")",
")",
"{",
"useCache",
"=",
"true",
";",
"break",
";",
"}",
"}",
"// Now we need to check our resource lists. The list of prefixes above won't",
"// cover everything that was installed initially, and those things still need",
"// to be read from cache. So we check if this request URL matches one of",
"// those lists.",
"// The resource lists contain some relative URLs and some absolute URLs. The",
"// check here will only be able to match the absolute ones, but that's enough,",
"// because the relative ones are covered by the loop above.",
"if",
"(",
"!",
"useCache",
")",
"{",
"if",
"(",
"CRITICAL_RESOURCES",
".",
"includes",
"(",
"event",
".",
"request",
".",
"url",
")",
"||",
"OPTIONAL_RESOURCES",
".",
"includes",
"(",
"event",
".",
"request",
".",
"url",
")",
")",
"{",
"useCache",
"=",
"true",
";",
"}",
"}",
"if",
"(",
"useCache",
")",
"{",
"event",
".",
"respondWith",
"(",
"fetchCacheableResource",
"(",
"event",
".",
"request",
")",
")",
";",
"}",
"}"
] | This event fires when any resource is fetched.
This is where we can use the cache to respond offline.
@param {!FetchEvent} event | [
"This",
"event",
"fires",
"when",
"any",
"resource",
"is",
"fetched",
".",
"This",
"is",
"where",
"we",
"can",
"use",
"the",
"cache",
"to",
"respond",
"offline",
"."
] | 01f7af9d4ee3eeb712719480cb55b7573a2b41fd | https://github.com/google/shaka-player/blob/01f7af9d4ee3eeb712719480cb55b7573a2b41fd/demo/service_worker.js#L202-L230 |
5,356 | google/shaka-player | demo/service_worker.js | fetchCacheableResource | async function fetchCacheableResource(request) {
const cache = await caches.open(CACHE_NAME);
const cachedResponse = await cache.match(request);
if (!navigator.onLine) {
// We are offline, and we know it. Just return the cached response, to
// avoid a bunch of pointless errors in the JS console that will confuse
// us developers. If there is no cached response, this will just be a
// failed request.
return cachedResponse;
}
if (cachedResponse) {
// We have it in cache. Try to fetch a live version and update the cache,
// but limit how long we will wait for the updated version.
try {
return timeout(NETWORK_TIMEOUT, fetchAndCache(cache, request));
} catch (error) {
// We tried to fetch a live version, but it either failed or took too
// long. If it took too long, the fetch and cache operation will continue
// in the background. In both cases, we should go ahead with a cached
// version.
return cachedResponse;
}
} else {
// We should have this in cache, but we don't. Fetch and cache a fresh
// copy and then return it.
return fetchAndCache(cache, request);
}
} | javascript | async function fetchCacheableResource(request) {
const cache = await caches.open(CACHE_NAME);
const cachedResponse = await cache.match(request);
if (!navigator.onLine) {
// We are offline, and we know it. Just return the cached response, to
// avoid a bunch of pointless errors in the JS console that will confuse
// us developers. If there is no cached response, this will just be a
// failed request.
return cachedResponse;
}
if (cachedResponse) {
// We have it in cache. Try to fetch a live version and update the cache,
// but limit how long we will wait for the updated version.
try {
return timeout(NETWORK_TIMEOUT, fetchAndCache(cache, request));
} catch (error) {
// We tried to fetch a live version, but it either failed or took too
// long. If it took too long, the fetch and cache operation will continue
// in the background. In both cases, we should go ahead with a cached
// version.
return cachedResponse;
}
} else {
// We should have this in cache, but we don't. Fetch and cache a fresh
// copy and then return it.
return fetchAndCache(cache, request);
}
} | [
"async",
"function",
"fetchCacheableResource",
"(",
"request",
")",
"{",
"const",
"cache",
"=",
"await",
"caches",
".",
"open",
"(",
"CACHE_NAME",
")",
";",
"const",
"cachedResponse",
"=",
"await",
"cache",
".",
"match",
"(",
"request",
")",
";",
"if",
"(",
"!",
"navigator",
".",
"onLine",
")",
"{",
"// We are offline, and we know it. Just return the cached response, to",
"// avoid a bunch of pointless errors in the JS console that will confuse",
"// us developers. If there is no cached response, this will just be a",
"// failed request.",
"return",
"cachedResponse",
";",
"}",
"if",
"(",
"cachedResponse",
")",
"{",
"// We have it in cache. Try to fetch a live version and update the cache,",
"// but limit how long we will wait for the updated version.",
"try",
"{",
"return",
"timeout",
"(",
"NETWORK_TIMEOUT",
",",
"fetchAndCache",
"(",
"cache",
",",
"request",
")",
")",
";",
"}",
"catch",
"(",
"error",
")",
"{",
"// We tried to fetch a live version, but it either failed or took too",
"// long. If it took too long, the fetch and cache operation will continue",
"// in the background. In both cases, we should go ahead with a cached",
"// version.",
"return",
"cachedResponse",
";",
"}",
"}",
"else",
"{",
"// We should have this in cache, but we don't. Fetch and cache a fresh",
"// copy and then return it.",
"return",
"fetchAndCache",
"(",
"cache",
",",
"request",
")",
";",
"}",
"}"
] | Fetch a cacheable resource. Decide whether to request from the network,
the cache, or both, and return the appropriate version of the resource.
@param {!Request} request
@return {!Promise.<!Response>} | [
"Fetch",
"a",
"cacheable",
"resource",
".",
"Decide",
"whether",
"to",
"request",
"from",
"the",
"network",
"the",
"cache",
"or",
"both",
"and",
"return",
"the",
"appropriate",
"version",
"of",
"the",
"resource",
"."
] | 01f7af9d4ee3eeb712719480cb55b7573a2b41fd | https://github.com/google/shaka-player/blob/01f7af9d4ee3eeb712719480cb55b7573a2b41fd/demo/service_worker.js#L239-L268 |
5,357 | google/shaka-player | demo/service_worker.js | fetchAndCache | async function fetchAndCache(cache, request) {
const response = await fetch(request);
cache.put(request, response.clone());
return response;
} | javascript | async function fetchAndCache(cache, request) {
const response = await fetch(request);
cache.put(request, response.clone());
return response;
} | [
"async",
"function",
"fetchAndCache",
"(",
"cache",
",",
"request",
")",
"{",
"const",
"response",
"=",
"await",
"fetch",
"(",
"request",
")",
";",
"cache",
".",
"put",
"(",
"request",
",",
"response",
".",
"clone",
"(",
")",
")",
";",
"return",
"response",
";",
"}"
] | Fetch the resource from the network, then store this new version in the
cache.
@param {!Cache} cache
@param {!Request} request
@return {!Promise.<!Response>} | [
"Fetch",
"the",
"resource",
"from",
"the",
"network",
"then",
"store",
"this",
"new",
"version",
"in",
"the",
"cache",
"."
] | 01f7af9d4ee3eeb712719480cb55b7573a2b41fd | https://github.com/google/shaka-player/blob/01f7af9d4ee3eeb712719480cb55b7573a2b41fd/demo/service_worker.js#L278-L282 |
5,358 | google/shaka-player | demo/service_worker.js | timeout | function timeout(seconds, asyncProcess) {
return Promise.race([
asyncProcess,
new Promise(function(_, reject) {
setTimeout(reject, seconds * 1000);
}),
]);
} | javascript | function timeout(seconds, asyncProcess) {
return Promise.race([
asyncProcess,
new Promise(function(_, reject) {
setTimeout(reject, seconds * 1000);
}),
]);
} | [
"function",
"timeout",
"(",
"seconds",
",",
"asyncProcess",
")",
"{",
"return",
"Promise",
".",
"race",
"(",
"[",
"asyncProcess",
",",
"new",
"Promise",
"(",
"function",
"(",
"_",
",",
"reject",
")",
"{",
"setTimeout",
"(",
"reject",
",",
"seconds",
"*",
"1000",
")",
";",
"}",
")",
",",
"]",
")",
";",
"}"
] | Returns a Promise which is resolved only if |asyncProcess| is resolved, and
only if it is resolved in less than |seconds| seconds.
If the returned Promise is resolved, it returns the same value as
|asyncProcess|.
If |asyncProcess| fails, the returned Promise is rejected.
If |asyncProcess| takes too long, the returned Promise is rejected, but
|asyncProcess| is still allowed to complete.
@param {number} seconds
@param {!Promise.<T>} asyncProcess
@return {!Promise.<T>}
@template T | [
"Returns",
"a",
"Promise",
"which",
"is",
"resolved",
"only",
"if",
"|asyncProcess|",
"is",
"resolved",
"and",
"only",
"if",
"it",
"is",
"resolved",
"in",
"less",
"than",
"|seconds|",
"seconds",
"."
] | 01f7af9d4ee3eeb712719480cb55b7573a2b41fd | https://github.com/google/shaka-player/blob/01f7af9d4ee3eeb712719480cb55b7573a2b41fd/demo/service_worker.js#L300-L307 |
5,359 | google/shaka-player | demo/cast_receiver/receiver_app.js | ShakaReceiver | function ShakaReceiver() {
/** @private {HTMLMediaElement} */
this.video_ = null;
/** @private {shaka.Player} */
this.player_ = null;
/** @private {shaka.cast.CastReceiver} */
this.receiver_ = null;
/** @private {Element} */
this.controlsElement_ = null;
/** @private {?number} */
this.controlsTimerId_ = null;
/** @private {Element} */
this.idle_ = null;
/** @private {?number} */
this.idleTimerId_ = null;
/**
* In seconds.
* @const
* @private {number}
*/
this.idleTimeout_ = 300;
} | javascript | function ShakaReceiver() {
/** @private {HTMLMediaElement} */
this.video_ = null;
/** @private {shaka.Player} */
this.player_ = null;
/** @private {shaka.cast.CastReceiver} */
this.receiver_ = null;
/** @private {Element} */
this.controlsElement_ = null;
/** @private {?number} */
this.controlsTimerId_ = null;
/** @private {Element} */
this.idle_ = null;
/** @private {?number} */
this.idleTimerId_ = null;
/**
* In seconds.
* @const
* @private {number}
*/
this.idleTimeout_ = 300;
} | [
"function",
"ShakaReceiver",
"(",
")",
"{",
"/** @private {HTMLMediaElement} */",
"this",
".",
"video_",
"=",
"null",
";",
"/** @private {shaka.Player} */",
"this",
".",
"player_",
"=",
"null",
";",
"/** @private {shaka.cast.CastReceiver} */",
"this",
".",
"receiver_",
"=",
"null",
";",
"/** @private {Element} */",
"this",
".",
"controlsElement_",
"=",
"null",
";",
"/** @private {?number} */",
"this",
".",
"controlsTimerId_",
"=",
"null",
";",
"/** @private {Element} */",
"this",
".",
"idle_",
"=",
"null",
";",
"/** @private {?number} */",
"this",
".",
"idleTimerId_",
"=",
"null",
";",
"/**\n * In seconds.\n * @const\n * @private {number}\n */",
"this",
".",
"idleTimeout_",
"=",
"300",
";",
"}"
] | A Chromecast receiver demo app.
@constructor
@suppress {missingProvide} | [
"A",
"Chromecast",
"receiver",
"demo",
"app",
"."
] | 01f7af9d4ee3eeb712719480cb55b7573a2b41fd | https://github.com/google/shaka-player/blob/01f7af9d4ee3eeb712719480cb55b7573a2b41fd/demo/cast_receiver/receiver_app.js#L27-L55 |
5,360 | agershun/alasql | src/99worker-start.js | alasql | function alasql(sql,params,cb){
params = params||[];
// Avoid setting params if not needed even with callback
if(typeof params === 'function'){
scope = cb;
cb = params;
params = [];
}
if(typeof params !== 'object'){
params = [params];
}
// Increase last request id
var id = alasql.lastid++;
// Save callback
alasql.buffer[id] = cb;
// Send a message to worker
alasql.webworker.postMessage({id:id,sql:sql,params:params});
} | javascript | function alasql(sql,params,cb){
params = params||[];
// Avoid setting params if not needed even with callback
if(typeof params === 'function'){
scope = cb;
cb = params;
params = [];
}
if(typeof params !== 'object'){
params = [params];
}
// Increase last request id
var id = alasql.lastid++;
// Save callback
alasql.buffer[id] = cb;
// Send a message to worker
alasql.webworker.postMessage({id:id,sql:sql,params:params});
} | [
"function",
"alasql",
"(",
"sql",
",",
"params",
",",
"cb",
")",
"{",
"params",
"=",
"params",
"||",
"[",
"]",
";",
"// Avoid setting params if not needed even with callback",
"if",
"(",
"typeof",
"params",
"===",
"'function'",
")",
"{",
"scope",
"=",
"cb",
";",
"cb",
"=",
"params",
";",
"params",
"=",
"[",
"]",
";",
"}",
"if",
"(",
"typeof",
"params",
"!==",
"'object'",
")",
"{",
"params",
"=",
"[",
"params",
"]",
";",
"}",
"// Increase last request id",
"var",
"id",
"=",
"alasql",
".",
"lastid",
"++",
";",
"// Save callback",
"alasql",
".",
"buffer",
"[",
"id",
"]",
"=",
"cb",
";",
"// Send a message to worker",
"alasql",
".",
"webworker",
".",
"postMessage",
"(",
"{",
"id",
":",
"id",
",",
"sql",
":",
"sql",
",",
"params",
":",
"params",
"}",
")",
";",
"}"
] | Main procedure for worker
@function
@param {string} sql SQL statement
@param {object} params List of parameters (can be omitted)
@param {callback} cb Callback function
@return {object} Query result | [
"Main",
"procedure",
"for",
"worker"
] | ac380c9869aec93f2ae41621225e22547d1d221b | https://github.com/agershun/alasql/blob/ac380c9869aec93f2ae41621225e22547d1d221b/src/99worker-start.js#L26-L47 |
5,361 | agershun/alasql | src/832xlsxml.js | hstyle | function hstyle(st) {
// Prepare string
var s = '';
for (var key in st) {
s += '<' + key;
for (var attr in st[key]) {
s += ' ';
if (attr.substr(0, 2) == 'x:') {
s += attr;
} else {
s += 'ss:';
}
s += attr + '="' + st[key][attr] + '"';
}
s += '/>';
}
var hh = hash(s);
// Store in hash
if (styles[hh]) {
} else {
styles[hh] = {styleid: stylesn};
s2 += '<Style ss:ID="s' + stylesn + '">';
s2 += s;
s2 += '</Style>';
stylesn++;
}
return 's' + styles[hh].styleid;
} | javascript | function hstyle(st) {
// Prepare string
var s = '';
for (var key in st) {
s += '<' + key;
for (var attr in st[key]) {
s += ' ';
if (attr.substr(0, 2) == 'x:') {
s += attr;
} else {
s += 'ss:';
}
s += attr + '="' + st[key][attr] + '"';
}
s += '/>';
}
var hh = hash(s);
// Store in hash
if (styles[hh]) {
} else {
styles[hh] = {styleid: stylesn};
s2 += '<Style ss:ID="s' + stylesn + '">';
s2 += s;
s2 += '</Style>';
stylesn++;
}
return 's' + styles[hh].styleid;
} | [
"function",
"hstyle",
"(",
"st",
")",
"{",
"// Prepare string",
"var",
"s",
"=",
"''",
";",
"for",
"(",
"var",
"key",
"in",
"st",
")",
"{",
"s",
"+=",
"'<'",
"+",
"key",
";",
"for",
"(",
"var",
"attr",
"in",
"st",
"[",
"key",
"]",
")",
"{",
"s",
"+=",
"' '",
";",
"if",
"(",
"attr",
".",
"substr",
"(",
"0",
",",
"2",
")",
"==",
"'x:'",
")",
"{",
"s",
"+=",
"attr",
";",
"}",
"else",
"{",
"s",
"+=",
"'ss:'",
";",
"}",
"s",
"+=",
"attr",
"+",
"'=\"'",
"+",
"st",
"[",
"key",
"]",
"[",
"attr",
"]",
"+",
"'\"'",
";",
"}",
"s",
"+=",
"'/>'",
";",
"}",
"var",
"hh",
"=",
"hash",
"(",
"s",
")",
";",
"// Store in hash",
"if",
"(",
"styles",
"[",
"hh",
"]",
")",
"{",
"}",
"else",
"{",
"styles",
"[",
"hh",
"]",
"=",
"{",
"styleid",
":",
"stylesn",
"}",
";",
"s2",
"+=",
"'<Style ss:ID=\"s'",
"+",
"stylesn",
"+",
"'\">'",
";",
"s2",
"+=",
"s",
";",
"s2",
"+=",
"'</Style>'",
";",
"stylesn",
"++",
";",
"}",
"return",
"'s'",
"+",
"styles",
"[",
"hh",
"]",
".",
"styleid",
";",
"}"
] | First style Generate style | [
"First",
"style",
"Generate",
"style"
] | ac380c9869aec93f2ae41621225e22547d1d221b | https://github.com/agershun/alasql/blob/ac380c9869aec93f2ae41621225e22547d1d221b/src/832xlsxml.js#L66-L94 |
5,362 | agershun/alasql | bin/alasql-cli.js | execute | function execute(sql, params) {
if (0 === sql.trim().length) {
console.error("\nNo SQL to process\n");
yargs.showHelp();
process.exit(1);
}
for (var i = 1; i < params.length; i++) {
var a = params[i];
if (a[0] !== '"' && a[0] !== "'") {
if (+a == a) { // jshint ignore:line
params[i] = +a;
}
}
}
alasql.promise(sql, params)
.then(function (res) {
if (!alasql.options.stdout) {
console.log(formatOutput(res));
}
process.exit(0);
}).catch(function (err) {
let errorJsonObj = JSON.parse(JSON.stringify(err, Object.getOwnPropertyNames(err)));
console.error(formatOutput({
error: errorJsonObj
}));
process.exit(1);
});
} | javascript | function execute(sql, params) {
if (0 === sql.trim().length) {
console.error("\nNo SQL to process\n");
yargs.showHelp();
process.exit(1);
}
for (var i = 1; i < params.length; i++) {
var a = params[i];
if (a[0] !== '"' && a[0] !== "'") {
if (+a == a) { // jshint ignore:line
params[i] = +a;
}
}
}
alasql.promise(sql, params)
.then(function (res) {
if (!alasql.options.stdout) {
console.log(formatOutput(res));
}
process.exit(0);
}).catch(function (err) {
let errorJsonObj = JSON.parse(JSON.stringify(err, Object.getOwnPropertyNames(err)));
console.error(formatOutput({
error: errorJsonObj
}));
process.exit(1);
});
} | [
"function",
"execute",
"(",
"sql",
",",
"params",
")",
"{",
"if",
"(",
"0",
"===",
"sql",
".",
"trim",
"(",
")",
".",
"length",
")",
"{",
"console",
".",
"error",
"(",
"\"\\nNo SQL to process\\n\"",
")",
";",
"yargs",
".",
"showHelp",
"(",
")",
";",
"process",
".",
"exit",
"(",
"1",
")",
";",
"}",
"for",
"(",
"var",
"i",
"=",
"1",
";",
"i",
"<",
"params",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"a",
"=",
"params",
"[",
"i",
"]",
";",
"if",
"(",
"a",
"[",
"0",
"]",
"!==",
"'\"'",
"&&",
"a",
"[",
"0",
"]",
"!==",
"\"'\"",
")",
"{",
"if",
"(",
"+",
"a",
"==",
"a",
")",
"{",
"// jshint ignore:line",
"params",
"[",
"i",
"]",
"=",
"+",
"a",
";",
"}",
"}",
"}",
"alasql",
".",
"promise",
"(",
"sql",
",",
"params",
")",
".",
"then",
"(",
"function",
"(",
"res",
")",
"{",
"if",
"(",
"!",
"alasql",
".",
"options",
".",
"stdout",
")",
"{",
"console",
".",
"log",
"(",
"formatOutput",
"(",
"res",
")",
")",
";",
"}",
"process",
".",
"exit",
"(",
"0",
")",
";",
"}",
")",
".",
"catch",
"(",
"function",
"(",
"err",
")",
"{",
"let",
"errorJsonObj",
"=",
"JSON",
".",
"parse",
"(",
"JSON",
".",
"stringify",
"(",
"err",
",",
"Object",
".",
"getOwnPropertyNames",
"(",
"err",
")",
")",
")",
";",
"console",
".",
"error",
"(",
"formatOutput",
"(",
"{",
"error",
":",
"errorJsonObj",
"}",
")",
")",
";",
"process",
".",
"exit",
"(",
"1",
")",
";",
"}",
")",
";",
"}"
] | Execute SQL query
@sql {String} SQL query
@param {String} Parameters
@returns {null} Result will be printet to console.log | [
"Execute",
"SQL",
"query"
] | ac380c9869aec93f2ae41621225e22547d1d221b | https://github.com/agershun/alasql/blob/ac380c9869aec93f2ae41621225e22547d1d221b/bin/alasql-cli.js#L92-L122 |
5,363 | agershun/alasql | bin/alasql-cli.js | isDirectory | function isDirectory(filePath) {
var isDir = false;
try {
var absolutePath = path.resolve(filePath);
isDir = fs.lstatSync(absolutePath).isDirectory();
} catch (e) {
isDir = e.code === 'ENOENT';
}
return isDir;
} | javascript | function isDirectory(filePath) {
var isDir = false;
try {
var absolutePath = path.resolve(filePath);
isDir = fs.lstatSync(absolutePath).isDirectory();
} catch (e) {
isDir = e.code === 'ENOENT';
}
return isDir;
} | [
"function",
"isDirectory",
"(",
"filePath",
")",
"{",
"var",
"isDir",
"=",
"false",
";",
"try",
"{",
"var",
"absolutePath",
"=",
"path",
".",
"resolve",
"(",
"filePath",
")",
";",
"isDir",
"=",
"fs",
".",
"lstatSync",
"(",
"absolutePath",
")",
".",
"isDirectory",
"(",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"isDir",
"=",
"e",
".",
"code",
"===",
"'ENOENT'",
";",
"}",
"return",
"isDir",
";",
"}"
] | Is this padh a Directory
@param {String} filePath
@returns {Boolean} | [
"Is",
"this",
"padh",
"a",
"Directory"
] | ac380c9869aec93f2ae41621225e22547d1d221b | https://github.com/agershun/alasql/blob/ac380c9869aec93f2ae41621225e22547d1d221b/bin/alasql-cli.js#L130-L139 |
5,364 | agershun/alasql | src/839zip.js | pack | function pack(items) {
var data = arguments,
idx = 0,
buffer,
bufferSize = 0;
// Calculate buffer size
items = items.split('');
items.forEach(function(type) {
if (type == 'v') {
bufferSize += 2;
} else if (type == 'V' || type == 'l') {
bufferSize += 4;
}
});
// Fill buffer
buffer = new Buffer(bufferSize);
items.forEach(function(type, index) {
if (type == 'v') {
buffer.writeUInt16LE(data[index + 1], idx);
idx += 2;
} else if (type == 'V') {
buffer.writeUInt32LE(data[index + 1], idx);
idx += 4;
} else if (type == 'l') {
buffer.writeInt32LE(data[index + 1], idx);
idx += 4;
}
});
return buffer;
} | javascript | function pack(items) {
var data = arguments,
idx = 0,
buffer,
bufferSize = 0;
// Calculate buffer size
items = items.split('');
items.forEach(function(type) {
if (type == 'v') {
bufferSize += 2;
} else if (type == 'V' || type == 'l') {
bufferSize += 4;
}
});
// Fill buffer
buffer = new Buffer(bufferSize);
items.forEach(function(type, index) {
if (type == 'v') {
buffer.writeUInt16LE(data[index + 1], idx);
idx += 2;
} else if (type == 'V') {
buffer.writeUInt32LE(data[index + 1], idx);
idx += 4;
} else if (type == 'l') {
buffer.writeInt32LE(data[index + 1], idx);
idx += 4;
}
});
return buffer;
} | [
"function",
"pack",
"(",
"items",
")",
"{",
"var",
"data",
"=",
"arguments",
",",
"idx",
"=",
"0",
",",
"buffer",
",",
"bufferSize",
"=",
"0",
";",
"// Calculate buffer size",
"items",
"=",
"items",
".",
"split",
"(",
"''",
")",
";",
"items",
".",
"forEach",
"(",
"function",
"(",
"type",
")",
"{",
"if",
"(",
"type",
"==",
"'v'",
")",
"{",
"bufferSize",
"+=",
"2",
";",
"}",
"else",
"if",
"(",
"type",
"==",
"'V'",
"||",
"type",
"==",
"'l'",
")",
"{",
"bufferSize",
"+=",
"4",
";",
"}",
"}",
")",
";",
"// Fill buffer",
"buffer",
"=",
"new",
"Buffer",
"(",
"bufferSize",
")",
";",
"items",
".",
"forEach",
"(",
"function",
"(",
"type",
",",
"index",
")",
"{",
"if",
"(",
"type",
"==",
"'v'",
")",
"{",
"buffer",
".",
"writeUInt16LE",
"(",
"data",
"[",
"index",
"+",
"1",
"]",
",",
"idx",
")",
";",
"idx",
"+=",
"2",
";",
"}",
"else",
"if",
"(",
"type",
"==",
"'V'",
")",
"{",
"buffer",
".",
"writeUInt32LE",
"(",
"data",
"[",
"index",
"+",
"1",
"]",
",",
"idx",
")",
";",
"idx",
"+=",
"4",
";",
"}",
"else",
"if",
"(",
"type",
"==",
"'l'",
")",
"{",
"buffer",
".",
"writeInt32LE",
"(",
"data",
"[",
"index",
"+",
"1",
"]",
",",
"idx",
")",
";",
"idx",
"+=",
"4",
";",
"}",
"}",
")",
";",
"return",
"buffer",
";",
"}"
] | Pack data in the buffer
@function
@param {array} items
@return {string} | [
"Pack",
"data",
"in",
"the",
"buffer"
] | ac380c9869aec93f2ae41621225e22547d1d221b | https://github.com/agershun/alasql/blob/ac380c9869aec93f2ae41621225e22547d1d221b/src/839zip.js#L290-L322 |
5,365 | agershun/alasql | src/843xml.js | xmlparse | function xmlparse(xml) {
xml = xml.trim();
// strip comments
xml = xml.replace(/<!--[\s\S]*?-->/g, '');
return document();
/**
* XML document.
*/
function document() {
return {
declaration: declaration(),
root: tag(),
};
}
/**
* Declaration.
*/
function declaration() {
var m = match(/^<\?xml\s*/);
if (!m) return;
// tag
var node = {
attributes: {},
};
// attributes
while (!(eos() || is('?>'))) {
var attr = attribute();
if (!attr) return node;
node.attributes[attr.name] = attr.value;
}
match(/\?>\s*/);
return node;
}
/**
* Tag.
*/
function tag() {
var m = match(/^<([\w-:.]+)\s*/);
if (!m) return;
// name
var node = {
name: m[1],
attributes: {},
children: [],
};
// attributes
while (!(eos() || is('>') || is('?>') || is('/>'))) {
var attr = attribute();
if (!attr) return node;
node.attributes[attr.name] = attr.value;
}
// self closing tag
if (match(/^\s*\/>\s*/)) {
return node;
}
match(/\??>\s*/);
// content
node.content = content();
// children
var child;
while ((child = tag())) {
node.children.push(child);
}
// closing
match(/^<\/[\w-:.]+>\s*/);
return node;
}
/**
* Text content.
*/
function content() {
var m = match(/^([^<]*)/);
if (m) return m[1];
return '';
}
/**
* Attribute.
*/
function attribute() {
var m = match(/([\w:-]+)\s*=\s*("[^"]*"|'[^']*'|\w+)\s*/);
if (!m) return;
return {name: m[1], value: strip(m[2])};
}
/**
* Strip quotes from `val`.
*/
function strip(val) {
return val.replace(/^['"]|['"]$/g, '');
}
/**
* Match `re` and advance the string.
*/
function match(re) {
var m = xml.match(re);
if (!m) return;
xml = xml.slice(m[0].length);
return m;
}
/**
* End-of-source.
*/
function eos() {
return 0 == xml.length;
}
/**
* Check for `prefix`.
*/
function is(prefix) {
return 0 == xml.indexOf(prefix);
}
} | javascript | function xmlparse(xml) {
xml = xml.trim();
// strip comments
xml = xml.replace(/<!--[\s\S]*?-->/g, '');
return document();
/**
* XML document.
*/
function document() {
return {
declaration: declaration(),
root: tag(),
};
}
/**
* Declaration.
*/
function declaration() {
var m = match(/^<\?xml\s*/);
if (!m) return;
// tag
var node = {
attributes: {},
};
// attributes
while (!(eos() || is('?>'))) {
var attr = attribute();
if (!attr) return node;
node.attributes[attr.name] = attr.value;
}
match(/\?>\s*/);
return node;
}
/**
* Tag.
*/
function tag() {
var m = match(/^<([\w-:.]+)\s*/);
if (!m) return;
// name
var node = {
name: m[1],
attributes: {},
children: [],
};
// attributes
while (!(eos() || is('>') || is('?>') || is('/>'))) {
var attr = attribute();
if (!attr) return node;
node.attributes[attr.name] = attr.value;
}
// self closing tag
if (match(/^\s*\/>\s*/)) {
return node;
}
match(/\??>\s*/);
// content
node.content = content();
// children
var child;
while ((child = tag())) {
node.children.push(child);
}
// closing
match(/^<\/[\w-:.]+>\s*/);
return node;
}
/**
* Text content.
*/
function content() {
var m = match(/^([^<]*)/);
if (m) return m[1];
return '';
}
/**
* Attribute.
*/
function attribute() {
var m = match(/([\w:-]+)\s*=\s*("[^"]*"|'[^']*'|\w+)\s*/);
if (!m) return;
return {name: m[1], value: strip(m[2])};
}
/**
* Strip quotes from `val`.
*/
function strip(val) {
return val.replace(/^['"]|['"]$/g, '');
}
/**
* Match `re` and advance the string.
*/
function match(re) {
var m = xml.match(re);
if (!m) return;
xml = xml.slice(m[0].length);
return m;
}
/**
* End-of-source.
*/
function eos() {
return 0 == xml.length;
}
/**
* Check for `prefix`.
*/
function is(prefix) {
return 0 == xml.indexOf(prefix);
}
} | [
"function",
"xmlparse",
"(",
"xml",
")",
"{",
"xml",
"=",
"xml",
".",
"trim",
"(",
")",
";",
"// strip comments",
"xml",
"=",
"xml",
".",
"replace",
"(",
"/",
"<!--[\\s\\S]*?-->",
"/",
"g",
",",
"''",
")",
";",
"return",
"document",
"(",
")",
";",
"/**\n\t * XML document.\n\t */",
"function",
"document",
"(",
")",
"{",
"return",
"{",
"declaration",
":",
"declaration",
"(",
")",
",",
"root",
":",
"tag",
"(",
")",
",",
"}",
";",
"}",
"/**\n\t * Declaration.\n\t */",
"function",
"declaration",
"(",
")",
"{",
"var",
"m",
"=",
"match",
"(",
"/",
"^<\\?xml\\s*",
"/",
")",
";",
"if",
"(",
"!",
"m",
")",
"return",
";",
"// tag",
"var",
"node",
"=",
"{",
"attributes",
":",
"{",
"}",
",",
"}",
";",
"// attributes",
"while",
"(",
"!",
"(",
"eos",
"(",
")",
"||",
"is",
"(",
"'?>'",
")",
")",
")",
"{",
"var",
"attr",
"=",
"attribute",
"(",
")",
";",
"if",
"(",
"!",
"attr",
")",
"return",
"node",
";",
"node",
".",
"attributes",
"[",
"attr",
".",
"name",
"]",
"=",
"attr",
".",
"value",
";",
"}",
"match",
"(",
"/",
"\\?>\\s*",
"/",
")",
";",
"return",
"node",
";",
"}",
"/**\n\t * Tag.\n\t */",
"function",
"tag",
"(",
")",
"{",
"var",
"m",
"=",
"match",
"(",
"/",
"^<([\\w-:.]+)\\s*",
"/",
")",
";",
"if",
"(",
"!",
"m",
")",
"return",
";",
"// name",
"var",
"node",
"=",
"{",
"name",
":",
"m",
"[",
"1",
"]",
",",
"attributes",
":",
"{",
"}",
",",
"children",
":",
"[",
"]",
",",
"}",
";",
"// attributes",
"while",
"(",
"!",
"(",
"eos",
"(",
")",
"||",
"is",
"(",
"'>'",
")",
"||",
"is",
"(",
"'?>'",
")",
"||",
"is",
"(",
"'/>'",
")",
")",
")",
"{",
"var",
"attr",
"=",
"attribute",
"(",
")",
";",
"if",
"(",
"!",
"attr",
")",
"return",
"node",
";",
"node",
".",
"attributes",
"[",
"attr",
".",
"name",
"]",
"=",
"attr",
".",
"value",
";",
"}",
"// self closing tag",
"if",
"(",
"match",
"(",
"/",
"^\\s*\\/>\\s*",
"/",
")",
")",
"{",
"return",
"node",
";",
"}",
"match",
"(",
"/",
"\\??>\\s*",
"/",
")",
";",
"// content",
"node",
".",
"content",
"=",
"content",
"(",
")",
";",
"// children",
"var",
"child",
";",
"while",
"(",
"(",
"child",
"=",
"tag",
"(",
")",
")",
")",
"{",
"node",
".",
"children",
".",
"push",
"(",
"child",
")",
";",
"}",
"// closing",
"match",
"(",
"/",
"^<\\/[\\w-:.]+>\\s*",
"/",
")",
";",
"return",
"node",
";",
"}",
"/**\n\t * Text content.\n\t */",
"function",
"content",
"(",
")",
"{",
"var",
"m",
"=",
"match",
"(",
"/",
"^([^<]*)",
"/",
")",
";",
"if",
"(",
"m",
")",
"return",
"m",
"[",
"1",
"]",
";",
"return",
"''",
";",
"}",
"/**\n\t * Attribute.\n\t */",
"function",
"attribute",
"(",
")",
"{",
"var",
"m",
"=",
"match",
"(",
"/",
"([\\w:-]+)\\s*=\\s*(\"[^\"]*\"|'[^']*'|\\w+)\\s*",
"/",
")",
";",
"if",
"(",
"!",
"m",
")",
"return",
";",
"return",
"{",
"name",
":",
"m",
"[",
"1",
"]",
",",
"value",
":",
"strip",
"(",
"m",
"[",
"2",
"]",
")",
"}",
";",
"}",
"/**\n\t * Strip quotes from `val`.\n\t */",
"function",
"strip",
"(",
"val",
")",
"{",
"return",
"val",
".",
"replace",
"(",
"/",
"^['\"]|['\"]$",
"/",
"g",
",",
"''",
")",
";",
"}",
"/**\n\t * Match `re` and advance the string.\n\t */",
"function",
"match",
"(",
"re",
")",
"{",
"var",
"m",
"=",
"xml",
".",
"match",
"(",
"re",
")",
";",
"if",
"(",
"!",
"m",
")",
"return",
";",
"xml",
"=",
"xml",
".",
"slice",
"(",
"m",
"[",
"0",
"]",
".",
"length",
")",
";",
"return",
"m",
";",
"}",
"/**\n\t * End-of-source.\n\t */",
"function",
"eos",
"(",
")",
"{",
"return",
"0",
"==",
"xml",
".",
"length",
";",
"}",
"/**\n\t * Check for `prefix`.\n\t */",
"function",
"is",
"(",
"prefix",
")",
"{",
"return",
"0",
"==",
"xml",
".",
"indexOf",
"(",
"prefix",
")",
";",
"}",
"}"
] | Parse the given string of `xml`.
@param {String} xml
@return {Object}
@api public | [
"Parse",
"the",
"given",
"string",
"of",
"xml",
"."
] | ac380c9869aec93f2ae41621225e22547d1d221b | https://github.com/agershun/alasql/blob/ac380c9869aec93f2ae41621225e22547d1d221b/src/843xml.js#L24-L166 |
5,366 | agershun/alasql | src/843xml.js | match | function match(re) {
var m = xml.match(re);
if (!m) return;
xml = xml.slice(m[0].length);
return m;
} | javascript | function match(re) {
var m = xml.match(re);
if (!m) return;
xml = xml.slice(m[0].length);
return m;
} | [
"function",
"match",
"(",
"re",
")",
"{",
"var",
"m",
"=",
"xml",
".",
"match",
"(",
"re",
")",
";",
"if",
"(",
"!",
"m",
")",
"return",
";",
"xml",
"=",
"xml",
".",
"slice",
"(",
"m",
"[",
"0",
"]",
".",
"length",
")",
";",
"return",
"m",
";",
"}"
] | Match `re` and advance the string. | [
"Match",
"re",
"and",
"advance",
"the",
"string",
"."
] | ac380c9869aec93f2ae41621225e22547d1d221b | https://github.com/agershun/alasql/blob/ac380c9869aec93f2ae41621225e22547d1d221b/src/843xml.js#L144-L149 |
5,367 | agershun/alasql | lib/xmldoc/xmldoc.js | extend | function extend(destination, source) {
for (var prop in source)
if (source.hasOwnProperty(prop))
destination[prop] = source[prop];
} | javascript | function extend(destination, source) {
for (var prop in source)
if (source.hasOwnProperty(prop))
destination[prop] = source[prop];
} | [
"function",
"extend",
"(",
"destination",
",",
"source",
")",
"{",
"for",
"(",
"var",
"prop",
"in",
"source",
")",
"if",
"(",
"source",
".",
"hasOwnProperty",
"(",
"prop",
")",
")",
"destination",
"[",
"prop",
"]",
"=",
"source",
"[",
"prop",
"]",
";",
"}"
] | a relatively standard extend method | [
"a",
"relatively",
"standard",
"extend",
"method"
] | ac380c9869aec93f2ae41621225e22547d1d221b | https://github.com/agershun/alasql/blob/ac380c9869aec93f2ae41621225e22547d1d221b/lib/xmldoc/xmldoc.js#L223-L227 |
5,368 | agershun/alasql | src/63createvertex.js | findVertex | function findVertex(name) {
var objects = alasql.databases[alasql.useid].objects;
for (var k in objects) {
if (objects[k].name === name) {
return objects[k];
}
}
return undefined;
} | javascript | function findVertex(name) {
var objects = alasql.databases[alasql.useid].objects;
for (var k in objects) {
if (objects[k].name === name) {
return objects[k];
}
}
return undefined;
} | [
"function",
"findVertex",
"(",
"name",
")",
"{",
"var",
"objects",
"=",
"alasql",
".",
"databases",
"[",
"alasql",
".",
"useid",
"]",
".",
"objects",
";",
"for",
"(",
"var",
"k",
"in",
"objects",
")",
"{",
"if",
"(",
"objects",
"[",
"k",
"]",
".",
"name",
"===",
"name",
")",
"{",
"return",
"objects",
"[",
"k",
"]",
";",
"}",
"}",
"return",
"undefined",
";",
"}"
] | Find vertex by name | [
"Find",
"vertex",
"by",
"name"
] | ac380c9869aec93f2ae41621225e22547d1d221b | https://github.com/agershun/alasql/blob/ac380c9869aec93f2ae41621225e22547d1d221b/src/63createvertex.js#L394-L402 |
5,369 | agershun/alasql | src/38query.js | queryfn | function queryfn(query, oldscope, cb, A, B) {
var aaa = query.sources.length;
var ms;
query.sourceslen = query.sources.length;
var slen = query.sourceslen;
query.query = query; // TODO Remove to prevent memory leaks
query.A = A;
query.B = B;
query.cb = cb;
query.oldscope = oldscope;
// Run all subqueries before main statement
if (query.queriesfn) {
query.sourceslen += query.queriesfn.length;
slen += query.queriesfn.length;
query.queriesdata = [];
// console.log(8);
query.queriesfn.forEach(function(q, idx) {
// if(query.explain) ms = Date.now();
//console.log(18,idx);
// var res = flatArray(q(query.params,null,queryfn2,(-idx-1),query));
// var res = flatArray(queryfn(q.query,null,queryfn2,(-idx-1),query));
// console.log(A,B);
// console.log(q);
q.query.params = query.params;
// query.queriesdata[idx] =
// if(false) {
// queryfn(q.query,query.oldscope,queryfn2,(-idx-1),query);
// } else {
queryfn2([], -idx - 1, query);
// }
// console.log(27,q);
// query.explaination.push({explid: query.explid++, description:'Query '+idx,ms:Date.now()-ms});
// query.queriesdata[idx] = res;
// return res;
});
// console.log(9,query.queriesdata.length);
// console.log(query.queriesdata[0]);
}
var scope;
if (!oldscope) scope = {};
else scope = cloneDeep(oldscope);
query.scope = scope;
// First - refresh data sources
var result;
query.sources.forEach(function(source, idx) {
// source.data = query.database.tables[source.tableid].data;
// console.log(666,idx);
source.query = query;
var rs = source.datafn(query, query.params, queryfn2, idx, alasql);
// console.log(333,rs);
if (typeof rs !== 'undefined') {
// TODO - this is a hack: check if result is array - check all cases and
// make it more logical
if ((query.intofn || query.intoallfn) && Array.isArray(rs)) rs = rs.length;
result = rs;
}
//
// Ugly hack to use in query.wherefn and source.srcwherefns functions
// constructions like this.queriesdata['test'].
// I can elimite it with source.srcwherefn.bind(this)()
// but it may be slow.
//
source.queriesdata = query.queriesdata;
});
if (query.sources.length == 0 || 0 === slen) result = queryfn3(query);
// console.log(82,aaa,slen,query.sourceslen, query.sources.length);
return result;
} | javascript | function queryfn(query, oldscope, cb, A, B) {
var aaa = query.sources.length;
var ms;
query.sourceslen = query.sources.length;
var slen = query.sourceslen;
query.query = query; // TODO Remove to prevent memory leaks
query.A = A;
query.B = B;
query.cb = cb;
query.oldscope = oldscope;
// Run all subqueries before main statement
if (query.queriesfn) {
query.sourceslen += query.queriesfn.length;
slen += query.queriesfn.length;
query.queriesdata = [];
// console.log(8);
query.queriesfn.forEach(function(q, idx) {
// if(query.explain) ms = Date.now();
//console.log(18,idx);
// var res = flatArray(q(query.params,null,queryfn2,(-idx-1),query));
// var res = flatArray(queryfn(q.query,null,queryfn2,(-idx-1),query));
// console.log(A,B);
// console.log(q);
q.query.params = query.params;
// query.queriesdata[idx] =
// if(false) {
// queryfn(q.query,query.oldscope,queryfn2,(-idx-1),query);
// } else {
queryfn2([], -idx - 1, query);
// }
// console.log(27,q);
// query.explaination.push({explid: query.explid++, description:'Query '+idx,ms:Date.now()-ms});
// query.queriesdata[idx] = res;
// return res;
});
// console.log(9,query.queriesdata.length);
// console.log(query.queriesdata[0]);
}
var scope;
if (!oldscope) scope = {};
else scope = cloneDeep(oldscope);
query.scope = scope;
// First - refresh data sources
var result;
query.sources.forEach(function(source, idx) {
// source.data = query.database.tables[source.tableid].data;
// console.log(666,idx);
source.query = query;
var rs = source.datafn(query, query.params, queryfn2, idx, alasql);
// console.log(333,rs);
if (typeof rs !== 'undefined') {
// TODO - this is a hack: check if result is array - check all cases and
// make it more logical
if ((query.intofn || query.intoallfn) && Array.isArray(rs)) rs = rs.length;
result = rs;
}
//
// Ugly hack to use in query.wherefn and source.srcwherefns functions
// constructions like this.queriesdata['test'].
// I can elimite it with source.srcwherefn.bind(this)()
// but it may be slow.
//
source.queriesdata = query.queriesdata;
});
if (query.sources.length == 0 || 0 === slen) result = queryfn3(query);
// console.log(82,aaa,slen,query.sourceslen, query.sources.length);
return result;
} | [
"function",
"queryfn",
"(",
"query",
",",
"oldscope",
",",
"cb",
",",
"A",
",",
"B",
")",
"{",
"var",
"aaa",
"=",
"query",
".",
"sources",
".",
"length",
";",
"var",
"ms",
";",
"query",
".",
"sourceslen",
"=",
"query",
".",
"sources",
".",
"length",
";",
"var",
"slen",
"=",
"query",
".",
"sourceslen",
";",
"query",
".",
"query",
"=",
"query",
";",
"// TODO Remove to prevent memory leaks\r",
"query",
".",
"A",
"=",
"A",
";",
"query",
".",
"B",
"=",
"B",
";",
"query",
".",
"cb",
"=",
"cb",
";",
"query",
".",
"oldscope",
"=",
"oldscope",
";",
"// Run all subqueries before main statement\r",
"if",
"(",
"query",
".",
"queriesfn",
")",
"{",
"query",
".",
"sourceslen",
"+=",
"query",
".",
"queriesfn",
".",
"length",
";",
"slen",
"+=",
"query",
".",
"queriesfn",
".",
"length",
";",
"query",
".",
"queriesdata",
"=",
"[",
"]",
";",
"//\t\tconsole.log(8);\r",
"query",
".",
"queriesfn",
".",
"forEach",
"(",
"function",
"(",
"q",
",",
"idx",
")",
"{",
"//\t\t\tif(query.explain) ms = Date.now();\r",
"//console.log(18,idx);\r",
"//\t\t\tvar res = flatArray(q(query.params,null,queryfn2,(-idx-1),query));\r",
"//\t\t\tvar res = flatArray(queryfn(q.query,null,queryfn2,(-idx-1),query));\r",
"//\t\t\tconsole.log(A,B);\r",
"// console.log(q);\r",
"q",
".",
"query",
".",
"params",
"=",
"query",
".",
"params",
";",
"//\t\t\tquery.queriesdata[idx] =\r",
"//\tif(false) {\r",
"//\t\t\tqueryfn(q.query,query.oldscope,queryfn2,(-idx-1),query);\r",
"//\t} else {\r",
"queryfn2",
"(",
"[",
"]",
",",
"-",
"idx",
"-",
"1",
",",
"query",
")",
";",
"//\t}\r",
"//\t\t\tconsole.log(27,q);\r",
"//\t\t\tquery.explaination.push({explid: query.explid++, description:'Query '+idx,ms:Date.now()-ms});\r",
"//\t\t\tquery.queriesdata[idx] = res;\r",
"//\t\t\treturn res;\r",
"}",
")",
";",
"//\t\tconsole.log(9,query.queriesdata.length);\r",
"//\t\tconsole.log(query.queriesdata[0]);\r",
"}",
"var",
"scope",
";",
"if",
"(",
"!",
"oldscope",
")",
"scope",
"=",
"{",
"}",
";",
"else",
"scope",
"=",
"cloneDeep",
"(",
"oldscope",
")",
";",
"query",
".",
"scope",
"=",
"scope",
";",
"// First - refresh data sources\r",
"var",
"result",
";",
"query",
".",
"sources",
".",
"forEach",
"(",
"function",
"(",
"source",
",",
"idx",
")",
"{",
"//\t\tsource.data = query.database.tables[source.tableid].data;\r",
"//\t\tconsole.log(666,idx);\r",
"source",
".",
"query",
"=",
"query",
";",
"var",
"rs",
"=",
"source",
".",
"datafn",
"(",
"query",
",",
"query",
".",
"params",
",",
"queryfn2",
",",
"idx",
",",
"alasql",
")",
";",
"//\t\tconsole.log(333,rs);\r",
"if",
"(",
"typeof",
"rs",
"!==",
"'undefined'",
")",
"{",
"// TODO - this is a hack: check if result is array - check all cases and\r",
"// make it more logical\r",
"if",
"(",
"(",
"query",
".",
"intofn",
"||",
"query",
".",
"intoallfn",
")",
"&&",
"Array",
".",
"isArray",
"(",
"rs",
")",
")",
"rs",
"=",
"rs",
".",
"length",
";",
"result",
"=",
"rs",
";",
"}",
"//\r",
"// Ugly hack to use in query.wherefn and source.srcwherefns functions\r",
"// constructions like this.queriesdata['test'].\r",
"// I can elimite it with source.srcwherefn.bind(this)()\r",
"// but it may be slow.\r",
"//\r",
"source",
".",
"queriesdata",
"=",
"query",
".",
"queriesdata",
";",
"}",
")",
";",
"if",
"(",
"query",
".",
"sources",
".",
"length",
"==",
"0",
"||",
"0",
"===",
"slen",
")",
"result",
"=",
"queryfn3",
"(",
"query",
")",
";",
"//\tconsole.log(82,aaa,slen,query.sourceslen, query.sources.length);\r",
"return",
"result",
";",
"}"
] | Main query procedure | [
"Main",
"query",
"procedure"
] | ac380c9869aec93f2ae41621225e22547d1d221b | https://github.com/agershun/alasql/blob/ac380c9869aec93f2ae41621225e22547d1d221b/src/38query.js#L2-L80 |
5,370 | hyperledger/indy-sdk | samples/nodejs/src/anoncredsRevocationScenario.js | createAndOpenWallet | async function createAndOpenWallet(actor) {
const walletConfig = {"id": actor + ".wallet"}
const walletCredentials = {"key": actor + ".wallet_key"}
await indy.createWallet(walletConfig, walletCredentials)
return await indy.openWallet(walletConfig, walletCredentials)
} | javascript | async function createAndOpenWallet(actor) {
const walletConfig = {"id": actor + ".wallet"}
const walletCredentials = {"key": actor + ".wallet_key"}
await indy.createWallet(walletConfig, walletCredentials)
return await indy.openWallet(walletConfig, walletCredentials)
} | [
"async",
"function",
"createAndOpenWallet",
"(",
"actor",
")",
"{",
"const",
"walletConfig",
"=",
"{",
"\"id\"",
":",
"actor",
"+",
"\".wallet\"",
"}",
"const",
"walletCredentials",
"=",
"{",
"\"key\"",
":",
"actor",
"+",
"\".wallet_key\"",
"}",
"await",
"indy",
".",
"createWallet",
"(",
"walletConfig",
",",
"walletCredentials",
")",
"return",
"await",
"indy",
".",
"openWallet",
"(",
"walletConfig",
",",
"walletCredentials",
")",
"}"
] | Functions for wallet | [
"Functions",
"for",
"wallet"
] | cb5dc804ca94850f35dfb429fa4e53b3fff21d67 | https://github.com/hyperledger/indy-sdk/blob/cb5dc804ca94850f35dfb429fa4e53b3fff21d67/samples/nodejs/src/anoncredsRevocationScenario.js#L45-L50 |
5,371 | hyperledger/indy-sdk | samples/nodejs/src/anoncredsRevocationScenario.js | createAndOpenPoolHandle | async function createAndOpenPoolHandle(actor) {
const poolName = actor + "-pool-sandbox"
const poolGenesisTxnPath = await util.getPoolGenesisTxnPath(poolName)
const poolConfig = {"genesis_txn": poolGenesisTxnPath}
await indy.createPoolLedgerConfig(poolName, poolConfig)
.catch(e => {
console.log("ERROR : ", e)
process.exit()
})
return await indy.openPoolLedger(poolName, poolConfig)
} | javascript | async function createAndOpenPoolHandle(actor) {
const poolName = actor + "-pool-sandbox"
const poolGenesisTxnPath = await util.getPoolGenesisTxnPath(poolName)
const poolConfig = {"genesis_txn": poolGenesisTxnPath}
await indy.createPoolLedgerConfig(poolName, poolConfig)
.catch(e => {
console.log("ERROR : ", e)
process.exit()
})
return await indy.openPoolLedger(poolName, poolConfig)
} | [
"async",
"function",
"createAndOpenPoolHandle",
"(",
"actor",
")",
"{",
"const",
"poolName",
"=",
"actor",
"+",
"\"-pool-sandbox\"",
"const",
"poolGenesisTxnPath",
"=",
"await",
"util",
".",
"getPoolGenesisTxnPath",
"(",
"poolName",
")",
"const",
"poolConfig",
"=",
"{",
"\"genesis_txn\"",
":",
"poolGenesisTxnPath",
"}",
"await",
"indy",
".",
"createPoolLedgerConfig",
"(",
"poolName",
",",
"poolConfig",
")",
".",
"catch",
"(",
"e",
"=>",
"{",
"console",
".",
"log",
"(",
"\"ERROR : \"",
",",
"e",
")",
"process",
".",
"exit",
"(",
")",
"}",
")",
"return",
"await",
"indy",
".",
"openPoolLedger",
"(",
"poolName",
",",
"poolConfig",
")",
"}"
] | Functions for pool handler | [
"Functions",
"for",
"pool",
"handler"
] | cb5dc804ca94850f35dfb429fa4e53b3fff21d67 | https://github.com/hyperledger/indy-sdk/blob/cb5dc804ca94850f35dfb429fa4e53b3fff21d67/samples/nodejs/src/anoncredsRevocationScenario.js#L61-L71 |
5,372 | hyperledger/indy-sdk | samples/nodejs/src/anoncredsRevocationScenario.js | postRevocRegDefRequestToLedger | async function postRevocRegDefRequestToLedger(poolHandle, wallet, did, revRegDef) {
const revocRegRequest = await indy.buildRevocRegDefRequest(did, revRegDef)
await ensureSignAndSubmitRequest(poolHandle, wallet, did, revocRegRequest)
} | javascript | async function postRevocRegDefRequestToLedger(poolHandle, wallet, did, revRegDef) {
const revocRegRequest = await indy.buildRevocRegDefRequest(did, revRegDef)
await ensureSignAndSubmitRequest(poolHandle, wallet, did, revocRegRequest)
} | [
"async",
"function",
"postRevocRegDefRequestToLedger",
"(",
"poolHandle",
",",
"wallet",
",",
"did",
",",
"revRegDef",
")",
"{",
"const",
"revocRegRequest",
"=",
"await",
"indy",
".",
"buildRevocRegDefRequest",
"(",
"did",
",",
"revRegDef",
")",
"await",
"ensureSignAndSubmitRequest",
"(",
"poolHandle",
",",
"wallet",
",",
"did",
",",
"revocRegRequest",
")",
"}"
] | Main "run" function | [
"Main",
"run",
"function"
] | cb5dc804ca94850f35dfb429fa4e53b3fff21d67 | https://github.com/hyperledger/indy-sdk/blob/cb5dc804ca94850f35dfb429fa4e53b3fff21d67/samples/nodejs/src/anoncredsRevocationScenario.js#L159-L162 |
5,373 | hyperledger/indy-sdk | wrappers/dotnet/docs/styles/docfx.js | renderLinks | function renderLinks() {
if ($("meta[property='docfx:newtab']").attr("content") === "true") {
$(document.links).filter(function () {
return this.hostname !== window.location.hostname;
}).attr('target', '_blank');
}
} | javascript | function renderLinks() {
if ($("meta[property='docfx:newtab']").attr("content") === "true") {
$(document.links).filter(function () {
return this.hostname !== window.location.hostname;
}).attr('target', '_blank');
}
} | [
"function",
"renderLinks",
"(",
")",
"{",
"if",
"(",
"$",
"(",
"\"meta[property='docfx:newtab']\"",
")",
".",
"attr",
"(",
"\"content\"",
")",
"===",
"\"true\"",
")",
"{",
"$",
"(",
"document",
".",
"links",
")",
".",
"filter",
"(",
"function",
"(",
")",
"{",
"return",
"this",
".",
"hostname",
"!==",
"window",
".",
"location",
".",
"hostname",
";",
"}",
")",
".",
"attr",
"(",
"'target'",
",",
"'_blank'",
")",
";",
"}",
"}"
] | Open links to different host in a new window. | [
"Open",
"links",
"to",
"different",
"host",
"in",
"a",
"new",
"window",
"."
] | cb5dc804ca94850f35dfb429fa4e53b3fff21d67 | https://github.com/hyperledger/indy-sdk/blob/cb5dc804ca94850f35dfb429fa4e53b3fff21d67/wrappers/dotnet/docs/styles/docfx.js#L68-L74 |
5,374 | hyperledger/indy-sdk | wrappers/dotnet/docs/styles/docfx.js | highlight | function highlight() {
$('pre code').each(function (i, block) {
hljs.highlightBlock(block);
});
$('pre code[highlight-lines]').each(function (i, block) {
if (block.innerHTML === "") return;
var lines = block.innerHTML.split('\n');
queryString = block.getAttribute('highlight-lines');
if (!queryString) return;
var ranges = queryString.split(',');
for (var j = 0, range; range = ranges[j++];) {
var found = range.match(/^(\d+)\-(\d+)?$/);
if (found) {
// consider region as `{startlinenumber}-{endlinenumber}`, in which {endlinenumber} is optional
var start = +found[1];
var end = +found[2];
if (isNaN(end) || end > lines.length) {
end = lines.length;
}
} else {
// consider region as a sigine line number
if (isNaN(range)) continue;
var start = +range;
var end = start;
}
if (start <= 0 || end <= 0 || start > end || start > lines.length) {
// skip current region if invalid
continue;
}
lines[start - 1] = '<span class="line-highlight">' + lines[start - 1];
lines[end - 1] = lines[end - 1] + '</span>';
}
block.innerHTML = lines.join('\n');
});
} | javascript | function highlight() {
$('pre code').each(function (i, block) {
hljs.highlightBlock(block);
});
$('pre code[highlight-lines]').each(function (i, block) {
if (block.innerHTML === "") return;
var lines = block.innerHTML.split('\n');
queryString = block.getAttribute('highlight-lines');
if (!queryString) return;
var ranges = queryString.split(',');
for (var j = 0, range; range = ranges[j++];) {
var found = range.match(/^(\d+)\-(\d+)?$/);
if (found) {
// consider region as `{startlinenumber}-{endlinenumber}`, in which {endlinenumber} is optional
var start = +found[1];
var end = +found[2];
if (isNaN(end) || end > lines.length) {
end = lines.length;
}
} else {
// consider region as a sigine line number
if (isNaN(range)) continue;
var start = +range;
var end = start;
}
if (start <= 0 || end <= 0 || start > end || start > lines.length) {
// skip current region if invalid
continue;
}
lines[start - 1] = '<span class="line-highlight">' + lines[start - 1];
lines[end - 1] = lines[end - 1] + '</span>';
}
block.innerHTML = lines.join('\n');
});
} | [
"function",
"highlight",
"(",
")",
"{",
"$",
"(",
"'pre code'",
")",
".",
"each",
"(",
"function",
"(",
"i",
",",
"block",
")",
"{",
"hljs",
".",
"highlightBlock",
"(",
"block",
")",
";",
"}",
")",
";",
"$",
"(",
"'pre code[highlight-lines]'",
")",
".",
"each",
"(",
"function",
"(",
"i",
",",
"block",
")",
"{",
"if",
"(",
"block",
".",
"innerHTML",
"===",
"\"\"",
")",
"return",
";",
"var",
"lines",
"=",
"block",
".",
"innerHTML",
".",
"split",
"(",
"'\\n'",
")",
";",
"queryString",
"=",
"block",
".",
"getAttribute",
"(",
"'highlight-lines'",
")",
";",
"if",
"(",
"!",
"queryString",
")",
"return",
";",
"var",
"ranges",
"=",
"queryString",
".",
"split",
"(",
"','",
")",
";",
"for",
"(",
"var",
"j",
"=",
"0",
",",
"range",
";",
"range",
"=",
"ranges",
"[",
"j",
"++",
"]",
";",
")",
"{",
"var",
"found",
"=",
"range",
".",
"match",
"(",
"/",
"^(\\d+)\\-(\\d+)?$",
"/",
")",
";",
"if",
"(",
"found",
")",
"{",
"// consider region as `{startlinenumber}-{endlinenumber}`, in which {endlinenumber} is optional",
"var",
"start",
"=",
"+",
"found",
"[",
"1",
"]",
";",
"var",
"end",
"=",
"+",
"found",
"[",
"2",
"]",
";",
"if",
"(",
"isNaN",
"(",
"end",
")",
"||",
"end",
">",
"lines",
".",
"length",
")",
"{",
"end",
"=",
"lines",
".",
"length",
";",
"}",
"}",
"else",
"{",
"// consider region as a sigine line number",
"if",
"(",
"isNaN",
"(",
"range",
")",
")",
"continue",
";",
"var",
"start",
"=",
"+",
"range",
";",
"var",
"end",
"=",
"start",
";",
"}",
"if",
"(",
"start",
"<=",
"0",
"||",
"end",
"<=",
"0",
"||",
"start",
">",
"end",
"||",
"start",
">",
"lines",
".",
"length",
")",
"{",
"// skip current region if invalid",
"continue",
";",
"}",
"lines",
"[",
"start",
"-",
"1",
"]",
"=",
"'<span class=\"line-highlight\">'",
"+",
"lines",
"[",
"start",
"-",
"1",
"]",
";",
"lines",
"[",
"end",
"-",
"1",
"]",
"=",
"lines",
"[",
"end",
"-",
"1",
"]",
"+",
"'</span>'",
";",
"}",
"block",
".",
"innerHTML",
"=",
"lines",
".",
"join",
"(",
"'\\n'",
")",
";",
"}",
")",
";",
"}"
] | Enable highlight.js | [
"Enable",
"highlight",
".",
"js"
] | cb5dc804ca94850f35dfb429fa4e53b3fff21d67 | https://github.com/hyperledger/indy-sdk/blob/cb5dc804ca94850f35dfb429fa4e53b3fff21d67/wrappers/dotnet/docs/styles/docfx.js#L77-L114 |
5,375 | hyperledger/indy-sdk | wrappers/dotnet/docs/styles/docfx.js | renderSearchBox | function renderSearchBox() {
autoCollapse();
$(window).on('resize', autoCollapse);
$(document).on('click', '.navbar-collapse.in', function (e) {
if ($(e.target).is('a')) {
$(this).collapse('hide');
}
});
function autoCollapse() {
var navbar = $('#autocollapse');
if (navbar.height() === null) {
setTimeout(autoCollapse, 300);
}
navbar.removeClass(collapsed);
if (navbar.height() > 60) {
navbar.addClass(collapsed);
}
}
} | javascript | function renderSearchBox() {
autoCollapse();
$(window).on('resize', autoCollapse);
$(document).on('click', '.navbar-collapse.in', function (e) {
if ($(e.target).is('a')) {
$(this).collapse('hide');
}
});
function autoCollapse() {
var navbar = $('#autocollapse');
if (navbar.height() === null) {
setTimeout(autoCollapse, 300);
}
navbar.removeClass(collapsed);
if (navbar.height() > 60) {
navbar.addClass(collapsed);
}
}
} | [
"function",
"renderSearchBox",
"(",
")",
"{",
"autoCollapse",
"(",
")",
";",
"$",
"(",
"window",
")",
".",
"on",
"(",
"'resize'",
",",
"autoCollapse",
")",
";",
"$",
"(",
"document",
")",
".",
"on",
"(",
"'click'",
",",
"'.navbar-collapse.in'",
",",
"function",
"(",
"e",
")",
"{",
"if",
"(",
"$",
"(",
"e",
".",
"target",
")",
".",
"is",
"(",
"'a'",
")",
")",
"{",
"$",
"(",
"this",
")",
".",
"collapse",
"(",
"'hide'",
")",
";",
"}",
"}",
")",
";",
"function",
"autoCollapse",
"(",
")",
"{",
"var",
"navbar",
"=",
"$",
"(",
"'#autocollapse'",
")",
";",
"if",
"(",
"navbar",
".",
"height",
"(",
")",
"===",
"null",
")",
"{",
"setTimeout",
"(",
"autoCollapse",
",",
"300",
")",
";",
"}",
"navbar",
".",
"removeClass",
"(",
"collapsed",
")",
";",
"if",
"(",
"navbar",
".",
"height",
"(",
")",
">",
"60",
")",
"{",
"navbar",
".",
"addClass",
"(",
"collapsed",
")",
";",
"}",
"}",
"}"
] | Adjust the position of search box in navbar | [
"Adjust",
"the",
"position",
"of",
"search",
"box",
"in",
"navbar"
] | cb5dc804ca94850f35dfb429fa4e53b3fff21d67 | https://github.com/hyperledger/indy-sdk/blob/cb5dc804ca94850f35dfb429fa4e53b3fff21d67/wrappers/dotnet/docs/styles/docfx.js#L139-L158 |
5,376 | hyperledger/indy-sdk | wrappers/dotnet/docs/styles/docfx.js | highlightKeywords | function highlightKeywords() {
var q = url('?q');
if (q !== null) {
var keywords = q.split("%20");
keywords.forEach(function (keyword) {
if (keyword !== "") {
$('.data-searchable *').mark(keyword);
$('article *').mark(keyword);
}
});
}
} | javascript | function highlightKeywords() {
var q = url('?q');
if (q !== null) {
var keywords = q.split("%20");
keywords.forEach(function (keyword) {
if (keyword !== "") {
$('.data-searchable *').mark(keyword);
$('article *').mark(keyword);
}
});
}
} | [
"function",
"highlightKeywords",
"(",
")",
"{",
"var",
"q",
"=",
"url",
"(",
"'?q'",
")",
";",
"if",
"(",
"q",
"!==",
"null",
")",
"{",
"var",
"keywords",
"=",
"q",
".",
"split",
"(",
"\"%20\"",
")",
";",
"keywords",
".",
"forEach",
"(",
"function",
"(",
"keyword",
")",
"{",
"if",
"(",
"keyword",
"!==",
"\"\"",
")",
"{",
"$",
"(",
"'.data-searchable *'",
")",
".",
"mark",
"(",
"keyword",
")",
";",
"$",
"(",
"'article *'",
")",
".",
"mark",
"(",
"keyword",
")",
";",
"}",
"}",
")",
";",
"}",
"}"
] | Highlight the searching keywords | [
"Highlight",
"the",
"searching",
"keywords"
] | cb5dc804ca94850f35dfb429fa4e53b3fff21d67 | https://github.com/hyperledger/indy-sdk/blob/cb5dc804ca94850f35dfb429fa4e53b3fff21d67/wrappers/dotnet/docs/styles/docfx.js#L224-L235 |
5,377 | hyperledger/indy-sdk | wrappers/dotnet/docs/styles/lunr.js | function (config) {
var builder = new lunr.Builder
builder.pipeline.add(
lunr.trimmer,
lunr.stopWordFilter,
lunr.stemmer
)
builder.searchPipeline.add(
lunr.stemmer
)
config.call(builder, builder)
return builder.build()
} | javascript | function (config) {
var builder = new lunr.Builder
builder.pipeline.add(
lunr.trimmer,
lunr.stopWordFilter,
lunr.stemmer
)
builder.searchPipeline.add(
lunr.stemmer
)
config.call(builder, builder)
return builder.build()
} | [
"function",
"(",
"config",
")",
"{",
"var",
"builder",
"=",
"new",
"lunr",
".",
"Builder",
"builder",
".",
"pipeline",
".",
"add",
"(",
"lunr",
".",
"trimmer",
",",
"lunr",
".",
"stopWordFilter",
",",
"lunr",
".",
"stemmer",
")",
"builder",
".",
"searchPipeline",
".",
"add",
"(",
"lunr",
".",
"stemmer",
")",
"config",
".",
"call",
"(",
"builder",
",",
"builder",
")",
"return",
"builder",
".",
"build",
"(",
")",
"}"
] | A convenience function for configuring and constructing
a new lunr Index.
A lunr.Builder instance is created and the pipeline setup
with a trimmer, stop word filter and stemmer.
This builder object is yielded to the configuration function
that is passed as a parameter, allowing the list of fields
and other builder parameters to be customised.
All documents _must_ be added within the passed config function.
@example
var idx = lunr(function () {
this.field('title')
this.field('body')
this.ref('id')
documents.forEach(function (doc) {
this.add(doc)
}, this)
})
@see {@link lunr.Builder}
@see {@link lunr.Pipeline}
@see {@link lunr.trimmer}
@see {@link lunr.stopWordFilter}
@see {@link lunr.stemmer}
@namespace {function} lunr | [
"A",
"convenience",
"function",
"for",
"configuring",
"and",
"constructing",
"a",
"new",
"lunr",
"Index",
"."
] | cb5dc804ca94850f35dfb429fa4e53b3fff21d67 | https://github.com/hyperledger/indy-sdk/blob/cb5dc804ca94850f35dfb429fa4e53b3fff21d67/wrappers/dotnet/docs/styles/lunr.js#L40-L55 |
|
5,378 | lihongxun945/jquery-weui | src/js/picker.js | isPopover | function isPopover() {
var toPopover = false;
if (!p.params.convertToPopover && !p.params.onlyInPopover) return toPopover;
if (!p.inline && p.params.input) {
if (p.params.onlyInPopover) toPopover = true;
else {
if ($.device.ios) {
toPopover = $.device.ipad ? true : false;
}
else {
if ($(window).width() >= 768) toPopover = true;
}
}
}
return toPopover;
} | javascript | function isPopover() {
var toPopover = false;
if (!p.params.convertToPopover && !p.params.onlyInPopover) return toPopover;
if (!p.inline && p.params.input) {
if (p.params.onlyInPopover) toPopover = true;
else {
if ($.device.ios) {
toPopover = $.device.ipad ? true : false;
}
else {
if ($(window).width() >= 768) toPopover = true;
}
}
}
return toPopover;
} | [
"function",
"isPopover",
"(",
")",
"{",
"var",
"toPopover",
"=",
"false",
";",
"if",
"(",
"!",
"p",
".",
"params",
".",
"convertToPopover",
"&&",
"!",
"p",
".",
"params",
".",
"onlyInPopover",
")",
"return",
"toPopover",
";",
"if",
"(",
"!",
"p",
".",
"inline",
"&&",
"p",
".",
"params",
".",
"input",
")",
"{",
"if",
"(",
"p",
".",
"params",
".",
"onlyInPopover",
")",
"toPopover",
"=",
"true",
";",
"else",
"{",
"if",
"(",
"$",
".",
"device",
".",
"ios",
")",
"{",
"toPopover",
"=",
"$",
".",
"device",
".",
"ipad",
"?",
"true",
":",
"false",
";",
"}",
"else",
"{",
"if",
"(",
"$",
"(",
"window",
")",
".",
"width",
"(",
")",
">=",
"768",
")",
"toPopover",
"=",
"true",
";",
"}",
"}",
"}",
"return",
"toPopover",
";",
"}"
] | Should be converted to popover | [
"Should",
"be",
"converted",
"to",
"popover"
] | e1efdff32318e8bf84e06778094a1705d5d99ddb | https://github.com/lihongxun945/jquery-weui/blob/e1efdff32318e8bf84e06778094a1705d5d99ddb/src/js/picker.js#L47-L62 |
5,379 | lihongxun945/jquery-weui | src/js/hammer.js | each | function each(obj, iterator, context) {
var i;
if (!obj) {
return;
}
if (obj.forEach) {
obj.forEach(iterator, context);
} else if (obj.length !== undefined) {
i = 0;
while (i < obj.length) {
iterator.call(context, obj[i], i, obj);
i++;
}
} else {
for (i in obj) {
obj.hasOwnProperty(i) && iterator.call(context, obj[i], i, obj);
}
}
} | javascript | function each(obj, iterator, context) {
var i;
if (!obj) {
return;
}
if (obj.forEach) {
obj.forEach(iterator, context);
} else if (obj.length !== undefined) {
i = 0;
while (i < obj.length) {
iterator.call(context, obj[i], i, obj);
i++;
}
} else {
for (i in obj) {
obj.hasOwnProperty(i) && iterator.call(context, obj[i], i, obj);
}
}
} | [
"function",
"each",
"(",
"obj",
",",
"iterator",
",",
"context",
")",
"{",
"var",
"i",
";",
"if",
"(",
"!",
"obj",
")",
"{",
"return",
";",
"}",
"if",
"(",
"obj",
".",
"forEach",
")",
"{",
"obj",
".",
"forEach",
"(",
"iterator",
",",
"context",
")",
";",
"}",
"else",
"if",
"(",
"obj",
".",
"length",
"!==",
"undefined",
")",
"{",
"i",
"=",
"0",
";",
"while",
"(",
"i",
"<",
"obj",
".",
"length",
")",
"{",
"iterator",
".",
"call",
"(",
"context",
",",
"obj",
"[",
"i",
"]",
",",
"i",
",",
"obj",
")",
";",
"i",
"++",
";",
"}",
"}",
"else",
"{",
"for",
"(",
"i",
"in",
"obj",
")",
"{",
"obj",
".",
"hasOwnProperty",
"(",
"i",
")",
"&&",
"iterator",
".",
"call",
"(",
"context",
",",
"obj",
"[",
"i",
"]",
",",
"i",
",",
"obj",
")",
";",
"}",
"}",
"}"
] | walk objects and arrays
@param {Object} obj
@param {Function} iterator
@param {Object} context | [
"walk",
"objects",
"and",
"arrays"
] | e1efdff32318e8bf84e06778094a1705d5d99ddb | https://github.com/lihongxun945/jquery-weui/blob/e1efdff32318e8bf84e06778094a1705d5d99ddb/src/js/hammer.js#L52-L72 |
5,380 | lihongxun945/jquery-weui | src/js/hammer.js | deprecate | function deprecate(method, name, message) {
var deprecationMessage = 'DEPRECATED METHOD: ' + name + '\n' + message + ' AT \n';
return function() {
var e = new Error('get-stack-trace');
var stack = e && e.stack ? e.stack.replace(/^[^\(]+?[\n$]/gm, '')
.replace(/^\s+at\s+/gm, '')
.replace(/^Object.<anonymous>\s*\(/gm, '{anonymous}()@') : 'Unknown Stack Trace';
var log = window.console && (window.console.warn || window.console.log);
if (log) {
log.call(window.console, deprecationMessage, stack);
}
return method.apply(this, arguments);
};
} | javascript | function deprecate(method, name, message) {
var deprecationMessage = 'DEPRECATED METHOD: ' + name + '\n' + message + ' AT \n';
return function() {
var e = new Error('get-stack-trace');
var stack = e && e.stack ? e.stack.replace(/^[^\(]+?[\n$]/gm, '')
.replace(/^\s+at\s+/gm, '')
.replace(/^Object.<anonymous>\s*\(/gm, '{anonymous}()@') : 'Unknown Stack Trace';
var log = window.console && (window.console.warn || window.console.log);
if (log) {
log.call(window.console, deprecationMessage, stack);
}
return method.apply(this, arguments);
};
} | [
"function",
"deprecate",
"(",
"method",
",",
"name",
",",
"message",
")",
"{",
"var",
"deprecationMessage",
"=",
"'DEPRECATED METHOD: '",
"+",
"name",
"+",
"'\\n'",
"+",
"message",
"+",
"' AT \\n'",
";",
"return",
"function",
"(",
")",
"{",
"var",
"e",
"=",
"new",
"Error",
"(",
"'get-stack-trace'",
")",
";",
"var",
"stack",
"=",
"e",
"&&",
"e",
".",
"stack",
"?",
"e",
".",
"stack",
".",
"replace",
"(",
"/",
"^[^\\(]+?[\\n$]",
"/",
"gm",
",",
"''",
")",
".",
"replace",
"(",
"/",
"^\\s+at\\s+",
"/",
"gm",
",",
"''",
")",
".",
"replace",
"(",
"/",
"^Object.<anonymous>\\s*\\(",
"/",
"gm",
",",
"'{anonymous}()@'",
")",
":",
"'Unknown Stack Trace'",
";",
"var",
"log",
"=",
"window",
".",
"console",
"&&",
"(",
"window",
".",
"console",
".",
"warn",
"||",
"window",
".",
"console",
".",
"log",
")",
";",
"if",
"(",
"log",
")",
"{",
"log",
".",
"call",
"(",
"window",
".",
"console",
",",
"deprecationMessage",
",",
"stack",
")",
";",
"}",
"return",
"method",
".",
"apply",
"(",
"this",
",",
"arguments",
")",
";",
"}",
";",
"}"
] | wrap a method with a deprecation warning and stack trace
@param {Function} method
@param {String} name
@param {String} message
@returns {Function} A new function wrapping the supplied method. | [
"wrap",
"a",
"method",
"with",
"a",
"deprecation",
"warning",
"and",
"stack",
"trace"
] | e1efdff32318e8bf84e06778094a1705d5d99ddb | https://github.com/lihongxun945/jquery-weui/blob/e1efdff32318e8bf84e06778094a1705d5d99ddb/src/js/hammer.js#L81-L95 |
5,381 | lihongxun945/jquery-weui | src/js/hammer.js | boolOrFn | function boolOrFn(val, args) {
if (typeof val == TYPE_FUNCTION) {
return val.apply(args ? args[0] || undefined : undefined, args);
}
return val;
} | javascript | function boolOrFn(val, args) {
if (typeof val == TYPE_FUNCTION) {
return val.apply(args ? args[0] || undefined : undefined, args);
}
return val;
} | [
"function",
"boolOrFn",
"(",
"val",
",",
"args",
")",
"{",
"if",
"(",
"typeof",
"val",
"==",
"TYPE_FUNCTION",
")",
"{",
"return",
"val",
".",
"apply",
"(",
"args",
"?",
"args",
"[",
"0",
"]",
"||",
"undefined",
":",
"undefined",
",",
"args",
")",
";",
"}",
"return",
"val",
";",
"}"
] | let a boolean value also be a function that must return a boolean
this first item in args will be used as the context
@param {Boolean|Function} val
@param {Array} [args]
@returns {Boolean} | [
"let",
"a",
"boolean",
"value",
"also",
"be",
"a",
"function",
"that",
"must",
"return",
"a",
"boolean",
"this",
"first",
"item",
"in",
"args",
"will",
"be",
"used",
"as",
"the",
"context"
] | e1efdff32318e8bf84e06778094a1705d5d99ddb | https://github.com/lihongxun945/jquery-weui/blob/e1efdff32318e8bf84e06778094a1705d5d99ddb/src/js/hammer.js#L197-L202 |
5,382 | lihongxun945/jquery-weui | src/js/hammer.js | addEventListeners | function addEventListeners(target, types, handler) {
each(splitStr(types), function(type) {
target.addEventListener(type, handler, false);
});
} | javascript | function addEventListeners(target, types, handler) {
each(splitStr(types), function(type) {
target.addEventListener(type, handler, false);
});
} | [
"function",
"addEventListeners",
"(",
"target",
",",
"types",
",",
"handler",
")",
"{",
"each",
"(",
"splitStr",
"(",
"types",
")",
",",
"function",
"(",
"type",
")",
"{",
"target",
".",
"addEventListener",
"(",
"type",
",",
"handler",
",",
"false",
")",
";",
"}",
")",
";",
"}"
] | addEventListener with multiple events at once
@param {EventTarget} target
@param {String} types
@param {Function} handler | [
"addEventListener",
"with",
"multiple",
"events",
"at",
"once"
] | e1efdff32318e8bf84e06778094a1705d5d99ddb | https://github.com/lihongxun945/jquery-weui/blob/e1efdff32318e8bf84e06778094a1705d5d99ddb/src/js/hammer.js#L220-L224 |
5,383 | lihongxun945/jquery-weui | src/js/hammer.js | removeEventListeners | function removeEventListeners(target, types, handler) {
each(splitStr(types), function(type) {
target.removeEventListener(type, handler, false);
});
} | javascript | function removeEventListeners(target, types, handler) {
each(splitStr(types), function(type) {
target.removeEventListener(type, handler, false);
});
} | [
"function",
"removeEventListeners",
"(",
"target",
",",
"types",
",",
"handler",
")",
"{",
"each",
"(",
"splitStr",
"(",
"types",
")",
",",
"function",
"(",
"type",
")",
"{",
"target",
".",
"removeEventListener",
"(",
"type",
",",
"handler",
",",
"false",
")",
";",
"}",
")",
";",
"}"
] | removeEventListener with multiple events at once
@param {EventTarget} target
@param {String} types
@param {Function} handler | [
"removeEventListener",
"with",
"multiple",
"events",
"at",
"once"
] | e1efdff32318e8bf84e06778094a1705d5d99ddb | https://github.com/lihongxun945/jquery-weui/blob/e1efdff32318e8bf84e06778094a1705d5d99ddb/src/js/hammer.js#L232-L236 |
5,384 | lihongxun945/jquery-weui | src/js/hammer.js | inArray | function inArray(src, find, findByKey) {
if (src.indexOf && !findByKey) {
return src.indexOf(find);
} else {
var i = 0;
while (i < src.length) {
if ((findByKey && src[i][findByKey] == find) || (!findByKey && src[i] === find)) {
return i;
}
i++;
}
return -1;
}
} | javascript | function inArray(src, find, findByKey) {
if (src.indexOf && !findByKey) {
return src.indexOf(find);
} else {
var i = 0;
while (i < src.length) {
if ((findByKey && src[i][findByKey] == find) || (!findByKey && src[i] === find)) {
return i;
}
i++;
}
return -1;
}
} | [
"function",
"inArray",
"(",
"src",
",",
"find",
",",
"findByKey",
")",
"{",
"if",
"(",
"src",
".",
"indexOf",
"&&",
"!",
"findByKey",
")",
"{",
"return",
"src",
".",
"indexOf",
"(",
"find",
")",
";",
"}",
"else",
"{",
"var",
"i",
"=",
"0",
";",
"while",
"(",
"i",
"<",
"src",
".",
"length",
")",
"{",
"if",
"(",
"(",
"findByKey",
"&&",
"src",
"[",
"i",
"]",
"[",
"findByKey",
"]",
"==",
"find",
")",
"||",
"(",
"!",
"findByKey",
"&&",
"src",
"[",
"i",
"]",
"===",
"find",
")",
")",
"{",
"return",
"i",
";",
"}",
"i",
"++",
";",
"}",
"return",
"-",
"1",
";",
"}",
"}"
] | find if a array contains the object using indexOf or a simple polyFill
@param {Array} src
@param {String} find
@param {String} [findByKey]
@return {Boolean|Number} false when not found, or the index | [
"find",
"if",
"a",
"array",
"contains",
"the",
"object",
"using",
"indexOf",
"or",
"a",
"simple",
"polyFill"
] | e1efdff32318e8bf84e06778094a1705d5d99ddb | https://github.com/lihongxun945/jquery-weui/blob/e1efdff32318e8bf84e06778094a1705d5d99ddb/src/js/hammer.js#L281-L294 |
5,385 | lihongxun945/jquery-weui | src/js/hammer.js | Input | function Input(manager, callback) {
var self = this;
this.manager = manager;
this.callback = callback;
this.element = manager.element;
this.target = manager.options.inputTarget;
// smaller wrapper around the handler, for the scope and the enabled state of the manager,
// so when disabled the input events are completely bypassed.
this.domHandler = function(ev) {
if (boolOrFn(manager.options.enable, [manager])) {
self.handler(ev);
}
};
this.init();
} | javascript | function Input(manager, callback) {
var self = this;
this.manager = manager;
this.callback = callback;
this.element = manager.element;
this.target = manager.options.inputTarget;
// smaller wrapper around the handler, for the scope and the enabled state of the manager,
// so when disabled the input events are completely bypassed.
this.domHandler = function(ev) {
if (boolOrFn(manager.options.enable, [manager])) {
self.handler(ev);
}
};
this.init();
} | [
"function",
"Input",
"(",
"manager",
",",
"callback",
")",
"{",
"var",
"self",
"=",
"this",
";",
"this",
".",
"manager",
"=",
"manager",
";",
"this",
".",
"callback",
"=",
"callback",
";",
"this",
".",
"element",
"=",
"manager",
".",
"element",
";",
"this",
".",
"target",
"=",
"manager",
".",
"options",
".",
"inputTarget",
";",
"// smaller wrapper around the handler, for the scope and the enabled state of the manager,",
"// so when disabled the input events are completely bypassed.",
"this",
".",
"domHandler",
"=",
"function",
"(",
"ev",
")",
"{",
"if",
"(",
"boolOrFn",
"(",
"manager",
".",
"options",
".",
"enable",
",",
"[",
"manager",
"]",
")",
")",
"{",
"self",
".",
"handler",
"(",
"ev",
")",
";",
"}",
"}",
";",
"this",
".",
"init",
"(",
")",
";",
"}"
] | create new input type manager
@param {Manager} manager
@param {Function} callback
@returns {Input}
@constructor | [
"create",
"new",
"input",
"type",
"manager"
] | e1efdff32318e8bf84e06778094a1705d5d99ddb | https://github.com/lihongxun945/jquery-weui/blob/e1efdff32318e8bf84e06778094a1705d5d99ddb/src/js/hammer.js#L419-L436 |
5,386 | lihongxun945/jquery-weui | src/js/hammer.js | computeIntervalInputData | function computeIntervalInputData(session, input) {
var last = session.lastInterval || input,
deltaTime = input.timeStamp - last.timeStamp,
velocity, velocityX, velocityY, direction;
if (input.eventType != INPUT_CANCEL && (deltaTime > COMPUTE_INTERVAL || last.velocity === undefined)) {
var deltaX = input.deltaX - last.deltaX;
var deltaY = input.deltaY - last.deltaY;
var v = getVelocity(deltaTime, deltaX, deltaY);
velocityX = v.x;
velocityY = v.y;
velocity = (abs(v.x) > abs(v.y)) ? v.x : v.y;
direction = getDirection(deltaX, deltaY);
session.lastInterval = input;
} else {
// use latest velocity info if it doesn't overtake a minimum period
velocity = last.velocity;
velocityX = last.velocityX;
velocityY = last.velocityY;
direction = last.direction;
}
input.velocity = velocity;
input.velocityX = velocityX;
input.velocityY = velocityY;
input.direction = direction;
} | javascript | function computeIntervalInputData(session, input) {
var last = session.lastInterval || input,
deltaTime = input.timeStamp - last.timeStamp,
velocity, velocityX, velocityY, direction;
if (input.eventType != INPUT_CANCEL && (deltaTime > COMPUTE_INTERVAL || last.velocity === undefined)) {
var deltaX = input.deltaX - last.deltaX;
var deltaY = input.deltaY - last.deltaY;
var v = getVelocity(deltaTime, deltaX, deltaY);
velocityX = v.x;
velocityY = v.y;
velocity = (abs(v.x) > abs(v.y)) ? v.x : v.y;
direction = getDirection(deltaX, deltaY);
session.lastInterval = input;
} else {
// use latest velocity info if it doesn't overtake a minimum period
velocity = last.velocity;
velocityX = last.velocityX;
velocityY = last.velocityY;
direction = last.direction;
}
input.velocity = velocity;
input.velocityX = velocityX;
input.velocityY = velocityY;
input.direction = direction;
} | [
"function",
"computeIntervalInputData",
"(",
"session",
",",
"input",
")",
"{",
"var",
"last",
"=",
"session",
".",
"lastInterval",
"||",
"input",
",",
"deltaTime",
"=",
"input",
".",
"timeStamp",
"-",
"last",
".",
"timeStamp",
",",
"velocity",
",",
"velocityX",
",",
"velocityY",
",",
"direction",
";",
"if",
"(",
"input",
".",
"eventType",
"!=",
"INPUT_CANCEL",
"&&",
"(",
"deltaTime",
">",
"COMPUTE_INTERVAL",
"||",
"last",
".",
"velocity",
"===",
"undefined",
")",
")",
"{",
"var",
"deltaX",
"=",
"input",
".",
"deltaX",
"-",
"last",
".",
"deltaX",
";",
"var",
"deltaY",
"=",
"input",
".",
"deltaY",
"-",
"last",
".",
"deltaY",
";",
"var",
"v",
"=",
"getVelocity",
"(",
"deltaTime",
",",
"deltaX",
",",
"deltaY",
")",
";",
"velocityX",
"=",
"v",
".",
"x",
";",
"velocityY",
"=",
"v",
".",
"y",
";",
"velocity",
"=",
"(",
"abs",
"(",
"v",
".",
"x",
")",
">",
"abs",
"(",
"v",
".",
"y",
")",
")",
"?",
"v",
".",
"x",
":",
"v",
".",
"y",
";",
"direction",
"=",
"getDirection",
"(",
"deltaX",
",",
"deltaY",
")",
";",
"session",
".",
"lastInterval",
"=",
"input",
";",
"}",
"else",
"{",
"// use latest velocity info if it doesn't overtake a minimum period",
"velocity",
"=",
"last",
".",
"velocity",
";",
"velocityX",
"=",
"last",
".",
"velocityX",
";",
"velocityY",
"=",
"last",
".",
"velocityY",
";",
"direction",
"=",
"last",
".",
"direction",
";",
"}",
"input",
".",
"velocity",
"=",
"velocity",
";",
"input",
".",
"velocityX",
"=",
"velocityX",
";",
"input",
".",
"velocityY",
"=",
"velocityY",
";",
"input",
".",
"direction",
"=",
"direction",
";",
"}"
] | velocity is calculated every x ms
@param {Object} session
@param {Object} input | [
"velocity",
"is",
"calculated",
"every",
"x",
"ms"
] | e1efdff32318e8bf84e06778094a1705d5d99ddb | https://github.com/lihongxun945/jquery-weui/blob/e1efdff32318e8bf84e06778094a1705d5d99ddb/src/js/hammer.js#L605-L633 |
5,387 | lihongxun945/jquery-weui | src/js/hammer.js | simpleCloneInputData | function simpleCloneInputData(input) {
// make a simple copy of the pointers because we will get a reference if we don't
// we only need clientXY for the calculations
var pointers = [];
var i = 0;
while (i < input.pointers.length) {
pointers[i] = {
clientX: round(input.pointers[i].clientX),
clientY: round(input.pointers[i].clientY)
};
i++;
}
return {
timeStamp: now(),
pointers: pointers,
center: getCenter(pointers),
deltaX: input.deltaX,
deltaY: input.deltaY
};
} | javascript | function simpleCloneInputData(input) {
// make a simple copy of the pointers because we will get a reference if we don't
// we only need clientXY for the calculations
var pointers = [];
var i = 0;
while (i < input.pointers.length) {
pointers[i] = {
clientX: round(input.pointers[i].clientX),
clientY: round(input.pointers[i].clientY)
};
i++;
}
return {
timeStamp: now(),
pointers: pointers,
center: getCenter(pointers),
deltaX: input.deltaX,
deltaY: input.deltaY
};
} | [
"function",
"simpleCloneInputData",
"(",
"input",
")",
"{",
"// make a simple copy of the pointers because we will get a reference if we don't",
"// we only need clientXY for the calculations",
"var",
"pointers",
"=",
"[",
"]",
";",
"var",
"i",
"=",
"0",
";",
"while",
"(",
"i",
"<",
"input",
".",
"pointers",
".",
"length",
")",
"{",
"pointers",
"[",
"i",
"]",
"=",
"{",
"clientX",
":",
"round",
"(",
"input",
".",
"pointers",
"[",
"i",
"]",
".",
"clientX",
")",
",",
"clientY",
":",
"round",
"(",
"input",
".",
"pointers",
"[",
"i",
"]",
".",
"clientY",
")",
"}",
";",
"i",
"++",
";",
"}",
"return",
"{",
"timeStamp",
":",
"now",
"(",
")",
",",
"pointers",
":",
"pointers",
",",
"center",
":",
"getCenter",
"(",
"pointers",
")",
",",
"deltaX",
":",
"input",
".",
"deltaX",
",",
"deltaY",
":",
"input",
".",
"deltaY",
"}",
";",
"}"
] | create a simple clone from the input used for storage of firstInput and firstMultiple
@param {Object} input
@returns {Object} clonedInputData | [
"create",
"a",
"simple",
"clone",
"from",
"the",
"input",
"used",
"for",
"storage",
"of",
"firstInput",
"and",
"firstMultiple"
] | e1efdff32318e8bf84e06778094a1705d5d99ddb | https://github.com/lihongxun945/jquery-weui/blob/e1efdff32318e8bf84e06778094a1705d5d99ddb/src/js/hammer.js#L640-L660 |
5,388 | lihongxun945/jquery-weui | src/js/hammer.js | getCenter | function getCenter(pointers) {
var pointersLength = pointers.length;
// no need to loop when only one touch
if (pointersLength === 1) {
return {
x: round(pointers[0].clientX),
y: round(pointers[0].clientY)
};
}
var x = 0, y = 0, i = 0;
while (i < pointersLength) {
x += pointers[i].clientX;
y += pointers[i].clientY;
i++;
}
return {
x: round(x / pointersLength),
y: round(y / pointersLength)
};
} | javascript | function getCenter(pointers) {
var pointersLength = pointers.length;
// no need to loop when only one touch
if (pointersLength === 1) {
return {
x: round(pointers[0].clientX),
y: round(pointers[0].clientY)
};
}
var x = 0, y = 0, i = 0;
while (i < pointersLength) {
x += pointers[i].clientX;
y += pointers[i].clientY;
i++;
}
return {
x: round(x / pointersLength),
y: round(y / pointersLength)
};
} | [
"function",
"getCenter",
"(",
"pointers",
")",
"{",
"var",
"pointersLength",
"=",
"pointers",
".",
"length",
";",
"// no need to loop when only one touch",
"if",
"(",
"pointersLength",
"===",
"1",
")",
"{",
"return",
"{",
"x",
":",
"round",
"(",
"pointers",
"[",
"0",
"]",
".",
"clientX",
")",
",",
"y",
":",
"round",
"(",
"pointers",
"[",
"0",
"]",
".",
"clientY",
")",
"}",
";",
"}",
"var",
"x",
"=",
"0",
",",
"y",
"=",
"0",
",",
"i",
"=",
"0",
";",
"while",
"(",
"i",
"<",
"pointersLength",
")",
"{",
"x",
"+=",
"pointers",
"[",
"i",
"]",
".",
"clientX",
";",
"y",
"+=",
"pointers",
"[",
"i",
"]",
".",
"clientY",
";",
"i",
"++",
";",
"}",
"return",
"{",
"x",
":",
"round",
"(",
"x",
"/",
"pointersLength",
")",
",",
"y",
":",
"round",
"(",
"y",
"/",
"pointersLength",
")",
"}",
";",
"}"
] | get the center of all the pointers
@param {Array} pointers
@return {Object} center contains `x` and `y` properties | [
"get",
"the",
"center",
"of",
"all",
"the",
"pointers"
] | e1efdff32318e8bf84e06778094a1705d5d99ddb | https://github.com/lihongxun945/jquery-weui/blob/e1efdff32318e8bf84e06778094a1705d5d99ddb/src/js/hammer.js#L667-L689 |
5,389 | lihongxun945/jquery-weui | src/js/hammer.js | getScale | function getScale(start, end) {
return getDistance(end[0], end[1], PROPS_CLIENT_XY) / getDistance(start[0], start[1], PROPS_CLIENT_XY);
} | javascript | function getScale(start, end) {
return getDistance(end[0], end[1], PROPS_CLIENT_XY) / getDistance(start[0], start[1], PROPS_CLIENT_XY);
} | [
"function",
"getScale",
"(",
"start",
",",
"end",
")",
"{",
"return",
"getDistance",
"(",
"end",
"[",
"0",
"]",
",",
"end",
"[",
"1",
"]",
",",
"PROPS_CLIENT_XY",
")",
"/",
"getDistance",
"(",
"start",
"[",
"0",
"]",
",",
"start",
"[",
"1",
"]",
",",
"PROPS_CLIENT_XY",
")",
";",
"}"
] | calculate the scale factor between two pointersets
no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out
@param {Array} start array of pointers
@param {Array} end array of pointers
@return {Number} scale | [
"calculate",
"the",
"scale",
"factor",
"between",
"two",
"pointersets",
"no",
"scale",
"is",
"1",
"and",
"goes",
"down",
"to",
"0",
"when",
"pinched",
"together",
"and",
"bigger",
"when",
"pinched",
"out"
] | e1efdff32318e8bf84e06778094a1705d5d99ddb | https://github.com/lihongxun945/jquery-weui/blob/e1efdff32318e8bf84e06778094a1705d5d99ddb/src/js/hammer.js#L772-L774 |
5,390 | lihongxun945/jquery-weui | src/js/hammer.js | MouseInput | function MouseInput() {
this.evEl = MOUSE_ELEMENT_EVENTS;
this.evWin = MOUSE_WINDOW_EVENTS;
this.pressed = false; // mousedown state
Input.apply(this, arguments);
} | javascript | function MouseInput() {
this.evEl = MOUSE_ELEMENT_EVENTS;
this.evWin = MOUSE_WINDOW_EVENTS;
this.pressed = false; // mousedown state
Input.apply(this, arguments);
} | [
"function",
"MouseInput",
"(",
")",
"{",
"this",
".",
"evEl",
"=",
"MOUSE_ELEMENT_EVENTS",
";",
"this",
".",
"evWin",
"=",
"MOUSE_WINDOW_EVENTS",
";",
"this",
".",
"pressed",
"=",
"false",
";",
"// mousedown state",
"Input",
".",
"apply",
"(",
"this",
",",
"arguments",
")",
";",
"}"
] | Mouse events input
@constructor
@extends Input | [
"Mouse",
"events",
"input"
] | e1efdff32318e8bf84e06778094a1705d5d99ddb | https://github.com/lihongxun945/jquery-weui/blob/e1efdff32318e8bf84e06778094a1705d5d99ddb/src/js/hammer.js#L790-L797 |
5,391 | lihongxun945/jquery-weui | src/js/hammer.js | PointerEventInput | function PointerEventInput() {
this.evEl = POINTER_ELEMENT_EVENTS;
this.evWin = POINTER_WINDOW_EVENTS;
Input.apply(this, arguments);
this.store = (this.manager.session.pointerEvents = []);
} | javascript | function PointerEventInput() {
this.evEl = POINTER_ELEMENT_EVENTS;
this.evWin = POINTER_WINDOW_EVENTS;
Input.apply(this, arguments);
this.store = (this.manager.session.pointerEvents = []);
} | [
"function",
"PointerEventInput",
"(",
")",
"{",
"this",
".",
"evEl",
"=",
"POINTER_ELEMENT_EVENTS",
";",
"this",
".",
"evWin",
"=",
"POINTER_WINDOW_EVENTS",
";",
"Input",
".",
"apply",
"(",
"this",
",",
"arguments",
")",
";",
"this",
".",
"store",
"=",
"(",
"this",
".",
"manager",
".",
"session",
".",
"pointerEvents",
"=",
"[",
"]",
")",
";",
"}"
] | Pointer events input
@constructor
@extends Input | [
"Pointer",
"events",
"input"
] | e1efdff32318e8bf84e06778094a1705d5d99ddb | https://github.com/lihongxun945/jquery-weui/blob/e1efdff32318e8bf84e06778094a1705d5d99ddb/src/js/hammer.js#L864-L871 |
5,392 | lihongxun945/jquery-weui | src/js/hammer.js | PEhandler | function PEhandler(ev) {
var store = this.store;
var removePointer = false;
var eventTypeNormalized = ev.type.toLowerCase().replace('ms', '');
var eventType = POINTER_INPUT_MAP[eventTypeNormalized];
var pointerType = IE10_POINTER_TYPE_ENUM[ev.pointerType] || ev.pointerType;
var isTouch = (pointerType == INPUT_TYPE_TOUCH);
// get index of the event in the store
var storeIndex = inArray(store, ev.pointerId, 'pointerId');
// start and mouse must be down
if (eventType & INPUT_START && (ev.button === 0 || isTouch)) {
if (storeIndex < 0) {
store.push(ev);
storeIndex = store.length - 1;
}
} else if (eventType & (INPUT_END | INPUT_CANCEL)) {
removePointer = true;
}
// it not found, so the pointer hasn't been down (so it's probably a hover)
if (storeIndex < 0) {
return;
}
// update the event in the store
store[storeIndex] = ev;
this.callback(this.manager, eventType, {
pointers: store,
changedPointers: [ev],
pointerType: pointerType,
srcEvent: ev
});
if (removePointer) {
// remove from the store
store.splice(storeIndex, 1);
}
} | javascript | function PEhandler(ev) {
var store = this.store;
var removePointer = false;
var eventTypeNormalized = ev.type.toLowerCase().replace('ms', '');
var eventType = POINTER_INPUT_MAP[eventTypeNormalized];
var pointerType = IE10_POINTER_TYPE_ENUM[ev.pointerType] || ev.pointerType;
var isTouch = (pointerType == INPUT_TYPE_TOUCH);
// get index of the event in the store
var storeIndex = inArray(store, ev.pointerId, 'pointerId');
// start and mouse must be down
if (eventType & INPUT_START && (ev.button === 0 || isTouch)) {
if (storeIndex < 0) {
store.push(ev);
storeIndex = store.length - 1;
}
} else if (eventType & (INPUT_END | INPUT_CANCEL)) {
removePointer = true;
}
// it not found, so the pointer hasn't been down (so it's probably a hover)
if (storeIndex < 0) {
return;
}
// update the event in the store
store[storeIndex] = ev;
this.callback(this.manager, eventType, {
pointers: store,
changedPointers: [ev],
pointerType: pointerType,
srcEvent: ev
});
if (removePointer) {
// remove from the store
store.splice(storeIndex, 1);
}
} | [
"function",
"PEhandler",
"(",
"ev",
")",
"{",
"var",
"store",
"=",
"this",
".",
"store",
";",
"var",
"removePointer",
"=",
"false",
";",
"var",
"eventTypeNormalized",
"=",
"ev",
".",
"type",
".",
"toLowerCase",
"(",
")",
".",
"replace",
"(",
"'ms'",
",",
"''",
")",
";",
"var",
"eventType",
"=",
"POINTER_INPUT_MAP",
"[",
"eventTypeNormalized",
"]",
";",
"var",
"pointerType",
"=",
"IE10_POINTER_TYPE_ENUM",
"[",
"ev",
".",
"pointerType",
"]",
"||",
"ev",
".",
"pointerType",
";",
"var",
"isTouch",
"=",
"(",
"pointerType",
"==",
"INPUT_TYPE_TOUCH",
")",
";",
"// get index of the event in the store",
"var",
"storeIndex",
"=",
"inArray",
"(",
"store",
",",
"ev",
".",
"pointerId",
",",
"'pointerId'",
")",
";",
"// start and mouse must be down",
"if",
"(",
"eventType",
"&",
"INPUT_START",
"&&",
"(",
"ev",
".",
"button",
"===",
"0",
"||",
"isTouch",
")",
")",
"{",
"if",
"(",
"storeIndex",
"<",
"0",
")",
"{",
"store",
".",
"push",
"(",
"ev",
")",
";",
"storeIndex",
"=",
"store",
".",
"length",
"-",
"1",
";",
"}",
"}",
"else",
"if",
"(",
"eventType",
"&",
"(",
"INPUT_END",
"|",
"INPUT_CANCEL",
")",
")",
"{",
"removePointer",
"=",
"true",
";",
"}",
"// it not found, so the pointer hasn't been down (so it's probably a hover)",
"if",
"(",
"storeIndex",
"<",
"0",
")",
"{",
"return",
";",
"}",
"// update the event in the store",
"store",
"[",
"storeIndex",
"]",
"=",
"ev",
";",
"this",
".",
"callback",
"(",
"this",
".",
"manager",
",",
"eventType",
",",
"{",
"pointers",
":",
"store",
",",
"changedPointers",
":",
"[",
"ev",
"]",
",",
"pointerType",
":",
"pointerType",
",",
"srcEvent",
":",
"ev",
"}",
")",
";",
"if",
"(",
"removePointer",
")",
"{",
"// remove from the store",
"store",
".",
"splice",
"(",
"storeIndex",
",",
"1",
")",
";",
"}",
"}"
] | handle mouse events
@param {Object} ev | [
"handle",
"mouse",
"events"
] | e1efdff32318e8bf84e06778094a1705d5d99ddb | https://github.com/lihongxun945/jquery-weui/blob/e1efdff32318e8bf84e06778094a1705d5d99ddb/src/js/hammer.js#L878-L920 |
5,393 | lihongxun945/jquery-weui | src/js/hammer.js | SingleTouchInput | function SingleTouchInput() {
this.evTarget = SINGLE_TOUCH_TARGET_EVENTS;
this.evWin = SINGLE_TOUCH_WINDOW_EVENTS;
this.started = false;
Input.apply(this, arguments);
} | javascript | function SingleTouchInput() {
this.evTarget = SINGLE_TOUCH_TARGET_EVENTS;
this.evWin = SINGLE_TOUCH_WINDOW_EVENTS;
this.started = false;
Input.apply(this, arguments);
} | [
"function",
"SingleTouchInput",
"(",
")",
"{",
"this",
".",
"evTarget",
"=",
"SINGLE_TOUCH_TARGET_EVENTS",
";",
"this",
".",
"evWin",
"=",
"SINGLE_TOUCH_WINDOW_EVENTS",
";",
"this",
".",
"started",
"=",
"false",
";",
"Input",
".",
"apply",
"(",
"this",
",",
"arguments",
")",
";",
"}"
] | Touch events input
@constructor
@extends Input | [
"Touch",
"events",
"input"
] | e1efdff32318e8bf84e06778094a1705d5d99ddb | https://github.com/lihongxun945/jquery-weui/blob/e1efdff32318e8bf84e06778094a1705d5d99ddb/src/js/hammer.js#L938-L944 |
5,394 | lihongxun945/jquery-weui | src/js/hammer.js | Recognizer | function Recognizer(options) {
this.options = assign({}, this.defaults, options || {});
this.id = uniqueId();
this.manager = null;
// default is enable true
this.options.enable = ifUndefined(this.options.enable, true);
this.state = STATE_POSSIBLE;
this.simultaneous = {};
this.requireFail = [];
} | javascript | function Recognizer(options) {
this.options = assign({}, this.defaults, options || {});
this.id = uniqueId();
this.manager = null;
// default is enable true
this.options.enable = ifUndefined(this.options.enable, true);
this.state = STATE_POSSIBLE;
this.simultaneous = {};
this.requireFail = [];
} | [
"function",
"Recognizer",
"(",
"options",
")",
"{",
"this",
".",
"options",
"=",
"assign",
"(",
"{",
"}",
",",
"this",
".",
"defaults",
",",
"options",
"||",
"{",
"}",
")",
";",
"this",
".",
"id",
"=",
"uniqueId",
"(",
")",
";",
"this",
".",
"manager",
"=",
"null",
";",
"// default is enable true",
"this",
".",
"options",
".",
"enable",
"=",
"ifUndefined",
"(",
"this",
".",
"options",
".",
"enable",
",",
"true",
")",
";",
"this",
".",
"state",
"=",
"STATE_POSSIBLE",
";",
"this",
".",
"simultaneous",
"=",
"{",
"}",
";",
"this",
".",
"requireFail",
"=",
"[",
"]",
";",
"}"
] | Recognizer
Every recognizer needs to extend from this class.
@constructor
@param {Object} options | [
"Recognizer",
"Every",
"recognizer",
"needs",
"to",
"extend",
"from",
"this",
"class",
"."
] | e1efdff32318e8bf84e06778094a1705d5d99ddb | https://github.com/lihongxun945/jquery-weui/blob/e1efdff32318e8bf84e06778094a1705d5d99ddb/src/js/hammer.js#L1393-L1407 |
5,395 | lihongxun945/jquery-weui | src/js/hammer.js | function(otherRecognizer) {
if (invokeArrayArg(otherRecognizer, 'recognizeWith', this)) {
return this;
}
var simultaneous = this.simultaneous;
otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this);
if (!simultaneous[otherRecognizer.id]) {
simultaneous[otherRecognizer.id] = otherRecognizer;
otherRecognizer.recognizeWith(this);
}
return this;
} | javascript | function(otherRecognizer) {
if (invokeArrayArg(otherRecognizer, 'recognizeWith', this)) {
return this;
}
var simultaneous = this.simultaneous;
otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this);
if (!simultaneous[otherRecognizer.id]) {
simultaneous[otherRecognizer.id] = otherRecognizer;
otherRecognizer.recognizeWith(this);
}
return this;
} | [
"function",
"(",
"otherRecognizer",
")",
"{",
"if",
"(",
"invokeArrayArg",
"(",
"otherRecognizer",
",",
"'recognizeWith'",
",",
"this",
")",
")",
"{",
"return",
"this",
";",
"}",
"var",
"simultaneous",
"=",
"this",
".",
"simultaneous",
";",
"otherRecognizer",
"=",
"getRecognizerByNameIfManager",
"(",
"otherRecognizer",
",",
"this",
")",
";",
"if",
"(",
"!",
"simultaneous",
"[",
"otherRecognizer",
".",
"id",
"]",
")",
"{",
"simultaneous",
"[",
"otherRecognizer",
".",
"id",
"]",
"=",
"otherRecognizer",
";",
"otherRecognizer",
".",
"recognizeWith",
"(",
"this",
")",
";",
"}",
"return",
"this",
";",
"}"
] | recognize simultaneous with an other recognizer.
@param {Recognizer} otherRecognizer
@returns {Recognizer} this | [
"recognize",
"simultaneous",
"with",
"an",
"other",
"recognizer",
"."
] | e1efdff32318e8bf84e06778094a1705d5d99ddb | https://github.com/lihongxun945/jquery-weui/blob/e1efdff32318e8bf84e06778094a1705d5d99ddb/src/js/hammer.js#L1434-L1446 |
|
5,396 | lihongxun945/jquery-weui | src/js/hammer.js | function() {
var i = 0;
while (i < this.requireFail.length) {
if (!(this.requireFail[i].state & (STATE_FAILED | STATE_POSSIBLE))) {
return false;
}
i++;
}
return true;
} | javascript | function() {
var i = 0;
while (i < this.requireFail.length) {
if (!(this.requireFail[i].state & (STATE_FAILED | STATE_POSSIBLE))) {
return false;
}
i++;
}
return true;
} | [
"function",
"(",
")",
"{",
"var",
"i",
"=",
"0",
";",
"while",
"(",
"i",
"<",
"this",
".",
"requireFail",
".",
"length",
")",
"{",
"if",
"(",
"!",
"(",
"this",
".",
"requireFail",
"[",
"i",
"]",
".",
"state",
"&",
"(",
"STATE_FAILED",
"|",
"STATE_POSSIBLE",
")",
")",
")",
"{",
"return",
"false",
";",
"}",
"i",
"++",
";",
"}",
"return",
"true",
";",
"}"
] | can we emit?
@returns {boolean} | [
"can",
"we",
"emit?"
] | e1efdff32318e8bf84e06778094a1705d5d99ddb | https://github.com/lihongxun945/jquery-weui/blob/e1efdff32318e8bf84e06778094a1705d5d99ddb/src/js/hammer.js#L1565-L1574 |
|
5,397 | lihongxun945/jquery-weui | src/js/hammer.js | function(inputData) {
// make a new copy of the inputData
// so we can change the inputData without messing up the other recognizers
var inputDataClone = assign({}, inputData);
// is is enabled and allow recognizing?
if (!boolOrFn(this.options.enable, [this, inputDataClone])) {
this.reset();
this.state = STATE_FAILED;
return;
}
// reset when we've reached the end
if (this.state & (STATE_RECOGNIZED | STATE_CANCELLED | STATE_FAILED)) {
this.state = STATE_POSSIBLE;
}
this.state = this.process(inputDataClone);
// the recognizer has recognized a gesture
// so trigger an event
if (this.state & (STATE_BEGAN | STATE_CHANGED | STATE_ENDED | STATE_CANCELLED)) {
this.tryEmit(inputDataClone);
}
} | javascript | function(inputData) {
// make a new copy of the inputData
// so we can change the inputData without messing up the other recognizers
var inputDataClone = assign({}, inputData);
// is is enabled and allow recognizing?
if (!boolOrFn(this.options.enable, [this, inputDataClone])) {
this.reset();
this.state = STATE_FAILED;
return;
}
// reset when we've reached the end
if (this.state & (STATE_RECOGNIZED | STATE_CANCELLED | STATE_FAILED)) {
this.state = STATE_POSSIBLE;
}
this.state = this.process(inputDataClone);
// the recognizer has recognized a gesture
// so trigger an event
if (this.state & (STATE_BEGAN | STATE_CHANGED | STATE_ENDED | STATE_CANCELLED)) {
this.tryEmit(inputDataClone);
}
} | [
"function",
"(",
"inputData",
")",
"{",
"// make a new copy of the inputData",
"// so we can change the inputData without messing up the other recognizers",
"var",
"inputDataClone",
"=",
"assign",
"(",
"{",
"}",
",",
"inputData",
")",
";",
"// is is enabled and allow recognizing?",
"if",
"(",
"!",
"boolOrFn",
"(",
"this",
".",
"options",
".",
"enable",
",",
"[",
"this",
",",
"inputDataClone",
"]",
")",
")",
"{",
"this",
".",
"reset",
"(",
")",
";",
"this",
".",
"state",
"=",
"STATE_FAILED",
";",
"return",
";",
"}",
"// reset when we've reached the end",
"if",
"(",
"this",
".",
"state",
"&",
"(",
"STATE_RECOGNIZED",
"|",
"STATE_CANCELLED",
"|",
"STATE_FAILED",
")",
")",
"{",
"this",
".",
"state",
"=",
"STATE_POSSIBLE",
";",
"}",
"this",
".",
"state",
"=",
"this",
".",
"process",
"(",
"inputDataClone",
")",
";",
"// the recognizer has recognized a gesture",
"// so trigger an event",
"if",
"(",
"this",
".",
"state",
"&",
"(",
"STATE_BEGAN",
"|",
"STATE_CHANGED",
"|",
"STATE_ENDED",
"|",
"STATE_CANCELLED",
")",
")",
"{",
"this",
".",
"tryEmit",
"(",
"inputDataClone",
")",
";",
"}",
"}"
] | update the recognizer
@param {Object} inputData | [
"update",
"the",
"recognizer"
] | e1efdff32318e8bf84e06778094a1705d5d99ddb | https://github.com/lihongxun945/jquery-weui/blob/e1efdff32318e8bf84e06778094a1705d5d99ddb/src/js/hammer.js#L1580-L1604 |
|
5,398 | lihongxun945/jquery-weui | src/js/hammer.js | stateStr | function stateStr(state) {
if (state & STATE_CANCELLED) {
return 'cancel';
} else if (state & STATE_ENDED) {
return 'end';
} else if (state & STATE_CHANGED) {
return 'move';
} else if (state & STATE_BEGAN) {
return 'start';
}
return '';
} | javascript | function stateStr(state) {
if (state & STATE_CANCELLED) {
return 'cancel';
} else if (state & STATE_ENDED) {
return 'end';
} else if (state & STATE_CHANGED) {
return 'move';
} else if (state & STATE_BEGAN) {
return 'start';
}
return '';
} | [
"function",
"stateStr",
"(",
"state",
")",
"{",
"if",
"(",
"state",
"&",
"STATE_CANCELLED",
")",
"{",
"return",
"'cancel'",
";",
"}",
"else",
"if",
"(",
"state",
"&",
"STATE_ENDED",
")",
"{",
"return",
"'end'",
";",
"}",
"else",
"if",
"(",
"state",
"&",
"STATE_CHANGED",
")",
"{",
"return",
"'move'",
";",
"}",
"else",
"if",
"(",
"state",
"&",
"STATE_BEGAN",
")",
"{",
"return",
"'start'",
";",
"}",
"return",
"''",
";",
"}"
] | get a usable string, used as event postfix
@param {Const} state
@returns {String} state | [
"get",
"a",
"usable",
"string",
"used",
"as",
"event",
"postfix"
] | e1efdff32318e8bf84e06778094a1705d5d99ddb | https://github.com/lihongxun945/jquery-weui/blob/e1efdff32318e8bf84e06778094a1705d5d99ddb/src/js/hammer.js#L1635-L1646 |
5,399 | lihongxun945/jquery-weui | src/js/hammer.js | directionStr | function directionStr(direction) {
if (direction == DIRECTION_DOWN) {
return 'down';
} else if (direction == DIRECTION_UP) {
return 'up';
} else if (direction == DIRECTION_LEFT) {
return 'left';
} else if (direction == DIRECTION_RIGHT) {
return 'right';
}
return '';
} | javascript | function directionStr(direction) {
if (direction == DIRECTION_DOWN) {
return 'down';
} else if (direction == DIRECTION_UP) {
return 'up';
} else if (direction == DIRECTION_LEFT) {
return 'left';
} else if (direction == DIRECTION_RIGHT) {
return 'right';
}
return '';
} | [
"function",
"directionStr",
"(",
"direction",
")",
"{",
"if",
"(",
"direction",
"==",
"DIRECTION_DOWN",
")",
"{",
"return",
"'down'",
";",
"}",
"else",
"if",
"(",
"direction",
"==",
"DIRECTION_UP",
")",
"{",
"return",
"'up'",
";",
"}",
"else",
"if",
"(",
"direction",
"==",
"DIRECTION_LEFT",
")",
"{",
"return",
"'left'",
";",
"}",
"else",
"if",
"(",
"direction",
"==",
"DIRECTION_RIGHT",
")",
"{",
"return",
"'right'",
";",
"}",
"return",
"''",
";",
"}"
] | direction cons to string
@param {Const} direction
@returns {String} | [
"direction",
"cons",
"to",
"string"
] | e1efdff32318e8bf84e06778094a1705d5d99ddb | https://github.com/lihongxun945/jquery-weui/blob/e1efdff32318e8bf84e06778094a1705d5d99ddb/src/js/hammer.js#L1653-L1664 |
Subsets and Splits