id
int32 0
58k
| repo
stringlengths 5
67
| path
stringlengths 4
116
| func_name
stringlengths 0
58
| original_string
stringlengths 52
373k
| language
stringclasses 1
value | code
stringlengths 52
373k
| code_tokens
list | docstring
stringlengths 4
11.8k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 86
226
|
|---|---|---|---|---|---|---|---|---|---|---|---|
18,400
|
zhangxiang958/vue-tab
|
src/lib/demo.js
|
function(cells, reflow) {
var columnIndex;
var columnHeight;
for(var j = 0, k = cells.length; j < k; j++) {
// Place the cell to column with the minimal height.
columnIndex = getMinKey(columnHeights);
columnHeight = columnHeights[columnIndex];
cells[j].style.height = (cells[j].offsetHeight - CELL_PADDING) + 'px';
cells[j].style.left = columnIndex * (COLUMN_WIDTH + GAP_WIDTH) + 'px';
cells[j].style.top = columnHeight + 'px';
columnHeights[columnIndex] = columnHeight + GAP_HEIGHT + cells[j].offsetHeight;
if(!reflow) {
cells[j].className = 'cell ready';
}
}
cellsContainer.style.height = getMaxVal(columnHeights) + 'px';
manageCells();
}
|
javascript
|
function(cells, reflow) {
var columnIndex;
var columnHeight;
for(var j = 0, k = cells.length; j < k; j++) {
// Place the cell to column with the minimal height.
columnIndex = getMinKey(columnHeights);
columnHeight = columnHeights[columnIndex];
cells[j].style.height = (cells[j].offsetHeight - CELL_PADDING) + 'px';
cells[j].style.left = columnIndex * (COLUMN_WIDTH + GAP_WIDTH) + 'px';
cells[j].style.top = columnHeight + 'px';
columnHeights[columnIndex] = columnHeight + GAP_HEIGHT + cells[j].offsetHeight;
if(!reflow) {
cells[j].className = 'cell ready';
}
}
cellsContainer.style.height = getMaxVal(columnHeights) + 'px';
manageCells();
}
|
[
"function",
"(",
"cells",
",",
"reflow",
")",
"{",
"var",
"columnIndex",
";",
"var",
"columnHeight",
";",
"for",
"(",
"var",
"j",
"=",
"0",
",",
"k",
"=",
"cells",
".",
"length",
";",
"j",
"<",
"k",
";",
"j",
"++",
")",
"{",
"// Place the cell to column with the minimal height.",
"columnIndex",
"=",
"getMinKey",
"(",
"columnHeights",
")",
";",
"columnHeight",
"=",
"columnHeights",
"[",
"columnIndex",
"]",
";",
"cells",
"[",
"j",
"]",
".",
"style",
".",
"height",
"=",
"(",
"cells",
"[",
"j",
"]",
".",
"offsetHeight",
"-",
"CELL_PADDING",
")",
"+",
"'px'",
";",
"cells",
"[",
"j",
"]",
".",
"style",
".",
"left",
"=",
"columnIndex",
"*",
"(",
"COLUMN_WIDTH",
"+",
"GAP_WIDTH",
")",
"+",
"'px'",
";",
"cells",
"[",
"j",
"]",
".",
"style",
".",
"top",
"=",
"columnHeight",
"+",
"'px'",
";",
"columnHeights",
"[",
"columnIndex",
"]",
"=",
"columnHeight",
"+",
"GAP_HEIGHT",
"+",
"cells",
"[",
"j",
"]",
".",
"offsetHeight",
";",
"if",
"(",
"!",
"reflow",
")",
"{",
"cells",
"[",
"j",
"]",
".",
"className",
"=",
"'cell ready'",
";",
"}",
"}",
"cellsContainer",
".",
"style",
".",
"height",
"=",
"getMaxVal",
"(",
"columnHeights",
")",
"+",
"'px'",
";",
"manageCells",
"(",
")",
";",
"}"
] |
Position the newly appended cells and update array of column heights.
|
[
"Position",
"the",
"newly",
"appended",
"cells",
"and",
"update",
"array",
"of",
"column",
"heights",
"."
] |
8d54e04abbfe134ecc63ccc21872f45f165516e4
|
https://github.com/zhangxiang958/vue-tab/blob/8d54e04abbfe134ecc63ccc21872f45f165516e4/src/lib/demo.js#L168-L185
|
|
18,401
|
zhangxiang958/vue-tab
|
src/lib/demo.js
|
function() {
// Calculate new column count after resize.
columnCount = getColumnCount();
if(columnHeights.length != columnCount) {
// Reset array of column heights and container width.
resetHeights(columnCount);
adjustCells(cellsContainer.children, true);
} else {
manageCells();
}
}
|
javascript
|
function() {
// Calculate new column count after resize.
columnCount = getColumnCount();
if(columnHeights.length != columnCount) {
// Reset array of column heights and container width.
resetHeights(columnCount);
adjustCells(cellsContainer.children, true);
} else {
manageCells();
}
}
|
[
"function",
"(",
")",
"{",
"// Calculate new column count after resize.",
"columnCount",
"=",
"getColumnCount",
"(",
")",
";",
"if",
"(",
"columnHeights",
".",
"length",
"!=",
"columnCount",
")",
"{",
"// Reset array of column heights and container width.",
"resetHeights",
"(",
"columnCount",
")",
";",
"adjustCells",
"(",
"cellsContainer",
".",
"children",
",",
"true",
")",
";",
"}",
"else",
"{",
"manageCells",
"(",
")",
";",
"}",
"}"
] |
Calculate new column data if it's necessary after resize.
|
[
"Calculate",
"new",
"column",
"data",
"if",
"it",
"s",
"necessary",
"after",
"resize",
"."
] |
8d54e04abbfe134ecc63ccc21872f45f165516e4
|
https://github.com/zhangxiang958/vue-tab/blob/8d54e04abbfe134ecc63ccc21872f45f165516e4/src/lib/demo.js#L188-L198
|
|
18,402
|
zhangxiang958/vue-tab
|
src/lib/demo.js
|
function() {
// Lock managing state to avoid another async call. See {Function} delayedScroll.
managing = true;
var cells = cellsContainer.children;
var viewportTop = (document.body.scrollTop || document.documentElement.scrollTop) - cellsContainer.offsetTop;
var viewportBottom = (window.innerHeight || document.documentElement.clientHeight) + viewportTop;
// Remove cells' contents if they are too far away from the viewport. Get them back if they are near.
// TODO: remove the cells from DOM should be better :<
for(var i = 0, l = cells.length; i < l; i++) {
if((cells[i].offsetTop - viewportBottom > THRESHOLD) || (viewportTop - cells[i].offsetTop - cells[i].offsetHeight > THRESHOLD)) {
if(cells[i].className === 'cell ready') {
cells[i].fragment = cells[i].innerHTML;
cells[i].innerHTML = '';
cells[i].className = 'cell shadow';
}
} else {
if(cells[i].className === 'cell shadow') {
cells[i].innerHTML = cells[i].fragment;
cells[i].className = 'cell ready';
}
}
}
// If there's space in viewport for a cell, request new cells.
if(viewportBottom > getMinVal(columnHeights)) {
// Remove the if/else statement in your project, just call the appendCells function.
if(isGithubDemo) {
appendCellsDemo(columnCount);
} else {
appendCells(columnCount);
}
}
// Unlock managing state.
managing = false;
}
|
javascript
|
function() {
// Lock managing state to avoid another async call. See {Function} delayedScroll.
managing = true;
var cells = cellsContainer.children;
var viewportTop = (document.body.scrollTop || document.documentElement.scrollTop) - cellsContainer.offsetTop;
var viewportBottom = (window.innerHeight || document.documentElement.clientHeight) + viewportTop;
// Remove cells' contents if they are too far away from the viewport. Get them back if they are near.
// TODO: remove the cells from DOM should be better :<
for(var i = 0, l = cells.length; i < l; i++) {
if((cells[i].offsetTop - viewportBottom > THRESHOLD) || (viewportTop - cells[i].offsetTop - cells[i].offsetHeight > THRESHOLD)) {
if(cells[i].className === 'cell ready') {
cells[i].fragment = cells[i].innerHTML;
cells[i].innerHTML = '';
cells[i].className = 'cell shadow';
}
} else {
if(cells[i].className === 'cell shadow') {
cells[i].innerHTML = cells[i].fragment;
cells[i].className = 'cell ready';
}
}
}
// If there's space in viewport for a cell, request new cells.
if(viewportBottom > getMinVal(columnHeights)) {
// Remove the if/else statement in your project, just call the appendCells function.
if(isGithubDemo) {
appendCellsDemo(columnCount);
} else {
appendCells(columnCount);
}
}
// Unlock managing state.
managing = false;
}
|
[
"function",
"(",
")",
"{",
"// Lock managing state to avoid another async call. See {Function} delayedScroll.",
"managing",
"=",
"true",
";",
"var",
"cells",
"=",
"cellsContainer",
".",
"children",
";",
"var",
"viewportTop",
"=",
"(",
"document",
".",
"body",
".",
"scrollTop",
"||",
"document",
".",
"documentElement",
".",
"scrollTop",
")",
"-",
"cellsContainer",
".",
"offsetTop",
";",
"var",
"viewportBottom",
"=",
"(",
"window",
".",
"innerHeight",
"||",
"document",
".",
"documentElement",
".",
"clientHeight",
")",
"+",
"viewportTop",
";",
"// Remove cells' contents if they are too far away from the viewport. Get them back if they are near.",
"// TODO: remove the cells from DOM should be better :<",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"l",
"=",
"cells",
".",
"length",
";",
"i",
"<",
"l",
";",
"i",
"++",
")",
"{",
"if",
"(",
"(",
"cells",
"[",
"i",
"]",
".",
"offsetTop",
"-",
"viewportBottom",
">",
"THRESHOLD",
")",
"||",
"(",
"viewportTop",
"-",
"cells",
"[",
"i",
"]",
".",
"offsetTop",
"-",
"cells",
"[",
"i",
"]",
".",
"offsetHeight",
">",
"THRESHOLD",
")",
")",
"{",
"if",
"(",
"cells",
"[",
"i",
"]",
".",
"className",
"===",
"'cell ready'",
")",
"{",
"cells",
"[",
"i",
"]",
".",
"fragment",
"=",
"cells",
"[",
"i",
"]",
".",
"innerHTML",
";",
"cells",
"[",
"i",
"]",
".",
"innerHTML",
"=",
"''",
";",
"cells",
"[",
"i",
"]",
".",
"className",
"=",
"'cell shadow'",
";",
"}",
"}",
"else",
"{",
"if",
"(",
"cells",
"[",
"i",
"]",
".",
"className",
"===",
"'cell shadow'",
")",
"{",
"cells",
"[",
"i",
"]",
".",
"innerHTML",
"=",
"cells",
"[",
"i",
"]",
".",
"fragment",
";",
"cells",
"[",
"i",
"]",
".",
"className",
"=",
"'cell ready'",
";",
"}",
"}",
"}",
"// If there's space in viewport for a cell, request new cells.",
"if",
"(",
"viewportBottom",
">",
"getMinVal",
"(",
"columnHeights",
")",
")",
"{",
"// Remove the if/else statement in your project, just call the appendCells function.",
"if",
"(",
"isGithubDemo",
")",
"{",
"appendCellsDemo",
"(",
"columnCount",
")",
";",
"}",
"else",
"{",
"appendCells",
"(",
"columnCount",
")",
";",
"}",
"}",
"// Unlock managing state.",
"managing",
"=",
"false",
";",
"}"
] |
Toggle old cells' contents from the DOM depending on their offset from the viewport, save memory. Load and append new cells if there's space in viewport for a cell.
|
[
"Toggle",
"old",
"cells",
"contents",
"from",
"the",
"DOM",
"depending",
"on",
"their",
"offset",
"from",
"the",
"viewport",
"save",
"memory",
".",
"Load",
"and",
"append",
"new",
"cells",
"if",
"there",
"s",
"space",
"in",
"viewport",
"for",
"a",
"cell",
"."
] |
8d54e04abbfe134ecc63ccc21872f45f165516e4
|
https://github.com/zhangxiang958/vue-tab/blob/8d54e04abbfe134ecc63ccc21872f45f165516e4/src/lib/demo.js#L202-L239
|
|
18,403
|
zhangxiang958/vue-tab
|
src/lib/demo.js
|
function() {
// Add other event listeners.
addEvent(cellsContainer, 'click', updateNotice);
addEvent(window, 'resize', delayedResize);
addEvent(window, 'scroll', delayedScroll);
// Initialize array of column heights and container width.
columnCount = getColumnCount();
resetHeights(columnCount);
// Load cells for the first time.
manageCells();
}
|
javascript
|
function() {
// Add other event listeners.
addEvent(cellsContainer, 'click', updateNotice);
addEvent(window, 'resize', delayedResize);
addEvent(window, 'scroll', delayedScroll);
// Initialize array of column heights and container width.
columnCount = getColumnCount();
resetHeights(columnCount);
// Load cells for the first time.
manageCells();
}
|
[
"function",
"(",
")",
"{",
"// Add other event listeners.",
"addEvent",
"(",
"cellsContainer",
",",
"'click'",
",",
"updateNotice",
")",
";",
"addEvent",
"(",
"window",
",",
"'resize'",
",",
"delayedResize",
")",
";",
"addEvent",
"(",
"window",
",",
"'scroll'",
",",
"delayedScroll",
")",
";",
"// Initialize array of column heights and container width.",
"columnCount",
"=",
"getColumnCount",
"(",
")",
";",
"resetHeights",
"(",
"columnCount",
")",
";",
"// Load cells for the first time.",
"manageCells",
"(",
")",
";",
"}"
] |
Initialize the layout.
|
[
"Initialize",
"the",
"layout",
"."
] |
8d54e04abbfe134ecc63ccc21872f45f165516e4
|
https://github.com/zhangxiang958/vue-tab/blob/8d54e04abbfe134ecc63ccc21872f45f165516e4/src/lib/demo.js#L257-L269
|
|
18,404
|
sebpiq/WebPd
|
lib/waa/dsp.js
|
function(time) {
if (this._queue.length === 0) return
var i = 0, line, oldLines
while ((line = this._queue[i++]) && time >= line.t2) 1
oldLines = this._queue.slice(0, i - 1)
this._queue = this._queue.slice(i - 1)
if (this._queue.length === 0)
this._lastValue = oldLines[oldLines.length - 1].v2
}
|
javascript
|
function(time) {
if (this._queue.length === 0) return
var i = 0, line, oldLines
while ((line = this._queue[i++]) && time >= line.t2) 1
oldLines = this._queue.slice(0, i - 1)
this._queue = this._queue.slice(i - 1)
if (this._queue.length === 0)
this._lastValue = oldLines[oldLines.length - 1].v2
}
|
[
"function",
"(",
"time",
")",
"{",
"if",
"(",
"this",
".",
"_queue",
".",
"length",
"===",
"0",
")",
"return",
"var",
"i",
"=",
"0",
",",
"line",
",",
"oldLines",
"while",
"(",
"(",
"line",
"=",
"this",
".",
"_queue",
"[",
"i",
"++",
"]",
")",
"&&",
"time",
">=",
"line",
".",
"t2",
")",
"1",
"oldLines",
"=",
"this",
".",
"_queue",
".",
"slice",
"(",
"0",
",",
"i",
"-",
"1",
")",
"this",
".",
"_queue",
"=",
"this",
".",
"_queue",
".",
"slice",
"(",
"i",
"-",
"1",
")",
"if",
"(",
"this",
".",
"_queue",
".",
"length",
"===",
"0",
")",
"this",
".",
"_lastValue",
"=",
"oldLines",
"[",
"oldLines",
".",
"length",
"-",
"1",
"]",
".",
"v2",
"}"
] |
Refresh the queue to `time`, removing old lines and setting `_lastValue` if appropriate.
|
[
"Refresh",
"the",
"queue",
"to",
"time",
"removing",
"old",
"lines",
"and",
"setting",
"_lastValue",
"if",
"appropriate",
"."
] |
2c922bd2c792e13b37c93f4fcf7ada344603e09d
|
https://github.com/sebpiq/WebPd/blob/2c922bd2c792e13b37c93f4fcf7ada344603e09d/lib/waa/dsp.js#L316-L324
|
|
18,405
|
sebpiq/WebPd
|
lib/waa/dsp.js
|
function(t1, v2, duration) {
var i = 0, line, newLines = []
// Find the point in the queue where we should insert the new line.
while ((line = this._queue[i++]) && (t1 >= line.t2)) 1
this._queue = this._queue.slice(0)
if (this._queue.length) {
var lastLine = this._queue[this._queue.length - 1]
// If the new line interrupts the last in the queue, we have to interpolate
// a new line
if (t1 < lastLine.t2) {
this._queue = this._queue.slice(0, -1)
line = {
t1: lastLine.t1, v1: lastLine.v1,
t2: t1, v2: this._interpolate(lastLine, t1)
}
newLines.push(line)
this._queue.push(line)
// Otherwise, we have to fill-in the gap with a straight line
} else if (t1 > lastLine.t2) {
line = {
t1: lastLine.t2, v1: lastLine.v2,
t2: t1, v2: lastLine.v2
}
newLines.push(line)
this._queue.push(line)
}
// If there isn't any value in the queue yet, we fill in the gap with
// a straight line from `_lastValue` all the way to `t1`
} else {
line = {
t1: 0, v1: this._lastValue,
t2: t1, v2: this._lastValue
}
newLines.push(line)
this._queue.push(line)
}
// Finally create the line and add it to the queue
line = {
t1: t1, v1: this._queue[this._queue.length - 1].v2,
t2: t1 + duration, v2: v2
}
newLines.push(line)
this._queue.push(line)
return newLines
}
|
javascript
|
function(t1, v2, duration) {
var i = 0, line, newLines = []
// Find the point in the queue where we should insert the new line.
while ((line = this._queue[i++]) && (t1 >= line.t2)) 1
this._queue = this._queue.slice(0)
if (this._queue.length) {
var lastLine = this._queue[this._queue.length - 1]
// If the new line interrupts the last in the queue, we have to interpolate
// a new line
if (t1 < lastLine.t2) {
this._queue = this._queue.slice(0, -1)
line = {
t1: lastLine.t1, v1: lastLine.v1,
t2: t1, v2: this._interpolate(lastLine, t1)
}
newLines.push(line)
this._queue.push(line)
// Otherwise, we have to fill-in the gap with a straight line
} else if (t1 > lastLine.t2) {
line = {
t1: lastLine.t2, v1: lastLine.v2,
t2: t1, v2: lastLine.v2
}
newLines.push(line)
this._queue.push(line)
}
// If there isn't any value in the queue yet, we fill in the gap with
// a straight line from `_lastValue` all the way to `t1`
} else {
line = {
t1: 0, v1: this._lastValue,
t2: t1, v2: this._lastValue
}
newLines.push(line)
this._queue.push(line)
}
// Finally create the line and add it to the queue
line = {
t1: t1, v1: this._queue[this._queue.length - 1].v2,
t2: t1 + duration, v2: v2
}
newLines.push(line)
this._queue.push(line)
return newLines
}
|
[
"function",
"(",
"t1",
",",
"v2",
",",
"duration",
")",
"{",
"var",
"i",
"=",
"0",
",",
"line",
",",
"newLines",
"=",
"[",
"]",
"// Find the point in the queue where we should insert the new line.",
"while",
"(",
"(",
"line",
"=",
"this",
".",
"_queue",
"[",
"i",
"++",
"]",
")",
"&&",
"(",
"t1",
">=",
"line",
".",
"t2",
")",
")",
"1",
"this",
".",
"_queue",
"=",
"this",
".",
"_queue",
".",
"slice",
"(",
"0",
")",
"if",
"(",
"this",
".",
"_queue",
".",
"length",
")",
"{",
"var",
"lastLine",
"=",
"this",
".",
"_queue",
"[",
"this",
".",
"_queue",
".",
"length",
"-",
"1",
"]",
"// If the new line interrupts the last in the queue, we have to interpolate",
"// a new line",
"if",
"(",
"t1",
"<",
"lastLine",
".",
"t2",
")",
"{",
"this",
".",
"_queue",
"=",
"this",
".",
"_queue",
".",
"slice",
"(",
"0",
",",
"-",
"1",
")",
"line",
"=",
"{",
"t1",
":",
"lastLine",
".",
"t1",
",",
"v1",
":",
"lastLine",
".",
"v1",
",",
"t2",
":",
"t1",
",",
"v2",
":",
"this",
".",
"_interpolate",
"(",
"lastLine",
",",
"t1",
")",
"}",
"newLines",
".",
"push",
"(",
"line",
")",
"this",
".",
"_queue",
".",
"push",
"(",
"line",
")",
"// Otherwise, we have to fill-in the gap with a straight line",
"}",
"else",
"if",
"(",
"t1",
">",
"lastLine",
".",
"t2",
")",
"{",
"line",
"=",
"{",
"t1",
":",
"lastLine",
".",
"t2",
",",
"v1",
":",
"lastLine",
".",
"v2",
",",
"t2",
":",
"t1",
",",
"v2",
":",
"lastLine",
".",
"v2",
"}",
"newLines",
".",
"push",
"(",
"line",
")",
"this",
".",
"_queue",
".",
"push",
"(",
"line",
")",
"}",
"// If there isn't any value in the queue yet, we fill in the gap with",
"// a straight line from `_lastValue` all the way to `t1` ",
"}",
"else",
"{",
"line",
"=",
"{",
"t1",
":",
"0",
",",
"v1",
":",
"this",
".",
"_lastValue",
",",
"t2",
":",
"t1",
",",
"v2",
":",
"this",
".",
"_lastValue",
"}",
"newLines",
".",
"push",
"(",
"line",
")",
"this",
".",
"_queue",
".",
"push",
"(",
"line",
")",
"}",
"// Finally create the line and add it to the queue",
"line",
"=",
"{",
"t1",
":",
"t1",
",",
"v1",
":",
"this",
".",
"_queue",
"[",
"this",
".",
"_queue",
".",
"length",
"-",
"1",
"]",
".",
"v2",
",",
"t2",
":",
"t1",
"+",
"duration",
",",
"v2",
":",
"v2",
"}",
"newLines",
".",
"push",
"(",
"line",
")",
"this",
".",
"_queue",
".",
"push",
"(",
"line",
")",
"return",
"newLines",
"}"
] |
push a line to the queue, overriding the lines that were after it, and creating new lines if interrupting something in its middle.
|
[
"push",
"a",
"line",
"to",
"the",
"queue",
"overriding",
"the",
"lines",
"that",
"were",
"after",
"it",
"and",
"creating",
"new",
"lines",
"if",
"interrupting",
"something",
"in",
"its",
"middle",
"."
] |
2c922bd2c792e13b37c93f4fcf7ada344603e09d
|
https://github.com/sebpiq/WebPd/blob/2c922bd2c792e13b37c93f4fcf7ada344603e09d/lib/waa/dsp.js#L328-L378
|
|
18,406
|
sebpiq/WebPd
|
lib/core/utils.js
|
function(array, ind) {
if (ind >= array.length || ind < 0)
throw new Error('$' + (ind + 1) + ': argument number out of range')
return array[ind]
}
|
javascript
|
function(array, ind) {
if (ind >= array.length || ind < 0)
throw new Error('$' + (ind + 1) + ': argument number out of range')
return array[ind]
}
|
[
"function",
"(",
"array",
",",
"ind",
")",
"{",
"if",
"(",
"ind",
">=",
"array",
".",
"length",
"||",
"ind",
"<",
"0",
")",
"throw",
"new",
"Error",
"(",
"'$'",
"+",
"(",
"ind",
"+",
"1",
")",
"+",
"': argument number out of range'",
")",
"return",
"array",
"[",
"ind",
"]",
"}"
] |
Simple helper to throw en error if the index is out of range
|
[
"Simple",
"helper",
"to",
"throw",
"en",
"error",
"if",
"the",
"index",
"is",
"out",
"of",
"range"
] |
2c922bd2c792e13b37c93f4fcf7ada344603e09d
|
https://github.com/sebpiq/WebPd/blob/2c922bd2c792e13b37c93f4fcf7ada344603e09d/lib/core/utils.js#L38-L42
|
|
18,407
|
sebpiq/WebPd
|
lib/global.js
|
function(obj, type, name, nameIsUnique, oldName) {
var nameMap, objList
this._store[type] = nameMap = this._store[type] || {}
nameMap[name] = objList = nameMap[name] || []
// Adding new mapping
if (objList.indexOf(obj) === -1) {
if (nameIsUnique && objList.length > 0)
throw new Error('there is already a ' + type + ' with name "' + name + '"')
objList.push(obj)
}
// Removing old mapping
if (oldName) {
objList = nameMap[oldName]
objList.splice(objList.indexOf(obj), 1)
}
exports.emitter.emit('namedObjects:registered:' + type, obj)
}
|
javascript
|
function(obj, type, name, nameIsUnique, oldName) {
var nameMap, objList
this._store[type] = nameMap = this._store[type] || {}
nameMap[name] = objList = nameMap[name] || []
// Adding new mapping
if (objList.indexOf(obj) === -1) {
if (nameIsUnique && objList.length > 0)
throw new Error('there is already a ' + type + ' with name "' + name + '"')
objList.push(obj)
}
// Removing old mapping
if (oldName) {
objList = nameMap[oldName]
objList.splice(objList.indexOf(obj), 1)
}
exports.emitter.emit('namedObjects:registered:' + type, obj)
}
|
[
"function",
"(",
"obj",
",",
"type",
",",
"name",
",",
"nameIsUnique",
",",
"oldName",
")",
"{",
"var",
"nameMap",
",",
"objList",
"this",
".",
"_store",
"[",
"type",
"]",
"=",
"nameMap",
"=",
"this",
".",
"_store",
"[",
"type",
"]",
"||",
"{",
"}",
"nameMap",
"[",
"name",
"]",
"=",
"objList",
"=",
"nameMap",
"[",
"name",
"]",
"||",
"[",
"]",
"// Adding new mapping",
"if",
"(",
"objList",
".",
"indexOf",
"(",
"obj",
")",
"===",
"-",
"1",
")",
"{",
"if",
"(",
"nameIsUnique",
"&&",
"objList",
".",
"length",
">",
"0",
")",
"throw",
"new",
"Error",
"(",
"'there is already a '",
"+",
"type",
"+",
"' with name \"'",
"+",
"name",
"+",
"'\"'",
")",
"objList",
".",
"push",
"(",
"obj",
")",
"}",
"// Removing old mapping",
"if",
"(",
"oldName",
")",
"{",
"objList",
"=",
"nameMap",
"[",
"oldName",
"]",
"objList",
".",
"splice",
"(",
"objList",
".",
"indexOf",
"(",
"obj",
")",
",",
"1",
")",
"}",
"exports",
".",
"emitter",
".",
"emit",
"(",
"'namedObjects:registered:'",
"+",
"type",
",",
"obj",
")",
"}"
] |
Registers a named object in the store.
|
[
"Registers",
"a",
"named",
"object",
"in",
"the",
"store",
"."
] |
2c922bd2c792e13b37c93f4fcf7ada344603e09d
|
https://github.com/sebpiq/WebPd/blob/2c922bd2c792e13b37c93f4fcf7ada344603e09d/lib/global.js#L82-L102
|
|
18,408
|
sebpiq/WebPd
|
lib/global.js
|
function(obj, type, name) {
var nameMap = this._store[type]
, objList = nameMap ? nameMap[name] : null
, ind
if (!objList) return
ind = objList.indexOf(obj)
if (ind === -1) return
objList.splice(ind, 1)
exports.emitter.emit('namedObjects:unregistered:' + type, obj)
}
|
javascript
|
function(obj, type, name) {
var nameMap = this._store[type]
, objList = nameMap ? nameMap[name] : null
, ind
if (!objList) return
ind = objList.indexOf(obj)
if (ind === -1) return
objList.splice(ind, 1)
exports.emitter.emit('namedObjects:unregistered:' + type, obj)
}
|
[
"function",
"(",
"obj",
",",
"type",
",",
"name",
")",
"{",
"var",
"nameMap",
"=",
"this",
".",
"_store",
"[",
"type",
"]",
",",
"objList",
"=",
"nameMap",
"?",
"nameMap",
"[",
"name",
"]",
":",
"null",
",",
"ind",
"if",
"(",
"!",
"objList",
")",
"return",
"ind",
"=",
"objList",
".",
"indexOf",
"(",
"obj",
")",
"if",
"(",
"ind",
"===",
"-",
"1",
")",
"return",
"objList",
".",
"splice",
"(",
"ind",
",",
"1",
")",
"exports",
".",
"emitter",
".",
"emit",
"(",
"'namedObjects:unregistered:'",
"+",
"type",
",",
"obj",
")",
"}"
] |
Unregisters a named object from the store
|
[
"Unregisters",
"a",
"named",
"object",
"from",
"the",
"store"
] |
2c922bd2c792e13b37c93f4fcf7ada344603e09d
|
https://github.com/sebpiq/WebPd/blob/2c922bd2c792e13b37c93f4fcf7ada344603e09d/lib/global.js#L105-L114
|
|
18,409
|
sebpiq/WebPd
|
lib/glue.js
|
function(rate) {
if (!_.isNumber(rate))
return console.error('invalid [metro] rate ' + rate)
this.rate = Math.max(rate, 1)
}
|
javascript
|
function(rate) {
if (!_.isNumber(rate))
return console.error('invalid [metro] rate ' + rate)
this.rate = Math.max(rate, 1)
}
|
[
"function",
"(",
"rate",
")",
"{",
"if",
"(",
"!",
"_",
".",
"isNumber",
"(",
"rate",
")",
")",
"return",
"console",
".",
"error",
"(",
"'invalid [metro] rate '",
"+",
"rate",
")",
"this",
".",
"rate",
"=",
"Math",
".",
"max",
"(",
"rate",
",",
"1",
")",
"}"
] |
Metronome rate, in ms per tick
|
[
"Metronome",
"rate",
"in",
"ms",
"per",
"tick"
] |
2c922bd2c792e13b37c93f4fcf7ada344603e09d
|
https://github.com/sebpiq/WebPd/blob/2c922bd2c792e13b37c93f4fcf7ada344603e09d/lib/glue.js#L894-L898
|
|
18,410
|
adzialocha/osc-js
|
src/atomic/string.js
|
charCodesToString
|
function charCodesToString(charCodes) {
// Use these methods to be able to convert large strings
if (hasProperty('Buffer')) {
return Buffer.from(charCodes).toString(STR_ENCODING)
} else if (hasProperty('TextDecoder')) {
return new TextDecoder(STR_ENCODING) // eslint-disable-line no-undef
.decode(new Int8Array(charCodes))
}
// Fallback method
let str = ''
for (let i = 0; i < charCodes.length; i += STR_SLICE_SIZE) {
str += String.fromCharCode.apply(
null,
charCodes.slice(i, i + STR_SLICE_SIZE)
)
}
return str
}
|
javascript
|
function charCodesToString(charCodes) {
// Use these methods to be able to convert large strings
if (hasProperty('Buffer')) {
return Buffer.from(charCodes).toString(STR_ENCODING)
} else if (hasProperty('TextDecoder')) {
return new TextDecoder(STR_ENCODING) // eslint-disable-line no-undef
.decode(new Int8Array(charCodes))
}
// Fallback method
let str = ''
for (let i = 0; i < charCodes.length; i += STR_SLICE_SIZE) {
str += String.fromCharCode.apply(
null,
charCodes.slice(i, i + STR_SLICE_SIZE)
)
}
return str
}
|
[
"function",
"charCodesToString",
"(",
"charCodes",
")",
"{",
"// Use these methods to be able to convert large strings",
"if",
"(",
"hasProperty",
"(",
"'Buffer'",
")",
")",
"{",
"return",
"Buffer",
".",
"from",
"(",
"charCodes",
")",
".",
"toString",
"(",
"STR_ENCODING",
")",
"}",
"else",
"if",
"(",
"hasProperty",
"(",
"'TextDecoder'",
")",
")",
"{",
"return",
"new",
"TextDecoder",
"(",
"STR_ENCODING",
")",
"// eslint-disable-line no-undef",
".",
"decode",
"(",
"new",
"Int8Array",
"(",
"charCodes",
")",
")",
"}",
"// Fallback method",
"let",
"str",
"=",
"''",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"charCodes",
".",
"length",
";",
"i",
"+=",
"STR_SLICE_SIZE",
")",
"{",
"str",
"+=",
"String",
".",
"fromCharCode",
".",
"apply",
"(",
"null",
",",
"charCodes",
".",
"slice",
"(",
"i",
",",
"i",
"+",
"STR_SLICE_SIZE",
")",
")",
"}",
"return",
"str",
"}"
] |
Helper method to decode a string using different methods depending on environment
@param {array} charCodes Array of char codes
@return {string} Decoded string
|
[
"Helper",
"method",
"to",
"decode",
"a",
"string",
"using",
"different",
"methods",
"depending",
"on",
"environment"
] |
40bde51c865657ad3386cbb8780c8644e21f1244
|
https://github.com/adzialocha/osc-js/blob/40bde51c865657ad3386cbb8780c8644e21f1244/src/atomic/string.js#L21-L41
|
18,411
|
OpenTriply/YASGUI.YASQE
|
src/tooltip.js
|
function() {
if ($(yasqe.getWrapperElement()).offset().top >= tooltip.offset().top) {
//shit, move the tooltip down. The tooltip now hovers over the top edge of the yasqe instance
tooltip.css("bottom", "auto");
tooltip.css("top", "26px");
}
}
|
javascript
|
function() {
if ($(yasqe.getWrapperElement()).offset().top >= tooltip.offset().top) {
//shit, move the tooltip down. The tooltip now hovers over the top edge of the yasqe instance
tooltip.css("bottom", "auto");
tooltip.css("top", "26px");
}
}
|
[
"function",
"(",
")",
"{",
"if",
"(",
"$",
"(",
"yasqe",
".",
"getWrapperElement",
"(",
")",
")",
".",
"offset",
"(",
")",
".",
"top",
">=",
"tooltip",
".",
"offset",
"(",
")",
".",
"top",
")",
"{",
"//shit, move the tooltip down. The tooltip now hovers over the top edge of the yasqe instance",
"tooltip",
".",
"css",
"(",
"\"bottom\"",
",",
"\"auto\"",
")",
";",
"tooltip",
".",
"css",
"(",
"\"top\"",
",",
"\"26px\"",
")",
";",
"}",
"}"
] |
only need to take into account top and bottom offset for this usecase
|
[
"only",
"need",
"to",
"take",
"into",
"account",
"top",
"and",
"bottom",
"offset",
"for",
"this",
"usecase"
] |
05bb14dba3a45a750281fb29d6f6738ddecbb1dc
|
https://github.com/OpenTriply/YASGUI.YASQE/blob/05bb14dba3a45a750281fb29d6f6738ddecbb1dc/src/tooltip.js#L27-L33
|
|
18,412
|
OpenTriply/YASGUI.YASQE
|
lib/grammar/tokenizer.js
|
setSideConditions
|
function setSideConditions(topSymbol) {
if (topSymbol === "prefixDecl") {
state.inPrefixDecl = true;
} else {
state.inPrefixDecl = false;
}
switch (topSymbol) {
case "disallowVars":
state.allowVars = false;
break;
case "allowVars":
state.allowVars = true;
break;
case "disallowBnodes":
state.allowBnodes = false;
break;
case "allowBnodes":
state.allowBnodes = true;
break;
case "storeProperty":
state.storeProperty = true;
break;
}
}
|
javascript
|
function setSideConditions(topSymbol) {
if (topSymbol === "prefixDecl") {
state.inPrefixDecl = true;
} else {
state.inPrefixDecl = false;
}
switch (topSymbol) {
case "disallowVars":
state.allowVars = false;
break;
case "allowVars":
state.allowVars = true;
break;
case "disallowBnodes":
state.allowBnodes = false;
break;
case "allowBnodes":
state.allowBnodes = true;
break;
case "storeProperty":
state.storeProperty = true;
break;
}
}
|
[
"function",
"setSideConditions",
"(",
"topSymbol",
")",
"{",
"if",
"(",
"topSymbol",
"===",
"\"prefixDecl\"",
")",
"{",
"state",
".",
"inPrefixDecl",
"=",
"true",
";",
"}",
"else",
"{",
"state",
".",
"inPrefixDecl",
"=",
"false",
";",
"}",
"switch",
"(",
"topSymbol",
")",
"{",
"case",
"\"disallowVars\"",
":",
"state",
".",
"allowVars",
"=",
"false",
";",
"break",
";",
"case",
"\"allowVars\"",
":",
"state",
".",
"allowVars",
"=",
"true",
";",
"break",
";",
"case",
"\"disallowBnodes\"",
":",
"state",
".",
"allowBnodes",
"=",
"false",
";",
"break",
";",
"case",
"\"allowBnodes\"",
":",
"state",
".",
"allowBnodes",
"=",
"true",
";",
"break",
";",
"case",
"\"storeProperty\"",
":",
"state",
".",
"storeProperty",
"=",
"true",
";",
"break",
";",
"}",
"}"
] |
Some fake non-terminals are just there to have side-effect on state - i.e. allow or disallow variables and bnodes in certain non-nesting contexts
|
[
"Some",
"fake",
"non",
"-",
"terminals",
"are",
"just",
"there",
"to",
"have",
"side",
"-",
"effect",
"on",
"state",
"-",
"i",
".",
"e",
".",
"allow",
"or",
"disallow",
"variables",
"and",
"bnodes",
"in",
"certain",
"non",
"-",
"nesting",
"contexts"
] |
05bb14dba3a45a750281fb29d6f6738ddecbb1dc
|
https://github.com/OpenTriply/YASGUI.YASQE/blob/05bb14dba3a45a750281fb29d6f6738ddecbb1dc/lib/grammar/tokenizer.js#L418-L441
|
18,413
|
OpenTriply/YASGUI.YASQE
|
src/main.js
|
function(yasqe) {
yasqe.cursor = $(".CodeMirror-cursor");
if (yasqe.buttons && yasqe.buttons.is(":visible") && yasqe.cursor.length > 0) {
if (utils.elementsOverlap(yasqe.cursor, yasqe.buttons)) {
yasqe.buttons.find("svg").attr("opacity", "0.2");
} else {
yasqe.buttons.find("svg").attr("opacity", "1.0");
}
}
}
|
javascript
|
function(yasqe) {
yasqe.cursor = $(".CodeMirror-cursor");
if (yasqe.buttons && yasqe.buttons.is(":visible") && yasqe.cursor.length > 0) {
if (utils.elementsOverlap(yasqe.cursor, yasqe.buttons)) {
yasqe.buttons.find("svg").attr("opacity", "0.2");
} else {
yasqe.buttons.find("svg").attr("opacity", "1.0");
}
}
}
|
[
"function",
"(",
"yasqe",
")",
"{",
"yasqe",
".",
"cursor",
"=",
"$",
"(",
"\".CodeMirror-cursor\"",
")",
";",
"if",
"(",
"yasqe",
".",
"buttons",
"&&",
"yasqe",
".",
"buttons",
".",
"is",
"(",
"\":visible\"",
")",
"&&",
"yasqe",
".",
"cursor",
".",
"length",
">",
"0",
")",
"{",
"if",
"(",
"utils",
".",
"elementsOverlap",
"(",
"yasqe",
".",
"cursor",
",",
"yasqe",
".",
"buttons",
")",
")",
"{",
"yasqe",
".",
"buttons",
".",
"find",
"(",
"\"svg\"",
")",
".",
"attr",
"(",
"\"opacity\"",
",",
"\"0.2\"",
")",
";",
"}",
"else",
"{",
"yasqe",
".",
"buttons",
".",
"find",
"(",
"\"svg\"",
")",
".",
"attr",
"(",
"\"opacity\"",
",",
"\"1.0\"",
")",
";",
"}",
"}",
"}"
] |
Update transparency of buttons. Increase transparency when cursor is below buttons
|
[
"Update",
"transparency",
"of",
"buttons",
".",
"Increase",
"transparency",
"when",
"cursor",
"is",
"below",
"buttons"
] |
05bb14dba3a45a750281fb29d6f6738ddecbb1dc
|
https://github.com/OpenTriply/YASGUI.YASQE/blob/05bb14dba3a45a750281fb29d6f6738ddecbb1dc/src/main.js#L376-L385
|
|
18,414
|
slushjs/slush
|
bin/slush.js
|
formatError
|
function formatError(e) {
if (!e.err) return e.message;
if (e.err.message) return e.err.message;
return JSON.stringify(e.err);
}
|
javascript
|
function formatError(e) {
if (!e.err) return e.message;
if (e.err.message) return e.err.message;
return JSON.stringify(e.err);
}
|
[
"function",
"formatError",
"(",
"e",
")",
"{",
"if",
"(",
"!",
"e",
".",
"err",
")",
"return",
"e",
".",
"message",
";",
"if",
"(",
"e",
".",
"err",
".",
"message",
")",
"return",
"e",
".",
"err",
".",
"message",
";",
"return",
"JSON",
".",
"stringify",
"(",
"e",
".",
"err",
")",
";",
"}"
] |
format orchestrator errors
|
[
"format",
"orchestrator",
"errors"
] |
771835e9b0a2f04c005a38a9fb3cb9ab53acfdd2
|
https://github.com/slushjs/slush/blob/771835e9b0a2f04c005a38a9fb3cb9ab53acfdd2/bin/slush.js#L133-L137
|
18,415
|
cnguy/kayn
|
examples/es5/v4/grabbing-matches-by-champions-out-of-a-ranked-match-list.js
|
main
|
function main(kayn) {
const config = {
query: 420,
champion: 67,
season: 7,
}
kayn.Summoner.by.name('Contractz').callback(function(error, summoner) {
// Note that the grabbing of a matchlist is currently limited by pagination.
// This API request only returns the first list.
kayn.Matchlist.by
.accountID(summoner.accountId)
.region('na')
.query(config)
.callback(function(error, matchlist) {
console.log(matchlist.totalGames, matchlist.matches.length)
})
})
}
|
javascript
|
function main(kayn) {
const config = {
query: 420,
champion: 67,
season: 7,
}
kayn.Summoner.by.name('Contractz').callback(function(error, summoner) {
// Note that the grabbing of a matchlist is currently limited by pagination.
// This API request only returns the first list.
kayn.Matchlist.by
.accountID(summoner.accountId)
.region('na')
.query(config)
.callback(function(error, matchlist) {
console.log(matchlist.totalGames, matchlist.matches.length)
})
})
}
|
[
"function",
"main",
"(",
"kayn",
")",
"{",
"const",
"config",
"=",
"{",
"query",
":",
"420",
",",
"champion",
":",
"67",
",",
"season",
":",
"7",
",",
"}",
"kayn",
".",
"Summoner",
".",
"by",
".",
"name",
"(",
"'Contractz'",
")",
".",
"callback",
"(",
"function",
"(",
"error",
",",
"summoner",
")",
"{",
"// Note that the grabbing of a matchlist is currently limited by pagination.",
"// This API request only returns the first list.",
"kayn",
".",
"Matchlist",
".",
"by",
".",
"accountID",
"(",
"summoner",
".",
"accountId",
")",
".",
"region",
"(",
"'na'",
")",
".",
"query",
"(",
"config",
")",
".",
"callback",
"(",
"function",
"(",
"error",
",",
"matchlist",
")",
"{",
"console",
".",
"log",
"(",
"matchlist",
".",
"totalGames",
",",
"matchlist",
".",
"matches",
".",
"length",
")",
"}",
")",
"}",
")",
"}"
] |
Out of a player's ranked matchlist, grabs every match where they played a certain champion.
|
[
"Out",
"of",
"a",
"player",
"s",
"ranked",
"matchlist",
"grabs",
"every",
"match",
"where",
"they",
"played",
"a",
"certain",
"champion",
"."
] |
7af0f347b274f626eafe56ca60fa2805abf6c7cb
|
https://github.com/cnguy/kayn/blob/7af0f347b274f626eafe56ca60fa2805abf6c7cb/examples/es5/v4/grabbing-matches-by-champions-out-of-a-ranked-match-list.js#L3-L21
|
18,416
|
micromatch/to-regex-range
|
index.js
|
rangeToPattern
|
function rangeToPattern(start, stop, options) {
if (start === stop) {
return { pattern: start, count: [], digits: 0 };
}
let zipped = zip(start, stop);
let digits = zipped.length;
let pattern = '';
let count = 0;
for (let i = 0; i < digits; i++) {
let [startDigit, stopDigit] = zipped[i];
if (startDigit === stopDigit) {
pattern += startDigit;
} else if (startDigit !== '0' || stopDigit !== '9') {
pattern += toCharacterClass(startDigit, stopDigit, options);
} else {
count++;
}
}
if (count) {
pattern += options.shorthand === true ? '\\d' : '[0-9]';
}
return { pattern, count: [count], digits };
}
|
javascript
|
function rangeToPattern(start, stop, options) {
if (start === stop) {
return { pattern: start, count: [], digits: 0 };
}
let zipped = zip(start, stop);
let digits = zipped.length;
let pattern = '';
let count = 0;
for (let i = 0; i < digits; i++) {
let [startDigit, stopDigit] = zipped[i];
if (startDigit === stopDigit) {
pattern += startDigit;
} else if (startDigit !== '0' || stopDigit !== '9') {
pattern += toCharacterClass(startDigit, stopDigit, options);
} else {
count++;
}
}
if (count) {
pattern += options.shorthand === true ? '\\d' : '[0-9]';
}
return { pattern, count: [count], digits };
}
|
[
"function",
"rangeToPattern",
"(",
"start",
",",
"stop",
",",
"options",
")",
"{",
"if",
"(",
"start",
"===",
"stop",
")",
"{",
"return",
"{",
"pattern",
":",
"start",
",",
"count",
":",
"[",
"]",
",",
"digits",
":",
"0",
"}",
";",
"}",
"let",
"zipped",
"=",
"zip",
"(",
"start",
",",
"stop",
")",
";",
"let",
"digits",
"=",
"zipped",
".",
"length",
";",
"let",
"pattern",
"=",
"''",
";",
"let",
"count",
"=",
"0",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"digits",
";",
"i",
"++",
")",
"{",
"let",
"[",
"startDigit",
",",
"stopDigit",
"]",
"=",
"zipped",
"[",
"i",
"]",
";",
"if",
"(",
"startDigit",
"===",
"stopDigit",
")",
"{",
"pattern",
"+=",
"startDigit",
";",
"}",
"else",
"if",
"(",
"startDigit",
"!==",
"'0'",
"||",
"stopDigit",
"!==",
"'9'",
")",
"{",
"pattern",
"+=",
"toCharacterClass",
"(",
"startDigit",
",",
"stopDigit",
",",
"options",
")",
";",
"}",
"else",
"{",
"count",
"++",
";",
"}",
"}",
"if",
"(",
"count",
")",
"{",
"pattern",
"+=",
"options",
".",
"shorthand",
"===",
"true",
"?",
"'\\\\d'",
":",
"'[0-9]'",
";",
"}",
"return",
"{",
"pattern",
",",
"count",
":",
"[",
"count",
"]",
",",
"digits",
"}",
";",
"}"
] |
Convert a range to a regex pattern
@param {Number} `start`
@param {Number} `stop`
@return {String}
|
[
"Convert",
"a",
"range",
"to",
"a",
"regex",
"pattern"
] |
1191a52afa82f52983e684ceeb8f8d3a150fa881
|
https://github.com/micromatch/to-regex-range/blob/1191a52afa82f52983e684ceeb8f8d3a150fa881/index.js#L129-L158
|
18,417
|
bem/html-differ
|
lib/logger.js
|
logDiffText
|
function logDiffText(diff, options) {
var diffText = getDiffText(diff, options);
if (diffText) {
console.log(inverseGreen('+ expected'), inverseRed('- actual'), '\n', diffText);
}
}
|
javascript
|
function logDiffText(diff, options) {
var diffText = getDiffText(diff, options);
if (diffText) {
console.log(inverseGreen('+ expected'), inverseRed('- actual'), '\n', diffText);
}
}
|
[
"function",
"logDiffText",
"(",
"diff",
",",
"options",
")",
"{",
"var",
"diffText",
"=",
"getDiffText",
"(",
"diff",
",",
"options",
")",
";",
"if",
"(",
"diffText",
")",
"{",
"console",
".",
"log",
"(",
"inverseGreen",
"(",
"'+ expected'",
")",
",",
"inverseRed",
"(",
"'- actual'",
")",
",",
"'\\n'",
",",
"diffText",
")",
";",
"}",
"}"
] |
Logs the diff of the given HTML docs to the console
@param {Object[]} diff
@param {Object} [options]
@param {Number} [options.charsAroundDiff=40]
|
[
"Logs",
"the",
"diff",
"of",
"the",
"given",
"HTML",
"docs",
"to",
"the",
"console"
] |
b3e83da780b2b2dad9c4b886e362acfe986e38be
|
https://github.com/bem/html-differ/blob/b3e83da780b2b2dad9c4b886e362acfe986e38be/lib/logger.js#L68-L74
|
18,418
|
bem/html-differ
|
lib/utils/mask.js
|
_concatNotDiffParts
|
function _concatNotDiffParts(diff) {
for (var i = 1; i < diff.length; i++) {
var currPart = diff[i],
prevPart = diff[i - 1];
if (!_isDiffPart(currPart) && !_isDiffPart(prevPart)) {
prevPart.value += currPart.value;
diff.splice(i--, 1);
}
}
return diff;
}
|
javascript
|
function _concatNotDiffParts(diff) {
for (var i = 1; i < diff.length; i++) {
var currPart = diff[i],
prevPart = diff[i - 1];
if (!_isDiffPart(currPart) && !_isDiffPart(prevPart)) {
prevPart.value += currPart.value;
diff.splice(i--, 1);
}
}
return diff;
}
|
[
"function",
"_concatNotDiffParts",
"(",
"diff",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"1",
";",
"i",
"<",
"diff",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"currPart",
"=",
"diff",
"[",
"i",
"]",
",",
"prevPart",
"=",
"diff",
"[",
"i",
"-",
"1",
"]",
";",
"if",
"(",
"!",
"_isDiffPart",
"(",
"currPart",
")",
"&&",
"!",
"_isDiffPart",
"(",
"prevPart",
")",
")",
"{",
"prevPart",
".",
"value",
"+=",
"currPart",
".",
"value",
";",
"diff",
".",
"splice",
"(",
"i",
"--",
",",
"1",
")",
";",
"}",
"}",
"return",
"diff",
";",
"}"
] |
Concats not diff parts which go one by one
@param {Diff[]} diff
@returns {Diff[]}
|
[
"Concats",
"not",
"diff",
"parts",
"which",
"go",
"one",
"by",
"one"
] |
b3e83da780b2b2dad9c4b886e362acfe986e38be
|
https://github.com/bem/html-differ/blob/b3e83da780b2b2dad9c4b886e362acfe986e38be/lib/utils/mask.js#L62-L75
|
18,419
|
bem/html-differ
|
lib/utils/modify.js
|
modify
|
function modify(value, options) {
var modifiedValue = '',
parser;
parser = new SimpleApiParser({
/**
* @param {String} name
* @param {String} publicId
* @param {String} systemId
*/
doctype: function (name, publicId, systemId) {
modifiedValue += serialize.doctype(name, publicId, systemId);
},
/**
* @param {String} tagName
* @param {Array} attrs
* @param {Boolean} selfClosing
*/
startTag: function (tagName, attrs, selfClosing) {
if (options.ignoreDuplicateAttributes) {
attrs = utils.removeDuplicateAttributes(attrs);
}
attrs = utils.sortAttrs(attrs) &&
utils.sortCssClasses(attrs) &&
utils.sortAttrsValues(attrs, options.compareAttributesAsJSON) &&
utils.removeAttrsValues(attrs, options.ignoreAttributes);
modifiedValue += serialize.startTag(tagName, attrs, selfClosing);
},
/**
* @param {String} tagName
*/
endTag: function (tagName) {
!options.ignoreEndTags && (modifiedValue += serialize.endTag(tagName));
},
/**
* @param {String} text
*/
text: function (text) {
options.ignoreWhitespaces && (text = utils.removeWhitespaces(text));
modifiedValue += serialize.text(text);
},
/**
* @param {String} comment
*/
comment: function (comment) {
var conditionalComment = utils.getConditionalComment(comment, modify, options);
if (conditionalComment) {
modifiedValue += serialize.comment(conditionalComment);
} else if (!options.ignoreComments) {
modifiedValue += serialize.comment(comment);
}
}
});
// Makes 'parse5' handle duplicate attributes
parser._reset = function (html) {
SimpleApiParser.prototype._reset.call(this, html);
this.tokenizerProxy.tokenizer._isDuplicateAttr = function () {
return false;
};
};
parser.parse(value);
return modifiedValue;
}
|
javascript
|
function modify(value, options) {
var modifiedValue = '',
parser;
parser = new SimpleApiParser({
/**
* @param {String} name
* @param {String} publicId
* @param {String} systemId
*/
doctype: function (name, publicId, systemId) {
modifiedValue += serialize.doctype(name, publicId, systemId);
},
/**
* @param {String} tagName
* @param {Array} attrs
* @param {Boolean} selfClosing
*/
startTag: function (tagName, attrs, selfClosing) {
if (options.ignoreDuplicateAttributes) {
attrs = utils.removeDuplicateAttributes(attrs);
}
attrs = utils.sortAttrs(attrs) &&
utils.sortCssClasses(attrs) &&
utils.sortAttrsValues(attrs, options.compareAttributesAsJSON) &&
utils.removeAttrsValues(attrs, options.ignoreAttributes);
modifiedValue += serialize.startTag(tagName, attrs, selfClosing);
},
/**
* @param {String} tagName
*/
endTag: function (tagName) {
!options.ignoreEndTags && (modifiedValue += serialize.endTag(tagName));
},
/**
* @param {String} text
*/
text: function (text) {
options.ignoreWhitespaces && (text = utils.removeWhitespaces(text));
modifiedValue += serialize.text(text);
},
/**
* @param {String} comment
*/
comment: function (comment) {
var conditionalComment = utils.getConditionalComment(comment, modify, options);
if (conditionalComment) {
modifiedValue += serialize.comment(conditionalComment);
} else if (!options.ignoreComments) {
modifiedValue += serialize.comment(comment);
}
}
});
// Makes 'parse5' handle duplicate attributes
parser._reset = function (html) {
SimpleApiParser.prototype._reset.call(this, html);
this.tokenizerProxy.tokenizer._isDuplicateAttr = function () {
return false;
};
};
parser.parse(value);
return modifiedValue;
}
|
[
"function",
"modify",
"(",
"value",
",",
"options",
")",
"{",
"var",
"modifiedValue",
"=",
"''",
",",
"parser",
";",
"parser",
"=",
"new",
"SimpleApiParser",
"(",
"{",
"/**\n * @param {String} name\n * @param {String} publicId\n * @param {String} systemId\n */",
"doctype",
":",
"function",
"(",
"name",
",",
"publicId",
",",
"systemId",
")",
"{",
"modifiedValue",
"+=",
"serialize",
".",
"doctype",
"(",
"name",
",",
"publicId",
",",
"systemId",
")",
";",
"}",
",",
"/**\n * @param {String} tagName\n * @param {Array} attrs\n * @param {Boolean} selfClosing\n */",
"startTag",
":",
"function",
"(",
"tagName",
",",
"attrs",
",",
"selfClosing",
")",
"{",
"if",
"(",
"options",
".",
"ignoreDuplicateAttributes",
")",
"{",
"attrs",
"=",
"utils",
".",
"removeDuplicateAttributes",
"(",
"attrs",
")",
";",
"}",
"attrs",
"=",
"utils",
".",
"sortAttrs",
"(",
"attrs",
")",
"&&",
"utils",
".",
"sortCssClasses",
"(",
"attrs",
")",
"&&",
"utils",
".",
"sortAttrsValues",
"(",
"attrs",
",",
"options",
".",
"compareAttributesAsJSON",
")",
"&&",
"utils",
".",
"removeAttrsValues",
"(",
"attrs",
",",
"options",
".",
"ignoreAttributes",
")",
";",
"modifiedValue",
"+=",
"serialize",
".",
"startTag",
"(",
"tagName",
",",
"attrs",
",",
"selfClosing",
")",
";",
"}",
",",
"/**\n * @param {String} tagName\n */",
"endTag",
":",
"function",
"(",
"tagName",
")",
"{",
"!",
"options",
".",
"ignoreEndTags",
"&&",
"(",
"modifiedValue",
"+=",
"serialize",
".",
"endTag",
"(",
"tagName",
")",
")",
";",
"}",
",",
"/**\n * @param {String} text\n */",
"text",
":",
"function",
"(",
"text",
")",
"{",
"options",
".",
"ignoreWhitespaces",
"&&",
"(",
"text",
"=",
"utils",
".",
"removeWhitespaces",
"(",
"text",
")",
")",
";",
"modifiedValue",
"+=",
"serialize",
".",
"text",
"(",
"text",
")",
";",
"}",
",",
"/**\n * @param {String} comment\n */",
"comment",
":",
"function",
"(",
"comment",
")",
"{",
"var",
"conditionalComment",
"=",
"utils",
".",
"getConditionalComment",
"(",
"comment",
",",
"modify",
",",
"options",
")",
";",
"if",
"(",
"conditionalComment",
")",
"{",
"modifiedValue",
"+=",
"serialize",
".",
"comment",
"(",
"conditionalComment",
")",
";",
"}",
"else",
"if",
"(",
"!",
"options",
".",
"ignoreComments",
")",
"{",
"modifiedValue",
"+=",
"serialize",
".",
"comment",
"(",
"comment",
")",
";",
"}",
"}",
"}",
")",
";",
"// Makes 'parse5' handle duplicate attributes",
"parser",
".",
"_reset",
"=",
"function",
"(",
"html",
")",
"{",
"SimpleApiParser",
".",
"prototype",
".",
"_reset",
".",
"call",
"(",
"this",
",",
"html",
")",
";",
"this",
".",
"tokenizerProxy",
".",
"tokenizer",
".",
"_isDuplicateAttr",
"=",
"function",
"(",
")",
"{",
"return",
"false",
";",
"}",
";",
"}",
";",
"parser",
".",
"parse",
"(",
"value",
")",
";",
"return",
"modifiedValue",
";",
"}"
] |
Parses the given HTML and modifies it according to the given options
@param {String} value
@param {Object} [options]
@param {String[]} [options.ignoreAttributes]
@param {String[]} [options.compareAttributesAsJSON]
@param {Boolean} [options.ignoreWhitespaces=true]
@param {Boolean} [options.ignoreComments=true]
@param {Boolean} [options.ignoreEndTags=false]
@param {Boolean} [options.ignoreDuplicateAttributes=false]
returns {String}
|
[
"Parses",
"the",
"given",
"HTML",
"and",
"modifies",
"it",
"according",
"to",
"the",
"given",
"options"
] |
b3e83da780b2b2dad9c4b886e362acfe986e38be
|
https://github.com/bem/html-differ/blob/b3e83da780b2b2dad9c4b886e362acfe986e38be/lib/utils/modify.js#L17-L86
|
18,420
|
bem/html-differ
|
lib/utils/utils.js
|
_getIndexesInArray
|
function _getIndexesInArray(attrs, attr) {
var res = [];
for (var i = 0; i < attrs.length; i++) {
if (attrs[i].name === attr) res.push(i);
}
return res;
}
|
javascript
|
function _getIndexesInArray(attrs, attr) {
var res = [];
for (var i = 0; i < attrs.length; i++) {
if (attrs[i].name === attr) res.push(i);
}
return res;
}
|
[
"function",
"_getIndexesInArray",
"(",
"attrs",
",",
"attr",
")",
"{",
"var",
"res",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"attrs",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"attrs",
"[",
"i",
"]",
".",
"name",
"===",
"attr",
")",
"res",
".",
"push",
"(",
"i",
")",
";",
"}",
"return",
"res",
";",
"}"
] |
Gets the attribute's indexes in the array of the attributes
@param {Array} attrs
@param {String} attr
@returns {Array}
|
[
"Gets",
"the",
"attribute",
"s",
"indexes",
"in",
"the",
"array",
"of",
"the",
"attributes"
] |
b3e83da780b2b2dad9c4b886e362acfe986e38be
|
https://github.com/bem/html-differ/blob/b3e83da780b2b2dad9c4b886e362acfe986e38be/lib/utils/utils.js#L9-L17
|
18,421
|
bem/html-differ
|
lib/utils/utils.js
|
sortAttrs
|
function sortAttrs(attrs) {
return attrs.sort(function (a, b) {
if (a.name < b.name) {
return -1;
} else if (a.name > b.name) {
return 1;
} else if (a.value < b.value) {
return -1;
} else if (a.value > b.value) {
return 1;
}
return 0;
});
}
|
javascript
|
function sortAttrs(attrs) {
return attrs.sort(function (a, b) {
if (a.name < b.name) {
return -1;
} else if (a.name > b.name) {
return 1;
} else if (a.value < b.value) {
return -1;
} else if (a.value > b.value) {
return 1;
}
return 0;
});
}
|
[
"function",
"sortAttrs",
"(",
"attrs",
")",
"{",
"return",
"attrs",
".",
"sort",
"(",
"function",
"(",
"a",
",",
"b",
")",
"{",
"if",
"(",
"a",
".",
"name",
"<",
"b",
".",
"name",
")",
"{",
"return",
"-",
"1",
";",
"}",
"else",
"if",
"(",
"a",
".",
"name",
">",
"b",
".",
"name",
")",
"{",
"return",
"1",
";",
"}",
"else",
"if",
"(",
"a",
".",
"value",
"<",
"b",
".",
"value",
")",
"{",
"return",
"-",
"1",
";",
"}",
"else",
"if",
"(",
"a",
".",
"value",
">",
"b",
".",
"value",
")",
"{",
"return",
"1",
";",
"}",
"return",
"0",
";",
"}",
")",
";",
"}"
] |
Sorts the attributes in alphabetical order
@param {Array} attrs
@returns {Array}
|
[
"Sorts",
"the",
"attributes",
"in",
"alphabetical",
"order"
] |
b3e83da780b2b2dad9c4b886e362acfe986e38be
|
https://github.com/bem/html-differ/blob/b3e83da780b2b2dad9c4b886e362acfe986e38be/lib/utils/utils.js#L24-L38
|
18,422
|
bem/html-differ
|
lib/utils/utils.js
|
sortCssClasses
|
function sortCssClasses(attrs) {
/**
* Sorts the given CSS class attribute
* @param {String} cssClasses
* @returns {String}
*/
function _sortCssClassesValues(cssClasses) {
var classList = (cssClasses || '').split(' ');
return _(classList)
.filter()
.uniq()
.sort()
.join(' ');
}
var classIndexes = _getIndexesInArray(attrs, 'class');
_.forEach(classIndexes, function (index) {
attrs[index].value = _sortCssClassesValues(attrs[index].value);
});
return attrs;
}
|
javascript
|
function sortCssClasses(attrs) {
/**
* Sorts the given CSS class attribute
* @param {String} cssClasses
* @returns {String}
*/
function _sortCssClassesValues(cssClasses) {
var classList = (cssClasses || '').split(' ');
return _(classList)
.filter()
.uniq()
.sort()
.join(' ');
}
var classIndexes = _getIndexesInArray(attrs, 'class');
_.forEach(classIndexes, function (index) {
attrs[index].value = _sortCssClassesValues(attrs[index].value);
});
return attrs;
}
|
[
"function",
"sortCssClasses",
"(",
"attrs",
")",
"{",
"/**\n * Sorts the given CSS class attribute\n * @param {String} cssClasses\n * @returns {String}\n */",
"function",
"_sortCssClassesValues",
"(",
"cssClasses",
")",
"{",
"var",
"classList",
"=",
"(",
"cssClasses",
"||",
"''",
")",
".",
"split",
"(",
"' '",
")",
";",
"return",
"_",
"(",
"classList",
")",
".",
"filter",
"(",
")",
".",
"uniq",
"(",
")",
".",
"sort",
"(",
")",
".",
"join",
"(",
"' '",
")",
";",
"}",
"var",
"classIndexes",
"=",
"_getIndexesInArray",
"(",
"attrs",
",",
"'class'",
")",
";",
"_",
".",
"forEach",
"(",
"classIndexes",
",",
"function",
"(",
"index",
")",
"{",
"attrs",
"[",
"index",
"]",
".",
"value",
"=",
"_sortCssClassesValues",
"(",
"attrs",
"[",
"index",
"]",
".",
"value",
")",
";",
"}",
")",
";",
"return",
"attrs",
";",
"}"
] |
Sorts values of the attribute 'class'
@param {Array} attrs
@returns {Array}
|
[
"Sorts",
"values",
"of",
"the",
"attribute",
"class"
] |
b3e83da780b2b2dad9c4b886e362acfe986e38be
|
https://github.com/bem/html-differ/blob/b3e83da780b2b2dad9c4b886e362acfe986e38be/lib/utils/utils.js#L45-L68
|
18,423
|
bem/html-differ
|
lib/utils/utils.js
|
_sortCssClassesValues
|
function _sortCssClassesValues(cssClasses) {
var classList = (cssClasses || '').split(' ');
return _(classList)
.filter()
.uniq()
.sort()
.join(' ');
}
|
javascript
|
function _sortCssClassesValues(cssClasses) {
var classList = (cssClasses || '').split(' ');
return _(classList)
.filter()
.uniq()
.sort()
.join(' ');
}
|
[
"function",
"_sortCssClassesValues",
"(",
"cssClasses",
")",
"{",
"var",
"classList",
"=",
"(",
"cssClasses",
"||",
"''",
")",
".",
"split",
"(",
"' '",
")",
";",
"return",
"_",
"(",
"classList",
")",
".",
"filter",
"(",
")",
".",
"uniq",
"(",
")",
".",
"sort",
"(",
")",
".",
"join",
"(",
"' '",
")",
";",
"}"
] |
Sorts the given CSS class attribute
@param {String} cssClasses
@returns {String}
|
[
"Sorts",
"the",
"given",
"CSS",
"class",
"attribute"
] |
b3e83da780b2b2dad9c4b886e362acfe986e38be
|
https://github.com/bem/html-differ/blob/b3e83da780b2b2dad9c4b886e362acfe986e38be/lib/utils/utils.js#L51-L59
|
18,424
|
bem/html-differ
|
lib/utils/utils.js
|
sortAttrsValues
|
function sortAttrsValues(attrs, compareAttributesAsJSON) {
/**
* Recursively sorts the given object by key
* @param {Object} obj
* @returns {Object}
*/
function _sortObj(obj) {
if (!_.isObject(obj)) {
return JSON.stringify(obj);
}
if (_.isArray(obj)) {
return '[' + _(obj).map(_sortObj).join(',') + ']';
}
return '{' +
_(obj)
.keys()
.sort()
.map(function (key) {
return JSON.stringify(key) + ':' + _sortObj(obj[key]);
})
.join(',') +
'}';
}
/**
* Parses the given in HTML attribute JSON
* @param {String} val
* @param {Boolean} [isClick]
* @returns {Object}
*/
function _parseAttr(val, isClick) {
try {
if (isClick) {
/*jshint evil: true */
var fn = Function(val);
return fn ? fn() : {};
}
return JSON.parse(val);
} catch (err) {
return undefined;
}
}
_.forEach(compareAttributesAsJSON, function (attr) {
if (typeof attr === 'string') {
var name = attr;
attr = {};
attr.name = name;
attr.isFunction = false;
}
var attrValue,
isFunction = (attr.isFunction),
attrIndexes = _getIndexesInArray(attrs, attr.name);
_.forEach(attrIndexes, function (index) {
attrValue = _parseAttr(attrs[index].value, isFunction);
attrValue = _sortObj(attrValue);
attrs[index].value = (isFunction && attrValue ? 'return ' : '') + attrValue;
});
});
return attrs;
}
|
javascript
|
function sortAttrsValues(attrs, compareAttributesAsJSON) {
/**
* Recursively sorts the given object by key
* @param {Object} obj
* @returns {Object}
*/
function _sortObj(obj) {
if (!_.isObject(obj)) {
return JSON.stringify(obj);
}
if (_.isArray(obj)) {
return '[' + _(obj).map(_sortObj).join(',') + ']';
}
return '{' +
_(obj)
.keys()
.sort()
.map(function (key) {
return JSON.stringify(key) + ':' + _sortObj(obj[key]);
})
.join(',') +
'}';
}
/**
* Parses the given in HTML attribute JSON
* @param {String} val
* @param {Boolean} [isClick]
* @returns {Object}
*/
function _parseAttr(val, isClick) {
try {
if (isClick) {
/*jshint evil: true */
var fn = Function(val);
return fn ? fn() : {};
}
return JSON.parse(val);
} catch (err) {
return undefined;
}
}
_.forEach(compareAttributesAsJSON, function (attr) {
if (typeof attr === 'string') {
var name = attr;
attr = {};
attr.name = name;
attr.isFunction = false;
}
var attrValue,
isFunction = (attr.isFunction),
attrIndexes = _getIndexesInArray(attrs, attr.name);
_.forEach(attrIndexes, function (index) {
attrValue = _parseAttr(attrs[index].value, isFunction);
attrValue = _sortObj(attrValue);
attrs[index].value = (isFunction && attrValue ? 'return ' : '') + attrValue;
});
});
return attrs;
}
|
[
"function",
"sortAttrsValues",
"(",
"attrs",
",",
"compareAttributesAsJSON",
")",
"{",
"/**\n * Recursively sorts the given object by key\n * @param {Object} obj\n * @returns {Object}\n */",
"function",
"_sortObj",
"(",
"obj",
")",
"{",
"if",
"(",
"!",
"_",
".",
"isObject",
"(",
"obj",
")",
")",
"{",
"return",
"JSON",
".",
"stringify",
"(",
"obj",
")",
";",
"}",
"if",
"(",
"_",
".",
"isArray",
"(",
"obj",
")",
")",
"{",
"return",
"'['",
"+",
"_",
"(",
"obj",
")",
".",
"map",
"(",
"_sortObj",
")",
".",
"join",
"(",
"','",
")",
"+",
"']'",
";",
"}",
"return",
"'{'",
"+",
"_",
"(",
"obj",
")",
".",
"keys",
"(",
")",
".",
"sort",
"(",
")",
".",
"map",
"(",
"function",
"(",
"key",
")",
"{",
"return",
"JSON",
".",
"stringify",
"(",
"key",
")",
"+",
"':'",
"+",
"_sortObj",
"(",
"obj",
"[",
"key",
"]",
")",
";",
"}",
")",
".",
"join",
"(",
"','",
")",
"+",
"'}'",
";",
"}",
"/**\n * Parses the given in HTML attribute JSON\n * @param {String} val\n * @param {Boolean} [isClick]\n * @returns {Object}\n */",
"function",
"_parseAttr",
"(",
"val",
",",
"isClick",
")",
"{",
"try",
"{",
"if",
"(",
"isClick",
")",
"{",
"/*jshint evil: true */",
"var",
"fn",
"=",
"Function",
"(",
"val",
")",
";",
"return",
"fn",
"?",
"fn",
"(",
")",
":",
"{",
"}",
";",
"}",
"return",
"JSON",
".",
"parse",
"(",
"val",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"return",
"undefined",
";",
"}",
"}",
"_",
".",
"forEach",
"(",
"compareAttributesAsJSON",
",",
"function",
"(",
"attr",
")",
"{",
"if",
"(",
"typeof",
"attr",
"===",
"'string'",
")",
"{",
"var",
"name",
"=",
"attr",
";",
"attr",
"=",
"{",
"}",
";",
"attr",
".",
"name",
"=",
"name",
";",
"attr",
".",
"isFunction",
"=",
"false",
";",
"}",
"var",
"attrValue",
",",
"isFunction",
"=",
"(",
"attr",
".",
"isFunction",
")",
",",
"attrIndexes",
"=",
"_getIndexesInArray",
"(",
"attrs",
",",
"attr",
".",
"name",
")",
";",
"_",
".",
"forEach",
"(",
"attrIndexes",
",",
"function",
"(",
"index",
")",
"{",
"attrValue",
"=",
"_parseAttr",
"(",
"attrs",
"[",
"index",
"]",
".",
"value",
",",
"isFunction",
")",
";",
"attrValue",
"=",
"_sortObj",
"(",
"attrValue",
")",
";",
"attrs",
"[",
"index",
"]",
".",
"value",
"=",
"(",
"isFunction",
"&&",
"attrValue",
"?",
"'return '",
":",
"''",
")",
"+",
"attrValue",
";",
"}",
")",
";",
"}",
")",
";",
"return",
"attrs",
";",
"}"
] |
Sorts values of attributes which have JSON format
@param {Array} attrs
@param {Array} compareAttributesAsJSON
return {Array}
|
[
"Sorts",
"values",
"of",
"attributes",
"which",
"have",
"JSON",
"format"
] |
b3e83da780b2b2dad9c4b886e362acfe986e38be
|
https://github.com/bem/html-differ/blob/b3e83da780b2b2dad9c4b886e362acfe986e38be/lib/utils/utils.js#L76-L145
|
18,425
|
bem/html-differ
|
lib/utils/utils.js
|
_sortObj
|
function _sortObj(obj) {
if (!_.isObject(obj)) {
return JSON.stringify(obj);
}
if (_.isArray(obj)) {
return '[' + _(obj).map(_sortObj).join(',') + ']';
}
return '{' +
_(obj)
.keys()
.sort()
.map(function (key) {
return JSON.stringify(key) + ':' + _sortObj(obj[key]);
})
.join(',') +
'}';
}
|
javascript
|
function _sortObj(obj) {
if (!_.isObject(obj)) {
return JSON.stringify(obj);
}
if (_.isArray(obj)) {
return '[' + _(obj).map(_sortObj).join(',') + ']';
}
return '{' +
_(obj)
.keys()
.sort()
.map(function (key) {
return JSON.stringify(key) + ':' + _sortObj(obj[key]);
})
.join(',') +
'}';
}
|
[
"function",
"_sortObj",
"(",
"obj",
")",
"{",
"if",
"(",
"!",
"_",
".",
"isObject",
"(",
"obj",
")",
")",
"{",
"return",
"JSON",
".",
"stringify",
"(",
"obj",
")",
";",
"}",
"if",
"(",
"_",
".",
"isArray",
"(",
"obj",
")",
")",
"{",
"return",
"'['",
"+",
"_",
"(",
"obj",
")",
".",
"map",
"(",
"_sortObj",
")",
".",
"join",
"(",
"','",
")",
"+",
"']'",
";",
"}",
"return",
"'{'",
"+",
"_",
"(",
"obj",
")",
".",
"keys",
"(",
")",
".",
"sort",
"(",
")",
".",
"map",
"(",
"function",
"(",
"key",
")",
"{",
"return",
"JSON",
".",
"stringify",
"(",
"key",
")",
"+",
"':'",
"+",
"_sortObj",
"(",
"obj",
"[",
"key",
"]",
")",
";",
"}",
")",
".",
"join",
"(",
"','",
")",
"+",
"'}'",
";",
"}"
] |
Recursively sorts the given object by key
@param {Object} obj
@returns {Object}
|
[
"Recursively",
"sorts",
"the",
"given",
"object",
"by",
"key"
] |
b3e83da780b2b2dad9c4b886e362acfe986e38be
|
https://github.com/bem/html-differ/blob/b3e83da780b2b2dad9c4b886e362acfe986e38be/lib/utils/utils.js#L82-L100
|
18,426
|
bem/html-differ
|
lib/utils/utils.js
|
_parseAttr
|
function _parseAttr(val, isClick) {
try {
if (isClick) {
/*jshint evil: true */
var fn = Function(val);
return fn ? fn() : {};
}
return JSON.parse(val);
} catch (err) {
return undefined;
}
}
|
javascript
|
function _parseAttr(val, isClick) {
try {
if (isClick) {
/*jshint evil: true */
var fn = Function(val);
return fn ? fn() : {};
}
return JSON.parse(val);
} catch (err) {
return undefined;
}
}
|
[
"function",
"_parseAttr",
"(",
"val",
",",
"isClick",
")",
"{",
"try",
"{",
"if",
"(",
"isClick",
")",
"{",
"/*jshint evil: true */",
"var",
"fn",
"=",
"Function",
"(",
"val",
")",
";",
"return",
"fn",
"?",
"fn",
"(",
")",
":",
"{",
"}",
";",
"}",
"return",
"JSON",
".",
"parse",
"(",
"val",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"return",
"undefined",
";",
"}",
"}"
] |
Parses the given in HTML attribute JSON
@param {String} val
@param {Boolean} [isClick]
@returns {Object}
|
[
"Parses",
"the",
"given",
"in",
"HTML",
"attribute",
"JSON"
] |
b3e83da780b2b2dad9c4b886e362acfe986e38be
|
https://github.com/bem/html-differ/blob/b3e83da780b2b2dad9c4b886e362acfe986e38be/lib/utils/utils.js#L108-L121
|
18,427
|
bem/html-differ
|
lib/utils/utils.js
|
removeAttrsValues
|
function removeAttrsValues(attrs, ignoreAttributes) {
_.forEach(ignoreAttributes, function (attr) {
var attrIndexes = _getIndexesInArray(attrs, attr);
_.forEach(attrIndexes, function (index) {
attrs[index].value = '';
});
});
return attrs;
}
|
javascript
|
function removeAttrsValues(attrs, ignoreAttributes) {
_.forEach(ignoreAttributes, function (attr) {
var attrIndexes = _getIndexesInArray(attrs, attr);
_.forEach(attrIndexes, function (index) {
attrs[index].value = '';
});
});
return attrs;
}
|
[
"function",
"removeAttrsValues",
"(",
"attrs",
",",
"ignoreAttributes",
")",
"{",
"_",
".",
"forEach",
"(",
"ignoreAttributes",
",",
"function",
"(",
"attr",
")",
"{",
"var",
"attrIndexes",
"=",
"_getIndexesInArray",
"(",
"attrs",
",",
"attr",
")",
";",
"_",
".",
"forEach",
"(",
"attrIndexes",
",",
"function",
"(",
"index",
")",
"{",
"attrs",
"[",
"index",
"]",
".",
"value",
"=",
"''",
";",
"}",
")",
";",
"}",
")",
";",
"return",
"attrs",
";",
"}"
] |
Replaces the values of attributes on an empty string
@param {Array} attrs
@param {Array} ignoreAttributes
@returns {Array}
|
[
"Replaces",
"the",
"values",
"of",
"attributes",
"on",
"an",
"empty",
"string"
] |
b3e83da780b2b2dad9c4b886e362acfe986e38be
|
https://github.com/bem/html-differ/blob/b3e83da780b2b2dad9c4b886e362acfe986e38be/lib/utils/utils.js#L153-L163
|
18,428
|
bem/html-differ
|
lib/utils/utils.js
|
removeDuplicateAttributes
|
function removeDuplicateAttributes(attrs) {
var attrsNames = [],
res = [];
_.forEach(attrs, function (attr) {
if (attrsNames.indexOf(attr.name) === -1) {
res.push(attr);
attrsNames.push(attr.name);
}
});
return res;
}
|
javascript
|
function removeDuplicateAttributes(attrs) {
var attrsNames = [],
res = [];
_.forEach(attrs, function (attr) {
if (attrsNames.indexOf(attr.name) === -1) {
res.push(attr);
attrsNames.push(attr.name);
}
});
return res;
}
|
[
"function",
"removeDuplicateAttributes",
"(",
"attrs",
")",
"{",
"var",
"attrsNames",
"=",
"[",
"]",
",",
"res",
"=",
"[",
"]",
";",
"_",
".",
"forEach",
"(",
"attrs",
",",
"function",
"(",
"attr",
")",
"{",
"if",
"(",
"attrsNames",
".",
"indexOf",
"(",
"attr",
".",
"name",
")",
"===",
"-",
"1",
")",
"{",
"res",
".",
"push",
"(",
"attr",
")",
";",
"attrsNames",
".",
"push",
"(",
"attr",
".",
"name",
")",
";",
"}",
"}",
")",
";",
"return",
"res",
";",
"}"
] |
Removes duplicate attributes from the given list
@param {Array} attrs
@returns {Array}
|
[
"Removes",
"duplicate",
"attributes",
"from",
"the",
"given",
"list"
] |
b3e83da780b2b2dad9c4b886e362acfe986e38be
|
https://github.com/bem/html-differ/blob/b3e83da780b2b2dad9c4b886e362acfe986e38be/lib/utils/utils.js#L182-L194
|
18,429
|
bem/html-differ
|
lib/utils/utils.js
|
getConditionalComment
|
function getConditionalComment(comment, modify, options) {
var START_IF = '^\\s*\\[if .*\\]>',
END_IF = '<!\\[endif\\]\\s*$',
matchedStartIF = comment.match(new RegExp(START_IF)),
matchedEndIF = comment.match(new RegExp(END_IF));
if (comment.match(new RegExp(START_IF + '\\s*$')) || comment.match(new RegExp(START_IF + '<!\\s*$')) ||
comment.match(new RegExp('^' + END_IF))) {
return comment.trim();
}
if (matchedStartIF && matchedEndIF) {
var start = matchedStartIF[0],
end = matchedEndIF[0],
modified = modify(comment.substring(start.length, matchedEndIF.index), options);
return (start + modified + end).trim();
}
}
|
javascript
|
function getConditionalComment(comment, modify, options) {
var START_IF = '^\\s*\\[if .*\\]>',
END_IF = '<!\\[endif\\]\\s*$',
matchedStartIF = comment.match(new RegExp(START_IF)),
matchedEndIF = comment.match(new RegExp(END_IF));
if (comment.match(new RegExp(START_IF + '\\s*$')) || comment.match(new RegExp(START_IF + '<!\\s*$')) ||
comment.match(new RegExp('^' + END_IF))) {
return comment.trim();
}
if (matchedStartIF && matchedEndIF) {
var start = matchedStartIF[0],
end = matchedEndIF[0],
modified = modify(comment.substring(start.length, matchedEndIF.index), options);
return (start + modified + end).trim();
}
}
|
[
"function",
"getConditionalComment",
"(",
"comment",
",",
"modify",
",",
"options",
")",
"{",
"var",
"START_IF",
"=",
"'^\\\\s*\\\\[if .*\\\\]>'",
",",
"END_IF",
"=",
"'<!\\\\[endif\\\\]\\\\s*$'",
",",
"matchedStartIF",
"=",
"comment",
".",
"match",
"(",
"new",
"RegExp",
"(",
"START_IF",
")",
")",
",",
"matchedEndIF",
"=",
"comment",
".",
"match",
"(",
"new",
"RegExp",
"(",
"END_IF",
")",
")",
";",
"if",
"(",
"comment",
".",
"match",
"(",
"new",
"RegExp",
"(",
"START_IF",
"+",
"'\\\\s*$'",
")",
")",
"||",
"comment",
".",
"match",
"(",
"new",
"RegExp",
"(",
"START_IF",
"+",
"'<!\\\\s*$'",
")",
")",
"||",
"comment",
".",
"match",
"(",
"new",
"RegExp",
"(",
"'^'",
"+",
"END_IF",
")",
")",
")",
"{",
"return",
"comment",
".",
"trim",
"(",
")",
";",
"}",
"if",
"(",
"matchedStartIF",
"&&",
"matchedEndIF",
")",
"{",
"var",
"start",
"=",
"matchedStartIF",
"[",
"0",
"]",
",",
"end",
"=",
"matchedEndIF",
"[",
"0",
"]",
",",
"modified",
"=",
"modify",
"(",
"comment",
".",
"substring",
"(",
"start",
".",
"length",
",",
"matchedEndIF",
".",
"index",
")",
",",
"options",
")",
";",
"return",
"(",
"start",
"+",
"modified",
"+",
"end",
")",
".",
"trim",
"(",
")",
";",
"}",
"}"
] |
Processes a conditional comment
@param {String} comment
@param {Function} modify
@param {Object} options
@returns {String|undefined}
|
[
"Processes",
"a",
"conditional",
"comment"
] |
b3e83da780b2b2dad9c4b886e362acfe986e38be
|
https://github.com/bem/html-differ/blob/b3e83da780b2b2dad9c4b886e362acfe986e38be/lib/utils/utils.js#L203-L221
|
18,430
|
domvm/domvm
|
demos/playground/demos/scoreboard/scoreboard.js
|
sortedByScoreDesc
|
function sortedByScoreDesc(players) {
return players.slice().sort(function(a, b) {
if (b.score == a.score)
return a.name.localeCompare(b.name); // stabalize the sort
return b.score - a.score;
});
}
|
javascript
|
function sortedByScoreDesc(players) {
return players.slice().sort(function(a, b) {
if (b.score == a.score)
return a.name.localeCompare(b.name); // stabalize the sort
return b.score - a.score;
});
}
|
[
"function",
"sortedByScoreDesc",
"(",
"players",
")",
"{",
"return",
"players",
".",
"slice",
"(",
")",
".",
"sort",
"(",
"function",
"(",
"a",
",",
"b",
")",
"{",
"if",
"(",
"b",
".",
"score",
"==",
"a",
".",
"score",
")",
"return",
"a",
".",
"name",
".",
"localeCompare",
"(",
"b",
".",
"name",
")",
";",
"// stabalize the sort",
"return",
"b",
".",
"score",
"-",
"a",
".",
"score",
";",
"}",
")",
";",
"}"
] |
makes a sorted copy
|
[
"makes",
"a",
"sorted",
"copy"
] |
e6ba38ec26cdbfe6c47e918ee73647f13ef1a45a
|
https://github.com/domvm/domvm/blob/e6ba38ec26cdbfe6c47e918ee73647f13ef1a45a/demos/playground/demos/scoreboard/scoreboard.js#L48-L55
|
18,431
|
domvm/domvm
|
demos/playground/demos/scoreboard/scoreboard.js
|
calcPlayerStyle
|
function calcPlayerStyle(player, delayed) {
// delayed
if (delayed)
return {transition: "250ms", transform: null};
// initial
else {
var offset = (lastPos.get(player) * 18) - (curPos.get(player) * 18);
return {
transform: "translateY(" + offset + "px)",
transition: null//offset == 0 ? "",
};
}
}
|
javascript
|
function calcPlayerStyle(player, delayed) {
// delayed
if (delayed)
return {transition: "250ms", transform: null};
// initial
else {
var offset = (lastPos.get(player) * 18) - (curPos.get(player) * 18);
return {
transform: "translateY(" + offset + "px)",
transition: null//offset == 0 ? "",
};
}
}
|
[
"function",
"calcPlayerStyle",
"(",
"player",
",",
"delayed",
")",
"{",
"// delayed",
"if",
"(",
"delayed",
")",
"return",
"{",
"transition",
":",
"\"250ms\"",
",",
"transform",
":",
"null",
"}",
";",
"// initial",
"else",
"{",
"var",
"offset",
"=",
"(",
"lastPos",
".",
"get",
"(",
"player",
")",
"*",
"18",
")",
"-",
"(",
"curPos",
".",
"get",
"(",
"player",
")",
"*",
"18",
")",
";",
"return",
"{",
"transform",
":",
"\"translateY(\"",
"+",
"offset",
"+",
"\"px)\"",
",",
"transition",
":",
"null",
"//offset == 0 ? \"\",",
"}",
";",
"}",
"}"
] |
gets transform for prior pos order
|
[
"gets",
"transform",
"for",
"prior",
"pos",
"order"
] |
e6ba38ec26cdbfe6c47e918ee73647f13ef1a45a
|
https://github.com/domvm/domvm/blob/e6ba38ec26cdbfe6c47e918ee73647f13ef1a45a/demos/playground/demos/scoreboard/scoreboard.js#L58-L70
|
18,432
|
domvm/domvm
|
build.js
|
buildDistTable
|
function buildDistTable() {
var builds = getBuilds();
var branch = getCurBranch();
var colWidths = {
build: 0,
"min / gz": 0,
contents: 0,
descr: 0,
};
var appendix = [];
builds.forEach(function(build, i) {
var buildName = build.build;
var path = "dist/" + buildName + "/domvm." + buildName + ".min.js";
appendix.push("["+(i+1)+"]: https://github.com/domvm/domvm/blob/" + branch + "/" + path);
var minified = fs.readFileSync("./" + path, 'utf8');
var gzipped = zlib.gzipSync(minified, {level: 6});
var minLen = (minified.length / 1024).toFixed(1);
var gzLen = (gzipped.length / 1024).toFixed(1);
build["min / gz"] = minLen + "k / " + gzLen + "k";
build.build = "[" + buildName + "][" + (i+1) + "]";
for (var colName in colWidths)
colWidths[colName] = Math.max(colWidths[colName], build[colName].length);
});
var table = '';
for (var colName in colWidths)
table += "| " + padRight(colName, " ", colWidths[colName] + 1);
table += "|\n";
for (var colName in colWidths)
table += "| " + padRight("", "-", colWidths[colName]) + " ";
table += "|\n";
builds.forEach(function(build, i) {
for (var colName in colWidths)
table += "| " + padRight(build[colName], " ", colWidths[colName] + 1);
table += "|\n";
});
table += "\n" + appendix.join("\n");
fs.writeFileSync("./dist/README.md", table, 'utf8');
}
|
javascript
|
function buildDistTable() {
var builds = getBuilds();
var branch = getCurBranch();
var colWidths = {
build: 0,
"min / gz": 0,
contents: 0,
descr: 0,
};
var appendix = [];
builds.forEach(function(build, i) {
var buildName = build.build;
var path = "dist/" + buildName + "/domvm." + buildName + ".min.js";
appendix.push("["+(i+1)+"]: https://github.com/domvm/domvm/blob/" + branch + "/" + path);
var minified = fs.readFileSync("./" + path, 'utf8');
var gzipped = zlib.gzipSync(minified, {level: 6});
var minLen = (minified.length / 1024).toFixed(1);
var gzLen = (gzipped.length / 1024).toFixed(1);
build["min / gz"] = minLen + "k / " + gzLen + "k";
build.build = "[" + buildName + "][" + (i+1) + "]";
for (var colName in colWidths)
colWidths[colName] = Math.max(colWidths[colName], build[colName].length);
});
var table = '';
for (var colName in colWidths)
table += "| " + padRight(colName, " ", colWidths[colName] + 1);
table += "|\n";
for (var colName in colWidths)
table += "| " + padRight("", "-", colWidths[colName]) + " ";
table += "|\n";
builds.forEach(function(build, i) {
for (var colName in colWidths)
table += "| " + padRight(build[colName], " ", colWidths[colName] + 1);
table += "|\n";
});
table += "\n" + appendix.join("\n");
fs.writeFileSync("./dist/README.md", table, 'utf8');
}
|
[
"function",
"buildDistTable",
"(",
")",
"{",
"var",
"builds",
"=",
"getBuilds",
"(",
")",
";",
"var",
"branch",
"=",
"getCurBranch",
"(",
")",
";",
"var",
"colWidths",
"=",
"{",
"build",
":",
"0",
",",
"\"min / gz\"",
":",
"0",
",",
"contents",
":",
"0",
",",
"descr",
":",
"0",
",",
"}",
";",
"var",
"appendix",
"=",
"[",
"]",
";",
"builds",
".",
"forEach",
"(",
"function",
"(",
"build",
",",
"i",
")",
"{",
"var",
"buildName",
"=",
"build",
".",
"build",
";",
"var",
"path",
"=",
"\"dist/\"",
"+",
"buildName",
"+",
"\"/domvm.\"",
"+",
"buildName",
"+",
"\".min.js\"",
";",
"appendix",
".",
"push",
"(",
"\"[\"",
"+",
"(",
"i",
"+",
"1",
")",
"+",
"\"]: https://github.com/domvm/domvm/blob/\"",
"+",
"branch",
"+",
"\"/\"",
"+",
"path",
")",
";",
"var",
"minified",
"=",
"fs",
".",
"readFileSync",
"(",
"\"./\"",
"+",
"path",
",",
"'utf8'",
")",
";",
"var",
"gzipped",
"=",
"zlib",
".",
"gzipSync",
"(",
"minified",
",",
"{",
"level",
":",
"6",
"}",
")",
";",
"var",
"minLen",
"=",
"(",
"minified",
".",
"length",
"/",
"1024",
")",
".",
"toFixed",
"(",
"1",
")",
";",
"var",
"gzLen",
"=",
"(",
"gzipped",
".",
"length",
"/",
"1024",
")",
".",
"toFixed",
"(",
"1",
")",
";",
"build",
"[",
"\"min / gz\"",
"]",
"=",
"minLen",
"+",
"\"k / \"",
"+",
"gzLen",
"+",
"\"k\"",
";",
"build",
".",
"build",
"=",
"\"[\"",
"+",
"buildName",
"+",
"\"][\"",
"+",
"(",
"i",
"+",
"1",
")",
"+",
"\"]\"",
";",
"for",
"(",
"var",
"colName",
"in",
"colWidths",
")",
"colWidths",
"[",
"colName",
"]",
"=",
"Math",
".",
"max",
"(",
"colWidths",
"[",
"colName",
"]",
",",
"build",
"[",
"colName",
"]",
".",
"length",
")",
";",
"}",
")",
";",
"var",
"table",
"=",
"''",
";",
"for",
"(",
"var",
"colName",
"in",
"colWidths",
")",
"table",
"+=",
"\"| \"",
"+",
"padRight",
"(",
"colName",
",",
"\" \"",
",",
"colWidths",
"[",
"colName",
"]",
"+",
"1",
")",
";",
"table",
"+=",
"\"|\\n\"",
";",
"for",
"(",
"var",
"colName",
"in",
"colWidths",
")",
"table",
"+=",
"\"| \"",
"+",
"padRight",
"(",
"\"\"",
",",
"\"-\"",
",",
"colWidths",
"[",
"colName",
"]",
")",
"+",
"\" \"",
";",
"table",
"+=",
"\"|\\n\"",
";",
"builds",
".",
"forEach",
"(",
"function",
"(",
"build",
",",
"i",
")",
"{",
"for",
"(",
"var",
"colName",
"in",
"colWidths",
")",
"table",
"+=",
"\"| \"",
"+",
"padRight",
"(",
"build",
"[",
"colName",
"]",
",",
"\" \"",
",",
"colWidths",
"[",
"colName",
"]",
"+",
"1",
")",
";",
"table",
"+=",
"\"|\\n\"",
";",
"}",
")",
";",
"table",
"+=",
"\"\\n\"",
"+",
"appendix",
".",
"join",
"(",
"\"\\n\"",
")",
";",
"fs",
".",
"writeFileSync",
"(",
"\"./dist/README.md\"",
",",
"table",
",",
"'utf8'",
")",
";",
"}"
] |
builds markdown table
|
[
"builds",
"markdown",
"table"
] |
e6ba38ec26cdbfe6c47e918ee73647f13ef1a45a
|
https://github.com/domvm/domvm/blob/e6ba38ec26cdbfe6c47e918ee73647f13ef1a45a/build.js#L282-L335
|
18,433
|
domvm/domvm
|
dist/pico/domvm.pico.es.js
|
deepSet
|
function deepSet(targ, path, val) {
var seg;
while (seg = path.shift()) {
if (path.length === 0)
{ targ[seg] = val; }
else
{ targ[seg] = targ = targ[seg] || {}; }
}
}
|
javascript
|
function deepSet(targ, path, val) {
var seg;
while (seg = path.shift()) {
if (path.length === 0)
{ targ[seg] = val; }
else
{ targ[seg] = targ = targ[seg] || {}; }
}
}
|
[
"function",
"deepSet",
"(",
"targ",
",",
"path",
",",
"val",
")",
"{",
"var",
"seg",
";",
"while",
"(",
"seg",
"=",
"path",
".",
"shift",
"(",
")",
")",
"{",
"if",
"(",
"path",
".",
"length",
"===",
"0",
")",
"{",
"targ",
"[",
"seg",
"]",
"=",
"val",
";",
"}",
"else",
"{",
"targ",
"[",
"seg",
"]",
"=",
"targ",
"=",
"targ",
"[",
"seg",
"]",
"||",
"{",
"}",
";",
"}",
"}",
"}"
] |
export const defProp = Object.defineProperty;
|
[
"export",
"const",
"defProp",
"=",
"Object",
".",
"defineProperty",
";"
] |
e6ba38ec26cdbfe6c47e918ee73647f13ef1a45a
|
https://github.com/domvm/domvm/blob/e6ba38ec26cdbfe6c47e918ee73647f13ef1a45a/dist/pico/domvm.pico.es.js#L65-L74
|
18,434
|
domvm/domvm
|
dist/pico/domvm.pico.es.js
|
patchStyle
|
function patchStyle(n, o) {
var ns = (n.attrs || emptyObj).style;
var os = o ? (o.attrs || emptyObj).style : null;
// replace or remove in full
if (ns == null || isVal(ns))
{ n.el.style.cssText = ns; }
else {
for (var nn in ns) {
var nv = ns[nn];
if (os == null || nv != null && nv !== os[nn])
{ n.el.style[nn] = autoPx(nn, nv); }
}
// clean old
if (os) {
for (var on in os) {
if (ns[on] == null)
{ n.el.style[on] = ""; }
}
}
}
}
|
javascript
|
function patchStyle(n, o) {
var ns = (n.attrs || emptyObj).style;
var os = o ? (o.attrs || emptyObj).style : null;
// replace or remove in full
if (ns == null || isVal(ns))
{ n.el.style.cssText = ns; }
else {
for (var nn in ns) {
var nv = ns[nn];
if (os == null || nv != null && nv !== os[nn])
{ n.el.style[nn] = autoPx(nn, nv); }
}
// clean old
if (os) {
for (var on in os) {
if (ns[on] == null)
{ n.el.style[on] = ""; }
}
}
}
}
|
[
"function",
"patchStyle",
"(",
"n",
",",
"o",
")",
"{",
"var",
"ns",
"=",
"(",
"n",
".",
"attrs",
"||",
"emptyObj",
")",
".",
"style",
";",
"var",
"os",
"=",
"o",
"?",
"(",
"o",
".",
"attrs",
"||",
"emptyObj",
")",
".",
"style",
":",
"null",
";",
"// replace or remove in full",
"if",
"(",
"ns",
"==",
"null",
"||",
"isVal",
"(",
"ns",
")",
")",
"{",
"n",
".",
"el",
".",
"style",
".",
"cssText",
"=",
"ns",
";",
"}",
"else",
"{",
"for",
"(",
"var",
"nn",
"in",
"ns",
")",
"{",
"var",
"nv",
"=",
"ns",
"[",
"nn",
"]",
";",
"if",
"(",
"os",
"==",
"null",
"||",
"nv",
"!=",
"null",
"&&",
"nv",
"!==",
"os",
"[",
"nn",
"]",
")",
"{",
"n",
".",
"el",
".",
"style",
"[",
"nn",
"]",
"=",
"autoPx",
"(",
"nn",
",",
"nv",
")",
";",
"}",
"}",
"// clean old",
"if",
"(",
"os",
")",
"{",
"for",
"(",
"var",
"on",
"in",
"os",
")",
"{",
"if",
"(",
"ns",
"[",
"on",
"]",
"==",
"null",
")",
"{",
"n",
".",
"el",
".",
"style",
"[",
"on",
"]",
"=",
"\"\"",
";",
"}",
"}",
"}",
"}",
"}"
] |
assumes if styles exist both are objects or both are strings
|
[
"assumes",
"if",
"styles",
"exist",
"both",
"are",
"objects",
"or",
"both",
"are",
"strings"
] |
e6ba38ec26cdbfe6c47e918ee73647f13ef1a45a
|
https://github.com/domvm/domvm/blob/e6ba38ec26cdbfe6c47e918ee73647f13ef1a45a/dist/pico/domvm.pico.es.js#L443-L466
|
18,435
|
domvm/domvm
|
dist/pico/domvm.pico.es.js
|
ViewModel
|
function ViewModel(view, data, key, opts) {
var vm = this;
vm.view = view;
vm.data = data;
vm.key = key;
if (opts) {
vm.opts = opts;
vm.cfg(opts);
}
var out = isPlainObj(view) ? view : view.call(vm, vm, data, key, opts);
if (isFunc(out))
{ vm.render = out; }
else {
vm.render = out.render;
vm.cfg(out);
}
vm.init && vm.init.call(vm, vm, vm.data, vm.key, opts);
}
|
javascript
|
function ViewModel(view, data, key, opts) {
var vm = this;
vm.view = view;
vm.data = data;
vm.key = key;
if (opts) {
vm.opts = opts;
vm.cfg(opts);
}
var out = isPlainObj(view) ? view : view.call(vm, vm, data, key, opts);
if (isFunc(out))
{ vm.render = out; }
else {
vm.render = out.render;
vm.cfg(out);
}
vm.init && vm.init.call(vm, vm, vm.data, vm.key, opts);
}
|
[
"function",
"ViewModel",
"(",
"view",
",",
"data",
",",
"key",
",",
"opts",
")",
"{",
"var",
"vm",
"=",
"this",
";",
"vm",
".",
"view",
"=",
"view",
";",
"vm",
".",
"data",
"=",
"data",
";",
"vm",
".",
"key",
"=",
"key",
";",
"if",
"(",
"opts",
")",
"{",
"vm",
".",
"opts",
"=",
"opts",
";",
"vm",
".",
"cfg",
"(",
"opts",
")",
";",
"}",
"var",
"out",
"=",
"isPlainObj",
"(",
"view",
")",
"?",
"view",
":",
"view",
".",
"call",
"(",
"vm",
",",
"vm",
",",
"data",
",",
"key",
",",
"opts",
")",
";",
"if",
"(",
"isFunc",
"(",
"out",
")",
")",
"{",
"vm",
".",
"render",
"=",
"out",
";",
"}",
"else",
"{",
"vm",
".",
"render",
"=",
"out",
".",
"render",
";",
"vm",
".",
"cfg",
"(",
"out",
")",
";",
"}",
"vm",
".",
"init",
"&&",
"vm",
".",
"init",
".",
"call",
"(",
"vm",
",",
"vm",
",",
"vm",
".",
"data",
",",
"vm",
".",
"key",
",",
"opts",
")",
";",
"}"
] |
view + key serve as the vm's unique identity
|
[
"view",
"+",
"key",
"serve",
"as",
"the",
"vm",
"s",
"unique",
"identity"
] |
e6ba38ec26cdbfe6c47e918ee73647f13ef1a45a
|
https://github.com/domvm/domvm/blob/e6ba38ec26cdbfe6c47e918ee73647f13ef1a45a/dist/pico/domvm.pico.es.js#L1257-L1279
|
18,436
|
domvm/domvm
|
dist/pico/domvm.pico.es.js
|
VView
|
function VView(view, data, key, opts) {
this.view = view;
this.data = data;
this.key = key;
this.opts = opts;
}
|
javascript
|
function VView(view, data, key, opts) {
this.view = view;
this.data = data;
this.key = key;
this.opts = opts;
}
|
[
"function",
"VView",
"(",
"view",
",",
"data",
",",
"key",
",",
"opts",
")",
"{",
"this",
".",
"view",
"=",
"view",
";",
"this",
".",
"data",
"=",
"data",
";",
"this",
".",
"key",
"=",
"key",
";",
"this",
".",
"opts",
"=",
"opts",
";",
"}"
] |
placeholder for declared views
|
[
"placeholder",
"for",
"declared",
"views"
] |
e6ba38ec26cdbfe6c47e918ee73647f13ef1a45a
|
https://github.com/domvm/domvm/blob/e6ba38ec26cdbfe6c47e918ee73647f13ef1a45a/dist/pico/domvm.pico.es.js#L1544-L1549
|
18,437
|
domvm/domvm
|
demos/playground/demos/calendar/calendar.js
|
rendMonth
|
function rendMonth(year, month) {
var prevEnd = daysInMonth(year, month - 1),
start = firstDayOfMonth(year, month),
end = daysInMonth(year, month),
// if start of month day < start of week cfg, roll back 1 wk
wkOffs = start < wkStart ? -7 : 0;
return el("table.month", [
el("caption", months[month]),
el("tr", wkdays.map(function(day) {
return el("th", day.substr(0,3));
})),
range(rows).map(function(r) {
return el("tr.week", range(cols).map(function(c) {
var idx = (r * cols + c) + wkOffs + wkStart,
off = idx - start + 1,
date = year+"-"+month+"-"+off,
cellClass = (idx < start || off > end ? ".dim" : "") + (!!api.selected[date] ? ".sel" : ""),
cellText = idx < start ? prevEnd + off : off > end ? off - end : off;
return el("td.day" + cellClass, {onclick: [api.selectDate, date]}, cellText);
}));
})
]);
}
|
javascript
|
function rendMonth(year, month) {
var prevEnd = daysInMonth(year, month - 1),
start = firstDayOfMonth(year, month),
end = daysInMonth(year, month),
// if start of month day < start of week cfg, roll back 1 wk
wkOffs = start < wkStart ? -7 : 0;
return el("table.month", [
el("caption", months[month]),
el("tr", wkdays.map(function(day) {
return el("th", day.substr(0,3));
})),
range(rows).map(function(r) {
return el("tr.week", range(cols).map(function(c) {
var idx = (r * cols + c) + wkOffs + wkStart,
off = idx - start + 1,
date = year+"-"+month+"-"+off,
cellClass = (idx < start || off > end ? ".dim" : "") + (!!api.selected[date] ? ".sel" : ""),
cellText = idx < start ? prevEnd + off : off > end ? off - end : off;
return el("td.day" + cellClass, {onclick: [api.selectDate, date]}, cellText);
}));
})
]);
}
|
[
"function",
"rendMonth",
"(",
"year",
",",
"month",
")",
"{",
"var",
"prevEnd",
"=",
"daysInMonth",
"(",
"year",
",",
"month",
"-",
"1",
")",
",",
"start",
"=",
"firstDayOfMonth",
"(",
"year",
",",
"month",
")",
",",
"end",
"=",
"daysInMonth",
"(",
"year",
",",
"month",
")",
",",
"// if start of month day < start of week cfg, roll back 1 wk",
"wkOffs",
"=",
"start",
"<",
"wkStart",
"?",
"-",
"7",
":",
"0",
";",
"return",
"el",
"(",
"\"table.month\"",
",",
"[",
"el",
"(",
"\"caption\"",
",",
"months",
"[",
"month",
"]",
")",
",",
"el",
"(",
"\"tr\"",
",",
"wkdays",
".",
"map",
"(",
"function",
"(",
"day",
")",
"{",
"return",
"el",
"(",
"\"th\"",
",",
"day",
".",
"substr",
"(",
"0",
",",
"3",
")",
")",
";",
"}",
")",
")",
",",
"range",
"(",
"rows",
")",
".",
"map",
"(",
"function",
"(",
"r",
")",
"{",
"return",
"el",
"(",
"\"tr.week\"",
",",
"range",
"(",
"cols",
")",
".",
"map",
"(",
"function",
"(",
"c",
")",
"{",
"var",
"idx",
"=",
"(",
"r",
"*",
"cols",
"+",
"c",
")",
"+",
"wkOffs",
"+",
"wkStart",
",",
"off",
"=",
"idx",
"-",
"start",
"+",
"1",
",",
"date",
"=",
"year",
"+",
"\"-\"",
"+",
"month",
"+",
"\"-\"",
"+",
"off",
",",
"cellClass",
"=",
"(",
"idx",
"<",
"start",
"||",
"off",
">",
"end",
"?",
"\".dim\"",
":",
"\"\"",
")",
"+",
"(",
"!",
"!",
"api",
".",
"selected",
"[",
"date",
"]",
"?",
"\".sel\"",
":",
"\"\"",
")",
",",
"cellText",
"=",
"idx",
"<",
"start",
"?",
"prevEnd",
"+",
"off",
":",
"off",
">",
"end",
"?",
"off",
"-",
"end",
":",
"off",
";",
"return",
"el",
"(",
"\"td.day\"",
"+",
"cellClass",
",",
"{",
"onclick",
":",
"[",
"api",
".",
"selectDate",
",",
"date",
"]",
"}",
",",
"cellText",
")",
";",
"}",
")",
")",
";",
"}",
")",
"]",
")",
";",
"}"
] |
sub-render
|
[
"sub",
"-",
"render"
] |
e6ba38ec26cdbfe6c47e918ee73647f13ef1a45a
|
https://github.com/domvm/domvm/blob/e6ba38ec26cdbfe6c47e918ee73647f13ef1a45a/demos/playground/demos/calendar/calendar.js#L52-L76
|
18,438
|
domvm/domvm
|
demos/playground/demos/calendar/calendar.js
|
rendYear
|
function rendYear(vm, args) {
var prevYear = args.year - 1,
nextYear = args.year + 1;
return el(".year", [
el("header", [
el("button.prev", {onclick: [api.loadYear, prevYear]}, "< " + prevYear),
el("strong", {style: {fontSize: "18pt"}}, args.year),
el("button.next", {onclick: [api.loadYear, nextYear]}, nextYear + " >"),
]),
range(12).map(function(month) {
return rendMonth(args.year, month);
}),
]);
}
|
javascript
|
function rendYear(vm, args) {
var prevYear = args.year - 1,
nextYear = args.year + 1;
return el(".year", [
el("header", [
el("button.prev", {onclick: [api.loadYear, prevYear]}, "< " + prevYear),
el("strong", {style: {fontSize: "18pt"}}, args.year),
el("button.next", {onclick: [api.loadYear, nextYear]}, nextYear + " >"),
]),
range(12).map(function(month) {
return rendMonth(args.year, month);
}),
]);
}
|
[
"function",
"rendYear",
"(",
"vm",
",",
"args",
")",
"{",
"var",
"prevYear",
"=",
"args",
".",
"year",
"-",
"1",
",",
"nextYear",
"=",
"args",
".",
"year",
"+",
"1",
";",
"return",
"el",
"(",
"\".year\"",
",",
"[",
"el",
"(",
"\"header\"",
",",
"[",
"el",
"(",
"\"button.prev\"",
",",
"{",
"onclick",
":",
"[",
"api",
".",
"loadYear",
",",
"prevYear",
"]",
"}",
",",
"\"< \"",
"+",
"prevYear",
")",
",",
"el",
"(",
"\"strong\"",
",",
"{",
"style",
":",
"{",
"fontSize",
":",
"\"18pt\"",
"}",
"}",
",",
"args",
".",
"year",
")",
",",
"el",
"(",
"\"button.next\"",
",",
"{",
"onclick",
":",
"[",
"api",
".",
"loadYear",
",",
"nextYear",
"]",
"}",
",",
"nextYear",
"+",
"\" >\"",
")",
",",
"]",
")",
",",
"range",
"(",
"12",
")",
".",
"map",
"(",
"function",
"(",
"month",
")",
"{",
"return",
"rendMonth",
"(",
"args",
".",
"year",
",",
"month",
")",
";",
"}",
")",
",",
"]",
")",
";",
"}"
] |
top-level render
|
[
"top",
"-",
"level",
"render"
] |
e6ba38ec26cdbfe6c47e918ee73647f13ef1a45a
|
https://github.com/domvm/domvm/blob/e6ba38ec26cdbfe6c47e918ee73647f13ef1a45a/demos/playground/demos/calendar/calendar.js#L79-L93
|
18,439
|
domvm/domvm
|
demos/ThreaditJS/app.js
|
CommentReplyView
|
function CommentReplyView(vm, comment) {
var redraw = vm.redraw.bind(vm);
var status = prop(LOADED, redraw);
var error;
var tmpComment = prop("", redraw);
function toggleReplyMode(e) {
status(INTERACTING);
return false;
}
function postComment(e) {
status(SUBMITTING);
// TODO: flatten? dry?
endPoints.postComment(tmpComment(), comment.id)
.then(comment2 => {
tmpComment("", false);
status(RELOADING);
return endPoints.getComments(comment.id);
})
.then(c => {
comment.children = Object.values(c.lookup).slice(1); // have to slice off self
status(LOADED, false);
vm.parent().redraw();
})
.catch(e => {
error = e;
status(ERROR);
});
return false;
}
function previewReply(e, node) {
tmpComment(node.el.value);
}
return function() {
return (
status() == ERROR ? errorTpl(error)
: status() == SUBMITTING ? statusTpl("Submitting comment...")
: status() == RELOADING ? statusTpl("Submitted! Reloading comments...")
: el(".reply", [
status() == INTERACTING ?
el("form", {onsubmit: postComment}, [
el("textarea", {
value: tmpComment(),
onkeyup: [previewReply],
}),
el("input", {type: "submit", value: "Reply!"}),
el(".preview", {".innerHTML": T.previewComment(tmpComment())}),
])
: el("a", {href: "#", onclick: toggleReplyMode}, "Reply!")
])
);
}
}
|
javascript
|
function CommentReplyView(vm, comment) {
var redraw = vm.redraw.bind(vm);
var status = prop(LOADED, redraw);
var error;
var tmpComment = prop("", redraw);
function toggleReplyMode(e) {
status(INTERACTING);
return false;
}
function postComment(e) {
status(SUBMITTING);
// TODO: flatten? dry?
endPoints.postComment(tmpComment(), comment.id)
.then(comment2 => {
tmpComment("", false);
status(RELOADING);
return endPoints.getComments(comment.id);
})
.then(c => {
comment.children = Object.values(c.lookup).slice(1); // have to slice off self
status(LOADED, false);
vm.parent().redraw();
})
.catch(e => {
error = e;
status(ERROR);
});
return false;
}
function previewReply(e, node) {
tmpComment(node.el.value);
}
return function() {
return (
status() == ERROR ? errorTpl(error)
: status() == SUBMITTING ? statusTpl("Submitting comment...")
: status() == RELOADING ? statusTpl("Submitted! Reloading comments...")
: el(".reply", [
status() == INTERACTING ?
el("form", {onsubmit: postComment}, [
el("textarea", {
value: tmpComment(),
onkeyup: [previewReply],
}),
el("input", {type: "submit", value: "Reply!"}),
el(".preview", {".innerHTML": T.previewComment(tmpComment())}),
])
: el("a", {href: "#", onclick: toggleReplyMode}, "Reply!")
])
);
}
}
|
[
"function",
"CommentReplyView",
"(",
"vm",
",",
"comment",
")",
"{",
"var",
"redraw",
"=",
"vm",
".",
"redraw",
".",
"bind",
"(",
"vm",
")",
";",
"var",
"status",
"=",
"prop",
"(",
"LOADED",
",",
"redraw",
")",
";",
"var",
"error",
";",
"var",
"tmpComment",
"=",
"prop",
"(",
"\"\"",
",",
"redraw",
")",
";",
"function",
"toggleReplyMode",
"(",
"e",
")",
"{",
"status",
"(",
"INTERACTING",
")",
";",
"return",
"false",
";",
"}",
"function",
"postComment",
"(",
"e",
")",
"{",
"status",
"(",
"SUBMITTING",
")",
";",
"// TODO: flatten? dry?",
"endPoints",
".",
"postComment",
"(",
"tmpComment",
"(",
")",
",",
"comment",
".",
"id",
")",
".",
"then",
"(",
"comment2",
"=>",
"{",
"tmpComment",
"(",
"\"\"",
",",
"false",
")",
";",
"status",
"(",
"RELOADING",
")",
";",
"return",
"endPoints",
".",
"getComments",
"(",
"comment",
".",
"id",
")",
";",
"}",
")",
".",
"then",
"(",
"c",
"=>",
"{",
"comment",
".",
"children",
"=",
"Object",
".",
"values",
"(",
"c",
".",
"lookup",
")",
".",
"slice",
"(",
"1",
")",
";",
"// have to slice off self",
"status",
"(",
"LOADED",
",",
"false",
")",
";",
"vm",
".",
"parent",
"(",
")",
".",
"redraw",
"(",
")",
";",
"}",
")",
".",
"catch",
"(",
"e",
"=>",
"{",
"error",
"=",
"e",
";",
"status",
"(",
"ERROR",
")",
";",
"}",
")",
";",
"return",
"false",
";",
"}",
"function",
"previewReply",
"(",
"e",
",",
"node",
")",
"{",
"tmpComment",
"(",
"node",
".",
"el",
".",
"value",
")",
";",
"}",
"return",
"function",
"(",
")",
"{",
"return",
"(",
"status",
"(",
")",
"==",
"ERROR",
"?",
"errorTpl",
"(",
"error",
")",
":",
"status",
"(",
")",
"==",
"SUBMITTING",
"?",
"statusTpl",
"(",
"\"Submitting comment...\"",
")",
":",
"status",
"(",
")",
"==",
"RELOADING",
"?",
"statusTpl",
"(",
"\"Submitted! Reloading comments...\"",
")",
":",
"el",
"(",
"\".reply\"",
",",
"[",
"status",
"(",
")",
"==",
"INTERACTING",
"?",
"el",
"(",
"\"form\"",
",",
"{",
"onsubmit",
":",
"postComment",
"}",
",",
"[",
"el",
"(",
"\"textarea\"",
",",
"{",
"value",
":",
"tmpComment",
"(",
")",
",",
"onkeyup",
":",
"[",
"previewReply",
"]",
",",
"}",
")",
",",
"el",
"(",
"\"input\"",
",",
"{",
"type",
":",
"\"submit\"",
",",
"value",
":",
"\"Reply!\"",
"}",
")",
",",
"el",
"(",
"\".preview\"",
",",
"{",
"\".innerHTML\"",
":",
"T",
".",
"previewComment",
"(",
"tmpComment",
"(",
")",
")",
"}",
")",
",",
"]",
")",
":",
"el",
"(",
"\"a\"",
",",
"{",
"href",
":",
"\"#\"",
",",
"onclick",
":",
"toggleReplyMode",
"}",
",",
"\"Reply!\"",
")",
"]",
")",
")",
";",
"}",
"}"
] |
sub-sub view
|
[
"sub",
"-",
"sub",
"view"
] |
e6ba38ec26cdbfe6c47e918ee73647f13ef1a45a
|
https://github.com/domvm/domvm/blob/e6ba38ec26cdbfe6c47e918ee73647f13ef1a45a/demos/ThreaditJS/app.js#L197-L255
|
18,440
|
domvm/domvm
|
dist/dev/domvm.dev.es.js
|
updateSync
|
function updateSync(newData, newParent, newIdx, withDOM, withRedraw) {
var vm = this;
if (newData != null) {
if (vm.data !== newData) {
{
devNotify("DATA_REPLACED", [vm, vm.data, newData]);
}
fireHook(vm.hooks, "willUpdate", vm, newData);
vm.data = newData;
}
}
return withRedraw ? vm._redraw(newParent, newIdx, withDOM) : vm;
}
|
javascript
|
function updateSync(newData, newParent, newIdx, withDOM, withRedraw) {
var vm = this;
if (newData != null) {
if (vm.data !== newData) {
{
devNotify("DATA_REPLACED", [vm, vm.data, newData]);
}
fireHook(vm.hooks, "willUpdate", vm, newData);
vm.data = newData;
}
}
return withRedraw ? vm._redraw(newParent, newIdx, withDOM) : vm;
}
|
[
"function",
"updateSync",
"(",
"newData",
",",
"newParent",
",",
"newIdx",
",",
"withDOM",
",",
"withRedraw",
")",
"{",
"var",
"vm",
"=",
"this",
";",
"if",
"(",
"newData",
"!=",
"null",
")",
"{",
"if",
"(",
"vm",
".",
"data",
"!==",
"newData",
")",
"{",
"{",
"devNotify",
"(",
"\"DATA_REPLACED\"",
",",
"[",
"vm",
",",
"vm",
".",
"data",
",",
"newData",
"]",
")",
";",
"}",
"fireHook",
"(",
"vm",
".",
"hooks",
",",
"\"willUpdate\"",
",",
"vm",
",",
"newData",
")",
";",
"vm",
".",
"data",
"=",
"newData",
";",
"}",
"}",
"return",
"withRedraw",
"?",
"vm",
".",
"_redraw",
"(",
"newParent",
",",
"newIdx",
",",
"withDOM",
")",
":",
"vm",
";",
"}"
] |
this also doubles as moveTo
|
[
"this",
"also",
"doubles",
"as",
"moveTo"
] |
e6ba38ec26cdbfe6c47e918ee73647f13ef1a45a
|
https://github.com/domvm/domvm/blob/e6ba38ec26cdbfe6c47e918ee73647f13ef1a45a/dist/dev/domvm.dev.es.js#L2239-L2253
|
18,441
|
RethinkRobotics-opensource/rosnodejs
|
src/ros_msg_utils/lib/base_serialize.js
|
UInt8ArraySerializer
|
function UInt8ArraySerializer(array, buffer, bufferOffset, specArrayLen=null) {
const arrLen = array.length;
if (specArrayLen === null || specArrayLen < 0) {
bufferOffset = buffer.writeUInt32LE(arrLen, bufferOffset, true);
}
buffer.set(array, bufferOffset);
return bufferOffset + arrLen;
}
|
javascript
|
function UInt8ArraySerializer(array, buffer, bufferOffset, specArrayLen=null) {
const arrLen = array.length;
if (specArrayLen === null || specArrayLen < 0) {
bufferOffset = buffer.writeUInt32LE(arrLen, bufferOffset, true);
}
buffer.set(array, bufferOffset);
return bufferOffset + arrLen;
}
|
[
"function",
"UInt8ArraySerializer",
"(",
"array",
",",
"buffer",
",",
"bufferOffset",
",",
"specArrayLen",
"=",
"null",
")",
"{",
"const",
"arrLen",
"=",
"array",
".",
"length",
";",
"if",
"(",
"specArrayLen",
"===",
"null",
"||",
"specArrayLen",
"<",
"0",
")",
"{",
"bufferOffset",
"=",
"buffer",
".",
"writeUInt32LE",
"(",
"arrLen",
",",
"bufferOffset",
",",
"true",
")",
";",
"}",
"buffer",
".",
"set",
"(",
"array",
",",
"bufferOffset",
")",
";",
"return",
"bufferOffset",
"+",
"arrLen",
";",
"}"
] |
Specialized array serialization for UInt8 Arrays
|
[
"Specialized",
"array",
"serialization",
"for",
"UInt8",
"Arrays"
] |
2b2921f5a66ebd52f515b70f3cf4fba781e924c2
|
https://github.com/RethinkRobotics-opensource/rosnodejs/blob/2b2921f5a66ebd52f515b70f3cf4fba781e924c2/src/ros_msg_utils/lib/base_serialize.js#L150-L159
|
18,442
|
RethinkRobotics-opensource/rosnodejs
|
src/utils/log/Logger.js
|
hashMessage
|
function hashMessage(msg) {
const sha1 = crypto.createHash('sha1');
sha1.update(msg);
return sha1.digest('hex');
}
|
javascript
|
function hashMessage(msg) {
const sha1 = crypto.createHash('sha1');
sha1.update(msg);
return sha1.digest('hex');
}
|
[
"function",
"hashMessage",
"(",
"msg",
")",
"{",
"const",
"sha1",
"=",
"crypto",
".",
"createHash",
"(",
"'sha1'",
")",
";",
"sha1",
".",
"update",
"(",
"msg",
")",
";",
"return",
"sha1",
".",
"digest",
"(",
"'hex'",
")",
";",
"}"
] |
Utility function to help hash messages when we throttle them.
|
[
"Utility",
"function",
"to",
"help",
"hash",
"messages",
"when",
"we",
"throttle",
"them",
"."
] |
2b2921f5a66ebd52f515b70f3cf4fba781e924c2
|
https://github.com/RethinkRobotics-opensource/rosnodejs/blob/2b2921f5a66ebd52f515b70f3cf4fba781e924c2/src/utils/log/Logger.js#L289-L293
|
18,443
|
RethinkRobotics-opensource/rosnodejs
|
src/utils/messageGeneration/messages.js
|
buildMessageClass
|
function buildMessageClass(msgSpec) {
function Message(values) {
if (!(this instanceof Message)) {
return new Message(values);
}
var that = this;
if (msgSpec.fields) {
msgSpec.fields.forEach(function(field) {
if (!field.isBuiltin) {
// sub-message class
// is it an array?
if (values && typeof values[field.name] != "undefined") {
// values provided
if (field.isArray) {
that[field.name] = values[field.name].map(function(value) {
return new (getMessageFromRegistry(field.baseType, 'msg'))(value);
});
} else {
that[field.name] =
new (getMessageFromRegistry(field.baseType, 'msg'))(values[field.name]);
}
} else {
// use defaults
if (field.isArray) {
// it's an array
const length = field.arrayLen || 0;
that[field.name] = new Array(length).fill(new (getMessageFromRegistry(field.baseType, 'msg'))());
} else {
that[field.name] = new (getMessageFromRegistry(field.baseType, 'msg'))();
}
}
} else {
// simple type
that[field.name] =
(values && typeof values[field.name] != "undefined") ?
values[field.name] :
(field.value || fieldsUtil.getDefaultValue(field.type));
}
});
}
};
Message.messageType = msgSpec.getFullMessageName();
// TODO: bring these back?
// Message.packageName = details.packageName;
// Message.messageName = Message.prototype.messageName = details.messageName;
// Message.md5 = Message.prototype.md5 = details.md5;
const md5Sum = msgSpec.getMd5sum();
Message.md5sum = function() {
return md5Sum;
};
Message.Constants = (() => {
const ret = {};
msgSpec.constants.forEach((constant) => {
ret[constant.name.toUpperCase()] = constant.value;
});
return ret;
})();
Message.fields = msgSpec.fields;
Message.serialize = function(obj, buffer, offset) {
serializeInnerMessage(msgSpec, obj, buffer, offset);
};
Message.deserialize = function(buffer) {
var message = new Message();
message = deserializeInnerMessage(msgSpec, message, buffer, [0]);
return message;
};
Message.getMessageSize = function(msg) { return fieldsUtil.getMessageSize(msg, msgSpec); };
const fullMsgDefinition = msgSpec.computeFullText();
Message.messageDefinition = function() { return fullMsgDefinition; };
Message.datatype = function() { return msgSpec.getFullMessageName(); };
return Message;
}
|
javascript
|
function buildMessageClass(msgSpec) {
function Message(values) {
if (!(this instanceof Message)) {
return new Message(values);
}
var that = this;
if (msgSpec.fields) {
msgSpec.fields.forEach(function(field) {
if (!field.isBuiltin) {
// sub-message class
// is it an array?
if (values && typeof values[field.name] != "undefined") {
// values provided
if (field.isArray) {
that[field.name] = values[field.name].map(function(value) {
return new (getMessageFromRegistry(field.baseType, 'msg'))(value);
});
} else {
that[field.name] =
new (getMessageFromRegistry(field.baseType, 'msg'))(values[field.name]);
}
} else {
// use defaults
if (field.isArray) {
// it's an array
const length = field.arrayLen || 0;
that[field.name] = new Array(length).fill(new (getMessageFromRegistry(field.baseType, 'msg'))());
} else {
that[field.name] = new (getMessageFromRegistry(field.baseType, 'msg'))();
}
}
} else {
// simple type
that[field.name] =
(values && typeof values[field.name] != "undefined") ?
values[field.name] :
(field.value || fieldsUtil.getDefaultValue(field.type));
}
});
}
};
Message.messageType = msgSpec.getFullMessageName();
// TODO: bring these back?
// Message.packageName = details.packageName;
// Message.messageName = Message.prototype.messageName = details.messageName;
// Message.md5 = Message.prototype.md5 = details.md5;
const md5Sum = msgSpec.getMd5sum();
Message.md5sum = function() {
return md5Sum;
};
Message.Constants = (() => {
const ret = {};
msgSpec.constants.forEach((constant) => {
ret[constant.name.toUpperCase()] = constant.value;
});
return ret;
})();
Message.fields = msgSpec.fields;
Message.serialize = function(obj, buffer, offset) {
serializeInnerMessage(msgSpec, obj, buffer, offset);
};
Message.deserialize = function(buffer) {
var message = new Message();
message = deserializeInnerMessage(msgSpec, message, buffer, [0]);
return message;
};
Message.getMessageSize = function(msg) { return fieldsUtil.getMessageSize(msg, msgSpec); };
const fullMsgDefinition = msgSpec.computeFullText();
Message.messageDefinition = function() { return fullMsgDefinition; };
Message.datatype = function() { return msgSpec.getFullMessageName(); };
return Message;
}
|
[
"function",
"buildMessageClass",
"(",
"msgSpec",
")",
"{",
"function",
"Message",
"(",
"values",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"Message",
")",
")",
"{",
"return",
"new",
"Message",
"(",
"values",
")",
";",
"}",
"var",
"that",
"=",
"this",
";",
"if",
"(",
"msgSpec",
".",
"fields",
")",
"{",
"msgSpec",
".",
"fields",
".",
"forEach",
"(",
"function",
"(",
"field",
")",
"{",
"if",
"(",
"!",
"field",
".",
"isBuiltin",
")",
"{",
"// sub-message class",
"// is it an array?",
"if",
"(",
"values",
"&&",
"typeof",
"values",
"[",
"field",
".",
"name",
"]",
"!=",
"\"undefined\"",
")",
"{",
"// values provided",
"if",
"(",
"field",
".",
"isArray",
")",
"{",
"that",
"[",
"field",
".",
"name",
"]",
"=",
"values",
"[",
"field",
".",
"name",
"]",
".",
"map",
"(",
"function",
"(",
"value",
")",
"{",
"return",
"new",
"(",
"getMessageFromRegistry",
"(",
"field",
".",
"baseType",
",",
"'msg'",
")",
")",
"(",
"value",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"that",
"[",
"field",
".",
"name",
"]",
"=",
"new",
"(",
"getMessageFromRegistry",
"(",
"field",
".",
"baseType",
",",
"'msg'",
")",
")",
"(",
"values",
"[",
"field",
".",
"name",
"]",
")",
";",
"}",
"}",
"else",
"{",
"// use defaults",
"if",
"(",
"field",
".",
"isArray",
")",
"{",
"// it's an array",
"const",
"length",
"=",
"field",
".",
"arrayLen",
"||",
"0",
";",
"that",
"[",
"field",
".",
"name",
"]",
"=",
"new",
"Array",
"(",
"length",
")",
".",
"fill",
"(",
"new",
"(",
"getMessageFromRegistry",
"(",
"field",
".",
"baseType",
",",
"'msg'",
")",
")",
"(",
")",
")",
";",
"}",
"else",
"{",
"that",
"[",
"field",
".",
"name",
"]",
"=",
"new",
"(",
"getMessageFromRegistry",
"(",
"field",
".",
"baseType",
",",
"'msg'",
")",
")",
"(",
")",
";",
"}",
"}",
"}",
"else",
"{",
"// simple type",
"that",
"[",
"field",
".",
"name",
"]",
"=",
"(",
"values",
"&&",
"typeof",
"values",
"[",
"field",
".",
"name",
"]",
"!=",
"\"undefined\"",
")",
"?",
"values",
"[",
"field",
".",
"name",
"]",
":",
"(",
"field",
".",
"value",
"||",
"fieldsUtil",
".",
"getDefaultValue",
"(",
"field",
".",
"type",
")",
")",
";",
"}",
"}",
")",
";",
"}",
"}",
";",
"Message",
".",
"messageType",
"=",
"msgSpec",
".",
"getFullMessageName",
"(",
")",
";",
"// TODO: bring these back?",
"// Message.packageName = details.packageName;",
"// Message.messageName = Message.prototype.messageName = details.messageName;",
"// Message.md5 = Message.prototype.md5 = details.md5;",
"const",
"md5Sum",
"=",
"msgSpec",
".",
"getMd5sum",
"(",
")",
";",
"Message",
".",
"md5sum",
"=",
"function",
"(",
")",
"{",
"return",
"md5Sum",
";",
"}",
";",
"Message",
".",
"Constants",
"=",
"(",
"(",
")",
"=>",
"{",
"const",
"ret",
"=",
"{",
"}",
";",
"msgSpec",
".",
"constants",
".",
"forEach",
"(",
"(",
"constant",
")",
"=>",
"{",
"ret",
"[",
"constant",
".",
"name",
".",
"toUpperCase",
"(",
")",
"]",
"=",
"constant",
".",
"value",
";",
"}",
")",
";",
"return",
"ret",
";",
"}",
")",
"(",
")",
";",
"Message",
".",
"fields",
"=",
"msgSpec",
".",
"fields",
";",
"Message",
".",
"serialize",
"=",
"function",
"(",
"obj",
",",
"buffer",
",",
"offset",
")",
"{",
"serializeInnerMessage",
"(",
"msgSpec",
",",
"obj",
",",
"buffer",
",",
"offset",
")",
";",
"}",
";",
"Message",
".",
"deserialize",
"=",
"function",
"(",
"buffer",
")",
"{",
"var",
"message",
"=",
"new",
"Message",
"(",
")",
";",
"message",
"=",
"deserializeInnerMessage",
"(",
"msgSpec",
",",
"message",
",",
"buffer",
",",
"[",
"0",
"]",
")",
";",
"return",
"message",
";",
"}",
";",
"Message",
".",
"getMessageSize",
"=",
"function",
"(",
"msg",
")",
"{",
"return",
"fieldsUtil",
".",
"getMessageSize",
"(",
"msg",
",",
"msgSpec",
")",
";",
"}",
";",
"const",
"fullMsgDefinition",
"=",
"msgSpec",
".",
"computeFullText",
"(",
")",
";",
"Message",
".",
"messageDefinition",
"=",
"function",
"(",
")",
"{",
"return",
"fullMsgDefinition",
";",
"}",
";",
"Message",
".",
"datatype",
"=",
"function",
"(",
")",
"{",
"return",
"msgSpec",
".",
"getFullMessageName",
"(",
")",
";",
"}",
";",
"return",
"Message",
";",
"}"
] |
Construct the class definition for the given message type. The
resulting class holds the data and has the methods required for
use with ROS, incl. serialization, deserialization, and md5sum.
|
[
"Construct",
"the",
"class",
"definition",
"for",
"the",
"given",
"message",
"type",
".",
"The",
"resulting",
"class",
"holds",
"the",
"data",
"and",
"has",
"the",
"methods",
"required",
"for",
"use",
"with",
"ROS",
"incl",
".",
"serialization",
"deserialization",
"and",
"md5sum",
"."
] |
2b2921f5a66ebd52f515b70f3cf4fba781e924c2
|
https://github.com/RethinkRobotics-opensource/rosnodejs/blob/2b2921f5a66ebd52f515b70f3cf4fba781e924c2/src/utils/messageGeneration/messages.js#L443-L522
|
18,444
|
RethinkRobotics-opensource/rosnodejs
|
src/ros_msg_utils/lib/base_deserialize.js
|
DefaultArrayDeserializer
|
function DefaultArrayDeserializer(deserializeFunc, buffer, bufferOffset, arrayLen=null) {
// interpret a negative array len as a variable length array
// so we need to parse its length ourselves
if (arrayLen === null || arrayLen < 0) {
arrayLen = getArrayLen(buffer, bufferOffset);
}
const array = new Array(arrayLen);
for (let i = 0; i < arrayLen; ++i) {
array[i] = deserializeFunc(buffer, bufferOffset, null);
}
return array;
}
|
javascript
|
function DefaultArrayDeserializer(deserializeFunc, buffer, bufferOffset, arrayLen=null) {
// interpret a negative array len as a variable length array
// so we need to parse its length ourselves
if (arrayLen === null || arrayLen < 0) {
arrayLen = getArrayLen(buffer, bufferOffset);
}
const array = new Array(arrayLen);
for (let i = 0; i < arrayLen; ++i) {
array[i] = deserializeFunc(buffer, bufferOffset, null);
}
return array;
}
|
[
"function",
"DefaultArrayDeserializer",
"(",
"deserializeFunc",
",",
"buffer",
",",
"bufferOffset",
",",
"arrayLen",
"=",
"null",
")",
"{",
"// interpret a negative array len as a variable length array",
"// so we need to parse its length ourselves",
"if",
"(",
"arrayLen",
"===",
"null",
"||",
"arrayLen",
"<",
"0",
")",
"{",
"arrayLen",
"=",
"getArrayLen",
"(",
"buffer",
",",
"bufferOffset",
")",
";",
"}",
"const",
"array",
"=",
"new",
"Array",
"(",
"arrayLen",
")",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"arrayLen",
";",
"++",
"i",
")",
"{",
"array",
"[",
"i",
"]",
"=",
"deserializeFunc",
"(",
"buffer",
",",
"bufferOffset",
",",
"null",
")",
";",
"}",
"return",
"array",
";",
"}"
] |
Template for most primitive array deserializers which are bound to this function and provide
the deserializeFunc param
@param deserializeFunc {function} function to deserialize a single instance of the type. Typically hidden
from users by binding.
@param buffer {Buffer} buffer to deserialize data from
@param bufferOffset {Array.number}
@param arrayLen {null|number}
@returns {Array}
@constructor
|
[
"Template",
"for",
"most",
"primitive",
"array",
"deserializers",
"which",
"are",
"bound",
"to",
"this",
"function",
"and",
"provide",
"the",
"deserializeFunc",
"param"
] |
2b2921f5a66ebd52f515b70f3cf4fba781e924c2
|
https://github.com/RethinkRobotics-opensource/rosnodejs/blob/2b2921f5a66ebd52f515b70f3cf4fba781e924c2/src/ros_msg_utils/lib/base_deserialize.js#L150-L161
|
18,445
|
RethinkRobotics-opensource/rosnodejs
|
src/ros_msg_utils/lib/base_deserialize.js
|
UInt8ArrayDeserializer
|
function UInt8ArrayDeserializer(buffer, bufferOffset, arrayLen=null) {
if (arrayLen === null || arrayLen < 0) {
arrayLen = getArrayLen(buffer, bufferOffset);
}
const array = buffer.slice(bufferOffset[0], bufferOffset[0] + arrayLen);
bufferOffset[0] += arrayLen;
return array;
}
|
javascript
|
function UInt8ArrayDeserializer(buffer, bufferOffset, arrayLen=null) {
if (arrayLen === null || arrayLen < 0) {
arrayLen = getArrayLen(buffer, bufferOffset);
}
const array = buffer.slice(bufferOffset[0], bufferOffset[0] + arrayLen);
bufferOffset[0] += arrayLen;
return array;
}
|
[
"function",
"UInt8ArrayDeserializer",
"(",
"buffer",
",",
"bufferOffset",
",",
"arrayLen",
"=",
"null",
")",
"{",
"if",
"(",
"arrayLen",
"===",
"null",
"||",
"arrayLen",
"<",
"0",
")",
"{",
"arrayLen",
"=",
"getArrayLen",
"(",
"buffer",
",",
"bufferOffset",
")",
";",
"}",
"const",
"array",
"=",
"buffer",
".",
"slice",
"(",
"bufferOffset",
"[",
"0",
"]",
",",
"bufferOffset",
"[",
"0",
"]",
"+",
"arrayLen",
")",
";",
"bufferOffset",
"[",
"0",
"]",
"+=",
"arrayLen",
";",
"return",
"array",
";",
"}"
] |
Specialized array deserialization for UInt8 Arrays
We return the raw buffer when deserializing uint8 arrays because it's much faster
|
[
"Specialized",
"array",
"deserialization",
"for",
"UInt8",
"Arrays",
"We",
"return",
"the",
"raw",
"buffer",
"when",
"deserializing",
"uint8",
"arrays",
"because",
"it",
"s",
"much",
"faster"
] |
2b2921f5a66ebd52f515b70f3cf4fba781e924c2
|
https://github.com/RethinkRobotics-opensource/rosnodejs/blob/2b2921f5a66ebd52f515b70f3cf4fba781e924c2/src/ros_msg_utils/lib/base_deserialize.js#L167-L175
|
18,446
|
jlongster/transducers.js
|
transducers.js
|
interpose
|
function interpose(coll, separator) {
if (arguments.length === 1) {
separator = coll;
return function(xform) {
return new Interpose(separator, xform);
};
}
return seq(coll, interpose(separator));
}
|
javascript
|
function interpose(coll, separator) {
if (arguments.length === 1) {
separator = coll;
return function(xform) {
return new Interpose(separator, xform);
};
}
return seq(coll, interpose(separator));
}
|
[
"function",
"interpose",
"(",
"coll",
",",
"separator",
")",
"{",
"if",
"(",
"arguments",
".",
"length",
"===",
"1",
")",
"{",
"separator",
"=",
"coll",
";",
"return",
"function",
"(",
"xform",
")",
"{",
"return",
"new",
"Interpose",
"(",
"separator",
",",
"xform",
")",
";",
"}",
";",
"}",
"return",
"seq",
"(",
"coll",
",",
"interpose",
"(",
"separator",
")",
")",
";",
"}"
] |
Returns a new collection containing elements of the given
collection, separated by the specified separator. Returns a
transducer if a collection is not provided.
|
[
"Returns",
"a",
"new",
"collection",
"containing",
"elements",
"of",
"the",
"given",
"collection",
"separated",
"by",
"the",
"specified",
"separator",
".",
"Returns",
"a",
"transducer",
"if",
"a",
"collection",
"is",
"not",
"provided",
"."
] |
28fcf69250ef5fad7407b4c3bbbac31c3744d05f
|
https://github.com/jlongster/transducers.js/blob/28fcf69250ef5fad7407b4c3bbbac31c3744d05f/transducers.js#L633-L641
|
18,447
|
jlongster/transducers.js
|
transducers.js
|
repeat
|
function repeat(coll, n) {
if (arguments.length === 1) {
n = coll;
return function(xform) {
return new Repeat(n, xform);
};
}
return seq(coll, repeat(n));
}
|
javascript
|
function repeat(coll, n) {
if (arguments.length === 1) {
n = coll;
return function(xform) {
return new Repeat(n, xform);
};
}
return seq(coll, repeat(n));
}
|
[
"function",
"repeat",
"(",
"coll",
",",
"n",
")",
"{",
"if",
"(",
"arguments",
".",
"length",
"===",
"1",
")",
"{",
"n",
"=",
"coll",
";",
"return",
"function",
"(",
"xform",
")",
"{",
"return",
"new",
"Repeat",
"(",
"n",
",",
"xform",
")",
";",
"}",
";",
"}",
"return",
"seq",
"(",
"coll",
",",
"repeat",
"(",
"n",
")",
")",
";",
"}"
] |
Returns a new collection containing elements of the given
collection, each repeated n times. Returns a transducer if a
collection is not provided.
|
[
"Returns",
"a",
"new",
"collection",
"containing",
"elements",
"of",
"the",
"given",
"collection",
"each",
"repeated",
"n",
"times",
".",
"Returns",
"a",
"transducer",
"if",
"a",
"collection",
"is",
"not",
"provided",
"."
] |
28fcf69250ef5fad7407b4c3bbbac31c3744d05f
|
https://github.com/jlongster/transducers.js/blob/28fcf69250ef5fad7407b4c3bbbac31c3744d05f/transducers.js#L673-L681
|
18,448
|
jlongster/transducers.js
|
transducers.js
|
takeNth
|
function takeNth(coll, nth) {
if (arguments.length === 1) {
nth = coll;
return function(xform) {
return new TakeNth(nth, xform);
};
}
return seq(coll, takeNth(nth));
}
|
javascript
|
function takeNth(coll, nth) {
if (arguments.length === 1) {
nth = coll;
return function(xform) {
return new TakeNth(nth, xform);
};
}
return seq(coll, takeNth(nth));
}
|
[
"function",
"takeNth",
"(",
"coll",
",",
"nth",
")",
"{",
"if",
"(",
"arguments",
".",
"length",
"===",
"1",
")",
"{",
"nth",
"=",
"coll",
";",
"return",
"function",
"(",
"xform",
")",
"{",
"return",
"new",
"TakeNth",
"(",
"nth",
",",
"xform",
")",
";",
"}",
";",
"}",
"return",
"seq",
"(",
"coll",
",",
"takeNth",
"(",
"nth",
")",
")",
";",
"}"
] |
Returns a new collection of every nth element of the given
collection. Returns a transducer if a collection is not provided.
|
[
"Returns",
"a",
"new",
"collection",
"of",
"every",
"nth",
"element",
"of",
"the",
"given",
"collection",
".",
"Returns",
"a",
"transducer",
"if",
"a",
"collection",
"is",
"not",
"provided",
"."
] |
28fcf69250ef5fad7407b4c3bbbac31c3744d05f
|
https://github.com/jlongster/transducers.js/blob/28fcf69250ef5fad7407b4c3bbbac31c3744d05f/transducers.js#L709-L717
|
18,449
|
jlongster/transducers.js
|
transducers.js
|
toArray
|
function toArray(coll, xform) {
if(!xform) {
return reduce(coll, arrayReducer, []);
}
return transduce(coll, xform, arrayReducer, []);
}
|
javascript
|
function toArray(coll, xform) {
if(!xform) {
return reduce(coll, arrayReducer, []);
}
return transduce(coll, xform, arrayReducer, []);
}
|
[
"function",
"toArray",
"(",
"coll",
",",
"xform",
")",
"{",
"if",
"(",
"!",
"xform",
")",
"{",
"return",
"reduce",
"(",
"coll",
",",
"arrayReducer",
",",
"[",
"]",
")",
";",
"}",
"return",
"transduce",
"(",
"coll",
",",
"xform",
",",
"arrayReducer",
",",
"[",
"]",
")",
";",
"}"
] |
building new collections
|
[
"building",
"new",
"collections"
] |
28fcf69250ef5fad7407b4c3bbbac31c3744d05f
|
https://github.com/jlongster/transducers.js/blob/28fcf69250ef5fad7407b4c3bbbac31c3744d05f/transducers.js#L800-L805
|
18,450
|
zendesk/ipcluster
|
lib/master.js
|
destroy_next
|
function destroy_next() {
if (old_retired_workers.length <= 0) {
return deferred.resolve();
}
destroyWorker.call(_self, old_retired_workers.shift().pid, reason, 0);
setTimeout(destroy_next, _self.options.spawn_delay);
}
|
javascript
|
function destroy_next() {
if (old_retired_workers.length <= 0) {
return deferred.resolve();
}
destroyWorker.call(_self, old_retired_workers.shift().pid, reason, 0);
setTimeout(destroy_next, _self.options.spawn_delay);
}
|
[
"function",
"destroy_next",
"(",
")",
"{",
"if",
"(",
"old_retired_workers",
".",
"length",
"<=",
"0",
")",
"{",
"return",
"deferred",
".",
"resolve",
"(",
")",
";",
"}",
"destroyWorker",
".",
"call",
"(",
"_self",
",",
"old_retired_workers",
".",
"shift",
"(",
")",
".",
"pid",
",",
"reason",
",",
"0",
")",
";",
"setTimeout",
"(",
"destroy_next",
",",
"_self",
".",
"options",
".",
"spawn_delay",
")",
";",
"}"
] |
we kill the retired workers with delay, to dampen the migrating hurd effect
|
[
"we",
"kill",
"the",
"retired",
"workers",
"with",
"delay",
"to",
"dampen",
"the",
"migrating",
"hurd",
"effect"
] |
30e4d57ba50452282fe4b140a7cda05319c13380
|
https://github.com/zendesk/ipcluster/blob/30e4d57ba50452282fe4b140a7cda05319c13380/lib/master.js#L395-L401
|
18,451
|
zendesk/ipcluster
|
lib/master.js
|
isWorkerCmd
|
function isWorkerCmd(cmd) {
cmd = cmd.concat(); // make a local copy of the array
// a worker has the same command line as the current process!
if (cmd.shift() !== process.execPath) return false; // execPath was used when spawning children
// workers *may* have more params, we care if all master params exist in the worker cli
for (var idx = 0; idx < master_args.length; idx++) {
if (cmd[idx] !== master_args[idx]) return false;
}
return true;
}
|
javascript
|
function isWorkerCmd(cmd) {
cmd = cmd.concat(); // make a local copy of the array
// a worker has the same command line as the current process!
if (cmd.shift() !== process.execPath) return false; // execPath was used when spawning children
// workers *may* have more params, we care if all master params exist in the worker cli
for (var idx = 0; idx < master_args.length; idx++) {
if (cmd[idx] !== master_args[idx]) return false;
}
return true;
}
|
[
"function",
"isWorkerCmd",
"(",
"cmd",
")",
"{",
"cmd",
"=",
"cmd",
".",
"concat",
"(",
")",
";",
"// make a local copy of the array",
"// a worker has the same command line as the current process!",
"if",
"(",
"cmd",
".",
"shift",
"(",
")",
"!==",
"process",
".",
"execPath",
")",
"return",
"false",
";",
"// execPath was used when spawning children",
"// workers *may* have more params, we care if all master params exist in the worker cli",
"for",
"(",
"var",
"idx",
"=",
"0",
";",
"idx",
"<",
"master_args",
".",
"length",
";",
"idx",
"++",
")",
"{",
"if",
"(",
"cmd",
"[",
"idx",
"]",
"!==",
"master_args",
"[",
"idx",
"]",
")",
"return",
"false",
";",
"}",
"return",
"true",
";",
"}"
] |
computed once now
|
[
"computed",
"once",
"now"
] |
30e4d57ba50452282fe4b140a7cda05319c13380
|
https://github.com/zendesk/ipcluster/blob/30e4d57ba50452282fe4b140a7cda05319c13380/lib/master.js#L528-L540
|
18,452
|
zendesk/ipcluster
|
lib/master.js
|
collect_worker_stats
|
function collect_worker_stats(worker, worker_type) {
var stats;
var band = ('band' in worker) ? worker.band : worker.xband;
stats = worker.getStats();
if (!('monitor_count' in stats))
stats.monitor_count = 1;
else
stats.monitor_count++;
// TODO: if a given stats object has been used to many times, something is wrong!
if (!collected[band]) {
collected[band] = {
live: null, retired: []
};
}
if (worker_type === 'live') {
collected[band].live = stats;
}
else {
collected[band].retired.push(stats);
}
var worker_rss = (stats && stats.mem && stats.mem.rss) || 0;
cluster_rss += worker_rss;
return worker_rss;
}
|
javascript
|
function collect_worker_stats(worker, worker_type) {
var stats;
var band = ('band' in worker) ? worker.band : worker.xband;
stats = worker.getStats();
if (!('monitor_count' in stats))
stats.monitor_count = 1;
else
stats.monitor_count++;
// TODO: if a given stats object has been used to many times, something is wrong!
if (!collected[band]) {
collected[band] = {
live: null, retired: []
};
}
if (worker_type === 'live') {
collected[band].live = stats;
}
else {
collected[band].retired.push(stats);
}
var worker_rss = (stats && stats.mem && stats.mem.rss) || 0;
cluster_rss += worker_rss;
return worker_rss;
}
|
[
"function",
"collect_worker_stats",
"(",
"worker",
",",
"worker_type",
")",
"{",
"var",
"stats",
";",
"var",
"band",
"=",
"(",
"'band'",
"in",
"worker",
")",
"?",
"worker",
".",
"band",
":",
"worker",
".",
"xband",
";",
"stats",
"=",
"worker",
".",
"getStats",
"(",
")",
";",
"if",
"(",
"!",
"(",
"'monitor_count'",
"in",
"stats",
")",
")",
"stats",
".",
"monitor_count",
"=",
"1",
";",
"else",
"stats",
".",
"monitor_count",
"++",
";",
"// TODO: if a given stats object has been used to many times, something is wrong!",
"if",
"(",
"!",
"collected",
"[",
"band",
"]",
")",
"{",
"collected",
"[",
"band",
"]",
"=",
"{",
"live",
":",
"null",
",",
"retired",
":",
"[",
"]",
"}",
";",
"}",
"if",
"(",
"worker_type",
"===",
"'live'",
")",
"{",
"collected",
"[",
"band",
"]",
".",
"live",
"=",
"stats",
";",
"}",
"else",
"{",
"collected",
"[",
"band",
"]",
".",
"retired",
".",
"push",
"(",
"stats",
")",
";",
"}",
"var",
"worker_rss",
"=",
"(",
"stats",
"&&",
"stats",
".",
"mem",
"&&",
"stats",
".",
"mem",
".",
"rss",
")",
"||",
"0",
";",
"cluster_rss",
"+=",
"worker_rss",
";",
"return",
"worker_rss",
";",
"}"
] |
Aggregate the worker stats into a data structure that will be passed to emitted events The function also returns the rss for that one worker
|
[
"Aggregate",
"the",
"worker",
"stats",
"into",
"a",
"data",
"structure",
"that",
"will",
"be",
"passed",
"to",
"emitted",
"events",
"The",
"function",
"also",
"returns",
"the",
"rss",
"for",
"that",
"one",
"worker"
] |
30e4d57ba50452282fe4b140a7cda05319c13380
|
https://github.com/zendesk/ipcluster/blob/30e4d57ba50452282fe4b140a7cda05319c13380/lib/master.js#L649-L680
|
18,453
|
macbre/analyze-css
|
rules/propertyResets.js
|
rule
|
function rule(analyzer) {
var debug = require('debug');
analyzer.setMetric('propertyResets');
analyzer.on('selector', function(rule, selector) {
var declarations = rule.declarations || [],
properties;
// prepare the list of properties used in this selector
properties = declarations.
map(function(declaration) {
return (declaration.type === 'declaration') ? declaration.property : false;
}).
filter(function(item) {
return item !== false;
});
debug('%s: %j', selector, properties);
// iterate through all properties, expand shorthand properties and
// check if there's no expanded version of it earlier in the array
properties.forEach(function(property, idx) {
var expanded;
// skip if the current property is not the shorthand version
if (typeof shorthandProperties.shorthandProperties[property] === 'undefined') {
return;
}
// property = 'margin'
// expanded = [ 'margin-top', 'margin-right', 'margin-bottom', 'margin-left' ]
expanded = shorthandProperties.expand(property);
debug('%s: %s', property, expanded.join(', '));
expanded.forEach(function(expandedProperty) {
var propertyPos = properties.indexOf(expandedProperty);
if (propertyPos > -1 && propertyPos < idx) {
analyzer.incrMetric('propertyResets');
analyzer.addOffender('propertyResets', format('%s: "%s" resets "%s" property set earlier', selector, property, expandedProperty));
}
});
});
});
}
|
javascript
|
function rule(analyzer) {
var debug = require('debug');
analyzer.setMetric('propertyResets');
analyzer.on('selector', function(rule, selector) {
var declarations = rule.declarations || [],
properties;
// prepare the list of properties used in this selector
properties = declarations.
map(function(declaration) {
return (declaration.type === 'declaration') ? declaration.property : false;
}).
filter(function(item) {
return item !== false;
});
debug('%s: %j', selector, properties);
// iterate through all properties, expand shorthand properties and
// check if there's no expanded version of it earlier in the array
properties.forEach(function(property, idx) {
var expanded;
// skip if the current property is not the shorthand version
if (typeof shorthandProperties.shorthandProperties[property] === 'undefined') {
return;
}
// property = 'margin'
// expanded = [ 'margin-top', 'margin-right', 'margin-bottom', 'margin-left' ]
expanded = shorthandProperties.expand(property);
debug('%s: %s', property, expanded.join(', '));
expanded.forEach(function(expandedProperty) {
var propertyPos = properties.indexOf(expandedProperty);
if (propertyPos > -1 && propertyPos < idx) {
analyzer.incrMetric('propertyResets');
analyzer.addOffender('propertyResets', format('%s: "%s" resets "%s" property set earlier', selector, property, expandedProperty));
}
});
});
});
}
|
[
"function",
"rule",
"(",
"analyzer",
")",
"{",
"var",
"debug",
"=",
"require",
"(",
"'debug'",
")",
";",
"analyzer",
".",
"setMetric",
"(",
"'propertyResets'",
")",
";",
"analyzer",
".",
"on",
"(",
"'selector'",
",",
"function",
"(",
"rule",
",",
"selector",
")",
"{",
"var",
"declarations",
"=",
"rule",
".",
"declarations",
"||",
"[",
"]",
",",
"properties",
";",
"// prepare the list of properties used in this selector",
"properties",
"=",
"declarations",
".",
"map",
"(",
"function",
"(",
"declaration",
")",
"{",
"return",
"(",
"declaration",
".",
"type",
"===",
"'declaration'",
")",
"?",
"declaration",
".",
"property",
":",
"false",
";",
"}",
")",
".",
"filter",
"(",
"function",
"(",
"item",
")",
"{",
"return",
"item",
"!==",
"false",
";",
"}",
")",
";",
"debug",
"(",
"'%s: %j'",
",",
"selector",
",",
"properties",
")",
";",
"// iterate through all properties, expand shorthand properties and",
"// check if there's no expanded version of it earlier in the array",
"properties",
".",
"forEach",
"(",
"function",
"(",
"property",
",",
"idx",
")",
"{",
"var",
"expanded",
";",
"// skip if the current property is not the shorthand version",
"if",
"(",
"typeof",
"shorthandProperties",
".",
"shorthandProperties",
"[",
"property",
"]",
"===",
"'undefined'",
")",
"{",
"return",
";",
"}",
"// property = 'margin'",
"// expanded = [ 'margin-top', 'margin-right', 'margin-bottom', 'margin-left' ]",
"expanded",
"=",
"shorthandProperties",
".",
"expand",
"(",
"property",
")",
";",
"debug",
"(",
"'%s: %s'",
",",
"property",
",",
"expanded",
".",
"join",
"(",
"', '",
")",
")",
";",
"expanded",
".",
"forEach",
"(",
"function",
"(",
"expandedProperty",
")",
"{",
"var",
"propertyPos",
"=",
"properties",
".",
"indexOf",
"(",
"expandedProperty",
")",
";",
"if",
"(",
"propertyPos",
">",
"-",
"1",
"&&",
"propertyPos",
"<",
"idx",
")",
"{",
"analyzer",
".",
"incrMetric",
"(",
"'propertyResets'",
")",
";",
"analyzer",
".",
"addOffender",
"(",
"'propertyResets'",
",",
"format",
"(",
"'%s: \"%s\" resets \"%s\" property set earlier'",
",",
"selector",
",",
"property",
",",
"expandedProperty",
")",
")",
";",
"}",
"}",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] |
Detect accidental property resets
@see http://css-tricks.com/accidental-css-resets/
|
[
"Detect",
"accidental",
"property",
"resets"
] |
1e93096f9d70a36bd353241855ac97b34e8ead54
|
https://github.com/macbre/analyze-css/blob/1e93096f9d70a36bd353241855ac97b34e8ead54/rules/propertyResets.js#L12-L57
|
18,454
|
macbre/analyze-css
|
rules/minified.js
|
rule
|
function rule(analyzer) {
analyzer.setMetric('notMinified');
/**
* A simple CSS minification detector
*/
function isMinified(css) {
// analyze the first 1024 characters
css = css.trim().substring(0, 1024);
// there should be no newline in minified file
return /\n/.test(css) === false;
}
analyzer.on('css', function(css) {
analyzer.setMetric('notMinified', isMinified(css) ? 0 : 1);
});
}
|
javascript
|
function rule(analyzer) {
analyzer.setMetric('notMinified');
/**
* A simple CSS minification detector
*/
function isMinified(css) {
// analyze the first 1024 characters
css = css.trim().substring(0, 1024);
// there should be no newline in minified file
return /\n/.test(css) === false;
}
analyzer.on('css', function(css) {
analyzer.setMetric('notMinified', isMinified(css) ? 0 : 1);
});
}
|
[
"function",
"rule",
"(",
"analyzer",
")",
"{",
"analyzer",
".",
"setMetric",
"(",
"'notMinified'",
")",
";",
"/**\n\t * A simple CSS minification detector\n\t */",
"function",
"isMinified",
"(",
"css",
")",
"{",
"// analyze the first 1024 characters",
"css",
"=",
"css",
".",
"trim",
"(",
")",
".",
"substring",
"(",
"0",
",",
"1024",
")",
";",
"// there should be no newline in minified file",
"return",
"/",
"\\n",
"/",
".",
"test",
"(",
"css",
")",
"===",
"false",
";",
"}",
"analyzer",
".",
"on",
"(",
"'css'",
",",
"function",
"(",
"css",
")",
"{",
"analyzer",
".",
"setMetric",
"(",
"'notMinified'",
",",
"isMinified",
"(",
"css",
")",
"?",
"0",
":",
"1",
")",
";",
"}",
")",
";",
"}"
] |
Detect not minified CSS
|
[
"Detect",
"not",
"minified",
"CSS"
] |
1e93096f9d70a36bd353241855ac97b34e8ead54
|
https://github.com/macbre/analyze-css/blob/1e93096f9d70a36bd353241855ac97b34e8ead54/rules/minified.js#L6-L23
|
18,455
|
macbre/analyze-css
|
rules/ieFixes.js
|
rule
|
function rule(analyzer) {
var re = {
property: /^(\*|-ms-filter)/,
selector: /^(\* html|html\s?>\s?body) /,
value: /progid:DXImageTransform\.Microsoft|!ie$/
};
analyzer.setMetric('oldIEFixes');
// * html // below IE7 fix
// html>body // IE6 excluded fix
// @see http://blogs.msdn.com/b/ie/archive/2005/09/02/460115.aspx
analyzer.on('selector', function(rule, selector) {
if (re.selector.test(selector)) {
analyzer.incrMetric('oldIEFixes');
analyzer.addOffender('oldIEFixes', selector);
}
});
// *foo: bar // IE7 and below fix
// -ms-filter // IE9 and below specific property
// !ie // IE 7 and below equivalent of !important
// @see http://www.impressivewebs.com/ie7-ie8-css-hacks/
analyzer.on('declaration', function(rule, property, value) {
if (re.property.test(property) || re.value.test(value)) {
analyzer.incrMetric('oldIEFixes');
analyzer.addOffender('oldIEFixes', format('%s {%s: %s}', rule.selectors.join(', '), property, value));
}
});
}
|
javascript
|
function rule(analyzer) {
var re = {
property: /^(\*|-ms-filter)/,
selector: /^(\* html|html\s?>\s?body) /,
value: /progid:DXImageTransform\.Microsoft|!ie$/
};
analyzer.setMetric('oldIEFixes');
// * html // below IE7 fix
// html>body // IE6 excluded fix
// @see http://blogs.msdn.com/b/ie/archive/2005/09/02/460115.aspx
analyzer.on('selector', function(rule, selector) {
if (re.selector.test(selector)) {
analyzer.incrMetric('oldIEFixes');
analyzer.addOffender('oldIEFixes', selector);
}
});
// *foo: bar // IE7 and below fix
// -ms-filter // IE9 and below specific property
// !ie // IE 7 and below equivalent of !important
// @see http://www.impressivewebs.com/ie7-ie8-css-hacks/
analyzer.on('declaration', function(rule, property, value) {
if (re.property.test(property) || re.value.test(value)) {
analyzer.incrMetric('oldIEFixes');
analyzer.addOffender('oldIEFixes', format('%s {%s: %s}', rule.selectors.join(', '), property, value));
}
});
}
|
[
"function",
"rule",
"(",
"analyzer",
")",
"{",
"var",
"re",
"=",
"{",
"property",
":",
"/",
"^(\\*|-ms-filter)",
"/",
",",
"selector",
":",
"/",
"^(\\* html|html\\s?>\\s?body) ",
"/",
",",
"value",
":",
"/",
"progid:DXImageTransform\\.Microsoft|!ie$",
"/",
"}",
";",
"analyzer",
".",
"setMetric",
"(",
"'oldIEFixes'",
")",
";",
"// * html // below IE7 fix",
"// html>body // IE6 excluded fix",
"// @see http://blogs.msdn.com/b/ie/archive/2005/09/02/460115.aspx",
"analyzer",
".",
"on",
"(",
"'selector'",
",",
"function",
"(",
"rule",
",",
"selector",
")",
"{",
"if",
"(",
"re",
".",
"selector",
".",
"test",
"(",
"selector",
")",
")",
"{",
"analyzer",
".",
"incrMetric",
"(",
"'oldIEFixes'",
")",
";",
"analyzer",
".",
"addOffender",
"(",
"'oldIEFixes'",
",",
"selector",
")",
";",
"}",
"}",
")",
";",
"// *foo: bar // IE7 and below fix",
"// -ms-filter // IE9 and below specific property",
"// !ie // IE 7 and below equivalent of !important",
"// @see http://www.impressivewebs.com/ie7-ie8-css-hacks/",
"analyzer",
".",
"on",
"(",
"'declaration'",
",",
"function",
"(",
"rule",
",",
"property",
",",
"value",
")",
"{",
"if",
"(",
"re",
".",
"property",
".",
"test",
"(",
"property",
")",
"||",
"re",
".",
"value",
".",
"test",
"(",
"value",
")",
")",
"{",
"analyzer",
".",
"incrMetric",
"(",
"'oldIEFixes'",
")",
";",
"analyzer",
".",
"addOffender",
"(",
"'oldIEFixes'",
",",
"format",
"(",
"'%s {%s: %s}'",
",",
"rule",
".",
"selectors",
".",
"join",
"(",
"', '",
")",
",",
"property",
",",
"value",
")",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Rules below match ugly fixes for IE9 and below
@see http://browserhacks.com/
|
[
"Rules",
"below",
"match",
"ugly",
"fixes",
"for",
"IE9",
"and",
"below"
] |
1e93096f9d70a36bd353241855ac97b34e8ead54
|
https://github.com/macbre/analyze-css/blob/1e93096f9d70a36bd353241855ac97b34e8ead54/rules/ieFixes.js#L10-L39
|
18,456
|
macbre/analyze-css
|
lib/runner.js
|
request
|
function request(requestOptions, callback) {
var debug = require('debug')('analyze-css:http'),
fetch = require('node-fetch');
debug('GET %s', requestOptions.url);
debug('Options: %j', requestOptions);
fetch(requestOptions.url, requestOptions).
then(function(resp) {
debug('HTTP %d %s', resp.status, resp.statusText);
debug('Headers: %j', resp.headers._headers);
if (!resp.ok) {
var err = new Error('HTTP request failed: ' + (err ? err.toString() : 'received HTTP ' + resp.status + ' ' + resp.statusText));
callback(err);
} else {
return resp.text(); // a promise
}
}).
then(function(body) {
debug('Received %d bytes of CSS', body.length);
callback(null, body);
}).
catch(function(err) {
debug(err);
callback(err);
});
}
|
javascript
|
function request(requestOptions, callback) {
var debug = require('debug')('analyze-css:http'),
fetch = require('node-fetch');
debug('GET %s', requestOptions.url);
debug('Options: %j', requestOptions);
fetch(requestOptions.url, requestOptions).
then(function(resp) {
debug('HTTP %d %s', resp.status, resp.statusText);
debug('Headers: %j', resp.headers._headers);
if (!resp.ok) {
var err = new Error('HTTP request failed: ' + (err ? err.toString() : 'received HTTP ' + resp.status + ' ' + resp.statusText));
callback(err);
} else {
return resp.text(); // a promise
}
}).
then(function(body) {
debug('Received %d bytes of CSS', body.length);
callback(null, body);
}).
catch(function(err) {
debug(err);
callback(err);
});
}
|
[
"function",
"request",
"(",
"requestOptions",
",",
"callback",
")",
"{",
"var",
"debug",
"=",
"require",
"(",
"'debug'",
")",
"(",
"'analyze-css:http'",
")",
",",
"fetch",
"=",
"require",
"(",
"'node-fetch'",
")",
";",
"debug",
"(",
"'GET %s'",
",",
"requestOptions",
".",
"url",
")",
";",
"debug",
"(",
"'Options: %j'",
",",
"requestOptions",
")",
";",
"fetch",
"(",
"requestOptions",
".",
"url",
",",
"requestOptions",
")",
".",
"then",
"(",
"function",
"(",
"resp",
")",
"{",
"debug",
"(",
"'HTTP %d %s'",
",",
"resp",
".",
"status",
",",
"resp",
".",
"statusText",
")",
";",
"debug",
"(",
"'Headers: %j'",
",",
"resp",
".",
"headers",
".",
"_headers",
")",
";",
"if",
"(",
"!",
"resp",
".",
"ok",
")",
"{",
"var",
"err",
"=",
"new",
"Error",
"(",
"'HTTP request failed: '",
"+",
"(",
"err",
"?",
"err",
".",
"toString",
"(",
")",
":",
"'received HTTP '",
"+",
"resp",
".",
"status",
"+",
"' '",
"+",
"resp",
".",
"statusText",
")",
")",
";",
"callback",
"(",
"err",
")",
";",
"}",
"else",
"{",
"return",
"resp",
".",
"text",
"(",
")",
";",
"// a promise",
"}",
"}",
")",
".",
"then",
"(",
"function",
"(",
"body",
")",
"{",
"debug",
"(",
"'Received %d bytes of CSS'",
",",
"body",
".",
"length",
")",
";",
"callback",
"(",
"null",
",",
"body",
")",
";",
"}",
")",
".",
"catch",
"(",
"function",
"(",
"err",
")",
"{",
"debug",
"(",
"err",
")",
";",
"callback",
"(",
"err",
")",
";",
"}",
")",
";",
"}"
] |
Simplified implementation of "request" npm module
@see https://www.npmjs.com/package/node-fetch
|
[
"Simplified",
"implementation",
"of",
"request",
"npm",
"module"
] |
1e93096f9d70a36bd353241855ac97b34e8ead54
|
https://github.com/macbre/analyze-css/blob/1e93096f9d70a36bd353241855ac97b34e8ead54/lib/runner.js#L37-L64
|
18,457
|
macbre/analyze-css
|
lib/runner.js
|
runner
|
function runner(options, callback) {
// call CommonJS module
var analyzerOpts = {
'noOffenders': options.noOffenders,
'preprocessor': false,
};
function analyze(css) {
new analyzer(css, analyzerOpts, callback);
}
if (options.url) {
debug('Fetching remote CSS file: %s', options.url);
// @see https://www.npmjs.com/package/node-fetch#options
var agentOptions = {},
requestOptions = {
url: options.url,
headers: {
'User-Agent': getUserAgent()
}
};
// handle options
// @see https://github.com/bitinn/node-fetch/issues/15
// @see https://nodejs.org/api/https.html#https_https_request_options_callback
if (options.ignoreSslErrors) {
agentOptions.rejectUnauthorized = false;
}
// @see https://gist.github.com/cojohn/1772154
if (options.authUser && options.authPass) {
requestOptions.headers.Authorization = "Basic " + new Buffer(options.authUser + ":" + options.authPass, "utf8").toString("base64");
}
// @see https://nodejs.org/api/http.html#http_class_http_agent
var client = require(/^https:/.test(options.url) ? 'https' : 'http');
requestOptions.agent = new client.Agent(agentOptions);
// @see http://stackoverflow.com/a/5810547
options.proxy = options.proxy || process.env.HTTP_PROXY;
if (options.proxy) {
debug('Using HTTP proxy: %s', options.proxy);
requestOptions.agent = new(require('http-proxy-agent'))(options.proxy);
}
request(requestOptions, function(err, css) {
if (err) {
err.code = analyzer.EXIT_URL_LOADING_FAILED;
debug(err);
callback(err);
} else {
analyze(css);
}
});
} else if (options.file) {
// resolve to the full path
options.file = resolve(process.cwd(), options.file);
debug('Loading local CSS file: %s', options.file);
fs.readFile(options.file, {
encoding: 'utf-8'
}, function(err, css) {
if (err) {
err = new Error('Loading CSS file failed: ' + err.toString());
err.code = analyzer.EXIT_FILE_LOADING_FAILED;
debug(err);
callback(err);
} else {
// find the matching preprocessor and use it
if (analyzerOpts.preprocessor === false) {
analyzerOpts.preprocessor = preprocessors.findMatchingByFileName(options.file);
}
// pass the name of the file being analyzed
analyzerOpts.file = options.file;
analyze(css);
}
});
} else if (options.stdin) {
debug('Reading from stdin');
cli.withStdin(analyze);
}
}
|
javascript
|
function runner(options, callback) {
// call CommonJS module
var analyzerOpts = {
'noOffenders': options.noOffenders,
'preprocessor': false,
};
function analyze(css) {
new analyzer(css, analyzerOpts, callback);
}
if (options.url) {
debug('Fetching remote CSS file: %s', options.url);
// @see https://www.npmjs.com/package/node-fetch#options
var agentOptions = {},
requestOptions = {
url: options.url,
headers: {
'User-Agent': getUserAgent()
}
};
// handle options
// @see https://github.com/bitinn/node-fetch/issues/15
// @see https://nodejs.org/api/https.html#https_https_request_options_callback
if (options.ignoreSslErrors) {
agentOptions.rejectUnauthorized = false;
}
// @see https://gist.github.com/cojohn/1772154
if (options.authUser && options.authPass) {
requestOptions.headers.Authorization = "Basic " + new Buffer(options.authUser + ":" + options.authPass, "utf8").toString("base64");
}
// @see https://nodejs.org/api/http.html#http_class_http_agent
var client = require(/^https:/.test(options.url) ? 'https' : 'http');
requestOptions.agent = new client.Agent(agentOptions);
// @see http://stackoverflow.com/a/5810547
options.proxy = options.proxy || process.env.HTTP_PROXY;
if (options.proxy) {
debug('Using HTTP proxy: %s', options.proxy);
requestOptions.agent = new(require('http-proxy-agent'))(options.proxy);
}
request(requestOptions, function(err, css) {
if (err) {
err.code = analyzer.EXIT_URL_LOADING_FAILED;
debug(err);
callback(err);
} else {
analyze(css);
}
});
} else if (options.file) {
// resolve to the full path
options.file = resolve(process.cwd(), options.file);
debug('Loading local CSS file: %s', options.file);
fs.readFile(options.file, {
encoding: 'utf-8'
}, function(err, css) {
if (err) {
err = new Error('Loading CSS file failed: ' + err.toString());
err.code = analyzer.EXIT_FILE_LOADING_FAILED;
debug(err);
callback(err);
} else {
// find the matching preprocessor and use it
if (analyzerOpts.preprocessor === false) {
analyzerOpts.preprocessor = preprocessors.findMatchingByFileName(options.file);
}
// pass the name of the file being analyzed
analyzerOpts.file = options.file;
analyze(css);
}
});
} else if (options.stdin) {
debug('Reading from stdin');
cli.withStdin(analyze);
}
}
|
[
"function",
"runner",
"(",
"options",
",",
"callback",
")",
"{",
"// call CommonJS module",
"var",
"analyzerOpts",
"=",
"{",
"'noOffenders'",
":",
"options",
".",
"noOffenders",
",",
"'preprocessor'",
":",
"false",
",",
"}",
";",
"function",
"analyze",
"(",
"css",
")",
"{",
"new",
"analyzer",
"(",
"css",
",",
"analyzerOpts",
",",
"callback",
")",
";",
"}",
"if",
"(",
"options",
".",
"url",
")",
"{",
"debug",
"(",
"'Fetching remote CSS file: %s'",
",",
"options",
".",
"url",
")",
";",
"// @see https://www.npmjs.com/package/node-fetch#options",
"var",
"agentOptions",
"=",
"{",
"}",
",",
"requestOptions",
"=",
"{",
"url",
":",
"options",
".",
"url",
",",
"headers",
":",
"{",
"'User-Agent'",
":",
"getUserAgent",
"(",
")",
"}",
"}",
";",
"// handle options",
"// @see https://github.com/bitinn/node-fetch/issues/15",
"// @see https://nodejs.org/api/https.html#https_https_request_options_callback",
"if",
"(",
"options",
".",
"ignoreSslErrors",
")",
"{",
"agentOptions",
".",
"rejectUnauthorized",
"=",
"false",
";",
"}",
"// @see https://gist.github.com/cojohn/1772154",
"if",
"(",
"options",
".",
"authUser",
"&&",
"options",
".",
"authPass",
")",
"{",
"requestOptions",
".",
"headers",
".",
"Authorization",
"=",
"\"Basic \"",
"+",
"new",
"Buffer",
"(",
"options",
".",
"authUser",
"+",
"\":\"",
"+",
"options",
".",
"authPass",
",",
"\"utf8\"",
")",
".",
"toString",
"(",
"\"base64\"",
")",
";",
"}",
"// @see https://nodejs.org/api/http.html#http_class_http_agent",
"var",
"client",
"=",
"require",
"(",
"/",
"^https:",
"/",
".",
"test",
"(",
"options",
".",
"url",
")",
"?",
"'https'",
":",
"'http'",
")",
";",
"requestOptions",
".",
"agent",
"=",
"new",
"client",
".",
"Agent",
"(",
"agentOptions",
")",
";",
"// @see http://stackoverflow.com/a/5810547",
"options",
".",
"proxy",
"=",
"options",
".",
"proxy",
"||",
"process",
".",
"env",
".",
"HTTP_PROXY",
";",
"if",
"(",
"options",
".",
"proxy",
")",
"{",
"debug",
"(",
"'Using HTTP proxy: %s'",
",",
"options",
".",
"proxy",
")",
";",
"requestOptions",
".",
"agent",
"=",
"new",
"(",
"require",
"(",
"'http-proxy-agent'",
")",
")",
"(",
"options",
".",
"proxy",
")",
";",
"}",
"request",
"(",
"requestOptions",
",",
"function",
"(",
"err",
",",
"css",
")",
"{",
"if",
"(",
"err",
")",
"{",
"err",
".",
"code",
"=",
"analyzer",
".",
"EXIT_URL_LOADING_FAILED",
";",
"debug",
"(",
"err",
")",
";",
"callback",
"(",
"err",
")",
";",
"}",
"else",
"{",
"analyze",
"(",
"css",
")",
";",
"}",
"}",
")",
";",
"}",
"else",
"if",
"(",
"options",
".",
"file",
")",
"{",
"// resolve to the full path",
"options",
".",
"file",
"=",
"resolve",
"(",
"process",
".",
"cwd",
"(",
")",
",",
"options",
".",
"file",
")",
";",
"debug",
"(",
"'Loading local CSS file: %s'",
",",
"options",
".",
"file",
")",
";",
"fs",
".",
"readFile",
"(",
"options",
".",
"file",
",",
"{",
"encoding",
":",
"'utf-8'",
"}",
",",
"function",
"(",
"err",
",",
"css",
")",
"{",
"if",
"(",
"err",
")",
"{",
"err",
"=",
"new",
"Error",
"(",
"'Loading CSS file failed: '",
"+",
"err",
".",
"toString",
"(",
")",
")",
";",
"err",
".",
"code",
"=",
"analyzer",
".",
"EXIT_FILE_LOADING_FAILED",
";",
"debug",
"(",
"err",
")",
";",
"callback",
"(",
"err",
")",
";",
"}",
"else",
"{",
"// find the matching preprocessor and use it",
"if",
"(",
"analyzerOpts",
".",
"preprocessor",
"===",
"false",
")",
"{",
"analyzerOpts",
".",
"preprocessor",
"=",
"preprocessors",
".",
"findMatchingByFileName",
"(",
"options",
".",
"file",
")",
";",
"}",
"// pass the name of the file being analyzed",
"analyzerOpts",
".",
"file",
"=",
"options",
".",
"file",
";",
"analyze",
"(",
"css",
")",
";",
"}",
"}",
")",
";",
"}",
"else",
"if",
"(",
"options",
".",
"stdin",
")",
"{",
"debug",
"(",
"'Reading from stdin'",
")",
";",
"cli",
".",
"withStdin",
"(",
"analyze",
")",
";",
"}",
"}"
] |
Module's main function
|
[
"Module",
"s",
"main",
"function"
] |
1e93096f9d70a36bd353241855ac97b34e8ead54
|
https://github.com/macbre/analyze-css/blob/1e93096f9d70a36bd353241855ac97b34e8ead54/lib/runner.js#L69-L158
|
18,458
|
TooTallNate/node-wav
|
lib/file-writer.js
|
FileWriter
|
function FileWriter (path, opts) {
if (!(this instanceof FileWriter)) return new FileWriter(path, opts);
Writer.call(this, opts);
this.path = path;
this.file = fs.createWriteStream(path, opts);
this.pipe(this.file);
this.on('header', this._onHeader);
}
|
javascript
|
function FileWriter (path, opts) {
if (!(this instanceof FileWriter)) return new FileWriter(path, opts);
Writer.call(this, opts);
this.path = path;
this.file = fs.createWriteStream(path, opts);
this.pipe(this.file);
this.on('header', this._onHeader);
}
|
[
"function",
"FileWriter",
"(",
"path",
",",
"opts",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"FileWriter",
")",
")",
"return",
"new",
"FileWriter",
"(",
"path",
",",
"opts",
")",
";",
"Writer",
".",
"call",
"(",
"this",
",",
"opts",
")",
";",
"this",
".",
"path",
"=",
"path",
";",
"this",
".",
"file",
"=",
"fs",
".",
"createWriteStream",
"(",
"path",
",",
"opts",
")",
";",
"this",
".",
"pipe",
"(",
"this",
".",
"file",
")",
";",
"this",
".",
"on",
"(",
"'header'",
",",
"this",
".",
"_onHeader",
")",
";",
"}"
] |
The `FileWriter` class.
@param {String} path The file path to write the WAVE file to
@param {Object} opts Object contains options for the stream and format info
@api public
|
[
"The",
"FileWriter",
"class",
"."
] |
a7f9fd33909321a8c1212cc87d6c03223923cad4
|
https://github.com/TooTallNate/node-wav/blob/a7f9fd33909321a8c1212cc87d6c03223923cad4/lib/file-writer.js#L24-L31
|
18,459
|
feathers-plus/feathers-authentication-management
|
src/check-unique.js
|
checkUnique
|
async function checkUnique (options, identifyUser, ownId, meta) {
debug('checkUnique', identifyUser, ownId, meta);
const usersService = options.app.service(options.service);
const usersServiceIdName = usersService.id;
const allProps = [];
const keys = Object.keys(identifyUser).filter(
key => !isNullsy(identifyUser[key])
);
try {
for (let i = 0, ilen = keys.length; i < ilen; i++) {
const prop = keys[i];
const users = await usersService.find({ query: { [prop]: identifyUser[prop].trim() } });
const items = Array.isArray(users) ? users : users.data;
const isNotUnique = items.length > 1 ||
(items.length === 1 && items[0][usersServiceIdName] !== ownId);
allProps.push(isNotUnique ? prop : null);
}
} catch (err) {
throw new errors.BadRequest(meta.noErrMsg ? null : 'checkUnique unexpected error.',
{ errors: { msg: err.message, $className: 'unexpected' } }
);
}
const errProps = allProps.filter(prop => prop);
if (errProps.length) {
const errs = {};
errProps.forEach(prop => { errs[prop] = 'Already taken.'; });
throw new errors.BadRequest(meta.noErrMsg ? null : 'Values already taken.',
{ errors: errs }
);
}
return null;
}
|
javascript
|
async function checkUnique (options, identifyUser, ownId, meta) {
debug('checkUnique', identifyUser, ownId, meta);
const usersService = options.app.service(options.service);
const usersServiceIdName = usersService.id;
const allProps = [];
const keys = Object.keys(identifyUser).filter(
key => !isNullsy(identifyUser[key])
);
try {
for (let i = 0, ilen = keys.length; i < ilen; i++) {
const prop = keys[i];
const users = await usersService.find({ query: { [prop]: identifyUser[prop].trim() } });
const items = Array.isArray(users) ? users : users.data;
const isNotUnique = items.length > 1 ||
(items.length === 1 && items[0][usersServiceIdName] !== ownId);
allProps.push(isNotUnique ? prop : null);
}
} catch (err) {
throw new errors.BadRequest(meta.noErrMsg ? null : 'checkUnique unexpected error.',
{ errors: { msg: err.message, $className: 'unexpected' } }
);
}
const errProps = allProps.filter(prop => prop);
if (errProps.length) {
const errs = {};
errProps.forEach(prop => { errs[prop] = 'Already taken.'; });
throw new errors.BadRequest(meta.noErrMsg ? null : 'Values already taken.',
{ errors: errs }
);
}
return null;
}
|
[
"async",
"function",
"checkUnique",
"(",
"options",
",",
"identifyUser",
",",
"ownId",
",",
"meta",
")",
"{",
"debug",
"(",
"'checkUnique'",
",",
"identifyUser",
",",
"ownId",
",",
"meta",
")",
";",
"const",
"usersService",
"=",
"options",
".",
"app",
".",
"service",
"(",
"options",
".",
"service",
")",
";",
"const",
"usersServiceIdName",
"=",
"usersService",
".",
"id",
";",
"const",
"allProps",
"=",
"[",
"]",
";",
"const",
"keys",
"=",
"Object",
".",
"keys",
"(",
"identifyUser",
")",
".",
"filter",
"(",
"key",
"=>",
"!",
"isNullsy",
"(",
"identifyUser",
"[",
"key",
"]",
")",
")",
";",
"try",
"{",
"for",
"(",
"let",
"i",
"=",
"0",
",",
"ilen",
"=",
"keys",
".",
"length",
";",
"i",
"<",
"ilen",
";",
"i",
"++",
")",
"{",
"const",
"prop",
"=",
"keys",
"[",
"i",
"]",
";",
"const",
"users",
"=",
"await",
"usersService",
".",
"find",
"(",
"{",
"query",
":",
"{",
"[",
"prop",
"]",
":",
"identifyUser",
"[",
"prop",
"]",
".",
"trim",
"(",
")",
"}",
"}",
")",
";",
"const",
"items",
"=",
"Array",
".",
"isArray",
"(",
"users",
")",
"?",
"users",
":",
"users",
".",
"data",
";",
"const",
"isNotUnique",
"=",
"items",
".",
"length",
">",
"1",
"||",
"(",
"items",
".",
"length",
"===",
"1",
"&&",
"items",
"[",
"0",
"]",
"[",
"usersServiceIdName",
"]",
"!==",
"ownId",
")",
";",
"allProps",
".",
"push",
"(",
"isNotUnique",
"?",
"prop",
":",
"null",
")",
";",
"}",
"}",
"catch",
"(",
"err",
")",
"{",
"throw",
"new",
"errors",
".",
"BadRequest",
"(",
"meta",
".",
"noErrMsg",
"?",
"null",
":",
"'checkUnique unexpected error.'",
",",
"{",
"errors",
":",
"{",
"msg",
":",
"err",
".",
"message",
",",
"$className",
":",
"'unexpected'",
"}",
"}",
")",
";",
"}",
"const",
"errProps",
"=",
"allProps",
".",
"filter",
"(",
"prop",
"=>",
"prop",
")",
";",
"if",
"(",
"errProps",
".",
"length",
")",
"{",
"const",
"errs",
"=",
"{",
"}",
";",
"errProps",
".",
"forEach",
"(",
"prop",
"=>",
"{",
"errs",
"[",
"prop",
"]",
"=",
"'Already taken.'",
";",
"}",
")",
";",
"throw",
"new",
"errors",
".",
"BadRequest",
"(",
"meta",
".",
"noErrMsg",
"?",
"null",
":",
"'Values already taken.'",
",",
"{",
"errors",
":",
"errs",
"}",
")",
";",
"}",
"return",
"null",
";",
"}"
] |
This module is usually called from the UI to check username, email, etc. are unique.
|
[
"This",
"module",
"is",
"usually",
"called",
"from",
"the",
"UI",
"to",
"check",
"username",
"email",
"etc",
".",
"are",
"unique",
"."
] |
95e5801229adba72b69e2bc7a9eb507b280db8bc
|
https://github.com/feathers-plus/feathers-authentication-management/blob/95e5801229adba72b69e2bc7a9eb507b280db8bc/src/check-unique.js#L11-L48
|
18,460
|
feathers-plus/feathers-authentication-management
|
src/client.js
|
AuthManagement
|
function AuthManagement (app) { // eslint-disable-line no-unused-vars
if (!(this instanceof AuthManagement)) {
return new AuthManagement(app);
}
const authManagement = app.service('authManagement');
this.checkUnique = async (identifyUser, ownId, ifErrMsg) => await authManagement.create({
action: 'checkUnique',
value: identifyUser,
ownId,
meta: { noErrMsg: ifErrMsg }
}, {});
this.resendVerifySignup = async (identifyUser, notifierOptions) => await authManagement.create({
action: 'resendVerifySignup',
value: identifyUser,
notifierOptions
}, {});
this.verifySignupLong = async (verifyToken) => await authManagement.create({
action: 'verifySignupLong',
value: verifyToken
}, {});
this.verifySignupShort = async (verifyShortToken, identifyUser) => await authManagement.create({
action: 'verifySignupShort',
value: { user: identifyUser, token: verifyShortToken }
}, {});
this.sendResetPwd = async (identifyUser, notifierOptions) => await authManagement.create({
action: 'sendResetPwd',
value: identifyUser,
notifierOptions
}, {});
this.resetPwdLong = async (resetToken, password) => await authManagement.create({
action: 'resetPwdLong',
value: { token: resetToken, password }
}, {});
this.resetPwdShort = async (resetShortToken, identifyUser, password) => await authManagement.create({
action: 'resetPwdShort',
value: { user: identifyUser, token: resetShortToken, password }
}, {});
this.passwordChange = async (oldPassword, password, identifyUser) => await authManagement.create({
action: 'passwordChange',
value: { user: identifyUser, oldPassword, password }
}, {});
this.identityChange = async (password, changesIdentifyUser, identifyUser) => await authManagement.create({
action: 'identityChange',
value: { user: identifyUser, password, changes: changesIdentifyUser }
}, {});
this.authenticate = async (email, password, cb) => {
let cbCalled = false;
return app.authenticate({ type: 'local', email, password })
.then(result => {
const user = result.data;
if (!user || !user.isVerified) {
app.logout();
return cb(new Error(user ? 'User\'s email is not verified.' : 'No user returned.'));
}
if (cb) {
cbCalled = true;
return cb(null, user);
}
return user;
})
.catch((err) => {
if (!cbCalled) {
cb(err);
}
});
};
}
|
javascript
|
function AuthManagement (app) { // eslint-disable-line no-unused-vars
if (!(this instanceof AuthManagement)) {
return new AuthManagement(app);
}
const authManagement = app.service('authManagement');
this.checkUnique = async (identifyUser, ownId, ifErrMsg) => await authManagement.create({
action: 'checkUnique',
value: identifyUser,
ownId,
meta: { noErrMsg: ifErrMsg }
}, {});
this.resendVerifySignup = async (identifyUser, notifierOptions) => await authManagement.create({
action: 'resendVerifySignup',
value: identifyUser,
notifierOptions
}, {});
this.verifySignupLong = async (verifyToken) => await authManagement.create({
action: 'verifySignupLong',
value: verifyToken
}, {});
this.verifySignupShort = async (verifyShortToken, identifyUser) => await authManagement.create({
action: 'verifySignupShort',
value: { user: identifyUser, token: verifyShortToken }
}, {});
this.sendResetPwd = async (identifyUser, notifierOptions) => await authManagement.create({
action: 'sendResetPwd',
value: identifyUser,
notifierOptions
}, {});
this.resetPwdLong = async (resetToken, password) => await authManagement.create({
action: 'resetPwdLong',
value: { token: resetToken, password }
}, {});
this.resetPwdShort = async (resetShortToken, identifyUser, password) => await authManagement.create({
action: 'resetPwdShort',
value: { user: identifyUser, token: resetShortToken, password }
}, {});
this.passwordChange = async (oldPassword, password, identifyUser) => await authManagement.create({
action: 'passwordChange',
value: { user: identifyUser, oldPassword, password }
}, {});
this.identityChange = async (password, changesIdentifyUser, identifyUser) => await authManagement.create({
action: 'identityChange',
value: { user: identifyUser, password, changes: changesIdentifyUser }
}, {});
this.authenticate = async (email, password, cb) => {
let cbCalled = false;
return app.authenticate({ type: 'local', email, password })
.then(result => {
const user = result.data;
if (!user || !user.isVerified) {
app.logout();
return cb(new Error(user ? 'User\'s email is not verified.' : 'No user returned.'));
}
if (cb) {
cbCalled = true;
return cb(null, user);
}
return user;
})
.catch((err) => {
if (!cbCalled) {
cb(err);
}
});
};
}
|
[
"function",
"AuthManagement",
"(",
"app",
")",
"{",
"// eslint-disable-line no-unused-vars\r",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"AuthManagement",
")",
")",
"{",
"return",
"new",
"AuthManagement",
"(",
"app",
")",
";",
"}",
"const",
"authManagement",
"=",
"app",
".",
"service",
"(",
"'authManagement'",
")",
";",
"this",
".",
"checkUnique",
"=",
"async",
"(",
"identifyUser",
",",
"ownId",
",",
"ifErrMsg",
")",
"=>",
"await",
"authManagement",
".",
"create",
"(",
"{",
"action",
":",
"'checkUnique'",
",",
"value",
":",
"identifyUser",
",",
"ownId",
",",
"meta",
":",
"{",
"noErrMsg",
":",
"ifErrMsg",
"}",
"}",
",",
"{",
"}",
")",
";",
"this",
".",
"resendVerifySignup",
"=",
"async",
"(",
"identifyUser",
",",
"notifierOptions",
")",
"=>",
"await",
"authManagement",
".",
"create",
"(",
"{",
"action",
":",
"'resendVerifySignup'",
",",
"value",
":",
"identifyUser",
",",
"notifierOptions",
"}",
",",
"{",
"}",
")",
";",
"this",
".",
"verifySignupLong",
"=",
"async",
"(",
"verifyToken",
")",
"=>",
"await",
"authManagement",
".",
"create",
"(",
"{",
"action",
":",
"'verifySignupLong'",
",",
"value",
":",
"verifyToken",
"}",
",",
"{",
"}",
")",
";",
"this",
".",
"verifySignupShort",
"=",
"async",
"(",
"verifyShortToken",
",",
"identifyUser",
")",
"=>",
"await",
"authManagement",
".",
"create",
"(",
"{",
"action",
":",
"'verifySignupShort'",
",",
"value",
":",
"{",
"user",
":",
"identifyUser",
",",
"token",
":",
"verifyShortToken",
"}",
"}",
",",
"{",
"}",
")",
";",
"this",
".",
"sendResetPwd",
"=",
"async",
"(",
"identifyUser",
",",
"notifierOptions",
")",
"=>",
"await",
"authManagement",
".",
"create",
"(",
"{",
"action",
":",
"'sendResetPwd'",
",",
"value",
":",
"identifyUser",
",",
"notifierOptions",
"}",
",",
"{",
"}",
")",
";",
"this",
".",
"resetPwdLong",
"=",
"async",
"(",
"resetToken",
",",
"password",
")",
"=>",
"await",
"authManagement",
".",
"create",
"(",
"{",
"action",
":",
"'resetPwdLong'",
",",
"value",
":",
"{",
"token",
":",
"resetToken",
",",
"password",
"}",
"}",
",",
"{",
"}",
")",
";",
"this",
".",
"resetPwdShort",
"=",
"async",
"(",
"resetShortToken",
",",
"identifyUser",
",",
"password",
")",
"=>",
"await",
"authManagement",
".",
"create",
"(",
"{",
"action",
":",
"'resetPwdShort'",
",",
"value",
":",
"{",
"user",
":",
"identifyUser",
",",
"token",
":",
"resetShortToken",
",",
"password",
"}",
"}",
",",
"{",
"}",
")",
";",
"this",
".",
"passwordChange",
"=",
"async",
"(",
"oldPassword",
",",
"password",
",",
"identifyUser",
")",
"=>",
"await",
"authManagement",
".",
"create",
"(",
"{",
"action",
":",
"'passwordChange'",
",",
"value",
":",
"{",
"user",
":",
"identifyUser",
",",
"oldPassword",
",",
"password",
"}",
"}",
",",
"{",
"}",
")",
";",
"this",
".",
"identityChange",
"=",
"async",
"(",
"password",
",",
"changesIdentifyUser",
",",
"identifyUser",
")",
"=>",
"await",
"authManagement",
".",
"create",
"(",
"{",
"action",
":",
"'identityChange'",
",",
"value",
":",
"{",
"user",
":",
"identifyUser",
",",
"password",
",",
"changes",
":",
"changesIdentifyUser",
"}",
"}",
",",
"{",
"}",
")",
";",
"this",
".",
"authenticate",
"=",
"async",
"(",
"email",
",",
"password",
",",
"cb",
")",
"=>",
"{",
"let",
"cbCalled",
"=",
"false",
";",
"return",
"app",
".",
"authenticate",
"(",
"{",
"type",
":",
"'local'",
",",
"email",
",",
"password",
"}",
")",
".",
"then",
"(",
"result",
"=>",
"{",
"const",
"user",
"=",
"result",
".",
"data",
";",
"if",
"(",
"!",
"user",
"||",
"!",
"user",
".",
"isVerified",
")",
"{",
"app",
".",
"logout",
"(",
")",
";",
"return",
"cb",
"(",
"new",
"Error",
"(",
"user",
"?",
"'User\\'s email is not verified.'",
":",
"'No user returned.'",
")",
")",
";",
"}",
"if",
"(",
"cb",
")",
"{",
"cbCalled",
"=",
"true",
";",
"return",
"cb",
"(",
"null",
",",
"user",
")",
";",
"}",
"return",
"user",
";",
"}",
")",
".",
"catch",
"(",
"(",
"err",
")",
"=>",
"{",
"if",
"(",
"!",
"cbCalled",
")",
"{",
"cb",
"(",
"err",
")",
";",
"}",
"}",
")",
";",
"}",
";",
"}"
] |
Wrapper for client interface to feathers-authenticate-management
|
[
"Wrapper",
"for",
"client",
"interface",
"to",
"feathers",
"-",
"authenticate",
"-",
"management"
] |
95e5801229adba72b69e2bc7a9eb507b280db8bc
|
https://github.com/feathers-plus/feathers-authentication-management/blob/95e5801229adba72b69e2bc7a9eb507b280db8bc/src/client.js#L4-L85
|
18,461
|
gulp-sourcemaps/gulp-sourcemaps
|
src/write/index.js
|
write
|
function write(destPath, options) {
var debug = require('../debug').spawn('write');
debug(function() { return 'destPath'; });
debug(function() { return destPath; });
debug(function() { return 'original options';});
debug(function() { return options; });
if (options === undefined && typeof destPath !== 'string') {
options = destPath;
destPath = undefined;
}
options = options || {};
// set defaults for options if unset
if (options.includeContent === undefined) {
options.includeContent = true;
}
if (options.addComment === undefined) {
options.addComment = true;
}
if (options.charset === undefined) {
options.charset = 'utf8';
}
debug(function() { return 'derrived options'; });
debug(function() { return options; });
var internals = internalsInit(destPath, options);
function sourceMapWrite(file, encoding, callback) {
if (file.isNull() || !file.sourceMap) {
this.push(file);
return callback();
}
if (file.isStream()) {
return callback(new Error(utils.PLUGIN_NAME + '-write: Streaming not supported'));
}
// fix paths if Windows style paths
file.sourceMap.file = unixStylePath(file.relative);
internals.setSourceRoot(file);
internals.loadContent(file);
internals.mapSources(file);
internals.mapDestPath(file, this);
this.push(file);
callback();
}
return through.obj(sourceMapWrite);
}
|
javascript
|
function write(destPath, options) {
var debug = require('../debug').spawn('write');
debug(function() { return 'destPath'; });
debug(function() { return destPath; });
debug(function() { return 'original options';});
debug(function() { return options; });
if (options === undefined && typeof destPath !== 'string') {
options = destPath;
destPath = undefined;
}
options = options || {};
// set defaults for options if unset
if (options.includeContent === undefined) {
options.includeContent = true;
}
if (options.addComment === undefined) {
options.addComment = true;
}
if (options.charset === undefined) {
options.charset = 'utf8';
}
debug(function() { return 'derrived options'; });
debug(function() { return options; });
var internals = internalsInit(destPath, options);
function sourceMapWrite(file, encoding, callback) {
if (file.isNull() || !file.sourceMap) {
this.push(file);
return callback();
}
if (file.isStream()) {
return callback(new Error(utils.PLUGIN_NAME + '-write: Streaming not supported'));
}
// fix paths if Windows style paths
file.sourceMap.file = unixStylePath(file.relative);
internals.setSourceRoot(file);
internals.loadContent(file);
internals.mapSources(file);
internals.mapDestPath(file, this);
this.push(file);
callback();
}
return through.obj(sourceMapWrite);
}
|
[
"function",
"write",
"(",
"destPath",
",",
"options",
")",
"{",
"var",
"debug",
"=",
"require",
"(",
"'../debug'",
")",
".",
"spawn",
"(",
"'write'",
")",
";",
"debug",
"(",
"function",
"(",
")",
"{",
"return",
"'destPath'",
";",
"}",
")",
";",
"debug",
"(",
"function",
"(",
")",
"{",
"return",
"destPath",
";",
"}",
")",
";",
"debug",
"(",
"function",
"(",
")",
"{",
"return",
"'original options'",
";",
"}",
")",
";",
"debug",
"(",
"function",
"(",
")",
"{",
"return",
"options",
";",
"}",
")",
";",
"if",
"(",
"options",
"===",
"undefined",
"&&",
"typeof",
"destPath",
"!==",
"'string'",
")",
"{",
"options",
"=",
"destPath",
";",
"destPath",
"=",
"undefined",
";",
"}",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"// set defaults for options if unset",
"if",
"(",
"options",
".",
"includeContent",
"===",
"undefined",
")",
"{",
"options",
".",
"includeContent",
"=",
"true",
";",
"}",
"if",
"(",
"options",
".",
"addComment",
"===",
"undefined",
")",
"{",
"options",
".",
"addComment",
"=",
"true",
";",
"}",
"if",
"(",
"options",
".",
"charset",
"===",
"undefined",
")",
"{",
"options",
".",
"charset",
"=",
"'utf8'",
";",
"}",
"debug",
"(",
"function",
"(",
")",
"{",
"return",
"'derrived options'",
";",
"}",
")",
";",
"debug",
"(",
"function",
"(",
")",
"{",
"return",
"options",
";",
"}",
")",
";",
"var",
"internals",
"=",
"internalsInit",
"(",
"destPath",
",",
"options",
")",
";",
"function",
"sourceMapWrite",
"(",
"file",
",",
"encoding",
",",
"callback",
")",
"{",
"if",
"(",
"file",
".",
"isNull",
"(",
")",
"||",
"!",
"file",
".",
"sourceMap",
")",
"{",
"this",
".",
"push",
"(",
"file",
")",
";",
"return",
"callback",
"(",
")",
";",
"}",
"if",
"(",
"file",
".",
"isStream",
"(",
")",
")",
"{",
"return",
"callback",
"(",
"new",
"Error",
"(",
"utils",
".",
"PLUGIN_NAME",
"+",
"'-write: Streaming not supported'",
")",
")",
";",
"}",
"// fix paths if Windows style paths",
"file",
".",
"sourceMap",
".",
"file",
"=",
"unixStylePath",
"(",
"file",
".",
"relative",
")",
";",
"internals",
".",
"setSourceRoot",
"(",
"file",
")",
";",
"internals",
".",
"loadContent",
"(",
"file",
")",
";",
"internals",
".",
"mapSources",
"(",
"file",
")",
";",
"internals",
".",
"mapDestPath",
"(",
"file",
",",
"this",
")",
";",
"this",
".",
"push",
"(",
"file",
")",
";",
"callback",
"(",
")",
";",
"}",
"return",
"through",
".",
"obj",
"(",
"sourceMapWrite",
")",
";",
"}"
] |
Write the source map
@param options options to change the way the source map is written
|
[
"Write",
"the",
"source",
"map"
] |
bd0aeb0dbbdda2802b6b777edee79a0995a5784f
|
https://github.com/gulp-sourcemaps/gulp-sourcemaps/blob/bd0aeb0dbbdda2802b6b777edee79a0995a5784f/src/write/index.js#L13-L67
|
18,462
|
baalexander/node-portscanner
|
lib/portscanner.js
|
checkPortStatus
|
function checkPortStatus (port) {
var args, host, opts, callback
args = [].slice.call(arguments, 1)
if (typeof args[0] === 'string') {
host = args[0]
} else if (typeof args[0] === 'object') {
opts = args[0]
} else if (typeof args[0] === 'function') {
callback = args[0]
}
if (typeof args[1] === 'object') {
opts = args[1]
} else if (typeof args[1] === 'function') {
callback = args[1]
}
if (typeof args[2] === 'function') {
callback = args[2]
}
if (!callback) return promisify(checkPortStatus, arguments)
opts = opts || {}
host = host || opts.host || '127.0.0.1'
var timeout = opts.timeout || 400
var connectionRefused = false
var socket = new Socket()
var status = null
var error = null
// Socket connection established, port is open
socket.on('connect', function () {
status = 'open'
socket.destroy()
})
// If no response, assume port is not listening
socket.setTimeout(timeout)
socket.on('timeout', function () {
status = 'closed'
error = new Error('Timeout (' + timeout + 'ms) occurred waiting for ' + host + ':' + port + ' to be available')
socket.destroy()
})
// Assuming the port is not open if an error. May need to refine based on
// exception
socket.on('error', function (exception) {
if (exception.code !== 'ECONNREFUSED') {
error = exception
} else {
connectionRefused = true
}
status = 'closed'
})
// Return after the socket has closed
socket.on('close', function (exception) {
if (exception && !connectionRefused) { error = error || exception } else { error = null }
callback(error, status)
})
socket.connect(port, host)
}
|
javascript
|
function checkPortStatus (port) {
var args, host, opts, callback
args = [].slice.call(arguments, 1)
if (typeof args[0] === 'string') {
host = args[0]
} else if (typeof args[0] === 'object') {
opts = args[0]
} else if (typeof args[0] === 'function') {
callback = args[0]
}
if (typeof args[1] === 'object') {
opts = args[1]
} else if (typeof args[1] === 'function') {
callback = args[1]
}
if (typeof args[2] === 'function') {
callback = args[2]
}
if (!callback) return promisify(checkPortStatus, arguments)
opts = opts || {}
host = host || opts.host || '127.0.0.1'
var timeout = opts.timeout || 400
var connectionRefused = false
var socket = new Socket()
var status = null
var error = null
// Socket connection established, port is open
socket.on('connect', function () {
status = 'open'
socket.destroy()
})
// If no response, assume port is not listening
socket.setTimeout(timeout)
socket.on('timeout', function () {
status = 'closed'
error = new Error('Timeout (' + timeout + 'ms) occurred waiting for ' + host + ':' + port + ' to be available')
socket.destroy()
})
// Assuming the port is not open if an error. May need to refine based on
// exception
socket.on('error', function (exception) {
if (exception.code !== 'ECONNREFUSED') {
error = exception
} else {
connectionRefused = true
}
status = 'closed'
})
// Return after the socket has closed
socket.on('close', function (exception) {
if (exception && !connectionRefused) { error = error || exception } else { error = null }
callback(error, status)
})
socket.connect(port, host)
}
|
[
"function",
"checkPortStatus",
"(",
"port",
")",
"{",
"var",
"args",
",",
"host",
",",
"opts",
",",
"callback",
"args",
"=",
"[",
"]",
".",
"slice",
".",
"call",
"(",
"arguments",
",",
"1",
")",
"if",
"(",
"typeof",
"args",
"[",
"0",
"]",
"===",
"'string'",
")",
"{",
"host",
"=",
"args",
"[",
"0",
"]",
"}",
"else",
"if",
"(",
"typeof",
"args",
"[",
"0",
"]",
"===",
"'object'",
")",
"{",
"opts",
"=",
"args",
"[",
"0",
"]",
"}",
"else",
"if",
"(",
"typeof",
"args",
"[",
"0",
"]",
"===",
"'function'",
")",
"{",
"callback",
"=",
"args",
"[",
"0",
"]",
"}",
"if",
"(",
"typeof",
"args",
"[",
"1",
"]",
"===",
"'object'",
")",
"{",
"opts",
"=",
"args",
"[",
"1",
"]",
"}",
"else",
"if",
"(",
"typeof",
"args",
"[",
"1",
"]",
"===",
"'function'",
")",
"{",
"callback",
"=",
"args",
"[",
"1",
"]",
"}",
"if",
"(",
"typeof",
"args",
"[",
"2",
"]",
"===",
"'function'",
")",
"{",
"callback",
"=",
"args",
"[",
"2",
"]",
"}",
"if",
"(",
"!",
"callback",
")",
"return",
"promisify",
"(",
"checkPortStatus",
",",
"arguments",
")",
"opts",
"=",
"opts",
"||",
"{",
"}",
"host",
"=",
"host",
"||",
"opts",
".",
"host",
"||",
"'127.0.0.1'",
"var",
"timeout",
"=",
"opts",
".",
"timeout",
"||",
"400",
"var",
"connectionRefused",
"=",
"false",
"var",
"socket",
"=",
"new",
"Socket",
"(",
")",
"var",
"status",
"=",
"null",
"var",
"error",
"=",
"null",
"// Socket connection established, port is open",
"socket",
".",
"on",
"(",
"'connect'",
",",
"function",
"(",
")",
"{",
"status",
"=",
"'open'",
"socket",
".",
"destroy",
"(",
")",
"}",
")",
"// If no response, assume port is not listening",
"socket",
".",
"setTimeout",
"(",
"timeout",
")",
"socket",
".",
"on",
"(",
"'timeout'",
",",
"function",
"(",
")",
"{",
"status",
"=",
"'closed'",
"error",
"=",
"new",
"Error",
"(",
"'Timeout ('",
"+",
"timeout",
"+",
"'ms) occurred waiting for '",
"+",
"host",
"+",
"':'",
"+",
"port",
"+",
"' to be available'",
")",
"socket",
".",
"destroy",
"(",
")",
"}",
")",
"// Assuming the port is not open if an error. May need to refine based on",
"// exception",
"socket",
".",
"on",
"(",
"'error'",
",",
"function",
"(",
"exception",
")",
"{",
"if",
"(",
"exception",
".",
"code",
"!==",
"'ECONNREFUSED'",
")",
"{",
"error",
"=",
"exception",
"}",
"else",
"{",
"connectionRefused",
"=",
"true",
"}",
"status",
"=",
"'closed'",
"}",
")",
"// Return after the socket has closed",
"socket",
".",
"on",
"(",
"'close'",
",",
"function",
"(",
"exception",
")",
"{",
"if",
"(",
"exception",
"&&",
"!",
"connectionRefused",
")",
"{",
"error",
"=",
"error",
"||",
"exception",
"}",
"else",
"{",
"error",
"=",
"null",
"}",
"callback",
"(",
"error",
",",
"status",
")",
"}",
")",
"socket",
".",
"connect",
"(",
"port",
",",
"host",
")",
"}"
] |
Checks the status of an individual port.
@param {Number} port - Port to check status on.
@param {String} [host='127.0.0.1'] - Host of where to scan.
@param {checkPortCallback} [callback] - Function to call back with error or results.
@returns {Promise}
@param {Number} port - Port to check status on.
@param {Object} [opts={}] - Options object.
@param {String} [opts.host='127.0.0.1'] - Host of where to scan.
@param {Number} [opts.timeout=400] - Connection timeout in ms.
@param {checkPortCallback} [callback] - Function to call back with error or results.
@returns {Promise}
|
[
"Checks",
"the",
"status",
"of",
"an",
"individual",
"port",
"."
] |
9a92dcce423da9bc16b4f3c621bacdf7dcc0bfc1
|
https://github.com/baalexander/node-portscanner/blob/9a92dcce423da9bc16b4f3c621bacdf7dcc0bfc1/lib/portscanner.js#L68-L136
|
18,463
|
baalexander/node-portscanner
|
lib/portscanner.js
|
function (callback) {
checkPortStatus(port, host, opts, function (error, statusOfPort) {
numberOfPortsChecked++
if (statusOfPort === status) {
foundPort = true
callback(error)
} else {
port = portList ? portList[numberOfPortsChecked] : port + 1
callback(null)
}
})
}
|
javascript
|
function (callback) {
checkPortStatus(port, host, opts, function (error, statusOfPort) {
numberOfPortsChecked++
if (statusOfPort === status) {
foundPort = true
callback(error)
} else {
port = portList ? portList[numberOfPortsChecked] : port + 1
callback(null)
}
})
}
|
[
"function",
"(",
"callback",
")",
"{",
"checkPortStatus",
"(",
"port",
",",
"host",
",",
"opts",
",",
"function",
"(",
"error",
",",
"statusOfPort",
")",
"{",
"numberOfPortsChecked",
"++",
"if",
"(",
"statusOfPort",
"===",
"status",
")",
"{",
"foundPort",
"=",
"true",
"callback",
"(",
"error",
")",
"}",
"else",
"{",
"port",
"=",
"portList",
"?",
"portList",
"[",
"numberOfPortsChecked",
"]",
":",
"port",
"+",
"1",
"callback",
"(",
"null",
")",
"}",
"}",
")",
"}"
] |
Checks the status of the port
|
[
"Checks",
"the",
"status",
"of",
"the",
"port"
] |
9a92dcce423da9bc16b4f3c621bacdf7dcc0bfc1
|
https://github.com/baalexander/node-portscanner/blob/9a92dcce423da9bc16b4f3c621bacdf7dcc0bfc1/lib/portscanner.js#L211-L222
|
|
18,464
|
kayahr/jquery-fullscreen-plugin
|
jquery.fullscreen.js
|
fullScreen
|
function fullScreen(state)
{
var e, func, doc;
// Do nothing when nothing was selected
if (!this.length) return this;
// We only use the first selected element because it doesn't make sense
// to fullscreen multiple elements.
e = (/** @type {Element} */ this[0]);
// Find the real element and the document (Depends on whether the
// document itself or a HTML element was selected)
if (e.ownerDocument)
{
doc = e.ownerDocument;
}
else
{
doc = e;
e = doc.documentElement;
}
// When no state was specified then return the current state.
if (state == null)
{
// When fullscreen mode is not supported then return null
if (!((/** @type {?Function} */ doc["exitFullscreen"])
|| (/** @type {?Function} */ doc["webkitExitFullscreen"])
|| (/** @type {?Function} */ doc["webkitCancelFullScreen"])
|| (/** @type {?Function} */ doc["msExitFullscreen"])
|| (/** @type {?Function} */ doc["mozCancelFullScreen"])))
{
return null;
}
// Check fullscreen state
state = !!doc["fullscreenElement"]
|| !!doc["msFullscreenElement"]
|| !!doc["webkitIsFullScreen"]
|| !!doc["mozFullScreen"];
if (!state) return state;
// Return current fullscreen element or "true" if browser doesn't
// support this
return (/** @type {?Element} */ doc["fullscreenElement"])
|| (/** @type {?Element} */ doc["webkitFullscreenElement"])
|| (/** @type {?Element} */ doc["webkitCurrentFullScreenElement"])
|| (/** @type {?Element} */ doc["msFullscreenElement"])
|| (/** @type {?Element} */ doc["mozFullScreenElement"])
|| state;
}
// When state was specified then enter or exit fullscreen mode.
if (state)
{
// Enter fullscreen
func = (/** @type {?Function} */ e["requestFullscreen"])
|| (/** @type {?Function} */ e["webkitRequestFullscreen"])
|| (/** @type {?Function} */ e["webkitRequestFullScreen"])
|| (/** @type {?Function} */ e["msRequestFullscreen"])
|| (/** @type {?Function} */ e["mozRequestFullScreen"]);
if (func)
{
func.call(e);
}
return this;
}
else
{
// Exit fullscreen
func = (/** @type {?Function} */ doc["exitFullscreen"])
|| (/** @type {?Function} */ doc["webkitExitFullscreen"])
|| (/** @type {?Function} */ doc["webkitCancelFullScreen"])
|| (/** @type {?Function} */ doc["msExitFullscreen"])
|| (/** @type {?Function} */ doc["mozCancelFullScreen"]);
if (func) func.call(doc);
return this;
}
}
|
javascript
|
function fullScreen(state)
{
var e, func, doc;
// Do nothing when nothing was selected
if (!this.length) return this;
// We only use the first selected element because it doesn't make sense
// to fullscreen multiple elements.
e = (/** @type {Element} */ this[0]);
// Find the real element and the document (Depends on whether the
// document itself or a HTML element was selected)
if (e.ownerDocument)
{
doc = e.ownerDocument;
}
else
{
doc = e;
e = doc.documentElement;
}
// When no state was specified then return the current state.
if (state == null)
{
// When fullscreen mode is not supported then return null
if (!((/** @type {?Function} */ doc["exitFullscreen"])
|| (/** @type {?Function} */ doc["webkitExitFullscreen"])
|| (/** @type {?Function} */ doc["webkitCancelFullScreen"])
|| (/** @type {?Function} */ doc["msExitFullscreen"])
|| (/** @type {?Function} */ doc["mozCancelFullScreen"])))
{
return null;
}
// Check fullscreen state
state = !!doc["fullscreenElement"]
|| !!doc["msFullscreenElement"]
|| !!doc["webkitIsFullScreen"]
|| !!doc["mozFullScreen"];
if (!state) return state;
// Return current fullscreen element or "true" if browser doesn't
// support this
return (/** @type {?Element} */ doc["fullscreenElement"])
|| (/** @type {?Element} */ doc["webkitFullscreenElement"])
|| (/** @type {?Element} */ doc["webkitCurrentFullScreenElement"])
|| (/** @type {?Element} */ doc["msFullscreenElement"])
|| (/** @type {?Element} */ doc["mozFullScreenElement"])
|| state;
}
// When state was specified then enter or exit fullscreen mode.
if (state)
{
// Enter fullscreen
func = (/** @type {?Function} */ e["requestFullscreen"])
|| (/** @type {?Function} */ e["webkitRequestFullscreen"])
|| (/** @type {?Function} */ e["webkitRequestFullScreen"])
|| (/** @type {?Function} */ e["msRequestFullscreen"])
|| (/** @type {?Function} */ e["mozRequestFullScreen"]);
if (func)
{
func.call(e);
}
return this;
}
else
{
// Exit fullscreen
func = (/** @type {?Function} */ doc["exitFullscreen"])
|| (/** @type {?Function} */ doc["webkitExitFullscreen"])
|| (/** @type {?Function} */ doc["webkitCancelFullScreen"])
|| (/** @type {?Function} */ doc["msExitFullscreen"])
|| (/** @type {?Function} */ doc["mozCancelFullScreen"]);
if (func) func.call(doc);
return this;
}
}
|
[
"function",
"fullScreen",
"(",
"state",
")",
"{",
"var",
"e",
",",
"func",
",",
"doc",
";",
"// Do nothing when nothing was selected",
"if",
"(",
"!",
"this",
".",
"length",
")",
"return",
"this",
";",
"// We only use the first selected element because it doesn't make sense",
"// to fullscreen multiple elements.",
"e",
"=",
"(",
"/** @type {Element} */",
"this",
"[",
"0",
"]",
")",
";",
"// Find the real element and the document (Depends on whether the",
"// document itself or a HTML element was selected)",
"if",
"(",
"e",
".",
"ownerDocument",
")",
"{",
"doc",
"=",
"e",
".",
"ownerDocument",
";",
"}",
"else",
"{",
"doc",
"=",
"e",
";",
"e",
"=",
"doc",
".",
"documentElement",
";",
"}",
"// When no state was specified then return the current state.",
"if",
"(",
"state",
"==",
"null",
")",
"{",
"// When fullscreen mode is not supported then return null",
"if",
"(",
"!",
"(",
"(",
"/** @type {?Function} */",
"doc",
"[",
"\"exitFullscreen\"",
"]",
")",
"||",
"(",
"/** @type {?Function} */",
"doc",
"[",
"\"webkitExitFullscreen\"",
"]",
")",
"||",
"(",
"/** @type {?Function} */",
"doc",
"[",
"\"webkitCancelFullScreen\"",
"]",
")",
"||",
"(",
"/** @type {?Function} */",
"doc",
"[",
"\"msExitFullscreen\"",
"]",
")",
"||",
"(",
"/** @type {?Function} */",
"doc",
"[",
"\"mozCancelFullScreen\"",
"]",
")",
")",
")",
"{",
"return",
"null",
";",
"}",
"// Check fullscreen state",
"state",
"=",
"!",
"!",
"doc",
"[",
"\"fullscreenElement\"",
"]",
"||",
"!",
"!",
"doc",
"[",
"\"msFullscreenElement\"",
"]",
"||",
"!",
"!",
"doc",
"[",
"\"webkitIsFullScreen\"",
"]",
"||",
"!",
"!",
"doc",
"[",
"\"mozFullScreen\"",
"]",
";",
"if",
"(",
"!",
"state",
")",
"return",
"state",
";",
"// Return current fullscreen element or \"true\" if browser doesn't",
"// support this",
"return",
"(",
"/** @type {?Element} */",
"doc",
"[",
"\"fullscreenElement\"",
"]",
")",
"||",
"(",
"/** @type {?Element} */",
"doc",
"[",
"\"webkitFullscreenElement\"",
"]",
")",
"||",
"(",
"/** @type {?Element} */",
"doc",
"[",
"\"webkitCurrentFullScreenElement\"",
"]",
")",
"||",
"(",
"/** @type {?Element} */",
"doc",
"[",
"\"msFullscreenElement\"",
"]",
")",
"||",
"(",
"/** @type {?Element} */",
"doc",
"[",
"\"mozFullScreenElement\"",
"]",
")",
"||",
"state",
";",
"}",
"// When state was specified then enter or exit fullscreen mode.",
"if",
"(",
"state",
")",
"{",
"// Enter fullscreen",
"func",
"=",
"(",
"/** @type {?Function} */",
"e",
"[",
"\"requestFullscreen\"",
"]",
")",
"||",
"(",
"/** @type {?Function} */",
"e",
"[",
"\"webkitRequestFullscreen\"",
"]",
")",
"||",
"(",
"/** @type {?Function} */",
"e",
"[",
"\"webkitRequestFullScreen\"",
"]",
")",
"||",
"(",
"/** @type {?Function} */",
"e",
"[",
"\"msRequestFullscreen\"",
"]",
")",
"||",
"(",
"/** @type {?Function} */",
"e",
"[",
"\"mozRequestFullScreen\"",
"]",
")",
";",
"if",
"(",
"func",
")",
"{",
"func",
".",
"call",
"(",
"e",
")",
";",
"}",
"return",
"this",
";",
"}",
"else",
"{",
"// Exit fullscreen",
"func",
"=",
"(",
"/** @type {?Function} */",
"doc",
"[",
"\"exitFullscreen\"",
"]",
")",
"||",
"(",
"/** @type {?Function} */",
"doc",
"[",
"\"webkitExitFullscreen\"",
"]",
")",
"||",
"(",
"/** @type {?Function} */",
"doc",
"[",
"\"webkitCancelFullScreen\"",
"]",
")",
"||",
"(",
"/** @type {?Function} */",
"doc",
"[",
"\"msExitFullscreen\"",
"]",
")",
"||",
"(",
"/** @type {?Function} */",
"doc",
"[",
"\"mozCancelFullScreen\"",
"]",
")",
";",
"if",
"(",
"func",
")",
"func",
".",
"call",
"(",
"doc",
")",
";",
"return",
"this",
";",
"}",
"}"
] |
Sets or gets the fullscreen state.
@param {boolean=} state
True to enable fullscreen mode, false to disable it. If not
specified then the current fullscreen state is returned.
@return {boolean|Element|jQuery|null}
When querying the fullscreen state then the current fullscreen
element (or true if browser doesn't support it) is returned
when browser is currently in full screen mode. False is returned
if browser is not in full screen mode. Null is returned if
browser doesn't support fullscreen mode at all. When setting
the fullscreen state then the current jQuery selection is
returned for chaining.
@this {jQuery}
|
[
"Sets",
"or",
"gets",
"the",
"fullscreen",
"state",
"."
] |
9438016e72f83f04052e1209bd463e38c8457611
|
https://github.com/kayahr/jquery-fullscreen-plugin/blob/9438016e72f83f04052e1209bd463e38c8457611/jquery.fullscreen.js#L27-L106
|
18,465
|
kayahr/jquery-fullscreen-plugin
|
jquery.fullscreen.js
|
installFullScreenHandlers
|
function installFullScreenHandlers()
{
var e, change, error;
// Determine event name
e = document;
if (e["webkitCancelFullScreen"])
{
change = "webkitfullscreenchange";
error = "webkitfullscreenerror";
}
else if (e["msExitFullscreen"])
{
change = "MSFullscreenChange";
error = "MSFullscreenError";
}
else if (e["mozCancelFullScreen"])
{
change = "mozfullscreenchange";
error = "mozfullscreenerror";
}
else
{
change = "fullscreenchange";
error = "fullscreenerror";
}
// Install the event handlers
jQuery(document).bind(change, fullScreenChangeHandler);
jQuery(document).bind(error, fullScreenErrorHandler);
}
|
javascript
|
function installFullScreenHandlers()
{
var e, change, error;
// Determine event name
e = document;
if (e["webkitCancelFullScreen"])
{
change = "webkitfullscreenchange";
error = "webkitfullscreenerror";
}
else if (e["msExitFullscreen"])
{
change = "MSFullscreenChange";
error = "MSFullscreenError";
}
else if (e["mozCancelFullScreen"])
{
change = "mozfullscreenchange";
error = "mozfullscreenerror";
}
else
{
change = "fullscreenchange";
error = "fullscreenerror";
}
// Install the event handlers
jQuery(document).bind(change, fullScreenChangeHandler);
jQuery(document).bind(error, fullScreenErrorHandler);
}
|
[
"function",
"installFullScreenHandlers",
"(",
")",
"{",
"var",
"e",
",",
"change",
",",
"error",
";",
"// Determine event name",
"e",
"=",
"document",
";",
"if",
"(",
"e",
"[",
"\"webkitCancelFullScreen\"",
"]",
")",
"{",
"change",
"=",
"\"webkitfullscreenchange\"",
";",
"error",
"=",
"\"webkitfullscreenerror\"",
";",
"}",
"else",
"if",
"(",
"e",
"[",
"\"msExitFullscreen\"",
"]",
")",
"{",
"change",
"=",
"\"MSFullscreenChange\"",
";",
"error",
"=",
"\"MSFullscreenError\"",
";",
"}",
"else",
"if",
"(",
"e",
"[",
"\"mozCancelFullScreen\"",
"]",
")",
"{",
"change",
"=",
"\"mozfullscreenchange\"",
";",
"error",
"=",
"\"mozfullscreenerror\"",
";",
"}",
"else",
"{",
"change",
"=",
"\"fullscreenchange\"",
";",
"error",
"=",
"\"fullscreenerror\"",
";",
"}",
"// Install the event handlers",
"jQuery",
"(",
"document",
")",
".",
"bind",
"(",
"change",
",",
"fullScreenChangeHandler",
")",
";",
"jQuery",
"(",
"document",
")",
".",
"bind",
"(",
"error",
",",
"fullScreenErrorHandler",
")",
";",
"}"
] |
Installs the fullscreenchange event handler.
|
[
"Installs",
"the",
"fullscreenchange",
"event",
"handler",
"."
] |
9438016e72f83f04052e1209bd463e38c8457611
|
https://github.com/kayahr/jquery-fullscreen-plugin/blob/9438016e72f83f04052e1209bd463e38c8457611/jquery.fullscreen.js#L148-L178
|
18,466
|
Aconex/drakov
|
lib/parse/blueprint.js
|
saveRouteToTheList
|
function saveRouteToTheList(parsedUrl, action) {
// used to add options routes later
if (typeof allRoutesList[parsedUrl.url] === 'undefined') {
allRoutesList[parsedUrl.url] = [];
}
allRoutesList[parsedUrl.url].push(action);
}
|
javascript
|
function saveRouteToTheList(parsedUrl, action) {
// used to add options routes later
if (typeof allRoutesList[parsedUrl.url] === 'undefined') {
allRoutesList[parsedUrl.url] = [];
}
allRoutesList[parsedUrl.url].push(action);
}
|
[
"function",
"saveRouteToTheList",
"(",
"parsedUrl",
",",
"action",
")",
"{",
"// used to add options routes later",
"if",
"(",
"typeof",
"allRoutesList",
"[",
"parsedUrl",
".",
"url",
"]",
"===",
"'undefined'",
")",
"{",
"allRoutesList",
"[",
"parsedUrl",
".",
"url",
"]",
"=",
"[",
"]",
";",
"}",
"allRoutesList",
"[",
"parsedUrl",
".",
"url",
"]",
".",
"push",
"(",
"action",
")",
";",
"}"
] |
Adds route and its action to the allRoutesList. It appends the action when route already exists in the list.
@param resource Route URI
@param action HTTP action
|
[
"Adds",
"route",
"and",
"its",
"action",
"to",
"the",
"allRoutesList",
".",
"It",
"appends",
"the",
"action",
"when",
"route",
"already",
"exists",
"in",
"the",
"list",
"."
] |
b83e2411ff506a864db8940e75d724f36eb41935
|
https://github.com/Aconex/drakov/blob/b83e2411ff506a864db8940e75d724f36eb41935/lib/parse/blueprint.js#L58-L64
|
18,467
|
Promact/md2
|
tools/dgeni/processors/categorizer.js
|
decorateClassDoc
|
function decorateClassDoc(classDoc) {
// Resolve all methods and properties from the classDoc. Includes inherited docs.
classDoc.methods = resolveMethods(classDoc);
classDoc.properties = resolveProperties(classDoc);
// Call decorate hooks that can modify the method and property docs.
classDoc.methods.forEach(doc => decorateMethodDoc(doc));
classDoc.properties.forEach(doc => decoratePropertyDoc(doc));
// Categorize the current visited classDoc into its Angular type.
if (isDirective(classDoc)) {
classDoc.isDirective = true;
classDoc.directiveExportAs = getDirectiveExportAs(classDoc);
} else if (isService(classDoc)) {
classDoc.isService = true;
} else if (isNgModule(classDoc)) {
classDoc.isNgModule = true;
}
}
|
javascript
|
function decorateClassDoc(classDoc) {
// Resolve all methods and properties from the classDoc. Includes inherited docs.
classDoc.methods = resolveMethods(classDoc);
classDoc.properties = resolveProperties(classDoc);
// Call decorate hooks that can modify the method and property docs.
classDoc.methods.forEach(doc => decorateMethodDoc(doc));
classDoc.properties.forEach(doc => decoratePropertyDoc(doc));
// Categorize the current visited classDoc into its Angular type.
if (isDirective(classDoc)) {
classDoc.isDirective = true;
classDoc.directiveExportAs = getDirectiveExportAs(classDoc);
} else if (isService(classDoc)) {
classDoc.isService = true;
} else if (isNgModule(classDoc)) {
classDoc.isNgModule = true;
}
}
|
[
"function",
"decorateClassDoc",
"(",
"classDoc",
")",
"{",
"// Resolve all methods and properties from the classDoc. Includes inherited docs.",
"classDoc",
".",
"methods",
"=",
"resolveMethods",
"(",
"classDoc",
")",
";",
"classDoc",
".",
"properties",
"=",
"resolveProperties",
"(",
"classDoc",
")",
";",
"// Call decorate hooks that can modify the method and property docs.",
"classDoc",
".",
"methods",
".",
"forEach",
"(",
"doc",
"=>",
"decorateMethodDoc",
"(",
"doc",
")",
")",
";",
"classDoc",
".",
"properties",
".",
"forEach",
"(",
"doc",
"=>",
"decoratePropertyDoc",
"(",
"doc",
")",
")",
";",
"// Categorize the current visited classDoc into its Angular type.",
"if",
"(",
"isDirective",
"(",
"classDoc",
")",
")",
"{",
"classDoc",
".",
"isDirective",
"=",
"true",
";",
"classDoc",
".",
"directiveExportAs",
"=",
"getDirectiveExportAs",
"(",
"classDoc",
")",
";",
"}",
"else",
"if",
"(",
"isService",
"(",
"classDoc",
")",
")",
"{",
"classDoc",
".",
"isService",
"=",
"true",
";",
"}",
"else",
"if",
"(",
"isNgModule",
"(",
"classDoc",
")",
")",
"{",
"classDoc",
".",
"isNgModule",
"=",
"true",
";",
"}",
"}"
] |
Decorates all class docs inside of the dgeni pipeline.
- Methods and properties of a class-doc will be extracted into separate variables.
- Identifies directives, services or NgModules and marks them them in class-doc.
|
[
"Decorates",
"all",
"class",
"docs",
"inside",
"of",
"the",
"dgeni",
"pipeline",
".",
"-",
"Methods",
"and",
"properties",
"of",
"a",
"class",
"-",
"doc",
"will",
"be",
"extracted",
"into",
"separate",
"variables",
".",
"-",
"Identifies",
"directives",
"services",
"or",
"NgModules",
"and",
"marks",
"them",
"them",
"in",
"class",
"-",
"doc",
"."
] |
c649ecdbe99a5537364579ac7fdae17283dd931a
|
https://github.com/Promact/md2/blob/c649ecdbe99a5537364579ac7fdae17283dd931a/tools/dgeni/processors/categorizer.js#L22-L40
|
18,468
|
Promact/md2
|
tools/dgeni/processors/categorizer.js
|
decorateMethodDoc
|
function decorateMethodDoc(methodDoc) {
normalizeMethodParameters(methodDoc);
// Mark methods with a `void` return type so we can omit show the return type in the docs.
methodDoc.showReturns = methodDoc.returnType && methodDoc.returnType != 'void';
}
|
javascript
|
function decorateMethodDoc(methodDoc) {
normalizeMethodParameters(methodDoc);
// Mark methods with a `void` return type so we can omit show the return type in the docs.
methodDoc.showReturns = methodDoc.returnType && methodDoc.returnType != 'void';
}
|
[
"function",
"decorateMethodDoc",
"(",
"methodDoc",
")",
"{",
"normalizeMethodParameters",
"(",
"methodDoc",
")",
";",
"// Mark methods with a `void` return type so we can omit show the return type in the docs.",
"methodDoc",
".",
"showReturns",
"=",
"methodDoc",
".",
"returnType",
"&&",
"methodDoc",
".",
"returnType",
"!=",
"'void'",
";",
"}"
] |
Method that will be called for each method doc. The parameters for the method-docs
will be normalized, so that they can be easily used inside of dgeni templates.
|
[
"Method",
"that",
"will",
"be",
"called",
"for",
"each",
"method",
"doc",
".",
"The",
"parameters",
"for",
"the",
"method",
"-",
"docs",
"will",
"be",
"normalized",
"so",
"that",
"they",
"can",
"be",
"easily",
"used",
"inside",
"of",
"dgeni",
"templates",
"."
] |
c649ecdbe99a5537364579ac7fdae17283dd931a
|
https://github.com/Promact/md2/blob/c649ecdbe99a5537364579ac7fdae17283dd931a/tools/dgeni/processors/categorizer.js#L46-L51
|
18,469
|
Promact/md2
|
tools/dgeni/processors/categorizer.js
|
decoratePropertyDoc
|
function decoratePropertyDoc(propertyDoc) {
propertyDoc.isDirectiveInput = isDirectiveInput(propertyDoc);
propertyDoc.directiveInputAlias = getDirectiveInputAlias(propertyDoc);
propertyDoc.isDirectiveOutput = isDirectiveOutput(propertyDoc);
propertyDoc.directiveOutputAlias = getDirectiveOutputAlias(propertyDoc);
}
|
javascript
|
function decoratePropertyDoc(propertyDoc) {
propertyDoc.isDirectiveInput = isDirectiveInput(propertyDoc);
propertyDoc.directiveInputAlias = getDirectiveInputAlias(propertyDoc);
propertyDoc.isDirectiveOutput = isDirectiveOutput(propertyDoc);
propertyDoc.directiveOutputAlias = getDirectiveOutputAlias(propertyDoc);
}
|
[
"function",
"decoratePropertyDoc",
"(",
"propertyDoc",
")",
"{",
"propertyDoc",
".",
"isDirectiveInput",
"=",
"isDirectiveInput",
"(",
"propertyDoc",
")",
";",
"propertyDoc",
".",
"directiveInputAlias",
"=",
"getDirectiveInputAlias",
"(",
"propertyDoc",
")",
";",
"propertyDoc",
".",
"isDirectiveOutput",
"=",
"isDirectiveOutput",
"(",
"propertyDoc",
")",
";",
"propertyDoc",
".",
"directiveOutputAlias",
"=",
"getDirectiveOutputAlias",
"(",
"propertyDoc",
")",
";",
"}"
] |
Method that will be called for each property doc. Properties that are Angular inputs or
outputs will be marked. Aliases for the inputs or outputs will be stored as well.
|
[
"Method",
"that",
"will",
"be",
"called",
"for",
"each",
"property",
"doc",
".",
"Properties",
"that",
"are",
"Angular",
"inputs",
"or",
"outputs",
"will",
"be",
"marked",
".",
"Aliases",
"for",
"the",
"inputs",
"or",
"outputs",
"will",
"be",
"stored",
"as",
"well",
"."
] |
c649ecdbe99a5537364579ac7fdae17283dd931a
|
https://github.com/Promact/md2/blob/c649ecdbe99a5537364579ac7fdae17283dd931a/tools/dgeni/processors/categorizer.js#L57-L63
|
18,470
|
Promact/md2
|
tools/dgeni/processors/categorizer.js
|
resolveMethods
|
function resolveMethods(classDoc) {
let methods = classDoc.members.filter(member => member.hasOwnProperty('parameters'));
if (classDoc.inheritedDoc) {
methods = methods.concat(resolveMethods(classDoc.inheritedDoc));
}
return methods;
}
|
javascript
|
function resolveMethods(classDoc) {
let methods = classDoc.members.filter(member => member.hasOwnProperty('parameters'));
if (classDoc.inheritedDoc) {
methods = methods.concat(resolveMethods(classDoc.inheritedDoc));
}
return methods;
}
|
[
"function",
"resolveMethods",
"(",
"classDoc",
")",
"{",
"let",
"methods",
"=",
"classDoc",
".",
"members",
".",
"filter",
"(",
"member",
"=>",
"member",
".",
"hasOwnProperty",
"(",
"'parameters'",
")",
")",
";",
"if",
"(",
"classDoc",
".",
"inheritedDoc",
")",
"{",
"methods",
"=",
"methods",
".",
"concat",
"(",
"resolveMethods",
"(",
"classDoc",
".",
"inheritedDoc",
")",
")",
";",
"}",
"return",
"methods",
";",
"}"
] |
Function that walks through all inherited docs and collects public methods.
|
[
"Function",
"that",
"walks",
"through",
"all",
"inherited",
"docs",
"and",
"collects",
"public",
"methods",
"."
] |
c649ecdbe99a5537364579ac7fdae17283dd931a
|
https://github.com/Promact/md2/blob/c649ecdbe99a5537364579ac7fdae17283dd931a/tools/dgeni/processors/categorizer.js#L67-L75
|
18,471
|
Promact/md2
|
tools/dgeni/processors/categorizer.js
|
resolveProperties
|
function resolveProperties(classDoc) {
let properties = classDoc.members.filter(member => !member.hasOwnProperty('parameters'));
if (classDoc.inheritedDoc) {
properties = properties.concat(resolveProperties(classDoc.inheritedDoc));
}
return properties;
}
|
javascript
|
function resolveProperties(classDoc) {
let properties = classDoc.members.filter(member => !member.hasOwnProperty('parameters'));
if (classDoc.inheritedDoc) {
properties = properties.concat(resolveProperties(classDoc.inheritedDoc));
}
return properties;
}
|
[
"function",
"resolveProperties",
"(",
"classDoc",
")",
"{",
"let",
"properties",
"=",
"classDoc",
".",
"members",
".",
"filter",
"(",
"member",
"=>",
"!",
"member",
".",
"hasOwnProperty",
"(",
"'parameters'",
")",
")",
";",
"if",
"(",
"classDoc",
".",
"inheritedDoc",
")",
"{",
"properties",
"=",
"properties",
".",
"concat",
"(",
"resolveProperties",
"(",
"classDoc",
".",
"inheritedDoc",
")",
")",
";",
"}",
"return",
"properties",
";",
"}"
] |
Function that walks through all inherited docs and collects public properties.
|
[
"Function",
"that",
"walks",
"through",
"all",
"inherited",
"docs",
"and",
"collects",
"public",
"properties",
"."
] |
c649ecdbe99a5537364579ac7fdae17283dd931a
|
https://github.com/Promact/md2/blob/c649ecdbe99a5537364579ac7fdae17283dd931a/tools/dgeni/processors/categorizer.js#L78-L86
|
18,472
|
Promact/md2
|
tools/axe-protractor/axe-protractor.js
|
onPageStable
|
function onPageStable() {
AxeBuilder(browser.driver)
.configure(this.config || {})
.analyze(results => handleResults(this, results));
}
|
javascript
|
function onPageStable() {
AxeBuilder(browser.driver)
.configure(this.config || {})
.analyze(results => handleResults(this, results));
}
|
[
"function",
"onPageStable",
"(",
")",
"{",
"AxeBuilder",
"(",
"browser",
".",
"driver",
")",
".",
"configure",
"(",
"this",
".",
"config",
"||",
"{",
"}",
")",
".",
"analyze",
"(",
"results",
"=>",
"handleResults",
"(",
"this",
",",
"results",
")",
")",
";",
"}"
] |
Protractor plugin hook which always runs when Angular successfully bootstrapped.
|
[
"Protractor",
"plugin",
"hook",
"which",
"always",
"runs",
"when",
"Angular",
"successfully",
"bootstrapped",
"."
] |
c649ecdbe99a5537364579ac7fdae17283dd931a
|
https://github.com/Promact/md2/blob/c649ecdbe99a5537364579ac7fdae17283dd931a/tools/axe-protractor/axe-protractor.js#L16-L20
|
18,473
|
Promact/md2
|
tools/axe-protractor/axe-protractor.js
|
handleResults
|
function handleResults(context, results) {
if (checkedPages.indexOf(results.url) === -1) {
checkedPages.push(results.url);
results.violations.forEach(violation => {
let specName = `${violation.help} (${results.url})`;
let message = '\n' + buildMessage(violation);
context.addFailure(message, {specName});
});
}
}
|
javascript
|
function handleResults(context, results) {
if (checkedPages.indexOf(results.url) === -1) {
checkedPages.push(results.url);
results.violations.forEach(violation => {
let specName = `${violation.help} (${results.url})`;
let message = '\n' + buildMessage(violation);
context.addFailure(message, {specName});
});
}
}
|
[
"function",
"handleResults",
"(",
"context",
",",
"results",
")",
"{",
"if",
"(",
"checkedPages",
".",
"indexOf",
"(",
"results",
".",
"url",
")",
"===",
"-",
"1",
")",
"{",
"checkedPages",
".",
"push",
"(",
"results",
".",
"url",
")",
";",
"results",
".",
"violations",
".",
"forEach",
"(",
"violation",
"=>",
"{",
"let",
"specName",
"=",
"`",
"${",
"violation",
".",
"help",
"}",
"${",
"results",
".",
"url",
"}",
"`",
";",
"let",
"message",
"=",
"'\\n'",
"+",
"buildMessage",
"(",
"violation",
")",
";",
"context",
".",
"addFailure",
"(",
"message",
",",
"{",
"specName",
"}",
")",
";",
"}",
")",
";",
"}",
"}"
] |
Processes the axe-core results by reporting recognized violations
to Protractor and printing them out.
@param {!protractor.ProtractorPlugin} context
@param {!axe.AxeResults} results
|
[
"Processes",
"the",
"axe",
"-",
"core",
"results",
"by",
"reporting",
"recognized",
"violations",
"to",
"Protractor",
"and",
"printing",
"them",
"out",
"."
] |
c649ecdbe99a5537364579ac7fdae17283dd931a
|
https://github.com/Promact/md2/blob/c649ecdbe99a5537364579ac7fdae17283dd931a/tools/axe-protractor/axe-protractor.js#L28-L45
|
18,474
|
tamtakoe/oi.select
|
dist/select-tpls.js
|
contains
|
function contains(container, contained, className) {
var current = contained;
while (current && current.ownerDocument && current.nodeType !== 11) {
if (className) {
if (current === container) {
return false;
}
if (current.className.indexOf(className) >= 0) { //current.classList.contains(className) doesn't work in IE9
return true;
}
} else {
if (current === container) {
return true;
}
}
current = current.parentNode;
}
return false;
}
|
javascript
|
function contains(container, contained, className) {
var current = contained;
while (current && current.ownerDocument && current.nodeType !== 11) {
if (className) {
if (current === container) {
return false;
}
if (current.className.indexOf(className) >= 0) { //current.classList.contains(className) doesn't work in IE9
return true;
}
} else {
if (current === container) {
return true;
}
}
current = current.parentNode;
}
return false;
}
|
[
"function",
"contains",
"(",
"container",
",",
"contained",
",",
"className",
")",
"{",
"var",
"current",
"=",
"contained",
";",
"while",
"(",
"current",
"&&",
"current",
".",
"ownerDocument",
"&&",
"current",
".",
"nodeType",
"!==",
"11",
")",
"{",
"if",
"(",
"className",
")",
"{",
"if",
"(",
"current",
"===",
"container",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"current",
".",
"className",
".",
"indexOf",
"(",
"className",
")",
">=",
"0",
")",
"{",
"//current.classList.contains(className) doesn't work in IE9",
"return",
"true",
";",
"}",
"}",
"else",
"{",
"if",
"(",
"current",
"===",
"container",
")",
"{",
"return",
"true",
";",
"}",
"}",
"current",
"=",
"current",
".",
"parentNode",
";",
"}",
"return",
"false",
";",
"}"
] |
Check to see if a DOM element is a descendant of another DOM element.
@param {DOM element} container
@param {DOM element} contained
@param {string} class name of element in container
@returns {boolean}
|
[
"Check",
"to",
"see",
"if",
"a",
"DOM",
"element",
"is",
"a",
"descendant",
"of",
"another",
"DOM",
"element",
"."
] |
ed466fbdce90f7c3c6237ffff665bedc369acf1e
|
https://github.com/tamtakoe/oi.select/blob/ed466fbdce90f7c3c6237ffff665bedc369acf1e/dist/select-tpls.js#L57-L77
|
18,475
|
tamtakoe/oi.select
|
dist/select-tpls.js
|
intersection
|
function intersection(xArr, yArr, xFilter, yFilter, invert) {
var i, j, n, filteredX, filteredY, out = invert ? [].concat(xArr) : [];
for (i = 0, n = xArr.length; i < xArr.length; i++) {
filteredX = xFilter ? xFilter(xArr[i]) : xArr[i];
for (j = 0; j < yArr.length; j++) {
filteredY = yFilter ? yFilter(yArr[j]) : yArr[j];
if (angular.equals(filteredX, filteredY, xArr, yArr, i, j)) {
invert ? out.splice(i + out.length - n, 1) : out.push(yArr[j]);
break;
}
}
}
return out;
}
|
javascript
|
function intersection(xArr, yArr, xFilter, yFilter, invert) {
var i, j, n, filteredX, filteredY, out = invert ? [].concat(xArr) : [];
for (i = 0, n = xArr.length; i < xArr.length; i++) {
filteredX = xFilter ? xFilter(xArr[i]) : xArr[i];
for (j = 0; j < yArr.length; j++) {
filteredY = yFilter ? yFilter(yArr[j]) : yArr[j];
if (angular.equals(filteredX, filteredY, xArr, yArr, i, j)) {
invert ? out.splice(i + out.length - n, 1) : out.push(yArr[j]);
break;
}
}
}
return out;
}
|
[
"function",
"intersection",
"(",
"xArr",
",",
"yArr",
",",
"xFilter",
",",
"yFilter",
",",
"invert",
")",
"{",
"var",
"i",
",",
"j",
",",
"n",
",",
"filteredX",
",",
"filteredY",
",",
"out",
"=",
"invert",
"?",
"[",
"]",
".",
"concat",
"(",
"xArr",
")",
":",
"[",
"]",
";",
"for",
"(",
"i",
"=",
"0",
",",
"n",
"=",
"xArr",
".",
"length",
";",
"i",
"<",
"xArr",
".",
"length",
";",
"i",
"++",
")",
"{",
"filteredX",
"=",
"xFilter",
"?",
"xFilter",
"(",
"xArr",
"[",
"i",
"]",
")",
":",
"xArr",
"[",
"i",
"]",
";",
"for",
"(",
"j",
"=",
"0",
";",
"j",
"<",
"yArr",
".",
"length",
";",
"j",
"++",
")",
"{",
"filteredY",
"=",
"yFilter",
"?",
"yFilter",
"(",
"yArr",
"[",
"j",
"]",
")",
":",
"yArr",
"[",
"j",
"]",
";",
"if",
"(",
"angular",
".",
"equals",
"(",
"filteredX",
",",
"filteredY",
",",
"xArr",
",",
"yArr",
",",
"i",
",",
"j",
")",
")",
"{",
"invert",
"?",
"out",
".",
"splice",
"(",
"i",
"+",
"out",
".",
"length",
"-",
"n",
",",
"1",
")",
":",
"out",
".",
"push",
"(",
"yArr",
"[",
"j",
"]",
")",
";",
"break",
";",
"}",
"}",
"}",
"return",
"out",
";",
"}"
] |
lodash _.intersection + filter + invert
|
[
"lodash",
"_",
".",
"intersection",
"+",
"filter",
"+",
"invert"
] |
ed466fbdce90f7c3c6237ffff665bedc369acf1e
|
https://github.com/tamtakoe/oi.select/blob/ed466fbdce90f7c3c6237ffff665bedc369acf1e/dist/select-tpls.js#L297-L313
|
18,476
|
publishlab/node-acme-client
|
src/crypto/openssl.js
|
getAction
|
function getAction(key) {
const keyString = key.toString();
if (keyString.match(/CERTIFICATE\sREQUEST-{5}$/m)) {
return 'req';
}
else if (keyString.match(/(PUBLIC|PRIVATE)\sKEY-{5}$/m)) {
return 'rsa';
}
return 'x509';
}
|
javascript
|
function getAction(key) {
const keyString = key.toString();
if (keyString.match(/CERTIFICATE\sREQUEST-{5}$/m)) {
return 'req';
}
else if (keyString.match(/(PUBLIC|PRIVATE)\sKEY-{5}$/m)) {
return 'rsa';
}
return 'x509';
}
|
[
"function",
"getAction",
"(",
"key",
")",
"{",
"const",
"keyString",
"=",
"key",
".",
"toString",
"(",
")",
";",
"if",
"(",
"keyString",
".",
"match",
"(",
"/",
"CERTIFICATE\\sREQUEST-{5}$",
"/",
"m",
")",
")",
"{",
"return",
"'req'",
";",
"}",
"else",
"if",
"(",
"keyString",
".",
"match",
"(",
"/",
"(PUBLIC|PRIVATE)\\sKEY-{5}$",
"/",
"m",
")",
")",
"{",
"return",
"'rsa'",
";",
"}",
"return",
"'x509'",
";",
"}"
] |
Get OpenSSL action from buffer
@private
@param {buffer} key Private key, certificate or CSR
@returns {string} OpenSSL action
|
[
"Get",
"OpenSSL",
"action",
"from",
"buffer"
] |
a58fd0bff5931bc52ca92c39909f25db37b58f89
|
https://github.com/publishlab/node-acme-client/blob/a58fd0bff5931bc52ca92c39909f25db37b58f89/src/crypto/openssl.js#L68-L79
|
18,477
|
publishlab/node-acme-client
|
src/crypto/openssl.js
|
generateCsr
|
async function generateCsr(opts, csrConfig, key) {
let tempConfigFilePath;
/* Write key to disk */
const tempKeyFilePath = tempfile();
await fs.writeFileAsync(tempKeyFilePath, key);
opts.key = tempKeyFilePath;
/* Write config to disk */
if (csrConfig) {
tempConfigFilePath = tempfile();
await fs.writeFileAsync(tempConfigFilePath, csrConfig);
opts.config = tempConfigFilePath;
}
/* Create CSR */
const result = await openssl('req', opts);
/* Clean up */
await fs.unlinkAsync(tempKeyFilePath);
if (tempConfigFilePath) {
await fs.unlinkAsync(tempConfigFilePath);
}
return result;
}
|
javascript
|
async function generateCsr(opts, csrConfig, key) {
let tempConfigFilePath;
/* Write key to disk */
const tempKeyFilePath = tempfile();
await fs.writeFileAsync(tempKeyFilePath, key);
opts.key = tempKeyFilePath;
/* Write config to disk */
if (csrConfig) {
tempConfigFilePath = tempfile();
await fs.writeFileAsync(tempConfigFilePath, csrConfig);
opts.config = tempConfigFilePath;
}
/* Create CSR */
const result = await openssl('req', opts);
/* Clean up */
await fs.unlinkAsync(tempKeyFilePath);
if (tempConfigFilePath) {
await fs.unlinkAsync(tempConfigFilePath);
}
return result;
}
|
[
"async",
"function",
"generateCsr",
"(",
"opts",
",",
"csrConfig",
",",
"key",
")",
"{",
"let",
"tempConfigFilePath",
";",
"/* Write key to disk */",
"const",
"tempKeyFilePath",
"=",
"tempfile",
"(",
")",
";",
"await",
"fs",
".",
"writeFileAsync",
"(",
"tempKeyFilePath",
",",
"key",
")",
";",
"opts",
".",
"key",
"=",
"tempKeyFilePath",
";",
"/* Write config to disk */",
"if",
"(",
"csrConfig",
")",
"{",
"tempConfigFilePath",
"=",
"tempfile",
"(",
")",
";",
"await",
"fs",
".",
"writeFileAsync",
"(",
"tempConfigFilePath",
",",
"csrConfig",
")",
";",
"opts",
".",
"config",
"=",
"tempConfigFilePath",
";",
"}",
"/* Create CSR */",
"const",
"result",
"=",
"await",
"openssl",
"(",
"'req'",
",",
"opts",
")",
";",
"/* Clean up */",
"await",
"fs",
".",
"unlinkAsync",
"(",
"tempKeyFilePath",
")",
";",
"if",
"(",
"tempConfigFilePath",
")",
"{",
"await",
"fs",
".",
"unlinkAsync",
"(",
"tempConfigFilePath",
")",
";",
"}",
"return",
"result",
";",
"}"
] |
Execute Certificate Signing Request generation
@private
@param {object} opts CSR options
@param {string} csrConfig CSR configuration file
@param {buffer} key CSR private key
@returns {Promise<buffer>} CSR
|
[
"Execute",
"Certificate",
"Signing",
"Request",
"generation"
] |
a58fd0bff5931bc52ca92c39909f25db37b58f89
|
https://github.com/publishlab/node-acme-client/blob/a58fd0bff5931bc52ca92c39909f25db37b58f89/src/crypto/openssl.js#L258-L284
|
18,478
|
publishlab/node-acme-client
|
src/crypto/openssl.js
|
createCsrSubject
|
function createCsrSubject(opts) {
const data = {
C: opts.country,
ST: opts.state,
L: opts.locality,
O: opts.organization,
OU: opts.organizationUnit,
CN: opts.commonName || 'localhost',
emailAddress: opts.emailAddress
};
return Object.entries(data).map(([key, value]) => {
value = (value || '').replace(/[^\w .*,@'-]+/g, ' ').trim();
return value ? `/${key}=${value}` : '';
}).join('');
}
|
javascript
|
function createCsrSubject(opts) {
const data = {
C: opts.country,
ST: opts.state,
L: opts.locality,
O: opts.organization,
OU: opts.organizationUnit,
CN: opts.commonName || 'localhost',
emailAddress: opts.emailAddress
};
return Object.entries(data).map(([key, value]) => {
value = (value || '').replace(/[^\w .*,@'-]+/g, ' ').trim();
return value ? `/${key}=${value}` : '';
}).join('');
}
|
[
"function",
"createCsrSubject",
"(",
"opts",
")",
"{",
"const",
"data",
"=",
"{",
"C",
":",
"opts",
".",
"country",
",",
"ST",
":",
"opts",
".",
"state",
",",
"L",
":",
"opts",
".",
"locality",
",",
"O",
":",
"opts",
".",
"organization",
",",
"OU",
":",
"opts",
".",
"organizationUnit",
",",
"CN",
":",
"opts",
".",
"commonName",
"||",
"'localhost'",
",",
"emailAddress",
":",
"opts",
".",
"emailAddress",
"}",
";",
"return",
"Object",
".",
"entries",
"(",
"data",
")",
".",
"map",
"(",
"(",
"[",
"key",
",",
"value",
"]",
")",
"=>",
"{",
"value",
"=",
"(",
"value",
"||",
"''",
")",
".",
"replace",
"(",
"/",
"[^\\w .*,@'-]+",
"/",
"g",
",",
"' '",
")",
".",
"trim",
"(",
")",
";",
"return",
"value",
"?",
"`",
"${",
"key",
"}",
"${",
"value",
"}",
"`",
":",
"''",
";",
"}",
")",
".",
"join",
"(",
"''",
")",
";",
"}"
] |
Create Certificate Signing Request subject
@private
@param {object} opts CSR subject options
@returns {string} CSR subject
|
[
"Create",
"Certificate",
"Signing",
"Request",
"subject"
] |
a58fd0bff5931bc52ca92c39909f25db37b58f89
|
https://github.com/publishlab/node-acme-client/blob/a58fd0bff5931bc52ca92c39909f25db37b58f89/src/crypto/openssl.js#L295-L310
|
18,479
|
publishlab/node-acme-client
|
src/verify.js
|
verifyHttpChallenge
|
async function verifyHttpChallenge(authz, challenge, keyAuthorization, suffix = `/.well-known/acme-challenge/${challenge.token}`) {
debug(`Sending HTTP query to ${authz.identifier.value}, suffix: ${suffix}`);
const challengeUrl = `http://${authz.identifier.value}${suffix}`;
const resp = await axios.get(challengeUrl);
debug(`Query successful, HTTP status code: ${resp.status}`);
if (!resp.data || (resp.data !== keyAuthorization)) {
throw new Error(`Authorization not found in HTTP response from ${authz.identifier.value}`);
}
debug(`Key authorization match for ${challenge.type}/${authz.identifier.value}, ACME challenge verified`);
return true;
}
|
javascript
|
async function verifyHttpChallenge(authz, challenge, keyAuthorization, suffix = `/.well-known/acme-challenge/${challenge.token}`) {
debug(`Sending HTTP query to ${authz.identifier.value}, suffix: ${suffix}`);
const challengeUrl = `http://${authz.identifier.value}${suffix}`;
const resp = await axios.get(challengeUrl);
debug(`Query successful, HTTP status code: ${resp.status}`);
if (!resp.data || (resp.data !== keyAuthorization)) {
throw new Error(`Authorization not found in HTTP response from ${authz.identifier.value}`);
}
debug(`Key authorization match for ${challenge.type}/${authz.identifier.value}, ACME challenge verified`);
return true;
}
|
[
"async",
"function",
"verifyHttpChallenge",
"(",
"authz",
",",
"challenge",
",",
"keyAuthorization",
",",
"suffix",
"=",
"`",
"${",
"challenge",
".",
"token",
"}",
"`",
")",
"{",
"debug",
"(",
"`",
"${",
"authz",
".",
"identifier",
".",
"value",
"}",
"${",
"suffix",
"}",
"`",
")",
";",
"const",
"challengeUrl",
"=",
"`",
"${",
"authz",
".",
"identifier",
".",
"value",
"}",
"${",
"suffix",
"}",
"`",
";",
"const",
"resp",
"=",
"await",
"axios",
".",
"get",
"(",
"challengeUrl",
")",
";",
"debug",
"(",
"`",
"${",
"resp",
".",
"status",
"}",
"`",
")",
";",
"if",
"(",
"!",
"resp",
".",
"data",
"||",
"(",
"resp",
".",
"data",
"!==",
"keyAuthorization",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"`",
"${",
"authz",
".",
"identifier",
".",
"value",
"}",
"`",
")",
";",
"}",
"debug",
"(",
"`",
"${",
"challenge",
".",
"type",
"}",
"${",
"authz",
".",
"identifier",
".",
"value",
"}",
"`",
")",
";",
"return",
"true",
";",
"}"
] |
Verify ACME HTTP challenge
https://github.com/ietf-wg-acme/acme/blob/master/draft-ietf-acme-acme.md#http-challenge
@param {object} authz Identifier authorization
@param {object} challenge Authorization challenge
@param {string} keyAuthorization Challenge key authorization
@param {string} [suffix] URL suffix
@returns {Promise<boolean>}
|
[
"Verify",
"ACME",
"HTTP",
"challenge"
] |
a58fd0bff5931bc52ca92c39909f25db37b58f89
|
https://github.com/publishlab/node-acme-client/blob/a58fd0bff5931bc52ca92c39909f25db37b58f89/src/verify.js#L23-L36
|
18,480
|
publishlab/node-acme-client
|
src/verify.js
|
verifyDnsChallenge
|
async function verifyDnsChallenge(authz, challenge, keyAuthorization, prefix = '_acme-challenge.') {
debug(`Resolving DNS TXT records for ${authz.identifier.value}, prefix: ${prefix}`);
let challengeRecord = `${prefix}${authz.identifier.value}`;
try {
/* Attempt CNAME record first */
debug(`Checking CNAME for record ${challengeRecord}`);
const cnameRecords = await dns.resolveCnameAsync(challengeRecord);
if (cnameRecords.length) {
debug(`CNAME found at ${challengeRecord}, new challenge record: ${cnameRecords[0]}`);
challengeRecord = cnameRecords[0];
}
}
catch (e) {
debug(`No CNAME found for record ${challengeRecord}`);
}
/* Read TXT record */
const result = await dns.resolveTxtAsync(challengeRecord);
const records = [].concat(...result);
debug(`Query successful, found ${records.length} DNS TXT records`);
if (records.indexOf(keyAuthorization) === -1) {
throw new Error(`Authorization not found in DNS TXT records for ${authz.identifier.value}`);
}
debug(`Key authorization match for ${challenge.type}/${authz.identifier.value}, ACME challenge verified`);
return true;
}
|
javascript
|
async function verifyDnsChallenge(authz, challenge, keyAuthorization, prefix = '_acme-challenge.') {
debug(`Resolving DNS TXT records for ${authz.identifier.value}, prefix: ${prefix}`);
let challengeRecord = `${prefix}${authz.identifier.value}`;
try {
/* Attempt CNAME record first */
debug(`Checking CNAME for record ${challengeRecord}`);
const cnameRecords = await dns.resolveCnameAsync(challengeRecord);
if (cnameRecords.length) {
debug(`CNAME found at ${challengeRecord}, new challenge record: ${cnameRecords[0]}`);
challengeRecord = cnameRecords[0];
}
}
catch (e) {
debug(`No CNAME found for record ${challengeRecord}`);
}
/* Read TXT record */
const result = await dns.resolveTxtAsync(challengeRecord);
const records = [].concat(...result);
debug(`Query successful, found ${records.length} DNS TXT records`);
if (records.indexOf(keyAuthorization) === -1) {
throw new Error(`Authorization not found in DNS TXT records for ${authz.identifier.value}`);
}
debug(`Key authorization match for ${challenge.type}/${authz.identifier.value}, ACME challenge verified`);
return true;
}
|
[
"async",
"function",
"verifyDnsChallenge",
"(",
"authz",
",",
"challenge",
",",
"keyAuthorization",
",",
"prefix",
"=",
"'_acme-challenge.'",
")",
"{",
"debug",
"(",
"`",
"${",
"authz",
".",
"identifier",
".",
"value",
"}",
"${",
"prefix",
"}",
"`",
")",
";",
"let",
"challengeRecord",
"=",
"`",
"${",
"prefix",
"}",
"${",
"authz",
".",
"identifier",
".",
"value",
"}",
"`",
";",
"try",
"{",
"/* Attempt CNAME record first */",
"debug",
"(",
"`",
"${",
"challengeRecord",
"}",
"`",
")",
";",
"const",
"cnameRecords",
"=",
"await",
"dns",
".",
"resolveCnameAsync",
"(",
"challengeRecord",
")",
";",
"if",
"(",
"cnameRecords",
".",
"length",
")",
"{",
"debug",
"(",
"`",
"${",
"challengeRecord",
"}",
"${",
"cnameRecords",
"[",
"0",
"]",
"}",
"`",
")",
";",
"challengeRecord",
"=",
"cnameRecords",
"[",
"0",
"]",
";",
"}",
"}",
"catch",
"(",
"e",
")",
"{",
"debug",
"(",
"`",
"${",
"challengeRecord",
"}",
"`",
")",
";",
"}",
"/* Read TXT record */",
"const",
"result",
"=",
"await",
"dns",
".",
"resolveTxtAsync",
"(",
"challengeRecord",
")",
";",
"const",
"records",
"=",
"[",
"]",
".",
"concat",
"(",
"...",
"result",
")",
";",
"debug",
"(",
"`",
"${",
"records",
".",
"length",
"}",
"`",
")",
";",
"if",
"(",
"records",
".",
"indexOf",
"(",
"keyAuthorization",
")",
"===",
"-",
"1",
")",
"{",
"throw",
"new",
"Error",
"(",
"`",
"${",
"authz",
".",
"identifier",
".",
"value",
"}",
"`",
")",
";",
"}",
"debug",
"(",
"`",
"${",
"challenge",
".",
"type",
"}",
"${",
"authz",
".",
"identifier",
".",
"value",
"}",
"`",
")",
";",
"return",
"true",
";",
"}"
] |
Verify ACME DNS challenge
https://github.com/ietf-wg-acme/acme/blob/master/draft-ietf-acme-acme.md#dns-challenge
@param {object} authz Identifier authorization
@param {object} challenge Authorization challenge
@param {string} keyAuthorization Challenge key authorization
@param {string} [prefix] DNS prefix
@returns {Promise<boolean>}
|
[
"Verify",
"ACME",
"DNS",
"challenge"
] |
a58fd0bff5931bc52ca92c39909f25db37b58f89
|
https://github.com/publishlab/node-acme-client/blob/a58fd0bff5931bc52ca92c39909f25db37b58f89/src/verify.js#L51-L81
|
18,481
|
publishlab/node-acme-client
|
examples/api.js
|
challengeRemoveFn
|
async function challengeRemoveFn(authz, challenge, keyAuthorization) {
/* Do something here */
log(JSON.stringify(authz));
log(JSON.stringify(challenge));
log(keyAuthorization);
}
|
javascript
|
async function challengeRemoveFn(authz, challenge, keyAuthorization) {
/* Do something here */
log(JSON.stringify(authz));
log(JSON.stringify(challenge));
log(keyAuthorization);
}
|
[
"async",
"function",
"challengeRemoveFn",
"(",
"authz",
",",
"challenge",
",",
"keyAuthorization",
")",
"{",
"/* Do something here */",
"log",
"(",
"JSON",
".",
"stringify",
"(",
"authz",
")",
")",
";",
"log",
"(",
"JSON",
".",
"stringify",
"(",
"challenge",
")",
")",
";",
"log",
"(",
"keyAuthorization",
")",
";",
"}"
] |
Function used to remove an ACME challenge response
@param {object} authz Authorization object
@param {object} challenge Selected challenge
@returns {Promise}
|
[
"Function",
"used",
"to",
"remove",
"an",
"ACME",
"challenge",
"response"
] |
a58fd0bff5931bc52ca92c39909f25db37b58f89
|
https://github.com/publishlab/node-acme-client/blob/a58fd0bff5931bc52ca92c39909f25db37b58f89/examples/api.js#L39-L44
|
18,482
|
publishlab/node-acme-client
|
src/helper.js
|
b64encode
|
function b64encode(str) {
const buf = Buffer.isBuffer(str) ? str : Buffer.from(str);
return b64escape(buf.toString('base64'));
}
|
javascript
|
function b64encode(str) {
const buf = Buffer.isBuffer(str) ? str : Buffer.from(str);
return b64escape(buf.toString('base64'));
}
|
[
"function",
"b64encode",
"(",
"str",
")",
"{",
"const",
"buf",
"=",
"Buffer",
".",
"isBuffer",
"(",
"str",
")",
"?",
"str",
":",
"Buffer",
".",
"from",
"(",
"str",
")",
";",
"return",
"b64escape",
"(",
"buf",
".",
"toString",
"(",
"'base64'",
")",
")",
";",
"}"
] |
Base64 encode and escape buffer or string
@param {buffer|string} str Buffer or string to be encoded
@returns {string} Escaped base64 encoded string
|
[
"Base64",
"encode",
"and",
"escape",
"buffer",
"or",
"string"
] |
a58fd0bff5931bc52ca92c39909f25db37b58f89
|
https://github.com/publishlab/node-acme-client/blob/a58fd0bff5931bc52ca92c39909f25db37b58f89/src/helper.js#L78-L81
|
18,483
|
publishlab/node-acme-client
|
src/helper.js
|
getPemBody
|
function getPemBody(str) {
const pemStr = Buffer.isBuffer(str) ? str.toString() : str;
return pemStr.replace(/(\s*-----(BEGIN|END) ([A-Z0-9- ]+)-----|\r|\n)*/g, '');
}
|
javascript
|
function getPemBody(str) {
const pemStr = Buffer.isBuffer(str) ? str.toString() : str;
return pemStr.replace(/(\s*-----(BEGIN|END) ([A-Z0-9- ]+)-----|\r|\n)*/g, '');
}
|
[
"function",
"getPemBody",
"(",
"str",
")",
"{",
"const",
"pemStr",
"=",
"Buffer",
".",
"isBuffer",
"(",
"str",
")",
"?",
"str",
".",
"toString",
"(",
")",
":",
"str",
";",
"return",
"pemStr",
".",
"replace",
"(",
"/",
"(\\s*-----(BEGIN|END) ([A-Z0-9- ]+)-----|\\r|\\n)*",
"/",
"g",
",",
"''",
")",
";",
"}"
] |
Parse PEM body from buffer or string
@param {buffer|string} str PEM encoded buffer or string
@returns {string} PEM body
|
[
"Parse",
"PEM",
"body",
"from",
"buffer",
"or",
"string"
] |
a58fd0bff5931bc52ca92c39909f25db37b58f89
|
https://github.com/publishlab/node-acme-client/blob/a58fd0bff5931bc52ca92c39909f25db37b58f89/src/helper.js#L91-L94
|
18,484
|
publishlab/node-acme-client
|
src/helper.js
|
formatResponseError
|
function formatResponseError(resp) {
let result;
if (resp.data.error) {
result = resp.data.error.detail || resp.data.error;
}
else {
result = resp.data.detail || JSON.stringify(resp.data);
}
return result.replace(/\n/g, '');
}
|
javascript
|
function formatResponseError(resp) {
let result;
if (resp.data.error) {
result = resp.data.error.detail || resp.data.error;
}
else {
result = resp.data.detail || JSON.stringify(resp.data);
}
return result.replace(/\n/g, '');
}
|
[
"function",
"formatResponseError",
"(",
"resp",
")",
"{",
"let",
"result",
";",
"if",
"(",
"resp",
".",
"data",
".",
"error",
")",
"{",
"result",
"=",
"resp",
".",
"data",
".",
"error",
".",
"detail",
"||",
"resp",
".",
"data",
".",
"error",
";",
"}",
"else",
"{",
"result",
"=",
"resp",
".",
"data",
".",
"detail",
"||",
"JSON",
".",
"stringify",
"(",
"resp",
".",
"data",
")",
";",
"}",
"return",
"result",
".",
"replace",
"(",
"/",
"\\n",
"/",
"g",
",",
"''",
")",
";",
"}"
] |
Find and format error in response object
@param {object} resp HTTP response
@returns {string} Error message
|
[
"Find",
"and",
"format",
"error",
"in",
"response",
"object"
] |
a58fd0bff5931bc52ca92c39909f25db37b58f89
|
https://github.com/publishlab/node-acme-client/blob/a58fd0bff5931bc52ca92c39909f25db37b58f89/src/helper.js#L104-L115
|
18,485
|
publishlab/node-acme-client
|
src/crypto/forge.js
|
forgeObjectFromPem
|
function forgeObjectFromPem(input) {
const msg = forge.pem.decode(input)[0];
let key;
switch (msg.type) {
case 'PRIVATE KEY':
case 'RSA PRIVATE KEY':
key = forge.pki.privateKeyFromPem(input);
break;
case 'PUBLIC KEY':
case 'RSA PUBLIC KEY':
key = forge.pki.publicKeyFromPem(input);
break;
case 'CERTIFICATE':
case 'X509 CERTIFICATE':
case 'TRUSTED CERTIFICATE':
key = forge.pki.certificateFromPem(input).publicKey;
break;
case 'CERTIFICATE REQUEST':
key = forge.pki.certificationRequestFromPem(input).publicKey;
break;
default:
throw new Error('Unable to detect forge message type');
}
return key;
}
|
javascript
|
function forgeObjectFromPem(input) {
const msg = forge.pem.decode(input)[0];
let key;
switch (msg.type) {
case 'PRIVATE KEY':
case 'RSA PRIVATE KEY':
key = forge.pki.privateKeyFromPem(input);
break;
case 'PUBLIC KEY':
case 'RSA PUBLIC KEY':
key = forge.pki.publicKeyFromPem(input);
break;
case 'CERTIFICATE':
case 'X509 CERTIFICATE':
case 'TRUSTED CERTIFICATE':
key = forge.pki.certificateFromPem(input).publicKey;
break;
case 'CERTIFICATE REQUEST':
key = forge.pki.certificationRequestFromPem(input).publicKey;
break;
default:
throw new Error('Unable to detect forge message type');
}
return key;
}
|
[
"function",
"forgeObjectFromPem",
"(",
"input",
")",
"{",
"const",
"msg",
"=",
"forge",
".",
"pem",
".",
"decode",
"(",
"input",
")",
"[",
"0",
"]",
";",
"let",
"key",
";",
"switch",
"(",
"msg",
".",
"type",
")",
"{",
"case",
"'PRIVATE KEY'",
":",
"case",
"'RSA PRIVATE KEY'",
":",
"key",
"=",
"forge",
".",
"pki",
".",
"privateKeyFromPem",
"(",
"input",
")",
";",
"break",
";",
"case",
"'PUBLIC KEY'",
":",
"case",
"'RSA PUBLIC KEY'",
":",
"key",
"=",
"forge",
".",
"pki",
".",
"publicKeyFromPem",
"(",
"input",
")",
";",
"break",
";",
"case",
"'CERTIFICATE'",
":",
"case",
"'X509 CERTIFICATE'",
":",
"case",
"'TRUSTED CERTIFICATE'",
":",
"key",
"=",
"forge",
".",
"pki",
".",
"certificateFromPem",
"(",
"input",
")",
".",
"publicKey",
";",
"break",
";",
"case",
"'CERTIFICATE REQUEST'",
":",
"key",
"=",
"forge",
".",
"pki",
".",
"certificationRequestFromPem",
"(",
"input",
")",
".",
"publicKey",
";",
"break",
";",
"default",
":",
"throw",
"new",
"Error",
"(",
"'Unable to detect forge message type'",
")",
";",
"}",
"return",
"key",
";",
"}"
] |
Attempt to parse forge object from PEM encoded string
@private
@param {string} input PEM string
@return {object}
|
[
"Attempt",
"to",
"parse",
"forge",
"object",
"from",
"PEM",
"encoded",
"string"
] |
a58fd0bff5931bc52ca92c39909f25db37b58f89
|
https://github.com/publishlab/node-acme-client/blob/a58fd0bff5931bc52ca92c39909f25db37b58f89/src/crypto/forge.js#L28-L58
|
18,486
|
publishlab/node-acme-client
|
src/crypto/forge.js
|
createPrivateKey
|
async function createPrivateKey(size = 2048) {
let pemKey;
/* Native implementation */
if (nativeGenKeyPair) {
const result = await nativeGenKeyPair('rsa', {
modulusLength: size,
publicKeyEncoding: { type: 'spki', format: 'pem' },
privateKeyEncoding: { type: 'pkcs8', format: 'pem' }
});
pemKey = result[1];
}
/* Forge implementation */
else {
const keyPair = await forgeGenKeyPair({ bits: size });
pemKey = forge.pki.privateKeyToPem(keyPair.privateKey);
}
return Buffer.from(pemKey);
}
|
javascript
|
async function createPrivateKey(size = 2048) {
let pemKey;
/* Native implementation */
if (nativeGenKeyPair) {
const result = await nativeGenKeyPair('rsa', {
modulusLength: size,
publicKeyEncoding: { type: 'spki', format: 'pem' },
privateKeyEncoding: { type: 'pkcs8', format: 'pem' }
});
pemKey = result[1];
}
/* Forge implementation */
else {
const keyPair = await forgeGenKeyPair({ bits: size });
pemKey = forge.pki.privateKeyToPem(keyPair.privateKey);
}
return Buffer.from(pemKey);
}
|
[
"async",
"function",
"createPrivateKey",
"(",
"size",
"=",
"2048",
")",
"{",
"let",
"pemKey",
";",
"/* Native implementation */",
"if",
"(",
"nativeGenKeyPair",
")",
"{",
"const",
"result",
"=",
"await",
"nativeGenKeyPair",
"(",
"'rsa'",
",",
"{",
"modulusLength",
":",
"size",
",",
"publicKeyEncoding",
":",
"{",
"type",
":",
"'spki'",
",",
"format",
":",
"'pem'",
"}",
",",
"privateKeyEncoding",
":",
"{",
"type",
":",
"'pkcs8'",
",",
"format",
":",
"'pem'",
"}",
"}",
")",
";",
"pemKey",
"=",
"result",
"[",
"1",
"]",
";",
"}",
"/* Forge implementation */",
"else",
"{",
"const",
"keyPair",
"=",
"await",
"forgeGenKeyPair",
"(",
"{",
"bits",
":",
"size",
"}",
")",
";",
"pemKey",
"=",
"forge",
".",
"pki",
".",
"privateKeyToPem",
"(",
"keyPair",
".",
"privateKey",
")",
";",
"}",
"return",
"Buffer",
".",
"from",
"(",
"pemKey",
")",
";",
"}"
] |
Generate a private RSA key
@param {number} [size] Size of the key, default: `2048`
@returns {Promise<buffer>} Private RSA key
|
[
"Generate",
"a",
"private",
"RSA",
"key"
] |
a58fd0bff5931bc52ca92c39909f25db37b58f89
|
https://github.com/publishlab/node-acme-client/blob/a58fd0bff5931bc52ca92c39909f25db37b58f89/src/crypto/forge.js#L111-L131
|
18,487
|
publishlab/node-acme-client
|
src/crypto/forge.js
|
createCsrSubject
|
function createCsrSubject(subjectObj) {
return Object.entries(subjectObj).reduce((result, [shortName, value]) => {
if (value) {
result.push({ shortName, value });
}
return result;
}, []);
}
|
javascript
|
function createCsrSubject(subjectObj) {
return Object.entries(subjectObj).reduce((result, [shortName, value]) => {
if (value) {
result.push({ shortName, value });
}
return result;
}, []);
}
|
[
"function",
"createCsrSubject",
"(",
"subjectObj",
")",
"{",
"return",
"Object",
".",
"entries",
"(",
"subjectObj",
")",
".",
"reduce",
"(",
"(",
"result",
",",
"[",
"shortName",
",",
"value",
"]",
")",
"=>",
"{",
"if",
"(",
"value",
")",
"{",
"result",
".",
"push",
"(",
"{",
"shortName",
",",
"value",
"}",
")",
";",
"}",
"return",
"result",
";",
"}",
",",
"[",
"]",
")",
";",
"}"
] |
Create array of short names and values for Certificate Signing Request subjects
@private
@param {object} subjectObj Key-value of short names and values
@returns {object[]} Certificate Signing Request subject array
|
[
"Create",
"array",
"of",
"short",
"names",
"and",
"values",
"for",
"Certificate",
"Signing",
"Request",
"subjects"
] |
a58fd0bff5931bc52ca92c39909f25db37b58f89
|
https://github.com/publishlab/node-acme-client/blob/a58fd0bff5931bc52ca92c39909f25db37b58f89/src/crypto/forge.js#L232-L240
|
18,488
|
postcss/postcss-custom-media
|
lib/transform-media-list.js
|
transformMedia
|
function transformMedia(media, customMedias) {
const transpiledMedias = [];
for (const index in media.nodes) {
const { value, nodes } = media.nodes[index];
const key = value.replace(customPseudoRegExp, '$1');
if (key in customMedias) {
for (const replacementMedia of customMedias[key].nodes) {
// use the first available modifier unless they cancel each other out
const modifier = media.modifier !== replacementMedia.modifier
? media.modifier || replacementMedia.modifier
: '';
const mediaClone = media.clone({
modifier,
// conditionally use the raws from the first available modifier
raws: !modifier || media.modifier
? { ...media.raws }
: { ...replacementMedia.raws },
type: media.type || replacementMedia.type,
});
// conditionally include more replacement raws when the type is present
if (mediaClone.type === replacementMedia.type) {
Object.assign(mediaClone.raws, {
and: replacementMedia.raws.and,
beforeAnd: replacementMedia.raws.beforeAnd,
beforeExpression: replacementMedia.raws.beforeExpression
});
}
mediaClone.nodes.splice(index, 1, ...replacementMedia.clone().nodes.map(node => {
// use raws and spacing from the current usage
if (media.nodes[index].raws.and) {
node.raws = { ...media.nodes[index].raws };
}
node.spaces = { ...media.nodes[index].spaces };
return node;
}));
// remove the currently transformed key to prevent recursion
const nextCustomMedia = getCustomMediasWithoutKey(customMedias, key);
const retranspiledMedias = transformMedia(mediaClone, nextCustomMedia);
if (retranspiledMedias.length) {
transpiledMedias.push(...retranspiledMedias);
} else {
transpiledMedias.push(mediaClone);
}
}
return transpiledMedias;
} else if (nodes && nodes.length) {
transformMediaList(media.nodes[index], customMedias);
}
}
return transpiledMedias;
}
|
javascript
|
function transformMedia(media, customMedias) {
const transpiledMedias = [];
for (const index in media.nodes) {
const { value, nodes } = media.nodes[index];
const key = value.replace(customPseudoRegExp, '$1');
if (key in customMedias) {
for (const replacementMedia of customMedias[key].nodes) {
// use the first available modifier unless they cancel each other out
const modifier = media.modifier !== replacementMedia.modifier
? media.modifier || replacementMedia.modifier
: '';
const mediaClone = media.clone({
modifier,
// conditionally use the raws from the first available modifier
raws: !modifier || media.modifier
? { ...media.raws }
: { ...replacementMedia.raws },
type: media.type || replacementMedia.type,
});
// conditionally include more replacement raws when the type is present
if (mediaClone.type === replacementMedia.type) {
Object.assign(mediaClone.raws, {
and: replacementMedia.raws.and,
beforeAnd: replacementMedia.raws.beforeAnd,
beforeExpression: replacementMedia.raws.beforeExpression
});
}
mediaClone.nodes.splice(index, 1, ...replacementMedia.clone().nodes.map(node => {
// use raws and spacing from the current usage
if (media.nodes[index].raws.and) {
node.raws = { ...media.nodes[index].raws };
}
node.spaces = { ...media.nodes[index].spaces };
return node;
}));
// remove the currently transformed key to prevent recursion
const nextCustomMedia = getCustomMediasWithoutKey(customMedias, key);
const retranspiledMedias = transformMedia(mediaClone, nextCustomMedia);
if (retranspiledMedias.length) {
transpiledMedias.push(...retranspiledMedias);
} else {
transpiledMedias.push(mediaClone);
}
}
return transpiledMedias;
} else if (nodes && nodes.length) {
transformMediaList(media.nodes[index], customMedias);
}
}
return transpiledMedias;
}
|
[
"function",
"transformMedia",
"(",
"media",
",",
"customMedias",
")",
"{",
"const",
"transpiledMedias",
"=",
"[",
"]",
";",
"for",
"(",
"const",
"index",
"in",
"media",
".",
"nodes",
")",
"{",
"const",
"{",
"value",
",",
"nodes",
"}",
"=",
"media",
".",
"nodes",
"[",
"index",
"]",
";",
"const",
"key",
"=",
"value",
".",
"replace",
"(",
"customPseudoRegExp",
",",
"'$1'",
")",
";",
"if",
"(",
"key",
"in",
"customMedias",
")",
"{",
"for",
"(",
"const",
"replacementMedia",
"of",
"customMedias",
"[",
"key",
"]",
".",
"nodes",
")",
"{",
"// use the first available modifier unless they cancel each other out",
"const",
"modifier",
"=",
"media",
".",
"modifier",
"!==",
"replacementMedia",
".",
"modifier",
"?",
"media",
".",
"modifier",
"||",
"replacementMedia",
".",
"modifier",
":",
"''",
";",
"const",
"mediaClone",
"=",
"media",
".",
"clone",
"(",
"{",
"modifier",
",",
"// conditionally use the raws from the first available modifier",
"raws",
":",
"!",
"modifier",
"||",
"media",
".",
"modifier",
"?",
"{",
"...",
"media",
".",
"raws",
"}",
":",
"{",
"...",
"replacementMedia",
".",
"raws",
"}",
",",
"type",
":",
"media",
".",
"type",
"||",
"replacementMedia",
".",
"type",
",",
"}",
")",
";",
"// conditionally include more replacement raws when the type is present",
"if",
"(",
"mediaClone",
".",
"type",
"===",
"replacementMedia",
".",
"type",
")",
"{",
"Object",
".",
"assign",
"(",
"mediaClone",
".",
"raws",
",",
"{",
"and",
":",
"replacementMedia",
".",
"raws",
".",
"and",
",",
"beforeAnd",
":",
"replacementMedia",
".",
"raws",
".",
"beforeAnd",
",",
"beforeExpression",
":",
"replacementMedia",
".",
"raws",
".",
"beforeExpression",
"}",
")",
";",
"}",
"mediaClone",
".",
"nodes",
".",
"splice",
"(",
"index",
",",
"1",
",",
"...",
"replacementMedia",
".",
"clone",
"(",
")",
".",
"nodes",
".",
"map",
"(",
"node",
"=>",
"{",
"// use raws and spacing from the current usage",
"if",
"(",
"media",
".",
"nodes",
"[",
"index",
"]",
".",
"raws",
".",
"and",
")",
"{",
"node",
".",
"raws",
"=",
"{",
"...",
"media",
".",
"nodes",
"[",
"index",
"]",
".",
"raws",
"}",
";",
"}",
"node",
".",
"spaces",
"=",
"{",
"...",
"media",
".",
"nodes",
"[",
"index",
"]",
".",
"spaces",
"}",
";",
"return",
"node",
";",
"}",
")",
")",
";",
"// remove the currently transformed key to prevent recursion",
"const",
"nextCustomMedia",
"=",
"getCustomMediasWithoutKey",
"(",
"customMedias",
",",
"key",
")",
";",
"const",
"retranspiledMedias",
"=",
"transformMedia",
"(",
"mediaClone",
",",
"nextCustomMedia",
")",
";",
"if",
"(",
"retranspiledMedias",
".",
"length",
")",
"{",
"transpiledMedias",
".",
"push",
"(",
"...",
"retranspiledMedias",
")",
";",
"}",
"else",
"{",
"transpiledMedias",
".",
"push",
"(",
"mediaClone",
")",
";",
"}",
"}",
"return",
"transpiledMedias",
";",
"}",
"else",
"if",
"(",
"nodes",
"&&",
"nodes",
".",
"length",
")",
"{",
"transformMediaList",
"(",
"media",
".",
"nodes",
"[",
"index",
"]",
",",
"customMedias",
")",
";",
"}",
"}",
"return",
"transpiledMedias",
";",
"}"
] |
return custom pseudo medias replaced with custom medias
|
[
"return",
"custom",
"pseudo",
"medias",
"replaced",
"with",
"custom",
"medias"
] |
ca22cf673fbffbc981807c1e4b758f1575fb8aec
|
https://github.com/postcss/postcss-custom-media/blob/ca22cf673fbffbc981807c1e4b758f1575fb8aec/lib/transform-media-list.js#L19-L79
|
18,489
|
00SteinsGate00/Node-MPV
|
lib/ipcInterface.js
|
function(options) {
this.options = {
"debug": false,
"verbose": false,
"socket": "/tmp/node-mpv.sock"
}
this.options = _.defaults(options || {}, this.options);
// intialize the event emitter
eventEmitter.call(this);
// socket object
this.socket = new net.Socket();
// partially "fixes" the EventEmitter leak
// the leaking listeners is "close", but I did not yet find any solution to fix it
this.socket.setMaxListeners(0);
// connect
this.socket.connect({path: this.options.socket}, function() {
if(this.options.debug){
console.log("Connected to socket " + this.options.socket);
}
}.bind(this));
// reestablish connection when lost
this.socket.on('close', function() {
if(this.options.debug){
console.log("Lost connection to socket. Atemping to reconnect");
}
// properly close the connection
this.socket.end();
// reconnect
this.socket.connect({path: this.options.socket}, function() {
if(this.options.verbose || this.options.debug){
console.log("Connected to socket " + this.options.socket);
}
}.bind(this));
}.bind(this));
// catch errors when occurrings
this.socket.on('error', function(error) {
if(this.options.debug){
console.log(error);
}
}.bind(this));
// received data is delivered upwards by an event
this.socket.on('data', function(data) {
// various messages might be fetched at once
var messages = data.toString().split('\n');
// each message is emitted seperately
messages.forEach(function (message) {
// empty messages may occur
if(message.length > 0){
this.emit('message', JSON.parse(message));
}
}.bind(this));
}.bind(this));
}
|
javascript
|
function(options) {
this.options = {
"debug": false,
"verbose": false,
"socket": "/tmp/node-mpv.sock"
}
this.options = _.defaults(options || {}, this.options);
// intialize the event emitter
eventEmitter.call(this);
// socket object
this.socket = new net.Socket();
// partially "fixes" the EventEmitter leak
// the leaking listeners is "close", but I did not yet find any solution to fix it
this.socket.setMaxListeners(0);
// connect
this.socket.connect({path: this.options.socket}, function() {
if(this.options.debug){
console.log("Connected to socket " + this.options.socket);
}
}.bind(this));
// reestablish connection when lost
this.socket.on('close', function() {
if(this.options.debug){
console.log("Lost connection to socket. Atemping to reconnect");
}
// properly close the connection
this.socket.end();
// reconnect
this.socket.connect({path: this.options.socket}, function() {
if(this.options.verbose || this.options.debug){
console.log("Connected to socket " + this.options.socket);
}
}.bind(this));
}.bind(this));
// catch errors when occurrings
this.socket.on('error', function(error) {
if(this.options.debug){
console.log(error);
}
}.bind(this));
// received data is delivered upwards by an event
this.socket.on('data', function(data) {
// various messages might be fetched at once
var messages = data.toString().split('\n');
// each message is emitted seperately
messages.forEach(function (message) {
// empty messages may occur
if(message.length > 0){
this.emit('message', JSON.parse(message));
}
}.bind(this));
}.bind(this));
}
|
[
"function",
"(",
"options",
")",
"{",
"this",
".",
"options",
"=",
"{",
"\"debug\"",
":",
"false",
",",
"\"verbose\"",
":",
"false",
",",
"\"socket\"",
":",
"\"/tmp/node-mpv.sock\"",
"}",
"this",
".",
"options",
"=",
"_",
".",
"defaults",
"(",
"options",
"||",
"{",
"}",
",",
"this",
".",
"options",
")",
";",
"// intialize the event emitter",
"eventEmitter",
".",
"call",
"(",
"this",
")",
";",
"// socket object",
"this",
".",
"socket",
"=",
"new",
"net",
".",
"Socket",
"(",
")",
";",
"// partially \"fixes\" the EventEmitter leak",
"// the leaking listeners is \"close\", but I did not yet find any solution to fix it",
"this",
".",
"socket",
".",
"setMaxListeners",
"(",
"0",
")",
";",
"// connect",
"this",
".",
"socket",
".",
"connect",
"(",
"{",
"path",
":",
"this",
".",
"options",
".",
"socket",
"}",
",",
"function",
"(",
")",
"{",
"if",
"(",
"this",
".",
"options",
".",
"debug",
")",
"{",
"console",
".",
"log",
"(",
"\"Connected to socket \"",
"+",
"this",
".",
"options",
".",
"socket",
")",
";",
"}",
"}",
".",
"bind",
"(",
"this",
")",
")",
";",
"// reestablish connection when lost",
"this",
".",
"socket",
".",
"on",
"(",
"'close'",
",",
"function",
"(",
")",
"{",
"if",
"(",
"this",
".",
"options",
".",
"debug",
")",
"{",
"console",
".",
"log",
"(",
"\"Lost connection to socket. Atemping to reconnect\"",
")",
";",
"}",
"// properly close the connection",
"this",
".",
"socket",
".",
"end",
"(",
")",
";",
"// reconnect",
"this",
".",
"socket",
".",
"connect",
"(",
"{",
"path",
":",
"this",
".",
"options",
".",
"socket",
"}",
",",
"function",
"(",
")",
"{",
"if",
"(",
"this",
".",
"options",
".",
"verbose",
"||",
"this",
".",
"options",
".",
"debug",
")",
"{",
"console",
".",
"log",
"(",
"\"Connected to socket \"",
"+",
"this",
".",
"options",
".",
"socket",
")",
";",
"}",
"}",
".",
"bind",
"(",
"this",
")",
")",
";",
"}",
".",
"bind",
"(",
"this",
")",
")",
";",
"// catch errors when occurrings",
"this",
".",
"socket",
".",
"on",
"(",
"'error'",
",",
"function",
"(",
"error",
")",
"{",
"if",
"(",
"this",
".",
"options",
".",
"debug",
")",
"{",
"console",
".",
"log",
"(",
"error",
")",
";",
"}",
"}",
".",
"bind",
"(",
"this",
")",
")",
";",
"// received data is delivered upwards by an event",
"this",
".",
"socket",
".",
"on",
"(",
"'data'",
",",
"function",
"(",
"data",
")",
"{",
"// various messages might be fetched at once",
"var",
"messages",
"=",
"data",
".",
"toString",
"(",
")",
".",
"split",
"(",
"'\\n'",
")",
";",
"// each message is emitted seperately",
"messages",
".",
"forEach",
"(",
"function",
"(",
"message",
")",
"{",
"// empty messages may occur",
"if",
"(",
"message",
".",
"length",
">",
"0",
")",
"{",
"this",
".",
"emit",
"(",
"'message'",
",",
"JSON",
".",
"parse",
"(",
"message",
")",
")",
";",
"}",
"}",
".",
"bind",
"(",
"this",
")",
")",
";",
"}",
".",
"bind",
"(",
"this",
")",
")",
";",
"}"
] |
connects to a socket reconnects when connection lost emits 'message' event when data is received from the socket
|
[
"connects",
"to",
"a",
"socket",
"reconnects",
"when",
"connection",
"lost",
"emits",
"message",
"event",
"when",
"data",
"is",
"received",
"from",
"the",
"socket"
] |
f93e8e28fc0f64e03c134e12a9608f0410f12ac1
|
https://github.com/00SteinsGate00/Node-MPV/blob/f93e8e28fc0f64e03c134e12a9608f0410f12ac1/lib/ipcInterface.js#L13-L78
|
|
18,490
|
00SteinsGate00/Node-MPV
|
lib/mpv/mpv.js
|
function(file, mode, options) {
mode = mode || "replace";
const args = options ? [file, mode].concat(util.formatOptions(options)) : [file, mode];
this.socket.command("loadfile", args);
}
|
javascript
|
function(file, mode, options) {
mode = mode || "replace";
const args = options ? [file, mode].concat(util.formatOptions(options)) : [file, mode];
this.socket.command("loadfile", args);
}
|
[
"function",
"(",
"file",
",",
"mode",
",",
"options",
")",
"{",
"mode",
"=",
"mode",
"||",
"\"replace\"",
";",
"const",
"args",
"=",
"options",
"?",
"[",
"file",
",",
"mode",
"]",
".",
"concat",
"(",
"util",
".",
"formatOptions",
"(",
"options",
")",
")",
":",
"[",
"file",
",",
"mode",
"]",
";",
"this",
".",
"socket",
".",
"command",
"(",
"\"loadfile\"",
",",
"args",
")",
";",
"}"
] |
loads a file or stream url into mpv mode replace replace current video append append to playlist append-play append to playlist and play, if the playlist was empty options further options
|
[
"loads",
"a",
"file",
"or",
"stream",
"url",
"into",
"mpv",
"mode",
"replace",
"replace",
"current",
"video",
"append",
"append",
"to",
"playlist",
"append",
"-",
"play",
"append",
"to",
"playlist",
"and",
"play",
"if",
"the",
"playlist",
"was",
"empty",
"options",
"further",
"options"
] |
f93e8e28fc0f64e03c134e12a9608f0410f12ac1
|
https://github.com/00SteinsGate00/Node-MPV/blob/f93e8e28fc0f64e03c134e12a9608f0410f12ac1/lib/mpv/mpv.js#L308-L312
|
|
18,491
|
mono-js/mono
|
lib/conf.js
|
customizer
|
function customizer(objValue, srcValue) {
if (isUndefined(objValue) && !isUndefined(srcValue)) return srcValue
if (isArray(objValue) && isArray(srcValue)) return srcValue
if (isRegExp(objValue) || isRegExp(srcValue)) return srcValue
if (isObject(objValue) || isObject(srcValue)) return mergeWith(objValue, srcValue, customizer)
}
|
javascript
|
function customizer(objValue, srcValue) {
if (isUndefined(objValue) && !isUndefined(srcValue)) return srcValue
if (isArray(objValue) && isArray(srcValue)) return srcValue
if (isRegExp(objValue) || isRegExp(srcValue)) return srcValue
if (isObject(objValue) || isObject(srcValue)) return mergeWith(objValue, srcValue, customizer)
}
|
[
"function",
"customizer",
"(",
"objValue",
",",
"srcValue",
")",
"{",
"if",
"(",
"isUndefined",
"(",
"objValue",
")",
"&&",
"!",
"isUndefined",
"(",
"srcValue",
")",
")",
"return",
"srcValue",
"if",
"(",
"isArray",
"(",
"objValue",
")",
"&&",
"isArray",
"(",
"srcValue",
")",
")",
"return",
"srcValue",
"if",
"(",
"isRegExp",
"(",
"objValue",
")",
"||",
"isRegExp",
"(",
"srcValue",
")",
")",
"return",
"srcValue",
"if",
"(",
"isObject",
"(",
"objValue",
")",
"||",
"isObject",
"(",
"srcValue",
")",
")",
"return",
"mergeWith",
"(",
"objValue",
",",
"srcValue",
",",
"customizer",
")",
"}"
] |
Customizer method to merge sources
|
[
"Customizer",
"method",
"to",
"merge",
"sources"
] |
8b2211c316b8067345d9299e1d648dfc76ba95c1
|
https://github.com/mono-js/mono/blob/8b2211c316b8067345d9299e1d648dfc76ba95c1/lib/conf.js#L8-L13
|
18,492
|
kevinsqi/react-piano
|
src/MidiNumbers.js
|
buildMidiNumberAttributes
|
function buildMidiNumberAttributes(midiNumber) {
const pitchIndex = (midiNumber - MIDI_NUMBER_C0) % NOTES_IN_OCTAVE;
const octave = Math.floor((midiNumber - MIDI_NUMBER_C0) / NOTES_IN_OCTAVE);
const pitchName = SORTED_PITCHES[pitchIndex];
return {
note: `${pitchName}${octave}`,
pitchName,
octave,
midiNumber,
isAccidental: ACCIDENTAL_PITCHES.includes(pitchName),
};
}
|
javascript
|
function buildMidiNumberAttributes(midiNumber) {
const pitchIndex = (midiNumber - MIDI_NUMBER_C0) % NOTES_IN_OCTAVE;
const octave = Math.floor((midiNumber - MIDI_NUMBER_C0) / NOTES_IN_OCTAVE);
const pitchName = SORTED_PITCHES[pitchIndex];
return {
note: `${pitchName}${octave}`,
pitchName,
octave,
midiNumber,
isAccidental: ACCIDENTAL_PITCHES.includes(pitchName),
};
}
|
[
"function",
"buildMidiNumberAttributes",
"(",
"midiNumber",
")",
"{",
"const",
"pitchIndex",
"=",
"(",
"midiNumber",
"-",
"MIDI_NUMBER_C0",
")",
"%",
"NOTES_IN_OCTAVE",
";",
"const",
"octave",
"=",
"Math",
".",
"floor",
"(",
"(",
"midiNumber",
"-",
"MIDI_NUMBER_C0",
")",
"/",
"NOTES_IN_OCTAVE",
")",
";",
"const",
"pitchName",
"=",
"SORTED_PITCHES",
"[",
"pitchIndex",
"]",
";",
"return",
"{",
"note",
":",
"`",
"${",
"pitchName",
"}",
"${",
"octave",
"}",
"`",
",",
"pitchName",
",",
"octave",
",",
"midiNumber",
",",
"isAccidental",
":",
"ACCIDENTAL_PITCHES",
".",
"includes",
"(",
"pitchName",
")",
",",
"}",
";",
"}"
] |
Build cache for getAttributes
|
[
"Build",
"cache",
"for",
"getAttributes"
] |
d5ef9b59e3fed2ae6f9fda6244ac2ba4659ece10
|
https://github.com/kevinsqi/react-piano/blob/d5ef9b59e3fed2ae6f9fda6244ac2ba4659ece10/src/MidiNumbers.js#L57-L68
|
18,493
|
EightShapes/esds-build
|
tasks/copy.js
|
getCompiledChildModuleDocsPath
|
function getCompiledChildModuleDocsPath(moduleName) {
let rootPath = c.rootPath;
if (process.cwd() !== c.rootPath) {
rootPath = path.join(process.cwd(), c.rootPath);
}
const childModuleRootPath = path.join(rootPath, c.dependenciesPath, moduleName),
cmc = config.get(childModuleRootPath),
childCompiledDocs = path.join(childModuleRootPath, cmc.webroot, cmc.latestVersionPath, '**/*.html');
return childCompiledDocs;
}
|
javascript
|
function getCompiledChildModuleDocsPath(moduleName) {
let rootPath = c.rootPath;
if (process.cwd() !== c.rootPath) {
rootPath = path.join(process.cwd(), c.rootPath);
}
const childModuleRootPath = path.join(rootPath, c.dependenciesPath, moduleName),
cmc = config.get(childModuleRootPath),
childCompiledDocs = path.join(childModuleRootPath, cmc.webroot, cmc.latestVersionPath, '**/*.html');
return childCompiledDocs;
}
|
[
"function",
"getCompiledChildModuleDocsPath",
"(",
"moduleName",
")",
"{",
"let",
"rootPath",
"=",
"c",
".",
"rootPath",
";",
"if",
"(",
"process",
".",
"cwd",
"(",
")",
"!==",
"c",
".",
"rootPath",
")",
"{",
"rootPath",
"=",
"path",
".",
"join",
"(",
"process",
".",
"cwd",
"(",
")",
",",
"c",
".",
"rootPath",
")",
";",
"}",
"const",
"childModuleRootPath",
"=",
"path",
".",
"join",
"(",
"rootPath",
",",
"c",
".",
"dependenciesPath",
",",
"moduleName",
")",
",",
"cmc",
"=",
"config",
".",
"get",
"(",
"childModuleRootPath",
")",
",",
"childCompiledDocs",
"=",
"path",
".",
"join",
"(",
"childModuleRootPath",
",",
"cmc",
".",
"webroot",
",",
"cmc",
".",
"latestVersionPath",
",",
"'**/*.html'",
")",
";",
"return",
"childCompiledDocs",
";",
"}"
] |
CHILD MODULE AUTO-COPYING Copying doc pages from a child module
|
[
"CHILD",
"MODULE",
"AUTO",
"-",
"COPYING",
"Copying",
"doc",
"pages",
"from",
"a",
"child",
"module"
] |
3e8519e5a0ef5fb589726b64cf292f07fd18b0b5
|
https://github.com/EightShapes/esds-build/blob/3e8519e5a0ef5fb589726b64cf292f07fd18b0b5/tasks/copy.js#L66-L75
|
18,494
|
NodeRedis/node-redis-parser
|
lib/parser.js
|
parseSimpleNumbers
|
function parseSimpleNumbers (parser) {
const length = parser.buffer.length - 1
var offset = parser.offset
var number = 0
var sign = 1
if (parser.buffer[offset] === 45) {
sign = -1
offset++
}
while (offset < length) {
const c1 = parser.buffer[offset++]
if (c1 === 13) { // \r\n
parser.offset = offset + 1
return sign * number
}
number = (number * 10) + (c1 - 48)
}
}
|
javascript
|
function parseSimpleNumbers (parser) {
const length = parser.buffer.length - 1
var offset = parser.offset
var number = 0
var sign = 1
if (parser.buffer[offset] === 45) {
sign = -1
offset++
}
while (offset < length) {
const c1 = parser.buffer[offset++]
if (c1 === 13) { // \r\n
parser.offset = offset + 1
return sign * number
}
number = (number * 10) + (c1 - 48)
}
}
|
[
"function",
"parseSimpleNumbers",
"(",
"parser",
")",
"{",
"const",
"length",
"=",
"parser",
".",
"buffer",
".",
"length",
"-",
"1",
"var",
"offset",
"=",
"parser",
".",
"offset",
"var",
"number",
"=",
"0",
"var",
"sign",
"=",
"1",
"if",
"(",
"parser",
".",
"buffer",
"[",
"offset",
"]",
"===",
"45",
")",
"{",
"sign",
"=",
"-",
"1",
"offset",
"++",
"}",
"while",
"(",
"offset",
"<",
"length",
")",
"{",
"const",
"c1",
"=",
"parser",
".",
"buffer",
"[",
"offset",
"++",
"]",
"if",
"(",
"c1",
"===",
"13",
")",
"{",
"// \\r\\n",
"parser",
".",
"offset",
"=",
"offset",
"+",
"1",
"return",
"sign",
"*",
"number",
"}",
"number",
"=",
"(",
"number",
"*",
"10",
")",
"+",
"(",
"c1",
"-",
"48",
")",
"}",
"}"
] |
Used for integer numbers only
@param {JavascriptRedisParser} parser
@returns {undefined|number}
|
[
"Used",
"for",
"integer",
"numbers",
"only"
] |
44ef4189b5da92ac301729cd5fc41079017544fd
|
https://github.com/NodeRedis/node-redis-parser/blob/44ef4189b5da92ac301729cd5fc41079017544fd/lib/parser.js#L20-L39
|
18,495
|
NodeRedis/node-redis-parser
|
lib/parser.js
|
parseStringNumbers
|
function parseStringNumbers (parser) {
const length = parser.buffer.length - 1
var offset = parser.offset
var number = 0
var res = ''
if (parser.buffer[offset] === 45) {
res += '-'
offset++
}
while (offset < length) {
var c1 = parser.buffer[offset++]
if (c1 === 13) { // \r\n
parser.offset = offset + 1
if (number !== 0) {
res += number
}
return res
} else if (number > 429496728) {
res += (number * 10) + (c1 - 48)
number = 0
} else if (c1 === 48 && number === 0) {
res += 0
} else {
number = (number * 10) + (c1 - 48)
}
}
}
|
javascript
|
function parseStringNumbers (parser) {
const length = parser.buffer.length - 1
var offset = parser.offset
var number = 0
var res = ''
if (parser.buffer[offset] === 45) {
res += '-'
offset++
}
while (offset < length) {
var c1 = parser.buffer[offset++]
if (c1 === 13) { // \r\n
parser.offset = offset + 1
if (number !== 0) {
res += number
}
return res
} else if (number > 429496728) {
res += (number * 10) + (c1 - 48)
number = 0
} else if (c1 === 48 && number === 0) {
res += 0
} else {
number = (number * 10) + (c1 - 48)
}
}
}
|
[
"function",
"parseStringNumbers",
"(",
"parser",
")",
"{",
"const",
"length",
"=",
"parser",
".",
"buffer",
".",
"length",
"-",
"1",
"var",
"offset",
"=",
"parser",
".",
"offset",
"var",
"number",
"=",
"0",
"var",
"res",
"=",
"''",
"if",
"(",
"parser",
".",
"buffer",
"[",
"offset",
"]",
"===",
"45",
")",
"{",
"res",
"+=",
"'-'",
"offset",
"++",
"}",
"while",
"(",
"offset",
"<",
"length",
")",
"{",
"var",
"c1",
"=",
"parser",
".",
"buffer",
"[",
"offset",
"++",
"]",
"if",
"(",
"c1",
"===",
"13",
")",
"{",
"// \\r\\n",
"parser",
".",
"offset",
"=",
"offset",
"+",
"1",
"if",
"(",
"number",
"!==",
"0",
")",
"{",
"res",
"+=",
"number",
"}",
"return",
"res",
"}",
"else",
"if",
"(",
"number",
">",
"429496728",
")",
"{",
"res",
"+=",
"(",
"number",
"*",
"10",
")",
"+",
"(",
"c1",
"-",
"48",
")",
"number",
"=",
"0",
"}",
"else",
"if",
"(",
"c1",
"===",
"48",
"&&",
"number",
"===",
"0",
")",
"{",
"res",
"+=",
"0",
"}",
"else",
"{",
"number",
"=",
"(",
"number",
"*",
"10",
")",
"+",
"(",
"c1",
"-",
"48",
")",
"}",
"}",
"}"
] |
Used for integer numbers in case of the returnNumbers option
Reading the string as parts of n SMI is more efficient than
using a string directly.
@param {JavascriptRedisParser} parser
@returns {undefined|string}
|
[
"Used",
"for",
"integer",
"numbers",
"in",
"case",
"of",
"the",
"returnNumbers",
"option"
] |
44ef4189b5da92ac301729cd5fc41079017544fd
|
https://github.com/NodeRedis/node-redis-parser/blob/44ef4189b5da92ac301729cd5fc41079017544fd/lib/parser.js#L50-L78
|
18,496
|
NodeRedis/node-redis-parser
|
lib/parser.js
|
parseSimpleString
|
function parseSimpleString (parser) {
const start = parser.offset
const buffer = parser.buffer
const length = buffer.length - 1
var offset = start
while (offset < length) {
if (buffer[offset++] === 13) { // \r\n
parser.offset = offset + 1
if (parser.optionReturnBuffers === true) {
return parser.buffer.slice(start, offset - 1)
}
return parser.buffer.toString('utf8', start, offset - 1)
}
}
}
|
javascript
|
function parseSimpleString (parser) {
const start = parser.offset
const buffer = parser.buffer
const length = buffer.length - 1
var offset = start
while (offset < length) {
if (buffer[offset++] === 13) { // \r\n
parser.offset = offset + 1
if (parser.optionReturnBuffers === true) {
return parser.buffer.slice(start, offset - 1)
}
return parser.buffer.toString('utf8', start, offset - 1)
}
}
}
|
[
"function",
"parseSimpleString",
"(",
"parser",
")",
"{",
"const",
"start",
"=",
"parser",
".",
"offset",
"const",
"buffer",
"=",
"parser",
".",
"buffer",
"const",
"length",
"=",
"buffer",
".",
"length",
"-",
"1",
"var",
"offset",
"=",
"start",
"while",
"(",
"offset",
"<",
"length",
")",
"{",
"if",
"(",
"buffer",
"[",
"offset",
"++",
"]",
"===",
"13",
")",
"{",
"// \\r\\n",
"parser",
".",
"offset",
"=",
"offset",
"+",
"1",
"if",
"(",
"parser",
".",
"optionReturnBuffers",
"===",
"true",
")",
"{",
"return",
"parser",
".",
"buffer",
".",
"slice",
"(",
"start",
",",
"offset",
"-",
"1",
")",
"}",
"return",
"parser",
".",
"buffer",
".",
"toString",
"(",
"'utf8'",
",",
"start",
",",
"offset",
"-",
"1",
")",
"}",
"}",
"}"
] |
Parse a '+' redis simple string response but forward the offsets
onto convertBufferRange to generate a string.
@param {JavascriptRedisParser} parser
@returns {undefined|string|Buffer}
|
[
"Parse",
"a",
"+",
"redis",
"simple",
"string",
"response",
"but",
"forward",
"the",
"offsets",
"onto",
"convertBufferRange",
"to",
"generate",
"a",
"string",
"."
] |
44ef4189b5da92ac301729cd5fc41079017544fd
|
https://github.com/NodeRedis/node-redis-parser/blob/44ef4189b5da92ac301729cd5fc41079017544fd/lib/parser.js#L86-L101
|
18,497
|
NodeRedis/node-redis-parser
|
lib/parser.js
|
parseLength
|
function parseLength (parser) {
const length = parser.buffer.length - 1
var offset = parser.offset
var number = 0
while (offset < length) {
const c1 = parser.buffer[offset++]
if (c1 === 13) {
parser.offset = offset + 1
return number
}
number = (number * 10) + (c1 - 48)
}
}
|
javascript
|
function parseLength (parser) {
const length = parser.buffer.length - 1
var offset = parser.offset
var number = 0
while (offset < length) {
const c1 = parser.buffer[offset++]
if (c1 === 13) {
parser.offset = offset + 1
return number
}
number = (number * 10) + (c1 - 48)
}
}
|
[
"function",
"parseLength",
"(",
"parser",
")",
"{",
"const",
"length",
"=",
"parser",
".",
"buffer",
".",
"length",
"-",
"1",
"var",
"offset",
"=",
"parser",
".",
"offset",
"var",
"number",
"=",
"0",
"while",
"(",
"offset",
"<",
"length",
")",
"{",
"const",
"c1",
"=",
"parser",
".",
"buffer",
"[",
"offset",
"++",
"]",
"if",
"(",
"c1",
"===",
"13",
")",
"{",
"parser",
".",
"offset",
"=",
"offset",
"+",
"1",
"return",
"number",
"}",
"number",
"=",
"(",
"number",
"*",
"10",
")",
"+",
"(",
"c1",
"-",
"48",
")",
"}",
"}"
] |
Returns the read length
@param {JavascriptRedisParser} parser
@returns {undefined|number}
|
[
"Returns",
"the",
"read",
"length"
] |
44ef4189b5da92ac301729cd5fc41079017544fd
|
https://github.com/NodeRedis/node-redis-parser/blob/44ef4189b5da92ac301729cd5fc41079017544fd/lib/parser.js#L108-L121
|
18,498
|
NodeRedis/node-redis-parser
|
lib/parser.js
|
parseError
|
function parseError (parser) {
var string = parseSimpleString(parser)
if (string !== undefined) {
if (parser.optionReturnBuffers === true) {
string = string.toString()
}
return new ReplyError(string)
}
}
|
javascript
|
function parseError (parser) {
var string = parseSimpleString(parser)
if (string !== undefined) {
if (parser.optionReturnBuffers === true) {
string = string.toString()
}
return new ReplyError(string)
}
}
|
[
"function",
"parseError",
"(",
"parser",
")",
"{",
"var",
"string",
"=",
"parseSimpleString",
"(",
"parser",
")",
"if",
"(",
"string",
"!==",
"undefined",
")",
"{",
"if",
"(",
"parser",
".",
"optionReturnBuffers",
"===",
"true",
")",
"{",
"string",
"=",
"string",
".",
"toString",
"(",
")",
"}",
"return",
"new",
"ReplyError",
"(",
"string",
")",
"}",
"}"
] |
Parse a '-' redis error response
@param {JavascriptRedisParser} parser
@returns {ReplyError}
|
[
"Parse",
"a",
"-",
"redis",
"error",
"response"
] |
44ef4189b5da92ac301729cd5fc41079017544fd
|
https://github.com/NodeRedis/node-redis-parser/blob/44ef4189b5da92ac301729cd5fc41079017544fd/lib/parser.js#L173-L181
|
18,499
|
NodeRedis/node-redis-parser
|
lib/parser.js
|
handleError
|
function handleError (parser, type) {
const err = new ParserError(
'Protocol error, got ' + JSON.stringify(String.fromCharCode(type)) + ' as reply type byte',
JSON.stringify(parser.buffer),
parser.offset
)
parser.buffer = null
parser.returnFatalError(err)
}
|
javascript
|
function handleError (parser, type) {
const err = new ParserError(
'Protocol error, got ' + JSON.stringify(String.fromCharCode(type)) + ' as reply type byte',
JSON.stringify(parser.buffer),
parser.offset
)
parser.buffer = null
parser.returnFatalError(err)
}
|
[
"function",
"handleError",
"(",
"parser",
",",
"type",
")",
"{",
"const",
"err",
"=",
"new",
"ParserError",
"(",
"'Protocol error, got '",
"+",
"JSON",
".",
"stringify",
"(",
"String",
".",
"fromCharCode",
"(",
"type",
")",
")",
"+",
"' as reply type byte'",
",",
"JSON",
".",
"stringify",
"(",
"parser",
".",
"buffer",
")",
",",
"parser",
".",
"offset",
")",
"parser",
".",
"buffer",
"=",
"null",
"parser",
".",
"returnFatalError",
"(",
"err",
")",
"}"
] |
Parsing error handler, resets parser buffer
@param {JavascriptRedisParser} parser
@param {number} type
@returns {undefined}
|
[
"Parsing",
"error",
"handler",
"resets",
"parser",
"buffer"
] |
44ef4189b5da92ac301729cd5fc41079017544fd
|
https://github.com/NodeRedis/node-redis-parser/blob/44ef4189b5da92ac301729cd5fc41079017544fd/lib/parser.js#L189-L197
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.