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
13,100
benfred/venn.js
venn.js
distanceFromIntersectArea
function distanceFromIntersectArea(r1, r2, overlap) { // handle complete overlapped circles if (Math.min(r1, r2) * Math.min(r1,r2) * Math.PI <= overlap + SMALL$1) { return Math.abs(r1 - r2); } return bisect(function(distance$$1) { return circleOverlap(r1, r2, distance$$1) - overlap; }, 0, r1 + r2); }
javascript
function distanceFromIntersectArea(r1, r2, overlap) { // handle complete overlapped circles if (Math.min(r1, r2) * Math.min(r1,r2) * Math.PI <= overlap + SMALL$1) { return Math.abs(r1 - r2); } return bisect(function(distance$$1) { return circleOverlap(r1, r2, distance$$1) - overlap; }, 0, r1 + r2); }
[ "function", "distanceFromIntersectArea", "(", "r1", ",", "r2", ",", "overlap", ")", "{", "// handle complete overlapped circles", "if", "(", "Math", ".", "min", "(", "r1", ",", "r2", ")", "*", "Math", ".", "min", "(", "r1", ",", "r2", ")", "*", "Math", ".", "PI", "<=", "overlap", "+", "SMALL$1", ")", "{", "return", "Math", ".", "abs", "(", "r1", "-", "r2", ")", ";", "}", "return", "bisect", "(", "function", "(", "distance$$1", ")", "{", "return", "circleOverlap", "(", "r1", ",", "r2", ",", "distance$$1", ")", "-", "overlap", ";", "}", ",", "0", ",", "r1", "+", "r2", ")", ";", "}" ]
Returns the distance necessary for two circles of radius r1 + r2 to have the overlap area 'overlap'
[ "Returns", "the", "distance", "necessary", "for", "two", "circles", "of", "radius", "r1", "+", "r2", "to", "have", "the", "overlap", "area", "overlap" ]
5ff0ef3ff450803a50c69493cd2bb6ce8b04f9fb
https://github.com/benfred/venn.js/blob/5ff0ef3ff450803a50c69493cd2bb6ce8b04f9fb/venn.js#L623-L632
13,101
highsource/jsonix
scripts/src/main/javascript/org/hisrc/jsonix/Jsonix/Model/ClassInfo.js
function(value, context, scope) { return this.isInstance(value, context, scope) || (Jsonix.Util.Type.isObject(value) && !Jsonix.Util.Type.isArray(value)); }
javascript
function(value, context, scope) { return this.isInstance(value, context, scope) || (Jsonix.Util.Type.isObject(value) && !Jsonix.Util.Type.isArray(value)); }
[ "function", "(", "value", ",", "context", ",", "scope", ")", "{", "return", "this", ".", "isInstance", "(", "value", ",", "context", ",", "scope", ")", "||", "(", "Jsonix", ".", "Util", ".", "Type", ".", "isObject", "(", "value", ")", "&&", "!", "Jsonix", ".", "Util", ".", "Type", ".", "isArray", "(", "value", ")", ")", ";", "}" ]
Checks if the value is marshallable
[ "Checks", "if", "the", "value", "is", "marshallable" ]
cb622447c59435558dd3142f3c460fbb6a274a3a
https://github.com/highsource/jsonix/blob/cb622447c59435558dd3142f3c460fbb6a274a3a/scripts/src/main/javascript/org/hisrc/jsonix/Jsonix/Model/ClassInfo.js#L252-L254
13,102
ded/script.js
vendor/mootools.js
function(value){ value = Function.from(value)(); value = (typeof value == 'string') ? value.split(' ') : Array.from(value); return value.map(function(val){ val = String(val); var found = false; Object.each(Fx.CSS.Parsers, function(parser, key){ if (found) return; var parsed = parser.parse(val); if (parsed || parsed === 0) found = {value: parsed, parser: parser}; }); found = found || {value: val, parser: Fx.CSS.Parsers.String}; return found; }); }
javascript
function(value){ value = Function.from(value)(); value = (typeof value == 'string') ? value.split(' ') : Array.from(value); return value.map(function(val){ val = String(val); var found = false; Object.each(Fx.CSS.Parsers, function(parser, key){ if (found) return; var parsed = parser.parse(val); if (parsed || parsed === 0) found = {value: parsed, parser: parser}; }); found = found || {value: val, parser: Fx.CSS.Parsers.String}; return found; }); }
[ "function", "(", "value", ")", "{", "value", "=", "Function", ".", "from", "(", "value", ")", "(", ")", ";", "value", "=", "(", "typeof", "value", "==", "'string'", ")", "?", "value", ".", "split", "(", "' '", ")", ":", "Array", ".", "from", "(", "value", ")", ";", "return", "value", ".", "map", "(", "function", "(", "val", ")", "{", "val", "=", "String", "(", "val", ")", ";", "var", "found", "=", "false", ";", "Object", ".", "each", "(", "Fx", ".", "CSS", ".", "Parsers", ",", "function", "(", "parser", ",", "key", ")", "{", "if", "(", "found", ")", "return", ";", "var", "parsed", "=", "parser", ".", "parse", "(", "val", ")", ";", "if", "(", "parsed", "||", "parsed", "===", "0", ")", "found", "=", "{", "value", ":", "parsed", ",", "parser", ":", "parser", "}", ";", "}", ")", ";", "found", "=", "found", "||", "{", "value", ":", "val", ",", "parser", ":", "Fx", ".", "CSS", ".", "Parsers", ".", "String", "}", ";", "return", "found", ";", "}", ")", ";", "}" ]
parses a value into an array
[ "parses", "a", "value", "into", "an", "array" ]
95ca7a60c75e266a492262e29dacb3ec2ea15a95
https://github.com/ded/script.js/blob/95ca7a60c75e266a492262e29dacb3ec2ea15a95/vendor/mootools.js#L4616-L4630
13,103
ded/script.js
vendor/mootools.js
function(from, to, delta){ var computed = []; (Math.min(from.length, to.length)).times(function(i){ computed.push({value: from[i].parser.compute(from[i].value, to[i].value, delta), parser: from[i].parser}); }); computed.$family = Function.from('fx:css:value'); return computed; }
javascript
function(from, to, delta){ var computed = []; (Math.min(from.length, to.length)).times(function(i){ computed.push({value: from[i].parser.compute(from[i].value, to[i].value, delta), parser: from[i].parser}); }); computed.$family = Function.from('fx:css:value'); return computed; }
[ "function", "(", "from", ",", "to", ",", "delta", ")", "{", "var", "computed", "=", "[", "]", ";", "(", "Math", ".", "min", "(", "from", ".", "length", ",", "to", ".", "length", ")", ")", ".", "times", "(", "function", "(", "i", ")", "{", "computed", ".", "push", "(", "{", "value", ":", "from", "[", "i", "]", ".", "parser", ".", "compute", "(", "from", "[", "i", "]", ".", "value", ",", "to", "[", "i", "]", ".", "value", ",", "delta", ")", ",", "parser", ":", "from", "[", "i", "]", ".", "parser", "}", ")", ";", "}", ")", ";", "computed", ".", "$family", "=", "Function", ".", "from", "(", "'fx:css:value'", ")", ";", "return", "computed", ";", "}" ]
computes by a from and to prepared objects, using their parsers.
[ "computes", "by", "a", "from", "and", "to", "prepared", "objects", "using", "their", "parsers", "." ]
95ca7a60c75e266a492262e29dacb3ec2ea15a95
https://github.com/ded/script.js/blob/95ca7a60c75e266a492262e29dacb3ec2ea15a95/vendor/mootools.js#L4634-L4641
13,104
ded/script.js
vendor/mootools.js
function(value, unit){ if (typeOf(value) != 'fx:css:value') value = this.parse(value); var returned = []; value.each(function(bit){ returned = returned.concat(bit.parser.serve(bit.value, unit)); }); return returned; }
javascript
function(value, unit){ if (typeOf(value) != 'fx:css:value') value = this.parse(value); var returned = []; value.each(function(bit){ returned = returned.concat(bit.parser.serve(bit.value, unit)); }); return returned; }
[ "function", "(", "value", ",", "unit", ")", "{", "if", "(", "typeOf", "(", "value", ")", "!=", "'fx:css:value'", ")", "value", "=", "this", ".", "parse", "(", "value", ")", ";", "var", "returned", "=", "[", "]", ";", "value", ".", "each", "(", "function", "(", "bit", ")", "{", "returned", "=", "returned", ".", "concat", "(", "bit", ".", "parser", ".", "serve", "(", "bit", ".", "value", ",", "unit", ")", ")", ";", "}", ")", ";", "return", "returned", ";", "}" ]
serves the value as settable
[ "serves", "the", "value", "as", "settable" ]
95ca7a60c75e266a492262e29dacb3ec2ea15a95
https://github.com/ded/script.js/blob/95ca7a60c75e266a492262e29dacb3ec2ea15a95/vendor/mootools.js#L4645-L4652
13,105
ded/script.js
vendor/mootools.js
function(element, property, value, unit){ element.setStyle(property, this.serve(value, unit)); }
javascript
function(element, property, value, unit){ element.setStyle(property, this.serve(value, unit)); }
[ "function", "(", "element", ",", "property", ",", "value", ",", "unit", ")", "{", "element", ".", "setStyle", "(", "property", ",", "this", ".", "serve", "(", "value", ",", "unit", ")", ")", ";", "}" ]
renders the change to an element
[ "renders", "the", "change", "to", "an", "element" ]
95ca7a60c75e266a492262e29dacb3ec2ea15a95
https://github.com/ded/script.js/blob/95ca7a60c75e266a492262e29dacb3ec2ea15a95/vendor/mootools.js#L4656-L4658
13,106
ded/script.js
vendor/lab2.js
isScriptLoaded
function isScriptLoaded(elem,scriptentry) { if ((elem[sREADYSTATE] && elem[sREADYSTATE]!==sCOMPLETE && elem[sREADYSTATE]!=="loaded") || scriptentry[sDONE]) { return bFALSE; } elem[sONLOAD] = elem[sONREADYSTATECHANGE] = nNULL; // prevent memory leak return bTRUE; }
javascript
function isScriptLoaded(elem,scriptentry) { if ((elem[sREADYSTATE] && elem[sREADYSTATE]!==sCOMPLETE && elem[sREADYSTATE]!=="loaded") || scriptentry[sDONE]) { return bFALSE; } elem[sONLOAD] = elem[sONREADYSTATECHANGE] = nNULL; // prevent memory leak return bTRUE; }
[ "function", "isScriptLoaded", "(", "elem", ",", "scriptentry", ")", "{", "if", "(", "(", "elem", "[", "sREADYSTATE", "]", "&&", "elem", "[", "sREADYSTATE", "]", "!==", "sCOMPLETE", "&&", "elem", "[", "sREADYSTATE", "]", "!==", "\"loaded\"", ")", "||", "scriptentry", "[", "sDONE", "]", ")", "{", "return", "bFALSE", ";", "}", "elem", "[", "sONLOAD", "]", "=", "elem", "[", "sONREADYSTATECHANGE", "]", "=", "nNULL", ";", "// prevent memory leak", "return", "bTRUE", ";", "}" ]
if all flags are turned off, preload is moot so disable it
[ "if", "all", "flags", "are", "turned", "off", "preload", "is", "moot", "so", "disable", "it" ]
95ca7a60c75e266a492262e29dacb3ec2ea15a95
https://github.com/ded/script.js/blob/95ca7a60c75e266a492262e29dacb3ec2ea15a95/vendor/lab2.js#L113-L117
13,107
bigspotteddog/ScrollToFixed
jquery-scrolltofixed.js
resetScroll
function resetScroll() { // Set the element to it original positioning. target.trigger('preUnfixed.ScrollToFixed'); setUnfixed(); target.trigger('unfixed.ScrollToFixed'); // Reset the last offset used to determine if the page has moved // horizontally. lastOffsetLeft = -1; // Capture the offset top of the target element. offsetTop = target.offset().top; // Capture the offset left of the target element. offsetLeft = target.offset().left; // If the offsets option is on, alter the left offset. if (base.options.offsets) { offsetLeft += (target.offset().left - target.position().left); } if (originalOffsetLeft == -1) { originalOffsetLeft = offsetLeft; } position = target.css('position'); // Set that this has been called at least once. isReset = true; if (base.options.bottom != -1) { target.trigger('preFixed.ScrollToFixed'); setFixed(); target.trigger('fixed.ScrollToFixed'); } }
javascript
function resetScroll() { // Set the element to it original positioning. target.trigger('preUnfixed.ScrollToFixed'); setUnfixed(); target.trigger('unfixed.ScrollToFixed'); // Reset the last offset used to determine if the page has moved // horizontally. lastOffsetLeft = -1; // Capture the offset top of the target element. offsetTop = target.offset().top; // Capture the offset left of the target element. offsetLeft = target.offset().left; // If the offsets option is on, alter the left offset. if (base.options.offsets) { offsetLeft += (target.offset().left - target.position().left); } if (originalOffsetLeft == -1) { originalOffsetLeft = offsetLeft; } position = target.css('position'); // Set that this has been called at least once. isReset = true; if (base.options.bottom != -1) { target.trigger('preFixed.ScrollToFixed'); setFixed(); target.trigger('fixed.ScrollToFixed'); } }
[ "function", "resetScroll", "(", ")", "{", "// Set the element to it original positioning.", "target", ".", "trigger", "(", "'preUnfixed.ScrollToFixed'", ")", ";", "setUnfixed", "(", ")", ";", "target", ".", "trigger", "(", "'unfixed.ScrollToFixed'", ")", ";", "// Reset the last offset used to determine if the page has moved", "// horizontally.", "lastOffsetLeft", "=", "-", "1", ";", "// Capture the offset top of the target element.", "offsetTop", "=", "target", ".", "offset", "(", ")", ".", "top", ";", "// Capture the offset left of the target element.", "offsetLeft", "=", "target", ".", "offset", "(", ")", ".", "left", ";", "// If the offsets option is on, alter the left offset.", "if", "(", "base", ".", "options", ".", "offsets", ")", "{", "offsetLeft", "+=", "(", "target", ".", "offset", "(", ")", ".", "left", "-", "target", ".", "position", "(", ")", ".", "left", ")", ";", "}", "if", "(", "originalOffsetLeft", "==", "-", "1", ")", "{", "originalOffsetLeft", "=", "offsetLeft", ";", "}", "position", "=", "target", ".", "css", "(", "'position'", ")", ";", "// Set that this has been called at least once.", "isReset", "=", "true", ";", "if", "(", "base", ".", "options", ".", "bottom", "!=", "-", "1", ")", "{", "target", ".", "trigger", "(", "'preFixed.ScrollToFixed'", ")", ";", "setFixed", "(", ")", ";", "target", ".", "trigger", "(", "'fixed.ScrollToFixed'", ")", ";", "}", "}" ]
Capture the original offsets for the target element. This needs to be called whenever the page size changes or when the page is first scrolled. For some reason, calling this before the page is first scrolled causes the element to become fixed too late.
[ "Capture", "the", "original", "offsets", "for", "the", "target", "element", ".", "This", "needs", "to", "be", "called", "whenever", "the", "page", "size", "changes", "or", "when", "the", "page", "is", "first", "scrolled", ".", "For", "some", "reason", "calling", "this", "before", "the", "page", "is", "first", "scrolled", "causes", "the", "element", "to", "become", "fixed", "too", "late", "." ]
a2f9dc0d20cfc8fc2468f5b2937fbc11937e2a98
https://github.com/bigspotteddog/ScrollToFixed/blob/a2f9dc0d20cfc8fc2468f5b2937fbc11937e2a98/jquery-scrolltofixed.js#L65-L100
13,108
bigspotteddog/ScrollToFixed
jquery-scrolltofixed.js
setFixed
function setFixed() { // Only fix the target element and the spacer if we need to. if (!isFixed()) { //get REAL dimensions (decimal fix) //Ref. http://stackoverflow.com/questions/3603065/how-to-make-jquery-to-not-round-value-returned-by-width var dimensions = target[0].getBoundingClientRect(); // Set the spacer to fill the height and width of the target // element, then display it. spacer.css({ 'display' : target.css('display'), 'width' : dimensions.width, 'height' : dimensions.height, 'float' : target.css('float') }); // Set the target element to fixed and set its width so it does // not fill the rest of the page horizontally. Also, set its top // to the margin top specified in the options. cssOptions={ 'z-index' : base.options.zIndex, 'position' : 'fixed', 'top' : base.options.bottom == -1?getMarginTop():'', 'bottom' : base.options.bottom == -1?'':base.options.bottom, 'margin-left' : '0px' } if (!base.options.dontSetWidth){ cssOptions['width']=target.css('width'); }; target.css(cssOptions); target.addClass(base.options.baseClassName); if (base.options.className) { target.addClass(base.options.className); } position = 'fixed'; } }
javascript
function setFixed() { // Only fix the target element and the spacer if we need to. if (!isFixed()) { //get REAL dimensions (decimal fix) //Ref. http://stackoverflow.com/questions/3603065/how-to-make-jquery-to-not-round-value-returned-by-width var dimensions = target[0].getBoundingClientRect(); // Set the spacer to fill the height and width of the target // element, then display it. spacer.css({ 'display' : target.css('display'), 'width' : dimensions.width, 'height' : dimensions.height, 'float' : target.css('float') }); // Set the target element to fixed and set its width so it does // not fill the rest of the page horizontally. Also, set its top // to the margin top specified in the options. cssOptions={ 'z-index' : base.options.zIndex, 'position' : 'fixed', 'top' : base.options.bottom == -1?getMarginTop():'', 'bottom' : base.options.bottom == -1?'':base.options.bottom, 'margin-left' : '0px' } if (!base.options.dontSetWidth){ cssOptions['width']=target.css('width'); }; target.css(cssOptions); target.addClass(base.options.baseClassName); if (base.options.className) { target.addClass(base.options.className); } position = 'fixed'; } }
[ "function", "setFixed", "(", ")", "{", "// Only fix the target element and the spacer if we need to.", "if", "(", "!", "isFixed", "(", ")", ")", "{", "//get REAL dimensions (decimal fix)", "//Ref. http://stackoverflow.com/questions/3603065/how-to-make-jquery-to-not-round-value-returned-by-width", "var", "dimensions", "=", "target", "[", "0", "]", ".", "getBoundingClientRect", "(", ")", ";", "// Set the spacer to fill the height and width of the target", "// element, then display it.", "spacer", ".", "css", "(", "{", "'display'", ":", "target", ".", "css", "(", "'display'", ")", ",", "'width'", ":", "dimensions", ".", "width", ",", "'height'", ":", "dimensions", ".", "height", ",", "'float'", ":", "target", ".", "css", "(", "'float'", ")", "}", ")", ";", "// Set the target element to fixed and set its width so it does", "// not fill the rest of the page horizontally. Also, set its top", "// to the margin top specified in the options.", "cssOptions", "=", "{", "'z-index'", ":", "base", ".", "options", ".", "zIndex", ",", "'position'", ":", "'fixed'", ",", "'top'", ":", "base", ".", "options", ".", "bottom", "==", "-", "1", "?", "getMarginTop", "(", ")", ":", "''", ",", "'bottom'", ":", "base", ".", "options", ".", "bottom", "==", "-", "1", "?", "''", ":", "base", ".", "options", ".", "bottom", ",", "'margin-left'", ":", "'0px'", "}", "if", "(", "!", "base", ".", "options", ".", "dontSetWidth", ")", "{", "cssOptions", "[", "'width'", "]", "=", "target", ".", "css", "(", "'width'", ")", ";", "}", ";", "target", ".", "css", "(", "cssOptions", ")", ";", "target", ".", "addClass", "(", "base", ".", "options", ".", "baseClassName", ")", ";", "if", "(", "base", ".", "options", ".", "className", ")", "{", "target", ".", "addClass", "(", "base", ".", "options", ".", "className", ")", ";", "}", "position", "=", "'fixed'", ";", "}", "}" ]
Sets the target element to fixed. Also, sets the spacer to fill the void left by the target element.
[ "Sets", "the", "target", "element", "to", "fixed", ".", "Also", "sets", "the", "spacer", "to", "fill", "the", "void", "left", "by", "the", "target", "element", "." ]
a2f9dc0d20cfc8fc2468f5b2937fbc11937e2a98
https://github.com/bigspotteddog/ScrollToFixed/blob/a2f9dc0d20cfc8fc2468f5b2937fbc11937e2a98/jquery-scrolltofixed.js#L128-L167
13,109
bigspotteddog/ScrollToFixed
jquery-scrolltofixed.js
setUnfixed
function setUnfixed() { // Only unfix the target element and the spacer if we need to. if (!isUnfixed()) { lastOffsetLeft = -1; // Hide the spacer now that the target element will fill the // space. spacer.css('display', 'none'); // Remove the style attributes that were added to the target. // This will reverse the target back to the its original style. target.css({ 'z-index' : originalZIndex, 'width' : '', 'position' : originalPosition, 'left' : '', 'top' : originalOffsetTop, 'margin-left' : '' }); target.removeClass('scroll-to-fixed-fixed'); if (base.options.className) { target.removeClass(base.options.className); } position = null; } }
javascript
function setUnfixed() { // Only unfix the target element and the spacer if we need to. if (!isUnfixed()) { lastOffsetLeft = -1; // Hide the spacer now that the target element will fill the // space. spacer.css('display', 'none'); // Remove the style attributes that were added to the target. // This will reverse the target back to the its original style. target.css({ 'z-index' : originalZIndex, 'width' : '', 'position' : originalPosition, 'left' : '', 'top' : originalOffsetTop, 'margin-left' : '' }); target.removeClass('scroll-to-fixed-fixed'); if (base.options.className) { target.removeClass(base.options.className); } position = null; } }
[ "function", "setUnfixed", "(", ")", "{", "// Only unfix the target element and the spacer if we need to.", "if", "(", "!", "isUnfixed", "(", ")", ")", "{", "lastOffsetLeft", "=", "-", "1", ";", "// Hide the spacer now that the target element will fill the", "// space.", "spacer", ".", "css", "(", "'display'", ",", "'none'", ")", ";", "// Remove the style attributes that were added to the target.", "// This will reverse the target back to the its original style.", "target", ".", "css", "(", "{", "'z-index'", ":", "originalZIndex", ",", "'width'", ":", "''", ",", "'position'", ":", "originalPosition", ",", "'left'", ":", "''", ",", "'top'", ":", "originalOffsetTop", ",", "'margin-left'", ":", "''", "}", ")", ";", "target", ".", "removeClass", "(", "'scroll-to-fixed-fixed'", ")", ";", "if", "(", "base", ".", "options", ".", "className", ")", "{", "target", ".", "removeClass", "(", "base", ".", "options", ".", "className", ")", ";", "}", "position", "=", "null", ";", "}", "}" ]
Sets the target element back to unfixed. Also, hides the spacer.
[ "Sets", "the", "target", "element", "back", "to", "unfixed", ".", "Also", "hides", "the", "spacer", "." ]
a2f9dc0d20cfc8fc2468f5b2937fbc11937e2a98
https://github.com/bigspotteddog/ScrollToFixed/blob/a2f9dc0d20cfc8fc2468f5b2937fbc11937e2a98/jquery-scrolltofixed.js#L194-L222
13,110
bigspotteddog/ScrollToFixed
jquery-scrolltofixed.js
setLeft
function setLeft(x) { // Only if the scroll is not what it was last time we did this. if (x != lastOffsetLeft) { // Move the target element horizontally relative to its original // horizontal position. target.css('left', offsetLeft - x); // Hold the last horizontal position set. lastOffsetLeft = x; } }
javascript
function setLeft(x) { // Only if the scroll is not what it was last time we did this. if (x != lastOffsetLeft) { // Move the target element horizontally relative to its original // horizontal position. target.css('left', offsetLeft - x); // Hold the last horizontal position set. lastOffsetLeft = x; } }
[ "function", "setLeft", "(", "x", ")", "{", "// Only if the scroll is not what it was last time we did this.", "if", "(", "x", "!=", "lastOffsetLeft", ")", "{", "// Move the target element horizontally relative to its original", "// horizontal position.", "target", ".", "css", "(", "'left'", ",", "offsetLeft", "-", "x", ")", ";", "// Hold the last horizontal position set.", "lastOffsetLeft", "=", "x", ";", "}", "}" ]
Moves the target element left or right relative to the horizontal scroll position.
[ "Moves", "the", "target", "element", "left", "or", "right", "relative", "to", "the", "horizontal", "scroll", "position", "." ]
a2f9dc0d20cfc8fc2468f5b2937fbc11937e2a98
https://github.com/bigspotteddog/ScrollToFixed/blob/a2f9dc0d20cfc8fc2468f5b2937fbc11937e2a98/jquery-scrolltofixed.js#L226-L236
13,111
h2non/jshashes
hashes.js
rstr2binb
function rstr2binb(input) { var i, l = input.length * 8, output = Array(input.length >> 2), lo = output.length; for (i = 0; i < lo; i += 1) { output[i] = 0; } for (i = 0; i < l; i += 8) { output[i >> 5] |= (input.charCodeAt(i / 8) & 0xFF) << (24 - i % 32); } return output; }
javascript
function rstr2binb(input) { var i, l = input.length * 8, output = Array(input.length >> 2), lo = output.length; for (i = 0; i < lo; i += 1) { output[i] = 0; } for (i = 0; i < l; i += 8) { output[i >> 5] |= (input.charCodeAt(i / 8) & 0xFF) << (24 - i % 32); } return output; }
[ "function", "rstr2binb", "(", "input", ")", "{", "var", "i", ",", "l", "=", "input", ".", "length", "*", "8", ",", "output", "=", "Array", "(", "input", ".", "length", ">>", "2", ")", ",", "lo", "=", "output", ".", "length", ";", "for", "(", "i", "=", "0", ";", "i", "<", "lo", ";", "i", "+=", "1", ")", "{", "output", "[", "i", "]", "=", "0", ";", "}", "for", "(", "i", "=", "0", ";", "i", "<", "l", ";", "i", "+=", "8", ")", "{", "output", "[", "i", ">>", "5", "]", "|=", "(", "input", ".", "charCodeAt", "(", "i", "/", "8", ")", "&", "0xFF", ")", "<<", "(", "24", "-", "i", "%", "32", ")", ";", "}", "return", "output", ";", "}" ]
Convert a raw string to an array of big-endian words Characters >255 have their high-byte silently ignored.
[ "Convert", "a", "raw", "string", "to", "an", "array", "of", "big", "-", "endian", "words", "Characters", ">", "255", "have", "their", "high", "-", "byte", "silently", "ignored", "." ]
88625b6c841ca3c90f8b9fefb0fedb78992017ad
https://github.com/h2non/jshashes/blob/88625b6c841ca3c90f8b9fefb0fedb78992017ad/hashes.js#L189-L200
13,112
h2non/jshashes
hashes.js
function(str) { var crc = 0, x = 0, y = 0, table, i, iTop; str = utf8Encode(str); table = [ '00000000 77073096 EE0E612C 990951BA 076DC419 706AF48F E963A535 9E6495A3 0EDB8832 ', '79DCB8A4 E0D5E91E 97D2D988 09B64C2B 7EB17CBD E7B82D07 90BF1D91 1DB71064 6AB020F2 F3B97148 ', '84BE41DE 1ADAD47D 6DDDE4EB F4D4B551 83D385C7 136C9856 646BA8C0 FD62F97A 8A65C9EC 14015C4F ', '63066CD9 FA0F3D63 8D080DF5 3B6E20C8 4C69105E D56041E4 A2677172 3C03E4D1 4B04D447 D20D85FD ', 'A50AB56B 35B5A8FA 42B2986C DBBBC9D6 ACBCF940 32D86CE3 45DF5C75 DCD60DCF ABD13D59 26D930AC ', '51DE003A C8D75180 BFD06116 21B4F4B5 56B3C423 CFBA9599 B8BDA50F 2802B89E 5F058808 C60CD9B2 ', 'B10BE924 2F6F7C87 58684C11 C1611DAB B6662D3D 76DC4190 01DB7106 98D220BC EFD5102A 71B18589 ', '06B6B51F 9FBFE4A5 E8B8D433 7807C9A2 0F00F934 9609A88E E10E9818 7F6A0DBB 086D3D2D 91646C97 ', 'E6635C01 6B6B51F4 1C6C6162 856530D8 F262004E 6C0695ED 1B01A57B 8208F4C1 F50FC457 65B0D9C6 ', '12B7E950 8BBEB8EA FCB9887C 62DD1DDF 15DA2D49 8CD37CF3 FBD44C65 4DB26158 3AB551CE A3BC0074 ', 'D4BB30E2 4ADFA541 3DD895D7 A4D1C46D D3D6F4FB 4369E96A 346ED9FC AD678846 DA60B8D0 44042D73 ', '33031DE5 AA0A4C5F DD0D7CC9 5005713C 270241AA BE0B1010 C90C2086 5768B525 206F85B3 B966D409 ', 'CE61E49F 5EDEF90E 29D9C998 B0D09822 C7D7A8B4 59B33D17 2EB40D81 B7BD5C3B C0BA6CAD EDB88320 ', '9ABFB3B6 03B6E20C 74B1D29A EAD54739 9DD277AF 04DB2615 73DC1683 E3630B12 94643B84 0D6D6A3E ', '7A6A5AA8 E40ECF0B 9309FF9D 0A00AE27 7D079EB1 F00F9344 8708A3D2 1E01F268 6906C2FE F762575D ', '806567CB 196C3671 6E6B06E7 FED41B76 89D32BE0 10DA7A5A 67DD4ACC F9B9DF6F 8EBEEFF9 17B7BE43 ', '60B08ED5 D6D6A3E8 A1D1937E 38D8C2C4 4FDFF252 D1BB67F1 A6BC5767 3FB506DD 48B2364B D80D2BDA ', 'AF0A1B4C 36034AF6 41047A60 DF60EFC3 A867DF55 316E8EEF 4669BE79 CB61B38C BC66831A 256FD2A0 ', '5268E236 CC0C7795 BB0B4703 220216B9 5505262F C5BA3BBE B2BD0B28 2BB45A92 5CB36A04 C2D7FFA7 ', 'B5D0CF31 2CD99E8B 5BDEAE1D 9B64C2B0 EC63F226 756AA39C 026D930A 9C0906A9 EB0E363F 72076785 ', '05005713 95BF4A82 E2B87A14 7BB12BAE 0CB61B38 92D28E9B E5D5BE0D 7CDCEFB7 0BDBDF21 86D3D2D4 ', 'F1D4E242 68DDB3F8 1FDA836E 81BE16CD F6B9265B 6FB077E1 18B74777 88085AE6 FF0F6A70 66063BCA ', '11010B5C 8F659EFF F862AE69 616BFFD3 166CCF45 A00AE278 D70DD2EE 4E048354 3903B3C2 A7672661 ', 'D06016F7 4969474D 3E6E77DB AED16A4A D9D65ADC 40DF0B66 37D83BF0 A9BCAE53 DEBB9EC5 47B2CF7F ', '30B5FFE9 BDBDF21C CABAC28A 53B39330 24B4A3A6 BAD03605 CDD70693 54DE5729 23D967BF B3667A2E ', 'C4614AB8 5D681B02 2A6F2B94 B40BBE37 C30C8EA1 5A05DF1B 2D02EF8D' ].join(''); crc = crc ^ (-1); for (i = 0, iTop = str.length; i < iTop; i += 1) { y = (crc ^ str.charCodeAt(i)) & 0xFF; x = '0x' + table.substr(y * 9, 8); crc = (crc >>> 8) ^ x; } // always return a positive number (that's what >>> 0 does) return (crc ^ (-1)) >>> 0; }
javascript
function(str) { var crc = 0, x = 0, y = 0, table, i, iTop; str = utf8Encode(str); table = [ '00000000 77073096 EE0E612C 990951BA 076DC419 706AF48F E963A535 9E6495A3 0EDB8832 ', '79DCB8A4 E0D5E91E 97D2D988 09B64C2B 7EB17CBD E7B82D07 90BF1D91 1DB71064 6AB020F2 F3B97148 ', '84BE41DE 1ADAD47D 6DDDE4EB F4D4B551 83D385C7 136C9856 646BA8C0 FD62F97A 8A65C9EC 14015C4F ', '63066CD9 FA0F3D63 8D080DF5 3B6E20C8 4C69105E D56041E4 A2677172 3C03E4D1 4B04D447 D20D85FD ', 'A50AB56B 35B5A8FA 42B2986C DBBBC9D6 ACBCF940 32D86CE3 45DF5C75 DCD60DCF ABD13D59 26D930AC ', '51DE003A C8D75180 BFD06116 21B4F4B5 56B3C423 CFBA9599 B8BDA50F 2802B89E 5F058808 C60CD9B2 ', 'B10BE924 2F6F7C87 58684C11 C1611DAB B6662D3D 76DC4190 01DB7106 98D220BC EFD5102A 71B18589 ', '06B6B51F 9FBFE4A5 E8B8D433 7807C9A2 0F00F934 9609A88E E10E9818 7F6A0DBB 086D3D2D 91646C97 ', 'E6635C01 6B6B51F4 1C6C6162 856530D8 F262004E 6C0695ED 1B01A57B 8208F4C1 F50FC457 65B0D9C6 ', '12B7E950 8BBEB8EA FCB9887C 62DD1DDF 15DA2D49 8CD37CF3 FBD44C65 4DB26158 3AB551CE A3BC0074 ', 'D4BB30E2 4ADFA541 3DD895D7 A4D1C46D D3D6F4FB 4369E96A 346ED9FC AD678846 DA60B8D0 44042D73 ', '33031DE5 AA0A4C5F DD0D7CC9 5005713C 270241AA BE0B1010 C90C2086 5768B525 206F85B3 B966D409 ', 'CE61E49F 5EDEF90E 29D9C998 B0D09822 C7D7A8B4 59B33D17 2EB40D81 B7BD5C3B C0BA6CAD EDB88320 ', '9ABFB3B6 03B6E20C 74B1D29A EAD54739 9DD277AF 04DB2615 73DC1683 E3630B12 94643B84 0D6D6A3E ', '7A6A5AA8 E40ECF0B 9309FF9D 0A00AE27 7D079EB1 F00F9344 8708A3D2 1E01F268 6906C2FE F762575D ', '806567CB 196C3671 6E6B06E7 FED41B76 89D32BE0 10DA7A5A 67DD4ACC F9B9DF6F 8EBEEFF9 17B7BE43 ', '60B08ED5 D6D6A3E8 A1D1937E 38D8C2C4 4FDFF252 D1BB67F1 A6BC5767 3FB506DD 48B2364B D80D2BDA ', 'AF0A1B4C 36034AF6 41047A60 DF60EFC3 A867DF55 316E8EEF 4669BE79 CB61B38C BC66831A 256FD2A0 ', '5268E236 CC0C7795 BB0B4703 220216B9 5505262F C5BA3BBE B2BD0B28 2BB45A92 5CB36A04 C2D7FFA7 ', 'B5D0CF31 2CD99E8B 5BDEAE1D 9B64C2B0 EC63F226 756AA39C 026D930A 9C0906A9 EB0E363F 72076785 ', '05005713 95BF4A82 E2B87A14 7BB12BAE 0CB61B38 92D28E9B E5D5BE0D 7CDCEFB7 0BDBDF21 86D3D2D4 ', 'F1D4E242 68DDB3F8 1FDA836E 81BE16CD F6B9265B 6FB077E1 18B74777 88085AE6 FF0F6A70 66063BCA ', '11010B5C 8F659EFF F862AE69 616BFFD3 166CCF45 A00AE278 D70DD2EE 4E048354 3903B3C2 A7672661 ', 'D06016F7 4969474D 3E6E77DB AED16A4A D9D65ADC 40DF0B66 37D83BF0 A9BCAE53 DEBB9EC5 47B2CF7F ', '30B5FFE9 BDBDF21C CABAC28A 53B39330 24B4A3A6 BAD03605 CDD70693 54DE5729 23D967BF B3667A2E ', 'C4614AB8 5D681B02 2A6F2B94 B40BBE37 C30C8EA1 5A05DF1B 2D02EF8D' ].join(''); crc = crc ^ (-1); for (i = 0, iTop = str.length; i < iTop; i += 1) { y = (crc ^ str.charCodeAt(i)) & 0xFF; x = '0x' + table.substr(y * 9, 8); crc = (crc >>> 8) ^ x; } // always return a positive number (that's what >>> 0 does) return (crc ^ (-1)) >>> 0; }
[ "function", "(", "str", ")", "{", "var", "crc", "=", "0", ",", "x", "=", "0", ",", "y", "=", "0", ",", "table", ",", "i", ",", "iTop", ";", "str", "=", "utf8Encode", "(", "str", ")", ";", "table", "=", "[", "'00000000 77073096 EE0E612C 990951BA 076DC419 706AF48F E963A535 9E6495A3 0EDB8832 '", ",", "'79DCB8A4 E0D5E91E 97D2D988 09B64C2B 7EB17CBD E7B82D07 90BF1D91 1DB71064 6AB020F2 F3B97148 '", ",", "'84BE41DE 1ADAD47D 6DDDE4EB F4D4B551 83D385C7 136C9856 646BA8C0 FD62F97A 8A65C9EC 14015C4F '", ",", "'63066CD9 FA0F3D63 8D080DF5 3B6E20C8 4C69105E D56041E4 A2677172 3C03E4D1 4B04D447 D20D85FD '", ",", "'A50AB56B 35B5A8FA 42B2986C DBBBC9D6 ACBCF940 32D86CE3 45DF5C75 DCD60DCF ABD13D59 26D930AC '", ",", "'51DE003A C8D75180 BFD06116 21B4F4B5 56B3C423 CFBA9599 B8BDA50F 2802B89E 5F058808 C60CD9B2 '", ",", "'B10BE924 2F6F7C87 58684C11 C1611DAB B6662D3D 76DC4190 01DB7106 98D220BC EFD5102A 71B18589 '", ",", "'06B6B51F 9FBFE4A5 E8B8D433 7807C9A2 0F00F934 9609A88E E10E9818 7F6A0DBB 086D3D2D 91646C97 '", ",", "'E6635C01 6B6B51F4 1C6C6162 856530D8 F262004E 6C0695ED 1B01A57B 8208F4C1 F50FC457 65B0D9C6 '", ",", "'12B7E950 8BBEB8EA FCB9887C 62DD1DDF 15DA2D49 8CD37CF3 FBD44C65 4DB26158 3AB551CE A3BC0074 '", ",", "'D4BB30E2 4ADFA541 3DD895D7 A4D1C46D D3D6F4FB 4369E96A 346ED9FC AD678846 DA60B8D0 44042D73 '", ",", "'33031DE5 AA0A4C5F DD0D7CC9 5005713C 270241AA BE0B1010 C90C2086 5768B525 206F85B3 B966D409 '", ",", "'CE61E49F 5EDEF90E 29D9C998 B0D09822 C7D7A8B4 59B33D17 2EB40D81 B7BD5C3B C0BA6CAD EDB88320 '", ",", "'9ABFB3B6 03B6E20C 74B1D29A EAD54739 9DD277AF 04DB2615 73DC1683 E3630B12 94643B84 0D6D6A3E '", ",", "'7A6A5AA8 E40ECF0B 9309FF9D 0A00AE27 7D079EB1 F00F9344 8708A3D2 1E01F268 6906C2FE F762575D '", ",", "'806567CB 196C3671 6E6B06E7 FED41B76 89D32BE0 10DA7A5A 67DD4ACC F9B9DF6F 8EBEEFF9 17B7BE43 '", ",", "'60B08ED5 D6D6A3E8 A1D1937E 38D8C2C4 4FDFF252 D1BB67F1 A6BC5767 3FB506DD 48B2364B D80D2BDA '", ",", "'AF0A1B4C 36034AF6 41047A60 DF60EFC3 A867DF55 316E8EEF 4669BE79 CB61B38C BC66831A 256FD2A0 '", ",", "'5268E236 CC0C7795 BB0B4703 220216B9 5505262F C5BA3BBE B2BD0B28 2BB45A92 5CB36A04 C2D7FFA7 '", ",", "'B5D0CF31 2CD99E8B 5BDEAE1D 9B64C2B0 EC63F226 756AA39C 026D930A 9C0906A9 EB0E363F 72076785 '", ",", "'05005713 95BF4A82 E2B87A14 7BB12BAE 0CB61B38 92D28E9B E5D5BE0D 7CDCEFB7 0BDBDF21 86D3D2D4 '", ",", "'F1D4E242 68DDB3F8 1FDA836E 81BE16CD F6B9265B 6FB077E1 18B74777 88085AE6 FF0F6A70 66063BCA '", ",", "'11010B5C 8F659EFF F862AE69 616BFFD3 166CCF45 A00AE278 D70DD2EE 4E048354 3903B3C2 A7672661 '", ",", "'D06016F7 4969474D 3E6E77DB AED16A4A D9D65ADC 40DF0B66 37D83BF0 A9BCAE53 DEBB9EC5 47B2CF7F '", ",", "'30B5FFE9 BDBDF21C CABAC28A 53B39330 24B4A3A6 BAD03605 CDD70693 54DE5729 23D967BF B3667A2E '", ",", "'C4614AB8 5D681B02 2A6F2B94 B40BBE37 C30C8EA1 5A05DF1B 2D02EF8D'", "]", ".", "join", "(", "''", ")", ";", "crc", "=", "crc", "^", "(", "-", "1", ")", ";", "for", "(", "i", "=", "0", ",", "iTop", "=", "str", ".", "length", ";", "i", "<", "iTop", ";", "i", "+=", "1", ")", "{", "y", "=", "(", "crc", "^", "str", ".", "charCodeAt", "(", "i", ")", ")", "&", "0xFF", ";", "x", "=", "'0x'", "+", "table", ".", "substr", "(", "y", "*", "9", ",", "8", ")", ";", "crc", "=", "(", "crc", ">>>", "8", ")", "^", "x", ";", "}", "// always return a positive number (that's what >>> 0 does)", "return", "(", "crc", "^", "(", "-", "1", ")", ")", ">>>", "0", ";", "}" ]
CRC-32 calculation @member Hashes @method CRC32 @static @param {String} str Input String @return {String}
[ "CRC", "-", "32", "calculation" ]
88625b6c841ca3c90f8b9fefb0fedb78992017ad
https://github.com/h2non/jshashes/blob/88625b6c841ca3c90f8b9fefb0fedb78992017ad/hashes.js#L384-L428
13,113
h2non/jshashes
hashes.js
rstr
function rstr(s) { s = (utf8) ? utf8Encode(s) : s; return binl2rstr(binl(rstr2binl(s), s.length * 8)); }
javascript
function rstr(s) { s = (utf8) ? utf8Encode(s) : s; return binl2rstr(binl(rstr2binl(s), s.length * 8)); }
[ "function", "rstr", "(", "s", ")", "{", "s", "=", "(", "utf8", ")", "?", "utf8Encode", "(", "s", ")", ":", "s", ";", "return", "binl2rstr", "(", "binl", "(", "rstr2binl", "(", "s", ")", ",", "s", ".", "length", "*", "8", ")", ")", ";", "}" ]
private methods Calculate the MD5 of a raw string
[ "private", "methods", "Calculate", "the", "MD5", "of", "a", "raw", "string" ]
88625b6c841ca3c90f8b9fefb0fedb78992017ad
https://github.com/h2non/jshashes/blob/88625b6c841ca3c90f8b9fefb0fedb78992017ad/hashes.js#L518-L521
13,114
h2non/jshashes
hashes.js
rstr
function rstr(s, utf8) { s = (utf8) ? utf8Encode(s) : s; return binb2rstr(binb(rstr2binb(s), s.length * 8)); }
javascript
function rstr(s, utf8) { s = (utf8) ? utf8Encode(s) : s; return binb2rstr(binb(rstr2binb(s), s.length * 8)); }
[ "function", "rstr", "(", "s", ",", "utf8", ")", "{", "s", "=", "(", "utf8", ")", "?", "utf8Encode", "(", "s", ")", ":", "s", ";", "return", "binb2rstr", "(", "binb", "(", "rstr2binb", "(", "s", ")", ",", "s", ".", "length", "*", "8", ")", ")", ";", "}" ]
private methods Calculate the SHA-512 of a raw string
[ "private", "methods", "Calculate", "the", "SHA", "-", "512", "of", "a", "raw", "string" ]
88625b6c841ca3c90f8b9fefb0fedb78992017ad
https://github.com/h2non/jshashes/blob/88625b6c841ca3c90f8b9fefb0fedb78992017ad/hashes.js#L956-L959
13,115
h2non/jshashes
hashes.js
int64copy
function int64copy(dst, src) { dst.h = src.h; dst.l = src.l; }
javascript
function int64copy(dst, src) { dst.h = src.h; dst.l = src.l; }
[ "function", "int64copy", "(", "dst", ",", "src", ")", "{", "dst", ".", "h", "=", "src", ".", "h", ";", "dst", ".", "l", "=", "src", ".", "l", ";", "}" ]
Copies src into dst, assuming both are 64-bit numbers
[ "Copies", "src", "into", "dst", "assuming", "both", "are", "64", "-", "bit", "numbers" ]
88625b6c841ca3c90f8b9fefb0fedb78992017ad
https://github.com/h2non/jshashes/blob/88625b6c841ca3c90f8b9fefb0fedb78992017ad/hashes.js#L1417-L1420
13,116
h2non/jshashes
hashes.js
int64revrrot
function int64revrrot(dst, x, shift) { dst.l = (x.h >>> shift) | (x.l << (32 - shift)); dst.h = (x.l >>> shift) | (x.h << (32 - shift)); }
javascript
function int64revrrot(dst, x, shift) { dst.l = (x.h >>> shift) | (x.l << (32 - shift)); dst.h = (x.l >>> shift) | (x.h << (32 - shift)); }
[ "function", "int64revrrot", "(", "dst", ",", "x", ",", "shift", ")", "{", "dst", ".", "l", "=", "(", "x", ".", "h", ">>>", "shift", ")", "|", "(", "x", ".", "l", "<<", "(", "32", "-", "shift", ")", ")", ";", "dst", ".", "h", "=", "(", "x", ".", "l", ">>>", "shift", ")", "|", "(", "x", ".", "h", "<<", "(", "32", "-", "shift", ")", ")", ";", "}" ]
Reverses the dwords of the source and then rotates right by shift. This is equivalent to rotation by 32+shift
[ "Reverses", "the", "dwords", "of", "the", "source", "and", "then", "rotates", "right", "by", "shift", ".", "This", "is", "equivalent", "to", "rotation", "by", "32", "+", "shift" ]
88625b6c841ca3c90f8b9fefb0fedb78992017ad
https://github.com/h2non/jshashes/blob/88625b6c841ca3c90f8b9fefb0fedb78992017ad/hashes.js#L1434-L1437
13,117
h2non/jshashes
hashes.js
int64shr
function int64shr(dst, x, shift) { dst.l = (x.l >>> shift) | (x.h << (32 - shift)); dst.h = (x.h >>> shift); }
javascript
function int64shr(dst, x, shift) { dst.l = (x.l >>> shift) | (x.h << (32 - shift)); dst.h = (x.h >>> shift); }
[ "function", "int64shr", "(", "dst", ",", "x", ",", "shift", ")", "{", "dst", ".", "l", "=", "(", "x", ".", "l", ">>>", "shift", ")", "|", "(", "x", ".", "h", "<<", "(", "32", "-", "shift", ")", ")", ";", "dst", ".", "h", "=", "(", "x", ".", "h", ">>>", "shift", ")", ";", "}" ]
Bitwise-shifts right a 64-bit number by shift Won't handle shift>=32, but it's never needed in SHA512
[ "Bitwise", "-", "shifts", "right", "a", "64", "-", "bit", "number", "by", "shift", "Won", "t", "handle", "shift", ">", "=", "32", "but", "it", "s", "never", "needed", "in", "SHA512" ]
88625b6c841ca3c90f8b9fefb0fedb78992017ad
https://github.com/h2non/jshashes/blob/88625b6c841ca3c90f8b9fefb0fedb78992017ad/hashes.js#L1442-L1445
13,118
h2non/jshashes
hashes.js
int64add
function int64add(dst, x, y) { var w0 = (x.l & 0xffff) + (y.l & 0xffff); var w1 = (x.l >>> 16) + (y.l >>> 16) + (w0 >>> 16); var w2 = (x.h & 0xffff) + (y.h & 0xffff) + (w1 >>> 16); var w3 = (x.h >>> 16) + (y.h >>> 16) + (w2 >>> 16); dst.l = (w0 & 0xffff) | (w1 << 16); dst.h = (w2 & 0xffff) | (w3 << 16); }
javascript
function int64add(dst, x, y) { var w0 = (x.l & 0xffff) + (y.l & 0xffff); var w1 = (x.l >>> 16) + (y.l >>> 16) + (w0 >>> 16); var w2 = (x.h & 0xffff) + (y.h & 0xffff) + (w1 >>> 16); var w3 = (x.h >>> 16) + (y.h >>> 16) + (w2 >>> 16); dst.l = (w0 & 0xffff) | (w1 << 16); dst.h = (w2 & 0xffff) | (w3 << 16); }
[ "function", "int64add", "(", "dst", ",", "x", ",", "y", ")", "{", "var", "w0", "=", "(", "x", ".", "l", "&", "0xffff", ")", "+", "(", "y", ".", "l", "&", "0xffff", ")", ";", "var", "w1", "=", "(", "x", ".", "l", ">>>", "16", ")", "+", "(", "y", ".", "l", ">>>", "16", ")", "+", "(", "w0", ">>>", "16", ")", ";", "var", "w2", "=", "(", "x", ".", "h", "&", "0xffff", ")", "+", "(", "y", ".", "h", "&", "0xffff", ")", "+", "(", "w1", ">>>", "16", ")", ";", "var", "w3", "=", "(", "x", ".", "h", ">>>", "16", ")", "+", "(", "y", ".", "h", ">>>", "16", ")", "+", "(", "w2", ">>>", "16", ")", ";", "dst", ".", "l", "=", "(", "w0", "&", "0xffff", ")", "|", "(", "w1", "<<", "16", ")", ";", "dst", ".", "h", "=", "(", "w2", "&", "0xffff", ")", "|", "(", "w3", "<<", "16", ")", ";", "}" ]
Adds two 64-bit numbers Like the original implementation, does not rely on 32-bit operations
[ "Adds", "two", "64", "-", "bit", "numbers", "Like", "the", "original", "implementation", "does", "not", "rely", "on", "32", "-", "bit", "operations" ]
88625b6c841ca3c90f8b9fefb0fedb78992017ad
https://github.com/h2non/jshashes/blob/88625b6c841ca3c90f8b9fefb0fedb78992017ad/hashes.js#L1450-L1457
13,119
h2non/jshashes
hashes.js
binl2rstr
function binl2rstr(input) { var i, output = '', l = input.length * 32; for (i = 0; i < l; i += 8) { output += String.fromCharCode((input[i >> 5] >>> (i % 32)) & 0xFF); } return output; }
javascript
function binl2rstr(input) { var i, output = '', l = input.length * 32; for (i = 0; i < l; i += 8) { output += String.fromCharCode((input[i >> 5] >>> (i % 32)) & 0xFF); } return output; }
[ "function", "binl2rstr", "(", "input", ")", "{", "var", "i", ",", "output", "=", "''", ",", "l", "=", "input", ".", "length", "*", "32", ";", "for", "(", "i", "=", "0", ";", "i", "<", "l", ";", "i", "+=", "8", ")", "{", "output", "+=", "String", ".", "fromCharCode", "(", "(", "input", "[", "i", ">>", "5", "]", ">>>", "(", "i", "%", "32", ")", ")", "&", "0xFF", ")", ";", "}", "return", "output", ";", "}" ]
Convert an array of little-endian words to a string
[ "Convert", "an", "array", "of", "little", "-", "endian", "words", "to", "a", "string" ]
88625b6c841ca3c90f8b9fefb0fedb78992017ad
https://github.com/h2non/jshashes/blob/88625b6c841ca3c90f8b9fefb0fedb78992017ad/hashes.js#L1640-L1647
13,120
h2non/jshashes
hashes.js
binl
function binl(x, len) { var T, j, i, l, h0 = 0x67452301, h1 = 0xefcdab89, h2 = 0x98badcfe, h3 = 0x10325476, h4 = 0xc3d2e1f0, A1, B1, C1, D1, E1, A2, B2, C2, D2, E2; /* append padding */ x[len >> 5] |= 0x80 << (len % 32); x[(((len + 64) >>> 9) << 4) + 14] = len; l = x.length; for (i = 0; i < l; i += 16) { A1 = A2 = h0; B1 = B2 = h1; C1 = C2 = h2; D1 = D2 = h3; E1 = E2 = h4; for (j = 0; j <= 79; j += 1) { T = safe_add(A1, rmd160_f(j, B1, C1, D1)); T = safe_add(T, x[i + rmd160_r1[j]]); T = safe_add(T, rmd160_K1(j)); T = safe_add(bit_rol(T, rmd160_s1[j]), E1); A1 = E1; E1 = D1; D1 = bit_rol(C1, 10); C1 = B1; B1 = T; T = safe_add(A2, rmd160_f(79 - j, B2, C2, D2)); T = safe_add(T, x[i + rmd160_r2[j]]); T = safe_add(T, rmd160_K2(j)); T = safe_add(bit_rol(T, rmd160_s2[j]), E2); A2 = E2; E2 = D2; D2 = bit_rol(C2, 10); C2 = B2; B2 = T; } T = safe_add(h1, safe_add(C1, D2)); h1 = safe_add(h2, safe_add(D1, E2)); h2 = safe_add(h3, safe_add(E1, A2)); h3 = safe_add(h4, safe_add(A1, B2)); h4 = safe_add(h0, safe_add(B1, C2)); h0 = T; } return [h0, h1, h2, h3, h4]; }
javascript
function binl(x, len) { var T, j, i, l, h0 = 0x67452301, h1 = 0xefcdab89, h2 = 0x98badcfe, h3 = 0x10325476, h4 = 0xc3d2e1f0, A1, B1, C1, D1, E1, A2, B2, C2, D2, E2; /* append padding */ x[len >> 5] |= 0x80 << (len % 32); x[(((len + 64) >>> 9) << 4) + 14] = len; l = x.length; for (i = 0; i < l; i += 16) { A1 = A2 = h0; B1 = B2 = h1; C1 = C2 = h2; D1 = D2 = h3; E1 = E2 = h4; for (j = 0; j <= 79; j += 1) { T = safe_add(A1, rmd160_f(j, B1, C1, D1)); T = safe_add(T, x[i + rmd160_r1[j]]); T = safe_add(T, rmd160_K1(j)); T = safe_add(bit_rol(T, rmd160_s1[j]), E1); A1 = E1; E1 = D1; D1 = bit_rol(C1, 10); C1 = B1; B1 = T; T = safe_add(A2, rmd160_f(79 - j, B2, C2, D2)); T = safe_add(T, x[i + rmd160_r2[j]]); T = safe_add(T, rmd160_K2(j)); T = safe_add(bit_rol(T, rmd160_s2[j]), E2); A2 = E2; E2 = D2; D2 = bit_rol(C2, 10); C2 = B2; B2 = T; } T = safe_add(h1, safe_add(C1, D2)); h1 = safe_add(h2, safe_add(D1, E2)); h2 = safe_add(h3, safe_add(E1, A2)); h3 = safe_add(h4, safe_add(A1, B2)); h4 = safe_add(h0, safe_add(B1, C2)); h0 = T; } return [h0, h1, h2, h3, h4]; }
[ "function", "binl", "(", "x", ",", "len", ")", "{", "var", "T", ",", "j", ",", "i", ",", "l", ",", "h0", "=", "0x67452301", ",", "h1", "=", "0xefcdab89", ",", "h2", "=", "0x98badcfe", ",", "h3", "=", "0x10325476", ",", "h4", "=", "0xc3d2e1f0", ",", "A1", ",", "B1", ",", "C1", ",", "D1", ",", "E1", ",", "A2", ",", "B2", ",", "C2", ",", "D2", ",", "E2", ";", "/* append padding */", "x", "[", "len", ">>", "5", "]", "|=", "0x80", "<<", "(", "len", "%", "32", ")", ";", "x", "[", "(", "(", "(", "len", "+", "64", ")", ">>>", "9", ")", "<<", "4", ")", "+", "14", "]", "=", "len", ";", "l", "=", "x", ".", "length", ";", "for", "(", "i", "=", "0", ";", "i", "<", "l", ";", "i", "+=", "16", ")", "{", "A1", "=", "A2", "=", "h0", ";", "B1", "=", "B2", "=", "h1", ";", "C1", "=", "C2", "=", "h2", ";", "D1", "=", "D2", "=", "h3", ";", "E1", "=", "E2", "=", "h4", ";", "for", "(", "j", "=", "0", ";", "j", "<=", "79", ";", "j", "+=", "1", ")", "{", "T", "=", "safe_add", "(", "A1", ",", "rmd160_f", "(", "j", ",", "B1", ",", "C1", ",", "D1", ")", ")", ";", "T", "=", "safe_add", "(", "T", ",", "x", "[", "i", "+", "rmd160_r1", "[", "j", "]", "]", ")", ";", "T", "=", "safe_add", "(", "T", ",", "rmd160_K1", "(", "j", ")", ")", ";", "T", "=", "safe_add", "(", "bit_rol", "(", "T", ",", "rmd160_s1", "[", "j", "]", ")", ",", "E1", ")", ";", "A1", "=", "E1", ";", "E1", "=", "D1", ";", "D1", "=", "bit_rol", "(", "C1", ",", "10", ")", ";", "C1", "=", "B1", ";", "B1", "=", "T", ";", "T", "=", "safe_add", "(", "A2", ",", "rmd160_f", "(", "79", "-", "j", ",", "B2", ",", "C2", ",", "D2", ")", ")", ";", "T", "=", "safe_add", "(", "T", ",", "x", "[", "i", "+", "rmd160_r2", "[", "j", "]", "]", ")", ";", "T", "=", "safe_add", "(", "T", ",", "rmd160_K2", "(", "j", ")", ")", ";", "T", "=", "safe_add", "(", "bit_rol", "(", "T", ",", "rmd160_s2", "[", "j", "]", ")", ",", "E2", ")", ";", "A2", "=", "E2", ";", "E2", "=", "D2", ";", "D2", "=", "bit_rol", "(", "C2", ",", "10", ")", ";", "C2", "=", "B2", ";", "B2", "=", "T", ";", "}", "T", "=", "safe_add", "(", "h1", ",", "safe_add", "(", "C1", ",", "D2", ")", ")", ";", "h1", "=", "safe_add", "(", "h2", ",", "safe_add", "(", "D1", ",", "E2", ")", ")", ";", "h2", "=", "safe_add", "(", "h3", ",", "safe_add", "(", "E1", ",", "A2", ")", ")", ";", "h3", "=", "safe_add", "(", "h4", ",", "safe_add", "(", "A1", ",", "B2", ")", ")", ";", "h4", "=", "safe_add", "(", "h0", ",", "safe_add", "(", "B1", ",", "C2", ")", ")", ";", "h0", "=", "T", ";", "}", "return", "[", "h0", ",", "h1", ",", "h2", ",", "h3", ",", "h4", "]", ";", "}" ]
Calculate the RIPE-MD160 of an array of little-endian words, and a bit length.
[ "Calculate", "the", "RIPE", "-", "MD160", "of", "an", "array", "of", "little", "-", "endian", "words", "and", "a", "bit", "length", "." ]
88625b6c841ca3c90f8b9fefb0fedb78992017ad
https://github.com/h2non/jshashes/blob/88625b6c841ca3c90f8b9fefb0fedb78992017ad/hashes.js#L1653-L1703
13,121
h2non/jshashes
hashes.js
rmd160_f
function rmd160_f(j, x, y, z) { return (0 <= j && j <= 15) ? (x ^ y ^ z) : (16 <= j && j <= 31) ? (x & y) | (~x & z) : (32 <= j && j <= 47) ? (x | ~y) ^ z : (48 <= j && j <= 63) ? (x & z) | (y & ~z) : (64 <= j && j <= 79) ? x ^ (y | ~z) : 'rmd160_f: j out of range'; }
javascript
function rmd160_f(j, x, y, z) { return (0 <= j && j <= 15) ? (x ^ y ^ z) : (16 <= j && j <= 31) ? (x & y) | (~x & z) : (32 <= j && j <= 47) ? (x | ~y) ^ z : (48 <= j && j <= 63) ? (x & z) | (y & ~z) : (64 <= j && j <= 79) ? x ^ (y | ~z) : 'rmd160_f: j out of range'; }
[ "function", "rmd160_f", "(", "j", ",", "x", ",", "y", ",", "z", ")", "{", "return", "(", "0", "<=", "j", "&&", "j", "<=", "15", ")", "?", "(", "x", "^", "y", "^", "z", ")", ":", "(", "16", "<=", "j", "&&", "j", "<=", "31", ")", "?", "(", "x", "&", "y", ")", "|", "(", "~", "x", "&", "z", ")", ":", "(", "32", "<=", "j", "&&", "j", "<=", "47", ")", "?", "(", "x", "|", "~", "y", ")", "^", "z", ":", "(", "48", "<=", "j", "&&", "j", "<=", "63", ")", "?", "(", "x", "&", "z", ")", "|", "(", "y", "&", "~", "z", ")", ":", "(", "64", "<=", "j", "&&", "j", "<=", "79", ")", "?", "x", "^", "(", "y", "|", "~", "z", ")", ":", "'rmd160_f: j out of range'", ";", "}" ]
specific algorithm methods
[ "specific", "algorithm", "methods" ]
88625b6c841ca3c90f8b9fefb0fedb78992017ad
https://github.com/h2non/jshashes/blob/88625b6c841ca3c90f8b9fefb0fedb78992017ad/hashes.js#L1707-L1714
13,122
arobson/rabbot
src/amqp/queue.js
purgeADQueue
function purgeADQueue (channel, connectionName, options, messages) { const name = options.uniqueName || options.name; return new Promise(function (resolve, reject) { const messageCount = messages.messages.length; if (messageCount > 0) { log.info(`Purge operation for queue '${options.name}' on '${connectionName}' is waiting for resolution on ${messageCount} messages`); messages.once('empty', function () { channel.purgeQueue(name) .then( result => resolve(result.messageCount), reject ); }); } else { channel.purgeQueue(name) .then( result => resolve(result.messageCount), reject ); } }); }
javascript
function purgeADQueue (channel, connectionName, options, messages) { const name = options.uniqueName || options.name; return new Promise(function (resolve, reject) { const messageCount = messages.messages.length; if (messageCount > 0) { log.info(`Purge operation for queue '${options.name}' on '${connectionName}' is waiting for resolution on ${messageCount} messages`); messages.once('empty', function () { channel.purgeQueue(name) .then( result => resolve(result.messageCount), reject ); }); } else { channel.purgeQueue(name) .then( result => resolve(result.messageCount), reject ); } }); }
[ "function", "purgeADQueue", "(", "channel", ",", "connectionName", ",", "options", ",", "messages", ")", "{", "const", "name", "=", "options", ".", "uniqueName", "||", "options", ".", "name", ";", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "const", "messageCount", "=", "messages", ".", "messages", ".", "length", ";", "if", "(", "messageCount", ">", "0", ")", "{", "log", ".", "info", "(", "`", "${", "options", ".", "name", "}", "${", "connectionName", "}", "${", "messageCount", "}", "`", ")", ";", "messages", ".", "once", "(", "'empty'", ",", "function", "(", ")", "{", "channel", ".", "purgeQueue", "(", "name", ")", ".", "then", "(", "result", "=>", "resolve", "(", "result", ".", "messageCount", ")", ",", "reject", ")", ";", "}", ")", ";", "}", "else", "{", "channel", ".", "purgeQueue", "(", "name", ")", ".", "then", "(", "result", "=>", "resolve", "(", "result", ".", "messageCount", ")", ",", "reject", ")", ";", "}", "}", ")", ";", "}" ]
purging an auto-delete queue means unsubscribing is not an option as it will cause the queue, binding and possibly upstream auto-delete exchanges to be deleted as well
[ "purging", "an", "auto", "-", "delete", "queue", "means", "unsubscribing", "is", "not", "an", "option", "as", "it", "will", "cause", "the", "queue", "binding", "and", "possibly", "upstream", "auto", "-", "delete", "exchanges", "to", "be", "deleted", "as", "well" ]
80b63c08bdb32d04fd36502f24180e0c8e8f69ee
https://github.com/arobson/rabbot/blob/80b63c08bdb32d04fd36502f24180e0c8e8f69ee/src/amqp/queue.js#L205-L226
13,123
filamentgroup/criticalCSS
critical.js
replaceDecls
function replaceDecls(originalRules, criticalRule){ // find all the rules in the original CSS that have the same selectors and // then create an array of all the associated declarations. Note that this // works with mutiple duplicate selectors on the original CSS var originalDecls = _.flatten( originalRules .filter(function(rule){ return _.isEqual(rule.selectors, criticalRule.selectors); }) .map(function(rule){ return rule.declarations; }) ); // take all the declarations that were found from the original CSS and use // them here, make sure that we de-dup any declarations from the original CSS criticalRule.declarations = _.uniqBy(criticalRule.declarations.concat(originalDecls), function(decl){ return decl.property + ":" + decl.value; }); return criticalRule; }
javascript
function replaceDecls(originalRules, criticalRule){ // find all the rules in the original CSS that have the same selectors and // then create an array of all the associated declarations. Note that this // works with mutiple duplicate selectors on the original CSS var originalDecls = _.flatten( originalRules .filter(function(rule){ return _.isEqual(rule.selectors, criticalRule.selectors); }) .map(function(rule){ return rule.declarations; }) ); // take all the declarations that were found from the original CSS and use // them here, make sure that we de-dup any declarations from the original CSS criticalRule.declarations = _.uniqBy(criticalRule.declarations.concat(originalDecls), function(decl){ return decl.property + ":" + decl.value; }); return criticalRule; }
[ "function", "replaceDecls", "(", "originalRules", ",", "criticalRule", ")", "{", "// find all the rules in the original CSS that have the same selectors and", "// then create an array of all the associated declarations. Note that this", "// works with mutiple duplicate selectors on the original CSS", "var", "originalDecls", "=", "_", ".", "flatten", "(", "originalRules", ".", "filter", "(", "function", "(", "rule", ")", "{", "return", "_", ".", "isEqual", "(", "rule", ".", "selectors", ",", "criticalRule", ".", "selectors", ")", ";", "}", ")", ".", "map", "(", "function", "(", "rule", ")", "{", "return", "rule", ".", "declarations", ";", "}", ")", ")", ";", "// take all the declarations that were found from the original CSS and use", "// them here, make sure that we de-dup any declarations from the original CSS", "criticalRule", ".", "declarations", "=", "_", ".", "uniqBy", "(", "criticalRule", ".", "declarations", ".", "concat", "(", "originalDecls", ")", ",", "function", "(", "decl", ")", "{", "return", "decl", ".", "property", "+", "\":\"", "+", "decl", ".", "value", ";", "}", ")", ";", "return", "criticalRule", ";", "}" ]
create a function that can be passed to `map` for a collection of critical css rules. The function will match original rules against the selector of the critical css declarations, concatenate them together, and then keep only the unique ones
[ "create", "a", "function", "that", "can", "be", "passed", "to", "map", "for", "a", "collection", "of", "critical", "css", "rules", ".", "The", "function", "will", "match", "original", "rules", "against", "the", "selector", "of", "the", "critical", "css", "declarations", "concatenate", "them", "together", "and", "then", "keep", "only", "the", "unique", "ones" ]
42e299907a0bd3a8113f83aef4b2fd69ca5d21e3
https://github.com/filamentgroup/criticalCSS/blob/42e299907a0bd3a8113f83aef4b2fd69ca5d21e3/critical.js#L127-L149
13,124
d3/d3-dsv
src/dsv.js
inferColumns
function inferColumns(rows) { var columnSet = Object.create(null), columns = []; rows.forEach(function(row) { for (var column in row) { if (!(column in columnSet)) { columns.push(columnSet[column] = column); } } }); return columns; }
javascript
function inferColumns(rows) { var columnSet = Object.create(null), columns = []; rows.forEach(function(row) { for (var column in row) { if (!(column in columnSet)) { columns.push(columnSet[column] = column); } } }); return columns; }
[ "function", "inferColumns", "(", "rows", ")", "{", "var", "columnSet", "=", "Object", ".", "create", "(", "null", ")", ",", "columns", "=", "[", "]", ";", "rows", ".", "forEach", "(", "function", "(", "row", ")", "{", "for", "(", "var", "column", "in", "row", ")", "{", "if", "(", "!", "(", "column", "in", "columnSet", ")", ")", "{", "columns", ".", "push", "(", "columnSet", "[", "column", "]", "=", "column", ")", ";", "}", "}", "}", ")", ";", "return", "columns", ";", "}" ]
Compute unique columns in order of discovery.
[ "Compute", "unique", "columns", "in", "order", "of", "discovery", "." ]
ff2d09f943c2d19d0f0fa96f9b6a39c7431ca7e8
https://github.com/d3/d3-dsv/blob/ff2d09f943c2d19d0f0fa96f9b6a39c7431ca7e8/src/dsv.js#L21-L34
13,125
Surnet/swagger-jsdoc
lib/helpers/filterJsDocComments.js
filterJsDocComments
function filterJsDocComments(jsDocComments) { const swaggerJsDocComments = []; for (let i = 0; i < jsDocComments.length; i += 1) { const jsDocComment = jsDocComments[i]; for (let j = 0; j < jsDocComment.tags.length; j += 1) { const tag = jsDocComment.tags[j]; if (tag.title === 'swagger') { swaggerJsDocComments.push(jsYaml.safeLoad(tag.description)); } } } return swaggerJsDocComments; }
javascript
function filterJsDocComments(jsDocComments) { const swaggerJsDocComments = []; for (let i = 0; i < jsDocComments.length; i += 1) { const jsDocComment = jsDocComments[i]; for (let j = 0; j < jsDocComment.tags.length; j += 1) { const tag = jsDocComment.tags[j]; if (tag.title === 'swagger') { swaggerJsDocComments.push(jsYaml.safeLoad(tag.description)); } } } return swaggerJsDocComments; }
[ "function", "filterJsDocComments", "(", "jsDocComments", ")", "{", "const", "swaggerJsDocComments", "=", "[", "]", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "jsDocComments", ".", "length", ";", "i", "+=", "1", ")", "{", "const", "jsDocComment", "=", "jsDocComments", "[", "i", "]", ";", "for", "(", "let", "j", "=", "0", ";", "j", "<", "jsDocComment", ".", "tags", ".", "length", ";", "j", "+=", "1", ")", "{", "const", "tag", "=", "jsDocComment", ".", "tags", "[", "j", "]", ";", "if", "(", "tag", ".", "title", "===", "'swagger'", ")", "{", "swaggerJsDocComments", ".", "push", "(", "jsYaml", ".", "safeLoad", "(", "tag", ".", "description", ")", ")", ";", "}", "}", "}", "return", "swaggerJsDocComments", ";", "}" ]
Filters JSDoc comments for those tagged with '@swagger' @function @param {array} jsDocComments - JSDoc comments @returns {array} JSDoc comments tagged with '@swagger' @requires js-yaml
[ "Filters", "JSDoc", "comments", "for", "those", "tagged", "with" ]
ece24be07458d9a4ff1b8a1020a4581624bb0f7c
https://github.com/Surnet/swagger-jsdoc/blob/ece24be07458d9a4ff1b8a1020a4581624bb0f7c/lib/helpers/filterJsDocComments.js#L10-L24
13,126
Surnet/swagger-jsdoc
lib/helpers/convertGlobPaths.js
convertGlobPaths
function convertGlobPaths(globs) { return globs .map(globString => glob.sync(globString)) .reduce((previous, current) => previous.concat(current), []); }
javascript
function convertGlobPaths(globs) { return globs .map(globString => glob.sync(globString)) .reduce((previous, current) => previous.concat(current), []); }
[ "function", "convertGlobPaths", "(", "globs", ")", "{", "return", "globs", ".", "map", "(", "globString", "=>", "glob", ".", "sync", "(", "globString", ")", ")", ".", "reduce", "(", "(", "previous", ",", "current", ")", "=>", "previous", ".", "concat", "(", "current", ")", ",", "[", "]", ")", ";", "}" ]
Converts an array of globs to full paths @function @param {array} globs - Array of globs and/or normal paths @return {array} Array of fully-qualified paths @requires glob
[ "Converts", "an", "array", "of", "globs", "to", "full", "paths" ]
ece24be07458d9a4ff1b8a1020a4581624bb0f7c
https://github.com/Surnet/swagger-jsdoc/blob/ece24be07458d9a4ff1b8a1020a4581624bb0f7c/lib/helpers/convertGlobPaths.js#L10-L14
13,127
Surnet/swagger-jsdoc
bin/swagger-jsdoc.js
createSpecification
function createSpecification(swaggerDefinition, apis, fileName) { // Options for the swagger docs const options = { // Import swaggerDefinitions swaggerDefinition, // Path to the API docs apis, }; // Initialize swagger-jsdoc -> returns validated JSON or YAML swagger spec let swaggerSpec; const ext = path.extname(fileName); if (ext === '.yml' || ext === '.yaml') { swaggerSpec = jsYaml.dump(swaggerJSDoc(options), { schema: jsYaml.JSON_SCHEMA, noRefs: true, }); } else { swaggerSpec = JSON.stringify(swaggerJSDoc(options), null, 2); } fs.writeFile(fileName, swaggerSpec, err => { if (err) { throw err; } console.log('Swagger specification is ready.'); }); }
javascript
function createSpecification(swaggerDefinition, apis, fileName) { // Options for the swagger docs const options = { // Import swaggerDefinitions swaggerDefinition, // Path to the API docs apis, }; // Initialize swagger-jsdoc -> returns validated JSON or YAML swagger spec let swaggerSpec; const ext = path.extname(fileName); if (ext === '.yml' || ext === '.yaml') { swaggerSpec = jsYaml.dump(swaggerJSDoc(options), { schema: jsYaml.JSON_SCHEMA, noRefs: true, }); } else { swaggerSpec = JSON.stringify(swaggerJSDoc(options), null, 2); } fs.writeFile(fileName, swaggerSpec, err => { if (err) { throw err; } console.log('Swagger specification is ready.'); }); }
[ "function", "createSpecification", "(", "swaggerDefinition", ",", "apis", ",", "fileName", ")", "{", "// Options for the swagger docs", "const", "options", "=", "{", "// Import swaggerDefinitions", "swaggerDefinition", ",", "// Path to the API docs", "apis", ",", "}", ";", "// Initialize swagger-jsdoc -> returns validated JSON or YAML swagger spec", "let", "swaggerSpec", ";", "const", "ext", "=", "path", ".", "extname", "(", "fileName", ")", ";", "if", "(", "ext", "===", "'.yml'", "||", "ext", "===", "'.yaml'", ")", "{", "swaggerSpec", "=", "jsYaml", ".", "dump", "(", "swaggerJSDoc", "(", "options", ")", ",", "{", "schema", ":", "jsYaml", ".", "JSON_SCHEMA", ",", "noRefs", ":", "true", ",", "}", ")", ";", "}", "else", "{", "swaggerSpec", "=", "JSON", ".", "stringify", "(", "swaggerJSDoc", "(", "options", ")", ",", "null", ",", "2", ")", ";", "}", "fs", ".", "writeFile", "(", "fileName", ",", "swaggerSpec", ",", "err", "=>", "{", "if", "(", "err", ")", "{", "throw", "err", ";", "}", "console", ".", "log", "(", "'Swagger specification is ready.'", ")", ";", "}", ")", ";", "}" ]
Creates a swagger specification from a definition and a set of files. @function @param {object} swaggerDefinition - The swagger definition object. @param {array} apis - List of files to extract documentation from. @param {string} fileName - Name the output file.
[ "Creates", "a", "swagger", "specification", "from", "a", "definition", "and", "a", "set", "of", "files", "." ]
ece24be07458d9a4ff1b8a1020a4581624bb0f7c
https://github.com/Surnet/swagger-jsdoc/blob/ece24be07458d9a4ff1b8a1020a4581624bb0f7c/bin/swagger-jsdoc.js#L25-L53
13,128
Surnet/swagger-jsdoc
bin/swagger-jsdoc.js
loadSpecification
function loadSpecification(defPath, data) { const resolvedPath = path.resolve(defPath); const extName = path.extname(resolvedPath); const loader = LOADERS[extName]; // Check whether the definition file is actually a usable file if (loader === undefined) { throw new Error('Definition file should be .js, .json, .yml or .yaml'); } const swaggerDefinition = loader(data, resolvedPath); return swaggerDefinition; }
javascript
function loadSpecification(defPath, data) { const resolvedPath = path.resolve(defPath); const extName = path.extname(resolvedPath); const loader = LOADERS[extName]; // Check whether the definition file is actually a usable file if (loader === undefined) { throw new Error('Definition file should be .js, .json, .yml or .yaml'); } const swaggerDefinition = loader(data, resolvedPath); return swaggerDefinition; }
[ "function", "loadSpecification", "(", "defPath", ",", "data", ")", "{", "const", "resolvedPath", "=", "path", ".", "resolve", "(", "defPath", ")", ";", "const", "extName", "=", "path", ".", "extname", "(", "resolvedPath", ")", ";", "const", "loader", "=", "LOADERS", "[", "extName", "]", ";", "// Check whether the definition file is actually a usable file", "if", "(", "loader", "===", "undefined", ")", "{", "throw", "new", "Error", "(", "'Definition file should be .js, .json, .yml or .yaml'", ")", ";", "}", "const", "swaggerDefinition", "=", "loader", "(", "data", ",", "resolvedPath", ")", ";", "return", "swaggerDefinition", ";", "}" ]
Get an object of the definition file configuration.
[ "Get", "an", "object", "of", "the", "definition", "file", "configuration", "." ]
ece24be07458d9a4ff1b8a1020a4581624bb0f7c
https://github.com/Surnet/swagger-jsdoc/blob/ece24be07458d9a4ff1b8a1020a4581624bb0f7c/bin/swagger-jsdoc.js#L77-L90
13,129
Surnet/swagger-jsdoc
lib/helpers/hasEmptyProperty.js
hasEmptyProperty
function hasEmptyProperty(obj) { return Object.keys(obj) .map(key => obj[key]) .every( keyObject => typeof keyObject === 'object' && Object.keys(keyObject).every(key => !(key in keyObject)) ); }
javascript
function hasEmptyProperty(obj) { return Object.keys(obj) .map(key => obj[key]) .every( keyObject => typeof keyObject === 'object' && Object.keys(keyObject).every(key => !(key in keyObject)) ); }
[ "function", "hasEmptyProperty", "(", "obj", ")", "{", "return", "Object", ".", "keys", "(", "obj", ")", ".", "map", "(", "key", "=>", "obj", "[", "key", "]", ")", ".", "every", "(", "keyObject", "=>", "typeof", "keyObject", "===", "'object'", "&&", "Object", ".", "keys", "(", "keyObject", ")", ".", "every", "(", "key", "=>", "!", "(", "key", "in", "keyObject", ")", ")", ")", ";", "}" ]
Checks if there is any properties of @obj that is a empty object @function @param {object} obj - the object to check
[ "Checks", "if", "there", "is", "any", "properties", "of" ]
ece24be07458d9a4ff1b8a1020a4581624bb0f7c
https://github.com/Surnet/swagger-jsdoc/blob/ece24be07458d9a4ff1b8a1020a4581624bb0f7c/lib/helpers/hasEmptyProperty.js#L6-L14
13,130
Surnet/swagger-jsdoc
lib/helpers/parseApiFile.js
parseApiFile
function parseApiFile(file) { const jsDocRegex = /\/\*\*([\s\S]*?)\*\//gm; const fileContent = fs.readFileSync(file, { encoding: 'utf8' }); const ext = path.extname(file); const yaml = []; const jsDocComments = []; if (ext === '.yaml' || ext === '.yml') { yaml.push(jsYaml.safeLoad(fileContent)); } else { const regexResults = fileContent.match(jsDocRegex); if (regexResults) { for (let i = 0; i < regexResults.length; i += 1) { const jsDocComment = doctrine.parse(regexResults[i], { unwrap: true }); jsDocComments.push(jsDocComment); } } } return { yaml, jsdoc: jsDocComments, }; }
javascript
function parseApiFile(file) { const jsDocRegex = /\/\*\*([\s\S]*?)\*\//gm; const fileContent = fs.readFileSync(file, { encoding: 'utf8' }); const ext = path.extname(file); const yaml = []; const jsDocComments = []; if (ext === '.yaml' || ext === '.yml') { yaml.push(jsYaml.safeLoad(fileContent)); } else { const regexResults = fileContent.match(jsDocRegex); if (regexResults) { for (let i = 0; i < regexResults.length; i += 1) { const jsDocComment = doctrine.parse(regexResults[i], { unwrap: true }); jsDocComments.push(jsDocComment); } } } return { yaml, jsdoc: jsDocComments, }; }
[ "function", "parseApiFile", "(", "file", ")", "{", "const", "jsDocRegex", "=", "/", "\\/\\*\\*([\\s\\S]*?)\\*\\/", "/", "gm", ";", "const", "fileContent", "=", "fs", ".", "readFileSync", "(", "file", ",", "{", "encoding", ":", "'utf8'", "}", ")", ";", "const", "ext", "=", "path", ".", "extname", "(", "file", ")", ";", "const", "yaml", "=", "[", "]", ";", "const", "jsDocComments", "=", "[", "]", ";", "if", "(", "ext", "===", "'.yaml'", "||", "ext", "===", "'.yml'", ")", "{", "yaml", ".", "push", "(", "jsYaml", ".", "safeLoad", "(", "fileContent", ")", ")", ";", "}", "else", "{", "const", "regexResults", "=", "fileContent", ".", "match", "(", "jsDocRegex", ")", ";", "if", "(", "regexResults", ")", "{", "for", "(", "let", "i", "=", "0", ";", "i", "<", "regexResults", ".", "length", ";", "i", "+=", "1", ")", "{", "const", "jsDocComment", "=", "doctrine", ".", "parse", "(", "regexResults", "[", "i", "]", ",", "{", "unwrap", ":", "true", "}", ")", ";", "jsDocComments", ".", "push", "(", "jsDocComment", ")", ";", "}", "}", "}", "return", "{", "yaml", ",", "jsdoc", ":", "jsDocComments", ",", "}", ";", "}" ]
Parses the provided API file for JSDoc comments. @function @param {string} file - File to be parsed @returns {{jsdoc: array, yaml: array}} JSDoc comments and Yaml files @requires doctrine
[ "Parses", "the", "provided", "API", "file", "for", "JSDoc", "comments", "." ]
ece24be07458d9a4ff1b8a1020a4581624bb0f7c
https://github.com/Surnet/swagger-jsdoc/blob/ece24be07458d9a4ff1b8a1020a4581624bb0f7c/lib/helpers/parseApiFile.js#L13-L36
13,131
anmonteiro/lumo
vendor/nexe/monkeypatch.js
_monkeypatch
function _monkeypatch(filePath, monkeyPatched, processor, complete) { async.waterfall( [ function read(next) { fs.readFile(filePath, 'utf8', next); }, // TODO - need to parse gyp file - this is a bit hacker function monkeypatch(content, next) { if (monkeyPatched(content)) return complete(); _log('monkey patch %s', filePath); processor(content, next); }, function write(content, next) { fs.writeFile(filePath, content, 'utf8', function(err) { return next(err); }); }, ], complete, ); }
javascript
function _monkeypatch(filePath, monkeyPatched, processor, complete) { async.waterfall( [ function read(next) { fs.readFile(filePath, 'utf8', next); }, // TODO - need to parse gyp file - this is a bit hacker function monkeypatch(content, next) { if (monkeyPatched(content)) return complete(); _log('monkey patch %s', filePath); processor(content, next); }, function write(content, next) { fs.writeFile(filePath, content, 'utf8', function(err) { return next(err); }); }, ], complete, ); }
[ "function", "_monkeypatch", "(", "filePath", ",", "monkeyPatched", ",", "processor", ",", "complete", ")", "{", "async", ".", "waterfall", "(", "[", "function", "read", "(", "next", ")", "{", "fs", ".", "readFile", "(", "filePath", ",", "'utf8'", ",", "next", ")", ";", "}", ",", "// TODO - need to parse gyp file - this is a bit hacker", "function", "monkeypatch", "(", "content", ",", "next", ")", "{", "if", "(", "monkeyPatched", "(", "content", ")", ")", "return", "complete", "(", ")", ";", "_log", "(", "'monkey patch %s'", ",", "filePath", ")", ";", "processor", "(", "content", ",", "next", ")", ";", "}", ",", "function", "write", "(", "content", ",", "next", ")", "{", "fs", ".", "writeFile", "(", "filePath", ",", "content", ",", "'utf8'", ",", "function", "(", "err", ")", "{", "return", "next", "(", "err", ")", ";", "}", ")", ";", "}", ",", "]", ",", "complete", ",", ")", ";", "}" ]
Monkey patch a file. @param {string} filePath - path to file. @param {function} monkeyPatched - function to process contents @param {function} processor - TODO: detail what this is @param {function} complete - callback @return undefined
[ "Monkey", "patch", "a", "file", "." ]
345bacd2c36f9648b416f74d2e41cdf55c2cc1f9
https://github.com/anmonteiro/lumo/blob/345bacd2c36f9648b416f74d2e41cdf55c2cc1f9/vendor/nexe/monkeypatch.js#L39-L62
13,132
anmonteiro/lumo
vendor/nexe/log.js
_log
function _log() { var args = Array.prototype.slice.call(arguments, 0), level = args.shift(); if (!~['log', 'error', 'warn'].indexOf(level)) { args.unshift(level); level = 'log'; } if (level == 'log') { args[0] = '----> ' + args[0]; } else if (level == 'error') { args[0] = '....> ' + colors.red('ERROR: ') + args[0]; } else if (level == 'warn') { args[0] = '....> ' + colors.yellow('WARNING: ') + args[0]; } console[level].apply(console, args); }
javascript
function _log() { var args = Array.prototype.slice.call(arguments, 0), level = args.shift(); if (!~['log', 'error', 'warn'].indexOf(level)) { args.unshift(level); level = 'log'; } if (level == 'log') { args[0] = '----> ' + args[0]; } else if (level == 'error') { args[0] = '....> ' + colors.red('ERROR: ') + args[0]; } else if (level == 'warn') { args[0] = '....> ' + colors.yellow('WARNING: ') + args[0]; } console[level].apply(console, args); }
[ "function", "_log", "(", ")", "{", "var", "args", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ",", "0", ")", ",", "level", "=", "args", ".", "shift", "(", ")", ";", "if", "(", "!", "~", "[", "'log'", ",", "'error'", ",", "'warn'", "]", ".", "indexOf", "(", "level", ")", ")", "{", "args", ".", "unshift", "(", "level", ")", ";", "level", "=", "'log'", ";", "}", "if", "(", "level", "==", "'log'", ")", "{", "args", "[", "0", "]", "=", "'----> '", "+", "args", "[", "0", "]", ";", "}", "else", "if", "(", "level", "==", "'error'", ")", "{", "args", "[", "0", "]", "=", "'....> '", "+", "colors", ".", "red", "(", "'ERROR: '", ")", "+", "args", "[", "0", "]", ";", "}", "else", "if", "(", "level", "==", "'warn'", ")", "{", "args", "[", "0", "]", "=", "'....> '", "+", "colors", ".", "yellow", "(", "'WARNING: '", ")", "+", "args", "[", "0", "]", ";", "}", "console", "[", "level", "]", ".", "apply", "(", "console", ",", "args", ")", ";", "}" ]
standard output, takes 3 different types. log, error, and warn @param {any} arguments - Text to output. @return undefined
[ "standard", "output", "takes", "3", "different", "types", ".", "log", "error", "and", "warn" ]
345bacd2c36f9648b416f74d2e41cdf55c2cc1f9
https://github.com/anmonteiro/lumo/blob/345bacd2c36f9648b416f74d2e41cdf55c2cc1f9/vendor/nexe/log.js#L35-L53
13,133
anmonteiro/lumo
vendor/nexe/embed.js
embed
function embed(resourceFiles, resourceRoot) { if (resourceFiles.length > 0) { let buffer = 'var embeddedFiles = {\n'; for (let i = 0; i < resourceFiles.length; ++i) { buffer += JSON.stringify(path.relative(resourceRoot, resourceFiles[i])) + ': "'; buffer += encode(resourceFiles[i]) + '",\n'; } buffer += '\n};\n\nmodule.exports.keys = function () { return Object.keys(embeddedFiles); }\n\nmodule.exports.get = '; buffer += accessor.toString(); return buffer; } }
javascript
function embed(resourceFiles, resourceRoot) { if (resourceFiles.length > 0) { let buffer = 'var embeddedFiles = {\n'; for (let i = 0; i < resourceFiles.length; ++i) { buffer += JSON.stringify(path.relative(resourceRoot, resourceFiles[i])) + ': "'; buffer += encode(resourceFiles[i]) + '",\n'; } buffer += '\n};\n\nmodule.exports.keys = function () { return Object.keys(embeddedFiles); }\n\nmodule.exports.get = '; buffer += accessor.toString(); return buffer; } }
[ "function", "embed", "(", "resourceFiles", ",", "resourceRoot", ")", "{", "if", "(", "resourceFiles", ".", "length", ">", "0", ")", "{", "let", "buffer", "=", "'var embeddedFiles = {\\n'", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "resourceFiles", ".", "length", ";", "++", "i", ")", "{", "buffer", "+=", "JSON", ".", "stringify", "(", "path", ".", "relative", "(", "resourceRoot", ",", "resourceFiles", "[", "i", "]", ")", ")", "+", "': \"'", ";", "buffer", "+=", "encode", "(", "resourceFiles", "[", "i", "]", ")", "+", "'\",\\n'", ";", "}", "buffer", "+=", "'\\n};\\n\\nmodule.exports.keys = function () { return Object.keys(embeddedFiles); }\\n\\nmodule.exports.get = '", ";", "buffer", "+=", "accessor", ".", "toString", "(", ")", ";", "return", "buffer", ";", "}", "}" ]
Embed files. @param {array} resourceFiles - array of files to embed. @param {string} resourceRoot - root of resources. @param {function} compelte - callback
[ "Embed", "files", "." ]
345bacd2c36f9648b416f74d2e41cdf55c2cc1f9
https://github.com/anmonteiro/lumo/blob/345bacd2c36f9648b416f74d2e41cdf55c2cc1f9/vendor/nexe/embed.js#L54-L69
13,134
anmonteiro/lumo
vendor/nexe/exe.js
checkOpts
function checkOpts(next) { /* failsafe */ if (options === undefined) { _log('error', 'no options given to .compile()'); process.exit(); } /** * Have we been given a custom flag for python executable? **/ if ( options.python !== 'python' && options.python !== '' && options.python !== undefined ) { if (isWin) { isPy = options.python.replace(/\//gm, '\\'); // use windows file paths, batch is sensitive. } else { isPy = options.python; } _log('set python as ' + isPy); } else { isPy = 'python'; } // remove dots options.framework = options.framework.replace(/\./g, ''); // set outter-scope framework variable. framework = options.framework; _log('framework => ' + framework); version = options.nodeVersion; // better framework vc // check iojs version if (framework === 'iojs' && version === 'latest') { _log('fetching iojs versions'); mkdirp(options.nodeTempDir); // make temp dir, probably repetive. // create write stream so we have control over events var output = fs.createWriteStream( path.join(options.nodeTempDir, 'iojs-versions.json'), ); request.get('https://iojs.org/dist/index.json').pipe(output); output.on('close', function() { _log('done'); var f = fs.readFileSync( path.join(options.nodeTempDir, 'iojs-versions.json'), ); f = JSON.parse(f); version = f[0].version.replace('v', ''); _log('iojs latest => ' + version); // continue down along the async road next(); }); } else { next(); } }
javascript
function checkOpts(next) { /* failsafe */ if (options === undefined) { _log('error', 'no options given to .compile()'); process.exit(); } /** * Have we been given a custom flag for python executable? **/ if ( options.python !== 'python' && options.python !== '' && options.python !== undefined ) { if (isWin) { isPy = options.python.replace(/\//gm, '\\'); // use windows file paths, batch is sensitive. } else { isPy = options.python; } _log('set python as ' + isPy); } else { isPy = 'python'; } // remove dots options.framework = options.framework.replace(/\./g, ''); // set outter-scope framework variable. framework = options.framework; _log('framework => ' + framework); version = options.nodeVersion; // better framework vc // check iojs version if (framework === 'iojs' && version === 'latest') { _log('fetching iojs versions'); mkdirp(options.nodeTempDir); // make temp dir, probably repetive. // create write stream so we have control over events var output = fs.createWriteStream( path.join(options.nodeTempDir, 'iojs-versions.json'), ); request.get('https://iojs.org/dist/index.json').pipe(output); output.on('close', function() { _log('done'); var f = fs.readFileSync( path.join(options.nodeTempDir, 'iojs-versions.json'), ); f = JSON.parse(f); version = f[0].version.replace('v', ''); _log('iojs latest => ' + version); // continue down along the async road next(); }); } else { next(); } }
[ "function", "checkOpts", "(", "next", ")", "{", "/* failsafe */", "if", "(", "options", "===", "undefined", ")", "{", "_log", "(", "'error'", ",", "'no options given to .compile()'", ")", ";", "process", ".", "exit", "(", ")", ";", "}", "/**\n * Have we been given a custom flag for python executable?\n **/", "if", "(", "options", ".", "python", "!==", "'python'", "&&", "options", ".", "python", "!==", "''", "&&", "options", ".", "python", "!==", "undefined", ")", "{", "if", "(", "isWin", ")", "{", "isPy", "=", "options", ".", "python", ".", "replace", "(", "/", "\\/", "/", "gm", ",", "'\\\\'", ")", ";", "// use windows file paths, batch is sensitive.", "}", "else", "{", "isPy", "=", "options", ".", "python", ";", "}", "_log", "(", "'set python as '", "+", "isPy", ")", ";", "}", "else", "{", "isPy", "=", "'python'", ";", "}", "// remove dots", "options", ".", "framework", "=", "options", ".", "framework", ".", "replace", "(", "/", "\\.", "/", "g", ",", "''", ")", ";", "// set outter-scope framework variable.", "framework", "=", "options", ".", "framework", ";", "_log", "(", "'framework => '", "+", "framework", ")", ";", "version", "=", "options", ".", "nodeVersion", ";", "// better framework vc", "// check iojs version", "if", "(", "framework", "===", "'iojs'", "&&", "version", "===", "'latest'", ")", "{", "_log", "(", "'fetching iojs versions'", ")", ";", "mkdirp", "(", "options", ".", "nodeTempDir", ")", ";", "// make temp dir, probably repetive.", "// create write stream so we have control over events", "var", "output", "=", "fs", ".", "createWriteStream", "(", "path", ".", "join", "(", "options", ".", "nodeTempDir", ",", "'iojs-versions.json'", ")", ",", ")", ";", "request", ".", "get", "(", "'https://iojs.org/dist/index.json'", ")", ".", "pipe", "(", "output", ")", ";", "output", ".", "on", "(", "'close'", ",", "function", "(", ")", "{", "_log", "(", "'done'", ")", ";", "var", "f", "=", "fs", ".", "readFileSync", "(", "path", ".", "join", "(", "options", ".", "nodeTempDir", ",", "'iojs-versions.json'", ")", ",", ")", ";", "f", "=", "JSON", ".", "parse", "(", "f", ")", ";", "version", "=", "f", "[", "0", "]", ".", "version", ".", "replace", "(", "'v'", ",", "''", ")", ";", "_log", "(", "'iojs latest => '", "+", "version", ")", ";", "// continue down along the async road", "next", "(", ")", ";", "}", ")", ";", "}", "else", "{", "next", "(", ")", ";", "}", "}" ]
check relevant options
[ "check", "relevant", "options" ]
345bacd2c36f9648b416f74d2e41cdf55c2cc1f9
https://github.com/anmonteiro/lumo/blob/345bacd2c36f9648b416f74d2e41cdf55c2cc1f9/vendor/nexe/exe.js#L63-L126
13,135
anmonteiro/lumo
vendor/nexe/exe.js
downloadNode
function downloadNode(next) { _downloadNode( version, options.nodeTempDir, options.nodeConfigureArgs, options.nodeMakeArgs, options.nodeVCBuildArgs, next, ); }
javascript
function downloadNode(next) { _downloadNode( version, options.nodeTempDir, options.nodeConfigureArgs, options.nodeMakeArgs, options.nodeVCBuildArgs, next, ); }
[ "function", "downloadNode", "(", "next", ")", "{", "_downloadNode", "(", "version", ",", "options", ".", "nodeTempDir", ",", "options", ".", "nodeConfigureArgs", ",", "options", ".", "nodeMakeArgs", ",", "options", ".", "nodeVCBuildArgs", ",", "next", ",", ")", ";", "}" ]
first download node
[ "first", "download", "node" ]
345bacd2c36f9648b416f74d2e41cdf55c2cc1f9
https://github.com/anmonteiro/lumo/blob/345bacd2c36f9648b416f74d2e41cdf55c2cc1f9/vendor/nexe/exe.js#L131-L140
13,136
anmonteiro/lumo
vendor/nexe/exe.js
embedResources
function embedResources(nc, next) { nodeCompiler = nc; options.resourceFiles = options.resourceFiles || []; options.resourceRoot = options.resourceRoot || ''; if (!Array.isArray(options.resourceFiles)) { throw new Error('Bad Argument: resourceFiles is not an array'); } const resourcesBuffer = embed( options.resourceFiles, options.resourceRoot, ); if (resourcesBuffer != null) { const resourcePath = path.join(nodeCompiler.dir, 'lib', 'nexeres.js'); // write nexeres.js _log('embedResources %s', options.resourceFiles); _log('resource -> %s', resourcePath); fs.writeFile(resourcePath, resourcesBuffer, next); } else { next(); } }
javascript
function embedResources(nc, next) { nodeCompiler = nc; options.resourceFiles = options.resourceFiles || []; options.resourceRoot = options.resourceRoot || ''; if (!Array.isArray(options.resourceFiles)) { throw new Error('Bad Argument: resourceFiles is not an array'); } const resourcesBuffer = embed( options.resourceFiles, options.resourceRoot, ); if (resourcesBuffer != null) { const resourcePath = path.join(nodeCompiler.dir, 'lib', 'nexeres.js'); // write nexeres.js _log('embedResources %s', options.resourceFiles); _log('resource -> %s', resourcePath); fs.writeFile(resourcePath, resourcesBuffer, next); } else { next(); } }
[ "function", "embedResources", "(", "nc", ",", "next", ")", "{", "nodeCompiler", "=", "nc", ";", "options", ".", "resourceFiles", "=", "options", ".", "resourceFiles", "||", "[", "]", ";", "options", ".", "resourceRoot", "=", "options", ".", "resourceRoot", "||", "''", ";", "if", "(", "!", "Array", ".", "isArray", "(", "options", ".", "resourceFiles", ")", ")", "{", "throw", "new", "Error", "(", "'Bad Argument: resourceFiles is not an array'", ")", ";", "}", "const", "resourcesBuffer", "=", "embed", "(", "options", ".", "resourceFiles", ",", "options", ".", "resourceRoot", ",", ")", ";", "if", "(", "resourcesBuffer", "!=", "null", ")", "{", "const", "resourcePath", "=", "path", ".", "join", "(", "nodeCompiler", ".", "dir", ",", "'lib'", ",", "'nexeres.js'", ")", ";", "// write nexeres.js", "_log", "(", "'embedResources %s'", ",", "options", ".", "resourceFiles", ")", ";", "_log", "(", "'resource -> %s'", ",", "resourcePath", ")", ";", "fs", ".", "writeFile", "(", "resourcePath", ",", "resourcesBuffer", ",", "next", ")", ";", "}", "else", "{", "next", "(", ")", ";", "}", "}" ]
Embed Resources into a base64 encoded array.
[ "Embed", "Resources", "into", "a", "base64", "encoded", "array", "." ]
345bacd2c36f9648b416f74d2e41cdf55c2cc1f9
https://github.com/anmonteiro/lumo/blob/345bacd2c36f9648b416f74d2e41cdf55c2cc1f9/vendor/nexe/exe.js#L145-L170
13,137
anmonteiro/lumo
vendor/nexe/exe.js
combineProject
function combineProject(next) { if (options.noBundle) { _log( 'using provided bundle %s since noBundle is true', options.input, ); const source = fs.readFileSync(options.input, 'utf8'); const thirdPartyMain = ` if (!process.send) { console.log('toine', global.process.argv); process.argv.splice(1, 0, 'nexe.js'); } const Module = require('module'); const initModule = new Module(process.execPath, null); initModule.paths = Module._nodeModulePaths(process.cwd()); return initModule._compile(${JSON.stringify(source)}, process.execPath); `; fs.writeFileSync( path.join(nodeCompiler.dir, 'lib', '_third_party_main.js'), thirdPartyMain, ); next(); } else { _log('bundle %s', options.input); bundle(options.input, nodeCompiler.dir, options, next); } }
javascript
function combineProject(next) { if (options.noBundle) { _log( 'using provided bundle %s since noBundle is true', options.input, ); const source = fs.readFileSync(options.input, 'utf8'); const thirdPartyMain = ` if (!process.send) { console.log('toine', global.process.argv); process.argv.splice(1, 0, 'nexe.js'); } const Module = require('module'); const initModule = new Module(process.execPath, null); initModule.paths = Module._nodeModulePaths(process.cwd()); return initModule._compile(${JSON.stringify(source)}, process.execPath); `; fs.writeFileSync( path.join(nodeCompiler.dir, 'lib', '_third_party_main.js'), thirdPartyMain, ); next(); } else { _log('bundle %s', options.input); bundle(options.input, nodeCompiler.dir, options, next); } }
[ "function", "combineProject", "(", "next", ")", "{", "if", "(", "options", ".", "noBundle", ")", "{", "_log", "(", "'using provided bundle %s since noBundle is true'", ",", "options", ".", "input", ",", ")", ";", "const", "source", "=", "fs", ".", "readFileSync", "(", "options", ".", "input", ",", "'utf8'", ")", ";", "const", "thirdPartyMain", "=", "`", "${", "JSON", ".", "stringify", "(", "source", ")", "}", "`", ";", "fs", ".", "writeFileSync", "(", "path", ".", "join", "(", "nodeCompiler", ".", "dir", ",", "'lib'", ",", "'_third_party_main.js'", ")", ",", "thirdPartyMain", ",", ")", ";", "next", "(", ")", ";", "}", "else", "{", "_log", "(", "'bundle %s'", ",", "options", ".", "input", ")", ";", "bundle", "(", "options", ".", "input", ",", "nodeCompiler", ".", "dir", ",", "options", ",", "next", ")", ";", "}", "}" ]
Bundle the application into one script
[ "Bundle", "the", "application", "into", "one", "script" ]
345bacd2c36f9648b416f74d2e41cdf55c2cc1f9
https://github.com/anmonteiro/lumo/blob/345bacd2c36f9648b416f74d2e41cdf55c2cc1f9/vendor/nexe/exe.js#L175-L202
13,138
anmonteiro/lumo
vendor/nexe/exe.js
cleanUpOldExecutable
function cleanUpOldExecutable(next) { fs.unlink(nodeCompiler.releasePath, function(err) { if (err) { if (err.code === 'ENOENT') { next(); } else { throw err; } } else { next(); } }); }
javascript
function cleanUpOldExecutable(next) { fs.unlink(nodeCompiler.releasePath, function(err) { if (err) { if (err.code === 'ENOENT') { next(); } else { throw err; } } else { next(); } }); }
[ "function", "cleanUpOldExecutable", "(", "next", ")", "{", "fs", ".", "unlink", "(", "nodeCompiler", ".", "releasePath", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "if", "(", "err", ".", "code", "===", "'ENOENT'", ")", "{", "next", "(", ")", ";", "}", "else", "{", "throw", "err", ";", "}", "}", "else", "{", "next", "(", ")", ";", "}", "}", ")", ";", "}" ]
If an old compiled executable exists in the Release directory, delete it. This lets us see if the build failed by checking the existence of this file later.
[ "If", "an", "old", "compiled", "executable", "exists", "in", "the", "Release", "directory", "delete", "it", ".", "This", "lets", "us", "see", "if", "the", "build", "failed", "by", "checking", "the", "existence", "of", "this", "file", "later", "." ]
345bacd2c36f9648b416f74d2e41cdf55c2cc1f9
https://github.com/anmonteiro/lumo/blob/345bacd2c36f9648b416f74d2e41cdf55c2cc1f9/vendor/nexe/exe.js#L245-L257
13,139
anmonteiro/lumo
vendor/nexe/exe.js
checkThatExecutableExists
function checkThatExecutableExists(next) { fs.exists(nodeCompiler.releasePath, function(exists) { if (!exists) { _log( 'error', 'The release executable has not been generated. ' + 'This indicates a failure in the build process. ' + 'There is likely additional information above.', ); process.exit(1); } else { next(); } }); }
javascript
function checkThatExecutableExists(next) { fs.exists(nodeCompiler.releasePath, function(exists) { if (!exists) { _log( 'error', 'The release executable has not been generated. ' + 'This indicates a failure in the build process. ' + 'There is likely additional information above.', ); process.exit(1); } else { next(); } }); }
[ "function", "checkThatExecutableExists", "(", "next", ")", "{", "fs", ".", "exists", "(", "nodeCompiler", ".", "releasePath", ",", "function", "(", "exists", ")", "{", "if", "(", "!", "exists", ")", "{", "_log", "(", "'error'", ",", "'The release executable has not been generated. '", "+", "'This indicates a failure in the build process. '", "+", "'There is likely additional information above.'", ",", ")", ";", "process", ".", "exit", "(", "1", ")", ";", "}", "else", "{", "next", "(", ")", ";", "}", "}", ")", ";", "}" ]
Verify that the executable was compiled successfully
[ "Verify", "that", "the", "executable", "was", "compiled", "successfully" ]
345bacd2c36f9648b416f74d2e41cdf55c2cc1f9
https://github.com/anmonteiro/lumo/blob/345bacd2c36f9648b416f74d2e41cdf55c2cc1f9/vendor/nexe/exe.js#L286-L300
13,140
anmonteiro/lumo
vendor/nexe/exe.js
copyBinaryToOutput
function copyBinaryToOutput(next) { _log('cp %s %s', nodeCompiler.releasePath, options.output); ncp(nodeCompiler.releasePath, options.output, function(err) { if (err) { _log('error', "Couldn't copy binary."); throw err; // dump raw error object } _log('copied'); next(); }); }
javascript
function copyBinaryToOutput(next) { _log('cp %s %s', nodeCompiler.releasePath, options.output); ncp(nodeCompiler.releasePath, options.output, function(err) { if (err) { _log('error', "Couldn't copy binary."); throw err; // dump raw error object } _log('copied'); next(); }); }
[ "function", "copyBinaryToOutput", "(", "next", ")", "{", "_log", "(", "'cp %s %s'", ",", "nodeCompiler", ".", "releasePath", ",", "options", ".", "output", ")", ";", "ncp", "(", "nodeCompiler", ".", "releasePath", ",", "options", ".", "output", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "_log", "(", "'error'", ",", "\"Couldn't copy binary.\"", ")", ";", "throw", "err", ";", "// dump raw error object", "}", "_log", "(", "'copied'", ")", ";", "next", "(", ")", ";", "}", ")", ";", "}" ]
Copy the compilied binary to the output specified.
[ "Copy", "the", "compilied", "binary", "to", "the", "output", "specified", "." ]
345bacd2c36f9648b416f74d2e41cdf55c2cc1f9
https://github.com/anmonteiro/lumo/blob/345bacd2c36f9648b416f74d2e41cdf55c2cc1f9/vendor/nexe/exe.js#L306-L317
13,141
anmonteiro/lumo
vendor/nexe/exe.js
downloadNode
function downloadNode(next) { if (fs.existsSync(nodeFilePath)) return next(); var uri = framework; if (framework === 'node') { uri = 'nodejs'; // if node, use nodejs uri } else if (framework === 'nodejs') { framework = 'node'; // support nodejs, and node, as framework. } var type = global.type; var url, prefix = 'https://' + uri + '.org/dist'; if (version === 'latest') { url = prefix + '/' + framework + '-' + version + '.tar.gz'; } else { url = prefix + '/v' + version + '/' + framework + '-v' + version + '.tar.gz'; } _log('downloading %s', url); var output = fs.createWriteStream(nodeFilePath, { flags: 'w+', }); // need to set user-agent to bypass some corporate firewalls var requestOptions = { url: url, headers: { 'User-Agent': 'Node.js', }, }; _logProgress(request(requestOptions)).pipe(output); output.on('close', function() { next(); }); }
javascript
function downloadNode(next) { if (fs.existsSync(nodeFilePath)) return next(); var uri = framework; if (framework === 'node') { uri = 'nodejs'; // if node, use nodejs uri } else if (framework === 'nodejs') { framework = 'node'; // support nodejs, and node, as framework. } var type = global.type; var url, prefix = 'https://' + uri + '.org/dist'; if (version === 'latest') { url = prefix + '/' + framework + '-' + version + '.tar.gz'; } else { url = prefix + '/v' + version + '/' + framework + '-v' + version + '.tar.gz'; } _log('downloading %s', url); var output = fs.createWriteStream(nodeFilePath, { flags: 'w+', }); // need to set user-agent to bypass some corporate firewalls var requestOptions = { url: url, headers: { 'User-Agent': 'Node.js', }, }; _logProgress(request(requestOptions)).pipe(output); output.on('close', function() { next(); }); }
[ "function", "downloadNode", "(", "next", ")", "{", "if", "(", "fs", ".", "existsSync", "(", "nodeFilePath", ")", ")", "return", "next", "(", ")", ";", "var", "uri", "=", "framework", ";", "if", "(", "framework", "===", "'node'", ")", "{", "uri", "=", "'nodejs'", ";", "// if node, use nodejs uri", "}", "else", "if", "(", "framework", "===", "'nodejs'", ")", "{", "framework", "=", "'node'", ";", "// support nodejs, and node, as framework.", "}", "var", "type", "=", "global", ".", "type", ";", "var", "url", ",", "prefix", "=", "'https://'", "+", "uri", "+", "'.org/dist'", ";", "if", "(", "version", "===", "'latest'", ")", "{", "url", "=", "prefix", "+", "'/'", "+", "framework", "+", "'-'", "+", "version", "+", "'.tar.gz'", ";", "}", "else", "{", "url", "=", "prefix", "+", "'/v'", "+", "version", "+", "'/'", "+", "framework", "+", "'-v'", "+", "version", "+", "'.tar.gz'", ";", "}", "_log", "(", "'downloading %s'", ",", "url", ")", ";", "var", "output", "=", "fs", ".", "createWriteStream", "(", "nodeFilePath", ",", "{", "flags", ":", "'w+'", ",", "}", ")", ";", "// need to set user-agent to bypass some corporate firewalls", "var", "requestOptions", "=", "{", "url", ":", "url", ",", "headers", ":", "{", "'User-Agent'", ":", "'Node.js'", ",", "}", ",", "}", ";", "_logProgress", "(", "request", "(", "requestOptions", ")", ")", ".", "pipe", "(", "output", ")", ";", "output", ".", "on", "(", "'close'", ",", "function", "(", ")", "{", "next", "(", ")", ";", "}", ")", ";", "}" ]
download node into the target directory
[ "download", "node", "into", "the", "target", "directory" ]
345bacd2c36f9648b416f74d2e41cdf55c2cc1f9
https://github.com/anmonteiro/lumo/blob/345bacd2c36f9648b416f74d2e41cdf55c2cc1f9/vendor/nexe/exe.js#L372-L420
13,142
anmonteiro/lumo
vendor/nexe/exe.js
unzipNodeTarball
function unzipNodeTarball(next) { var onError = function(err) { console.log(err.stack); _log('error', 'failed to extract the node source'); process.exit(1); }; if (isWin) { _log('extracting the node source [node-tar.gz]'); // tar-stream method w/ gunzip-maybe var read = fs.createReadStream(nodeFilePath); var extract = tarstream.extract(); var basedir = nodeFileDir; if (!fs.existsSync(nodeFileDir)) { fs.mkdirSync(nodeFileDir); } extract.on('entry', function(header, stream, callback) { // header is the tar header // stream is the content body (might be an empty stream) // call next when you are done with this entry var absolutepath = path.join(basedir, header.name); if (header.type === 'directory') { // handle directories. // console.log('dir:', header.name); fs.mkdirSync(absolutepath); return callback(); } else if (header.type === 'file') { // handle files // console.log('file:', header.name); } else { console.log(header.type + ':', header.name); _log('warn', 'unhandled type in tar extraction, skipping'); return callback(); } var write = fs.createWriteStream(absolutepath); stream.pipe(write); write.on('close', function() { return callback(); }); stream.on('error', function(err) { return onError(err); }); write.on('error', function(err) { return onError(err); }); stream.resume(); // just auto drain the stream }); extract.on('finish', function() { _log('extraction finished'); return next(); }); read.pipe(gunzip()).pipe(extract); } else { _log('extracting the node source [native tar]'); var cmd = ['tar', '-xf', nodeFilePath, '-C', nodeFileDir]; _log(cmd.join(' ')); var tar = spawn(cmd.shift(), cmd); tar.stdout.pipe(process.stdout); tar.stderr.pipe(process.stderr); tar.on('close', function() { return next(); }); tar.on('error', onError); } }
javascript
function unzipNodeTarball(next) { var onError = function(err) { console.log(err.stack); _log('error', 'failed to extract the node source'); process.exit(1); }; if (isWin) { _log('extracting the node source [node-tar.gz]'); // tar-stream method w/ gunzip-maybe var read = fs.createReadStream(nodeFilePath); var extract = tarstream.extract(); var basedir = nodeFileDir; if (!fs.existsSync(nodeFileDir)) { fs.mkdirSync(nodeFileDir); } extract.on('entry', function(header, stream, callback) { // header is the tar header // stream is the content body (might be an empty stream) // call next when you are done with this entry var absolutepath = path.join(basedir, header.name); if (header.type === 'directory') { // handle directories. // console.log('dir:', header.name); fs.mkdirSync(absolutepath); return callback(); } else if (header.type === 'file') { // handle files // console.log('file:', header.name); } else { console.log(header.type + ':', header.name); _log('warn', 'unhandled type in tar extraction, skipping'); return callback(); } var write = fs.createWriteStream(absolutepath); stream.pipe(write); write.on('close', function() { return callback(); }); stream.on('error', function(err) { return onError(err); }); write.on('error', function(err) { return onError(err); }); stream.resume(); // just auto drain the stream }); extract.on('finish', function() { _log('extraction finished'); return next(); }); read.pipe(gunzip()).pipe(extract); } else { _log('extracting the node source [native tar]'); var cmd = ['tar', '-xf', nodeFilePath, '-C', nodeFileDir]; _log(cmd.join(' ')); var tar = spawn(cmd.shift(), cmd); tar.stdout.pipe(process.stdout); tar.stderr.pipe(process.stderr); tar.on('close', function() { return next(); }); tar.on('error', onError); } }
[ "function", "unzipNodeTarball", "(", "next", ")", "{", "var", "onError", "=", "function", "(", "err", ")", "{", "console", ".", "log", "(", "err", ".", "stack", ")", ";", "_log", "(", "'error'", ",", "'failed to extract the node source'", ")", ";", "process", ".", "exit", "(", "1", ")", ";", "}", ";", "if", "(", "isWin", ")", "{", "_log", "(", "'extracting the node source [node-tar.gz]'", ")", ";", "// tar-stream method w/ gunzip-maybe", "var", "read", "=", "fs", ".", "createReadStream", "(", "nodeFilePath", ")", ";", "var", "extract", "=", "tarstream", ".", "extract", "(", ")", ";", "var", "basedir", "=", "nodeFileDir", ";", "if", "(", "!", "fs", ".", "existsSync", "(", "nodeFileDir", ")", ")", "{", "fs", ".", "mkdirSync", "(", "nodeFileDir", ")", ";", "}", "extract", ".", "on", "(", "'entry'", ",", "function", "(", "header", ",", "stream", ",", "callback", ")", "{", "// header is the tar header", "// stream is the content body (might be an empty stream)", "// call next when you are done with this entry", "var", "absolutepath", "=", "path", ".", "join", "(", "basedir", ",", "header", ".", "name", ")", ";", "if", "(", "header", ".", "type", "===", "'directory'", ")", "{", "// handle directories.", "// console.log('dir:', header.name);", "fs", ".", "mkdirSync", "(", "absolutepath", ")", ";", "return", "callback", "(", ")", ";", "}", "else", "if", "(", "header", ".", "type", "===", "'file'", ")", "{", "// handle files", "// console.log('file:', header.name);", "}", "else", "{", "console", ".", "log", "(", "header", ".", "type", "+", "':'", ",", "header", ".", "name", ")", ";", "_log", "(", "'warn'", ",", "'unhandled type in tar extraction, skipping'", ")", ";", "return", "callback", "(", ")", ";", "}", "var", "write", "=", "fs", ".", "createWriteStream", "(", "absolutepath", ")", ";", "stream", ".", "pipe", "(", "write", ")", ";", "write", ".", "on", "(", "'close'", ",", "function", "(", ")", "{", "return", "callback", "(", ")", ";", "}", ")", ";", "stream", ".", "on", "(", "'error'", ",", "function", "(", "err", ")", "{", "return", "onError", "(", "err", ")", ";", "}", ")", ";", "write", ".", "on", "(", "'error'", ",", "function", "(", "err", ")", "{", "return", "onError", "(", "err", ")", ";", "}", ")", ";", "stream", ".", "resume", "(", ")", ";", "// just auto drain the stream", "}", ")", ";", "extract", ".", "on", "(", "'finish'", ",", "function", "(", ")", "{", "_log", "(", "'extraction finished'", ")", ";", "return", "next", "(", ")", ";", "}", ")", ";", "read", ".", "pipe", "(", "gunzip", "(", ")", ")", ".", "pipe", "(", "extract", ")", ";", "}", "else", "{", "_log", "(", "'extracting the node source [native tar]'", ")", ";", "var", "cmd", "=", "[", "'tar'", ",", "'-xf'", ",", "nodeFilePath", ",", "'-C'", ",", "nodeFileDir", "]", ";", "_log", "(", "cmd", ".", "join", "(", "' '", ")", ")", ";", "var", "tar", "=", "spawn", "(", "cmd", ".", "shift", "(", ")", ",", "cmd", ")", ";", "tar", ".", "stdout", ".", "pipe", "(", "process", ".", "stdout", ")", ";", "tar", ".", "stderr", ".", "pipe", "(", "process", ".", "stderr", ")", ";", "tar", ".", "on", "(", "'close'", ",", "function", "(", ")", "{", "return", "next", "(", ")", ";", "}", ")", ";", "tar", ".", "on", "(", "'error'", ",", "onError", ")", ";", "}", "}" ]
unzip in the same directory
[ "unzip", "in", "the", "same", "directory" ]
345bacd2c36f9648b416f74d2e41cdf55c2cc1f9
https://github.com/anmonteiro/lumo/blob/345bacd2c36f9648b416f74d2e41cdf55c2cc1f9/vendor/nexe/exe.js#L426-L505
13,143
anmonteiro/lumo
vendor/nexe/exe.js
_loop
function _loop(dir) { /* eventually try every python file */ var pdir = fs.readdirSync(dir); pdir.forEach(function(v, i) { var stat = fs.statSync(dir + '/' + v); if (stat.isFile()) { // only process Makefiles and .mk targets. if (v !== 'Makefile' && path.extname(v) !== '.mk') { return; } _log('patching ' + v); /* patch the file */ var py = fs.readFileSync(dir + '/' + v, { encoding: 'utf8', }); py = py.replace(/([a-z]|\/)*python(\w|)/gm, isPy); // this is definently needed fs.writeFileSync(dir + '/' + v, py, { encoding: 'utf8', }); // write to file } else if (stat.isDirectory()) { // must be dir? // skip tests because we don't need them here if (v !== 'test') { _loop(dir + '/' + v); } } }); }
javascript
function _loop(dir) { /* eventually try every python file */ var pdir = fs.readdirSync(dir); pdir.forEach(function(v, i) { var stat = fs.statSync(dir + '/' + v); if (stat.isFile()) { // only process Makefiles and .mk targets. if (v !== 'Makefile' && path.extname(v) !== '.mk') { return; } _log('patching ' + v); /* patch the file */ var py = fs.readFileSync(dir + '/' + v, { encoding: 'utf8', }); py = py.replace(/([a-z]|\/)*python(\w|)/gm, isPy); // this is definently needed fs.writeFileSync(dir + '/' + v, py, { encoding: 'utf8', }); // write to file } else if (stat.isDirectory()) { // must be dir? // skip tests because we don't need them here if (v !== 'test') { _loop(dir + '/' + v); } } }); }
[ "function", "_loop", "(", "dir", ")", "{", "/* eventually try every python file */", "var", "pdir", "=", "fs", ".", "readdirSync", "(", "dir", ")", ";", "pdir", ".", "forEach", "(", "function", "(", "v", ",", "i", ")", "{", "var", "stat", "=", "fs", ".", "statSync", "(", "dir", "+", "'/'", "+", "v", ")", ";", "if", "(", "stat", ".", "isFile", "(", ")", ")", "{", "// only process Makefiles and .mk targets.", "if", "(", "v", "!==", "'Makefile'", "&&", "path", ".", "extname", "(", "v", ")", "!==", "'.mk'", ")", "{", "return", ";", "}", "_log", "(", "'patching '", "+", "v", ")", ";", "/* patch the file */", "var", "py", "=", "fs", ".", "readFileSync", "(", "dir", "+", "'/'", "+", "v", ",", "{", "encoding", ":", "'utf8'", ",", "}", ")", ";", "py", "=", "py", ".", "replace", "(", "/", "([a-z]|\\/)*python(\\w|)", "/", "gm", ",", "isPy", ")", ";", "// this is definently needed", "fs", ".", "writeFileSync", "(", "dir", "+", "'/'", "+", "v", ",", "py", ",", "{", "encoding", ":", "'utf8'", ",", "}", ")", ";", "// write to file", "}", "else", "if", "(", "stat", ".", "isDirectory", "(", ")", ")", "{", "// must be dir?", "// skip tests because we don't need them here", "if", "(", "v", "!==", "'test'", ")", "{", "_loop", "(", "dir", "+", "'/'", "+", "v", ")", ";", "}", "}", "}", ")", ";", "}" ]
local function, move to top eventually
[ "local", "function", "move", "to", "top", "eventually" ]
345bacd2c36f9648b416f74d2e41cdf55c2cc1f9
https://github.com/anmonteiro/lumo/blob/345bacd2c36f9648b416f74d2e41cdf55c2cc1f9/vendor/nexe/exe.js#L602-L632
13,144
anmonteiro/lumo
vendor/nexe/exe.js
_monkeyPatchGyp
function _monkeyPatchGyp(compiler, options, complete) { const hasNexeres = options.resourceFiles.length > 0; const gypPath = path.join(compiler.dir, 'node.gyp'); let replacementString = "'lib/fs.js', 'lib/_third_party_main.js', "; if (hasNexeres) { replacementString += "'lib/nexeres.js', "; } _monkeypatch( gypPath, function(content) { return ~content.indexOf('lib/_third_party_main.js'); }, function(content, next) { content = content.replace("'lib/fs.js',", replacementString); content = content.replace( "'deps/node-inspect/lib/internal/inspect_repl.js',", `'deps/node-inspect/lib/internal/inspect_repl.js', 'google-closure-compiler-js.js',`, ); next(null, content); }, complete, ); }
javascript
function _monkeyPatchGyp(compiler, options, complete) { const hasNexeres = options.resourceFiles.length > 0; const gypPath = path.join(compiler.dir, 'node.gyp'); let replacementString = "'lib/fs.js', 'lib/_third_party_main.js', "; if (hasNexeres) { replacementString += "'lib/nexeres.js', "; } _monkeypatch( gypPath, function(content) { return ~content.indexOf('lib/_third_party_main.js'); }, function(content, next) { content = content.replace("'lib/fs.js',", replacementString); content = content.replace( "'deps/node-inspect/lib/internal/inspect_repl.js',", `'deps/node-inspect/lib/internal/inspect_repl.js', 'google-closure-compiler-js.js',`, ); next(null, content); }, complete, ); }
[ "function", "_monkeyPatchGyp", "(", "compiler", ",", "options", ",", "complete", ")", "{", "const", "hasNexeres", "=", "options", ".", "resourceFiles", ".", "length", ">", "0", ";", "const", "gypPath", "=", "path", ".", "join", "(", "compiler", ".", "dir", ",", "'node.gyp'", ")", ";", "let", "replacementString", "=", "\"'lib/fs.js', 'lib/_third_party_main.js', \"", ";", "if", "(", "hasNexeres", ")", "{", "replacementString", "+=", "\"'lib/nexeres.js', \"", ";", "}", "_monkeypatch", "(", "gypPath", ",", "function", "(", "content", ")", "{", "return", "~", "content", ".", "indexOf", "(", "'lib/_third_party_main.js'", ")", ";", "}", ",", "function", "(", "content", ",", "next", ")", "{", "content", "=", "content", ".", "replace", "(", "\"'lib/fs.js',\"", ",", "replacementString", ")", ";", "content", "=", "content", ".", "replace", "(", "\"'deps/node-inspect/lib/internal/inspect_repl.js',\"", ",", "`", "`", ",", ")", ";", "next", "(", "null", ",", "content", ")", ";", "}", ",", "complete", ",", ")", ";", "}" ]
patch the gyp file to allow our custom includes
[ "patch", "the", "gyp", "file", "to", "allow", "our", "custom", "includes" ]
345bacd2c36f9648b416f74d2e41cdf55c2cc1f9
https://github.com/anmonteiro/lumo/blob/345bacd2c36f9648b416f74d2e41cdf55c2cc1f9/vendor/nexe/exe.js#L758-L784
13,145
anmonteiro/lumo
vendor/nexe/exe.js
_monkeyPatchConfigure
function _monkeyPatchConfigure(compiler, complete, options) { var configurePath = path.join(compiler.dir, 'configure.py'); var snapshotPath = options.startupSnapshot; if (snapshotPath != null) { _log('monkey patching configure file'); snapshotPath = path.join(process.cwd(), snapshotPath); return _monkeypatch( configurePath, function(content) { return ~content.indexOf('v8_embed_script'); }, function(content, next) { next( null, content.replace( 'def configure_v8(o):', `def configure_v8(o): o['variables']['v8_embed_script'] = r'${snapshotPath}' o['variables']['v8_warmup_script'] = r'${snapshotPath}'`, ), ); }, complete, ); } else { _log('not patching configure file'); } return complete(); }
javascript
function _monkeyPatchConfigure(compiler, complete, options) { var configurePath = path.join(compiler.dir, 'configure.py'); var snapshotPath = options.startupSnapshot; if (snapshotPath != null) { _log('monkey patching configure file'); snapshotPath = path.join(process.cwd(), snapshotPath); return _monkeypatch( configurePath, function(content) { return ~content.indexOf('v8_embed_script'); }, function(content, next) { next( null, content.replace( 'def configure_v8(o):', `def configure_v8(o): o['variables']['v8_embed_script'] = r'${snapshotPath}' o['variables']['v8_warmup_script'] = r'${snapshotPath}'`, ), ); }, complete, ); } else { _log('not patching configure file'); } return complete(); }
[ "function", "_monkeyPatchConfigure", "(", "compiler", ",", "complete", ",", "options", ")", "{", "var", "configurePath", "=", "path", ".", "join", "(", "compiler", ".", "dir", ",", "'configure.py'", ")", ";", "var", "snapshotPath", "=", "options", ".", "startupSnapshot", ";", "if", "(", "snapshotPath", "!=", "null", ")", "{", "_log", "(", "'monkey patching configure file'", ")", ";", "snapshotPath", "=", "path", ".", "join", "(", "process", ".", "cwd", "(", ")", ",", "snapshotPath", ")", ";", "return", "_monkeypatch", "(", "configurePath", ",", "function", "(", "content", ")", "{", "return", "~", "content", ".", "indexOf", "(", "'v8_embed_script'", ")", ";", "}", ",", "function", "(", "content", ",", "next", ")", "{", "next", "(", "null", ",", "content", ".", "replace", "(", "'def configure_v8(o):'", ",", "`", "${", "snapshotPath", "}", "${", "snapshotPath", "}", "`", ",", ")", ",", ")", ";", "}", ",", "complete", ",", ")", ";", "}", "else", "{", "_log", "(", "'not patching configure file'", ")", ";", "}", "return", "complete", "(", ")", ";", "}" ]
patch the configure file to allow for custom startup snapshots
[ "patch", "the", "configure", "file", "to", "allow", "for", "custom", "startup", "snapshots" ]
345bacd2c36f9648b416f74d2e41cdf55c2cc1f9
https://github.com/anmonteiro/lumo/blob/345bacd2c36f9648b416f74d2e41cdf55c2cc1f9/vendor/nexe/exe.js#L810-L840
13,146
anmonteiro/lumo
vendor/nexe/exe.js
_monkeyPatchMainCc
function _monkeyPatchMainCc(compiler, complete) { let finalContents; let mainPath = path.join(compiler.dir, 'src', 'node.cc'); let mainC = fs.readFileSync(mainPath, { encoding: 'utf8', }); // content split, and original start/end let constant_loc = 1; let lines = mainC.split('\n'); let startLine = lines.indexOf(' // TODO use parse opts'); let endLine = lines.indexOf(' option_end_index = i;'); // pre node 0.11.6 compat let isPatched = lines.indexOf('// NEXE_PATCH_IGNOREFLAGS'); if (isPatched !== -1) { _log('already patched node.cc'); return complete(); } /** * This is the new method of passing the args. Tested on node.js 0.12.5 * and iojs 2.3.1 **/ if (endLine === -1 && startLine === -1) { // only if the pre-0.12.5 failed. _log('using the after 0.12.5 method of ignoring flags.'); startLine = lines.indexOf( " while (index < nargs && argv[index][0] == '-') {", ); // beginning of the function endLine = lines.indexOf(' // Copy remaining arguments.'); endLine--; // space, then it's at the } constant_loc = lines.length + 1; } else { _log('using 0.10.x > method of ignoring flags'); lines[endLine] = ' option_end_index = 1;'; } /** * This is the method for 5.5.0 **/ if (endLine === -1 || startLine === -1) { _log('using the after 5.5.0 method of ignoring flags.'); startLine = lines.indexOf( " while (index < nargs && argv[index][0] == '-' && !short_circuit) {", ); // beginning of the function endLine = lines.indexOf(' // Copy remaining arguments.'); endLine--; // space, then it's at the } constant_loc = lines.length + 1; } // other versions here. if (endLine === -1 || startLine === -1) { // failsafe. _log('error', 'Failed to find a way to patch node.cc to ignoreFlags'); _log('startLine =', startLine, '| endLine =', endLine); if (!/^1(1|2)\./.test(compiler.version)) { process.exit(1); } } // check if it's been done lines[constant_loc] = '// NEXE_PATCH_IGNOREFLAGS'; for (var i = startLine; i < endLine; i++) { lines[i] = undefined; // set the value to undefined so it's skipped by the join } _log('patched node.cc'); finalContents = lines.join('\n'); // write the file contents fs.writeFile( mainPath, finalContents, { encoding: 'utf8', }, function(err) { if (err) { _log('error', 'failed to write to', mainPath); return process.exit(1); } return complete(); }, ); }
javascript
function _monkeyPatchMainCc(compiler, complete) { let finalContents; let mainPath = path.join(compiler.dir, 'src', 'node.cc'); let mainC = fs.readFileSync(mainPath, { encoding: 'utf8', }); // content split, and original start/end let constant_loc = 1; let lines = mainC.split('\n'); let startLine = lines.indexOf(' // TODO use parse opts'); let endLine = lines.indexOf(' option_end_index = i;'); // pre node 0.11.6 compat let isPatched = lines.indexOf('// NEXE_PATCH_IGNOREFLAGS'); if (isPatched !== -1) { _log('already patched node.cc'); return complete(); } /** * This is the new method of passing the args. Tested on node.js 0.12.5 * and iojs 2.3.1 **/ if (endLine === -1 && startLine === -1) { // only if the pre-0.12.5 failed. _log('using the after 0.12.5 method of ignoring flags.'); startLine = lines.indexOf( " while (index < nargs && argv[index][0] == '-') {", ); // beginning of the function endLine = lines.indexOf(' // Copy remaining arguments.'); endLine--; // space, then it's at the } constant_loc = lines.length + 1; } else { _log('using 0.10.x > method of ignoring flags'); lines[endLine] = ' option_end_index = 1;'; } /** * This is the method for 5.5.0 **/ if (endLine === -1 || startLine === -1) { _log('using the after 5.5.0 method of ignoring flags.'); startLine = lines.indexOf( " while (index < nargs && argv[index][0] == '-' && !short_circuit) {", ); // beginning of the function endLine = lines.indexOf(' // Copy remaining arguments.'); endLine--; // space, then it's at the } constant_loc = lines.length + 1; } // other versions here. if (endLine === -1 || startLine === -1) { // failsafe. _log('error', 'Failed to find a way to patch node.cc to ignoreFlags'); _log('startLine =', startLine, '| endLine =', endLine); if (!/^1(1|2)\./.test(compiler.version)) { process.exit(1); } } // check if it's been done lines[constant_loc] = '// NEXE_PATCH_IGNOREFLAGS'; for (var i = startLine; i < endLine; i++) { lines[i] = undefined; // set the value to undefined so it's skipped by the join } _log('patched node.cc'); finalContents = lines.join('\n'); // write the file contents fs.writeFile( mainPath, finalContents, { encoding: 'utf8', }, function(err) { if (err) { _log('error', 'failed to write to', mainPath); return process.exit(1); } return complete(); }, ); }
[ "function", "_monkeyPatchMainCc", "(", "compiler", ",", "complete", ")", "{", "let", "finalContents", ";", "let", "mainPath", "=", "path", ".", "join", "(", "compiler", ".", "dir", ",", "'src'", ",", "'node.cc'", ")", ";", "let", "mainC", "=", "fs", ".", "readFileSync", "(", "mainPath", ",", "{", "encoding", ":", "'utf8'", ",", "}", ")", ";", "// content split, and original start/end", "let", "constant_loc", "=", "1", ";", "let", "lines", "=", "mainC", ".", "split", "(", "'\\n'", ")", ";", "let", "startLine", "=", "lines", ".", "indexOf", "(", "' // TODO use parse opts'", ")", ";", "let", "endLine", "=", "lines", ".", "indexOf", "(", "' option_end_index = i;'", ")", ";", "// pre node 0.11.6 compat", "let", "isPatched", "=", "lines", ".", "indexOf", "(", "'// NEXE_PATCH_IGNOREFLAGS'", ")", ";", "if", "(", "isPatched", "!==", "-", "1", ")", "{", "_log", "(", "'already patched node.cc'", ")", ";", "return", "complete", "(", ")", ";", "}", "/**\n * This is the new method of passing the args. Tested on node.js 0.12.5\n * and iojs 2.3.1\n **/", "if", "(", "endLine", "===", "-", "1", "&&", "startLine", "===", "-", "1", ")", "{", "// only if the pre-0.12.5 failed.", "_log", "(", "'using the after 0.12.5 method of ignoring flags.'", ")", ";", "startLine", "=", "lines", ".", "indexOf", "(", "\" while (index < nargs && argv[index][0] == '-') {\"", ",", ")", ";", "// beginning of the function", "endLine", "=", "lines", ".", "indexOf", "(", "' // Copy remaining arguments.'", ")", ";", "endLine", "--", ";", "// space, then it's at the }", "constant_loc", "=", "lines", ".", "length", "+", "1", ";", "}", "else", "{", "_log", "(", "'using 0.10.x > method of ignoring flags'", ")", ";", "lines", "[", "endLine", "]", "=", "' option_end_index = 1;'", ";", "}", "/**\n * This is the method for 5.5.0\n **/", "if", "(", "endLine", "===", "-", "1", "||", "startLine", "===", "-", "1", ")", "{", "_log", "(", "'using the after 5.5.0 method of ignoring flags.'", ")", ";", "startLine", "=", "lines", ".", "indexOf", "(", "\" while (index < nargs && argv[index][0] == '-' && !short_circuit) {\"", ",", ")", ";", "// beginning of the function", "endLine", "=", "lines", ".", "indexOf", "(", "' // Copy remaining arguments.'", ")", ";", "endLine", "--", ";", "// space, then it's at the }", "constant_loc", "=", "lines", ".", "length", "+", "1", ";", "}", "// other versions here.", "if", "(", "endLine", "===", "-", "1", "||", "startLine", "===", "-", "1", ")", "{", "// failsafe.", "_log", "(", "'error'", ",", "'Failed to find a way to patch node.cc to ignoreFlags'", ")", ";", "_log", "(", "'startLine ='", ",", "startLine", ",", "'| endLine ='", ",", "endLine", ")", ";", "if", "(", "!", "/", "^1(1|2)\\.", "/", ".", "test", "(", "compiler", ".", "version", ")", ")", "{", "process", ".", "exit", "(", "1", ")", ";", "}", "}", "// check if it's been done", "lines", "[", "constant_loc", "]", "=", "'// NEXE_PATCH_IGNOREFLAGS'", ";", "for", "(", "var", "i", "=", "startLine", ";", "i", "<", "endLine", ";", "i", "++", ")", "{", "lines", "[", "i", "]", "=", "undefined", ";", "// set the value to undefined so it's skipped by the join", "}", "_log", "(", "'patched node.cc'", ")", ";", "finalContents", "=", "lines", ".", "join", "(", "'\\n'", ")", ";", "// write the file contents", "fs", ".", "writeFile", "(", "mainPath", ",", "finalContents", ",", "{", "encoding", ":", "'utf8'", ",", "}", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "_log", "(", "'error'", ",", "'failed to write to'", ",", "mainPath", ")", ";", "return", "process", ".", "exit", "(", "1", ")", ";", "}", "return", "complete", "(", ")", ";", "}", ",", ")", ";", "}" ]
Patch node.cc to not check the internal arguments.
[ "Patch", "node", ".", "cc", "to", "not", "check", "the", "internal", "arguments", "." ]
345bacd2c36f9648b416f74d2e41cdf55c2cc1f9
https://github.com/anmonteiro/lumo/blob/345bacd2c36f9648b416f74d2e41cdf55c2cc1f9/vendor/nexe/exe.js#L846-L938
13,147
anmonteiro/lumo
vendor/nexe/exe.js
_getFirstDirectory
function _getFirstDirectory(dir) { var files = glob.sync(dir + '/*'); for (var i = files.length; i--; ) { var file = files[i]; if (fs.statSync(file).isDirectory()) return file; } return false; }
javascript
function _getFirstDirectory(dir) { var files = glob.sync(dir + '/*'); for (var i = files.length; i--; ) { var file = files[i]; if (fs.statSync(file).isDirectory()) return file; } return false; }
[ "function", "_getFirstDirectory", "(", "dir", ")", "{", "var", "files", "=", "glob", ".", "sync", "(", "dir", "+", "'/*'", ")", ";", "for", "(", "var", "i", "=", "files", ".", "length", ";", "i", "--", ";", ")", "{", "var", "file", "=", "files", "[", "i", "]", ";", "if", "(", "fs", ".", "statSync", "(", "file", ")", ".", "isDirectory", "(", ")", ")", "return", "file", ";", "}", "return", "false", ";", "}" ]
Get the first directory of a string.
[ "Get", "the", "first", "directory", "of", "a", "string", "." ]
345bacd2c36f9648b416f74d2e41cdf55c2cc1f9
https://github.com/anmonteiro/lumo/blob/345bacd2c36f9648b416f74d2e41cdf55c2cc1f9/vendor/nexe/exe.js#L1078-L1087
13,148
anmonteiro/lumo
vendor/nexe/exe.js
_logProgress
function _logProgress(req) { req.on('response', function(resp) { var len = parseInt(resp.headers['content-length'], 10), bar = new ProgressBar('[:bar]', { complete: '=', incomplete: ' ', total: len, width: 100, // just use 100 }); req.on('data', function(chunk) { bar.tick(chunk.length); }); }); req.on('error', function(err) { console.log(err); _log('error', 'failed to download node sources,'); process.exit(1); }); return req; }
javascript
function _logProgress(req) { req.on('response', function(resp) { var len = parseInt(resp.headers['content-length'], 10), bar = new ProgressBar('[:bar]', { complete: '=', incomplete: ' ', total: len, width: 100, // just use 100 }); req.on('data', function(chunk) { bar.tick(chunk.length); }); }); req.on('error', function(err) { console.log(err); _log('error', 'failed to download node sources,'); process.exit(1); }); return req; }
[ "function", "_logProgress", "(", "req", ")", "{", "req", ".", "on", "(", "'response'", ",", "function", "(", "resp", ")", "{", "var", "len", "=", "parseInt", "(", "resp", ".", "headers", "[", "'content-length'", "]", ",", "10", ")", ",", "bar", "=", "new", "ProgressBar", "(", "'[:bar]'", ",", "{", "complete", ":", "'='", ",", "incomplete", ":", "' '", ",", "total", ":", "len", ",", "width", ":", "100", ",", "// just use 100", "}", ")", ";", "req", ".", "on", "(", "'data'", ",", "function", "(", "chunk", ")", "{", "bar", ".", "tick", "(", "chunk", ".", "length", ")", ";", "}", ")", ";", "}", ")", ";", "req", ".", "on", "(", "'error'", ",", "function", "(", "err", ")", "{", "console", ".", "log", "(", "err", ")", ";", "_log", "(", "'error'", ",", "'failed to download node sources,'", ")", ";", "process", ".", "exit", "(", "1", ")", ";", "}", ")", ";", "return", "req", ";", "}" ]
Log the progress of a request object.
[ "Log", "the", "progress", "of", "a", "request", "object", "." ]
345bacd2c36f9648b416f74d2e41cdf55c2cc1f9
https://github.com/anmonteiro/lumo/blob/345bacd2c36f9648b416f74d2e41cdf55c2cc1f9/vendor/nexe/exe.js#L1093-L1115
13,149
sequelize/umzug
src/helper.js
function (packageName) { let result; try { result = require.resolve(packageName, { basedir: process.cwd() }); result = require(result); } catch (e) { try { result = require(packageName); } catch (e) { result = undefined; } } return result; }
javascript
function (packageName) { let result; try { result = require.resolve(packageName, { basedir: process.cwd() }); result = require(result); } catch (e) { try { result = require(packageName); } catch (e) { result = undefined; } } return result; }
[ "function", "(", "packageName", ")", "{", "let", "result", ";", "try", "{", "result", "=", "require", ".", "resolve", "(", "packageName", ",", "{", "basedir", ":", "process", ".", "cwd", "(", ")", "}", ")", ";", "result", "=", "require", "(", "result", ")", ";", "}", "catch", "(", "e", ")", "{", "try", "{", "result", "=", "require", "(", "packageName", ")", ";", "}", "catch", "(", "e", ")", "{", "result", "=", "undefined", ";", "}", "}", "return", "result", ";", "}" ]
Try to require module from file relative to process cwd or regular require. @param {string} packageName - Filename relative to process' cwd or package name to be required. @returns {*|undefined} Required module
[ "Try", "to", "require", "module", "from", "file", "relative", "to", "process", "cwd", "or", "regular", "require", "." ]
ebb08d65d5365a77d54b68eb87e2cc1249cb727a
https://github.com/sequelize/umzug/blob/ebb08d65d5365a77d54b68eb87e2cc1249cb727a/src/helper.js#L9-L24
13,150
openlayers/ol-mapbox-style
webpack.config.js
getExamples
function getExamples(dirName, callback) { const example_files = fs.readdirSync(dirName); const entries = {}; // iterate through the list of files in the directory. for (const filename of example_files) { // ooo, javascript file! if (filename.endsWith('.js')) { // trim the entry name down to the file without the extension. const entry_name = filename.split('.')[0]; callback(entry_name, path.join(dirName, filename)); } } return entries; }
javascript
function getExamples(dirName, callback) { const example_files = fs.readdirSync(dirName); const entries = {}; // iterate through the list of files in the directory. for (const filename of example_files) { // ooo, javascript file! if (filename.endsWith('.js')) { // trim the entry name down to the file without the extension. const entry_name = filename.split('.')[0]; callback(entry_name, path.join(dirName, filename)); } } return entries; }
[ "function", "getExamples", "(", "dirName", ",", "callback", ")", "{", "const", "example_files", "=", "fs", ".", "readdirSync", "(", "dirName", ")", ";", "const", "entries", "=", "{", "}", ";", "// iterate through the list of files in the directory.", "for", "(", "const", "filename", "of", "example_files", ")", "{", "// ooo, javascript file!", "if", "(", "filename", ".", "endsWith", "(", "'.js'", ")", ")", "{", "// trim the entry name down to the file without the extension.", "const", "entry_name", "=", "filename", ".", "split", "(", "'.'", ")", "[", "0", "]", ";", "callback", "(", "entry_name", ",", "path", ".", "join", "(", "dirName", ",", "filename", ")", ")", ";", "}", "}", "return", "entries", ";", "}" ]
Get the list of examples from the example directory. @param {String} dirName - Name of the directory to read. @param {Function} callback - Function to execute for each example. @returns {undefined} Nothing.
[ "Get", "the", "list", "of", "examples", "from", "the", "example", "directory", "." ]
69f9032f98e7b11f17f581d6d4a6fdfcb4bea2db
https://github.com/openlayers/ol-mapbox-style/blob/69f9032f98e7b11f17f581d6d4a6fdfcb4bea2db/webpack.config.js#L14-L29
13,151
openlayers/ol-mapbox-style
webpack.config.js
getEntries
function getEntries(dirName) { const entries = {}; getExamples(dirName, (entryName, filename) => { entries[entryName] = filename; }); return entries; }
javascript
function getEntries(dirName) { const entries = {}; getExamples(dirName, (entryName, filename) => { entries[entryName] = filename; }); return entries; }
[ "function", "getEntries", "(", "dirName", ")", "{", "const", "entries", "=", "{", "}", ";", "getExamples", "(", "dirName", ",", "(", "entryName", ",", "filename", ")", "=>", "{", "entries", "[", "entryName", "]", "=", "filename", ";", "}", ")", ";", "return", "entries", ";", "}" ]
Creates an object with the entry names and file names to be transformed. @param {String} dirName - Name of the directory to read. @returns {Object} with webpack entry points.
[ "Creates", "an", "object", "with", "the", "entry", "names", "and", "file", "names", "to", "be", "transformed", "." ]
69f9032f98e7b11f17f581d6d4a6fdfcb4bea2db
https://github.com/openlayers/ol-mapbox-style/blob/69f9032f98e7b11f17f581d6d4a6fdfcb4bea2db/webpack.config.js#L38-L44
13,152
openlayers/ol-mapbox-style
webpack.config.js
getHtmlTemplates
function getHtmlTemplates(dirName) { const html_conf = []; // create the array of HTML plugins. const template = path.join(dirName, '_template.html'); getExamples(dirName, (entryName, filename) => { html_conf.push( new HtmlWebpackPlugin({ title: entryName, // ensure each output has a unique filename filename: entryName + '.html', template, // without specifying chunks, all chunks are // included with the file. chunks: ['common', entryName] }) ); }); return html_conf; }
javascript
function getHtmlTemplates(dirName) { const html_conf = []; // create the array of HTML plugins. const template = path.join(dirName, '_template.html'); getExamples(dirName, (entryName, filename) => { html_conf.push( new HtmlWebpackPlugin({ title: entryName, // ensure each output has a unique filename filename: entryName + '.html', template, // without specifying chunks, all chunks are // included with the file. chunks: ['common', entryName] }) ); }); return html_conf; }
[ "function", "getHtmlTemplates", "(", "dirName", ")", "{", "const", "html_conf", "=", "[", "]", ";", "// create the array of HTML plugins.", "const", "template", "=", "path", ".", "join", "(", "dirName", ",", "'_template.html'", ")", ";", "getExamples", "(", "dirName", ",", "(", "entryName", ",", "filename", ")", "=>", "{", "html_conf", ".", "push", "(", "new", "HtmlWebpackPlugin", "(", "{", "title", ":", "entryName", ",", "// ensure each output has a unique filename", "filename", ":", "entryName", "+", "'.html'", ",", "template", ",", "// without specifying chunks, all chunks are", "// included with the file.", "chunks", ":", "[", "'common'", ",", "entryName", "]", "}", ")", ")", ";", "}", ")", ";", "return", "html_conf", ";", "}" ]
Each example needs a dedicated HTML file. This will create a "plugin" that outputs HTML from a template. @param {String} dirName - Name of the directory to read. @returns {Array} specifying webpack plugins.
[ "Each", "example", "needs", "a", "dedicated", "HTML", "file", ".", "This", "will", "create", "a", "plugin", "that", "outputs", "HTML", "from", "a", "template", "." ]
69f9032f98e7b11f17f581d6d4a6fdfcb4bea2db
https://github.com/openlayers/ol-mapbox-style/blob/69f9032f98e7b11f17f581d6d4a6fdfcb4bea2db/webpack.config.js#L53-L71
13,153
leonidas/transparency
examples/todomvc/architecture-examples/backbone/js/views/app.js
function() { return { title: this.input.val().trim(), order: window.app.Todos.nextOrder(), completed: false }; }
javascript
function() { return { title: this.input.val().trim(), order: window.app.Todos.nextOrder(), completed: false }; }
[ "function", "(", ")", "{", "return", "{", "title", ":", "this", ".", "input", ".", "val", "(", ")", ".", "trim", "(", ")", ",", "order", ":", "window", ".", "app", ".", "Todos", ".", "nextOrder", "(", ")", ",", "completed", ":", "false", "}", ";", "}" ]
Generate the attributes for a new Todo item.
[ "Generate", "the", "attributes", "for", "a", "new", "Todo", "item", "." ]
92149b83e7202423a764e1cc2ec5d78e43f77ce2
https://github.com/leonidas/transparency/blob/92149b83e7202423a764e1cc2ec5d78e43f77ce2/examples/todomvc/architecture-examples/backbone/js/views/app.js#L99-L105
13,154
leonidas/transparency
examples/todomvc/architecture-examples/backbone/js/views/app.js
function() { _.each(window.app.Todos.completed(), function(todo){ todo.destroy(); }); return false; }
javascript
function() { _.each(window.app.Todos.completed(), function(todo){ todo.destroy(); }); return false; }
[ "function", "(", ")", "{", "_", ".", "each", "(", "window", ".", "app", ".", "Todos", ".", "completed", "(", ")", ",", "function", "(", "todo", ")", "{", "todo", ".", "destroy", "(", ")", ";", "}", ")", ";", "return", "false", ";", "}" ]
Clear all completed todo items, destroying their models.
[ "Clear", "all", "completed", "todo", "items", "destroying", "their", "models", "." ]
92149b83e7202423a764e1cc2ec5d78e43f77ce2
https://github.com/leonidas/transparency/blob/92149b83e7202423a764e1cc2ec5d78e43f77ce2/examples/todomvc/architecture-examples/backbone/js/views/app.js#L124-L127
13,155
socib/Leaflet.TimeDimension
examples/js/example15.js
function(feature, minTime, maxTime) { var featureStringTimes = this._getFeatureTimes(feature); if (featureStringTimes.length == 0) { return feature; } var featureTimes = []; for (var i = 0, l = featureStringTimes.length; i < l; i++) { var time = featureStringTimes[i] if (typeof time == 'string' || time instanceof String) { time = Date.parse(time.trim()); } featureTimes.push(time); } if (featureTimes[0] > maxTime || featureTimes[l - 1] < minTime) { return null; } return feature; }
javascript
function(feature, minTime, maxTime) { var featureStringTimes = this._getFeatureTimes(feature); if (featureStringTimes.length == 0) { return feature; } var featureTimes = []; for (var i = 0, l = featureStringTimes.length; i < l; i++) { var time = featureStringTimes[i] if (typeof time == 'string' || time instanceof String) { time = Date.parse(time.trim()); } featureTimes.push(time); } if (featureTimes[0] > maxTime || featureTimes[l - 1] < minTime) { return null; } return feature; }
[ "function", "(", "feature", ",", "minTime", ",", "maxTime", ")", "{", "var", "featureStringTimes", "=", "this", ".", "_getFeatureTimes", "(", "feature", ")", ";", "if", "(", "featureStringTimes", ".", "length", "==", "0", ")", "{", "return", "feature", ";", "}", "var", "featureTimes", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ",", "l", "=", "featureStringTimes", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "var", "time", "=", "featureStringTimes", "[", "i", "]", "if", "(", "typeof", "time", "==", "'string'", "||", "time", "instanceof", "String", ")", "{", "time", "=", "Date", ".", "parse", "(", "time", ".", "trim", "(", ")", ")", ";", "}", "featureTimes", ".", "push", "(", "time", ")", ";", "}", "if", "(", "featureTimes", "[", "0", "]", ">", "maxTime", "||", "featureTimes", "[", "l", "-", "1", "]", "<", "minTime", ")", "{", "return", "null", ";", "}", "return", "feature", ";", "}" ]
Do not modify features. Just return the feature if it intersects the time interval
[ "Do", "not", "modify", "features", ".", "Just", "return", "the", "feature", "if", "it", "intersects", "the", "time", "interval" ]
8045c2e8a62520fe647e41ab5801fe6bc7b021af
https://github.com/socib/Leaflet.TimeDimension/blob/8045c2e8a62520fe647e41ab5801fe6bc7b021af/examples/js/example15.js#L25-L43
13,156
pillarjs/router
index.js
generateOptionsResponder
function generateOptionsResponder(res, methods) { return function onDone(fn, err) { if (err || methods.length === 0) { return fn(err) } trySendOptionsResponse(res, methods, fn) } }
javascript
function generateOptionsResponder(res, methods) { return function onDone(fn, err) { if (err || methods.length === 0) { return fn(err) } trySendOptionsResponse(res, methods, fn) } }
[ "function", "generateOptionsResponder", "(", "res", ",", "methods", ")", "{", "return", "function", "onDone", "(", "fn", ",", "err", ")", "{", "if", "(", "err", "||", "methods", ".", "length", "===", "0", ")", "{", "return", "fn", "(", "err", ")", "}", "trySendOptionsResponse", "(", "res", ",", "methods", ",", "fn", ")", "}", "}" ]
Generate a callback that will make an OPTIONS response. @param {OutgoingMessage} res @param {array} methods @private
[ "Generate", "a", "callback", "that", "will", "make", "an", "OPTIONS", "response", "." ]
51c56e61b40ab486a936df7d6b09db006a3e9159
https://github.com/pillarjs/router/blob/51c56e61b40ab486a936df7d6b09db006a3e9159/index.js#L546-L554
13,157
pillarjs/router
index.js
mergeParams
function mergeParams(params, parent) { if (typeof parent !== 'object' || !parent) { return params } // make copy of parent for base var obj = mixin({}, parent) // simple non-numeric merging if (!(0 in params) || !(0 in parent)) { return mixin(obj, params) } var i = 0 var o = 0 // determine numeric gap in params while (i in params) { i++ } // determine numeric gap in parent while (o in parent) { o++ } // offset numeric indices in params before merge for (i--; i >= 0; i--) { params[i + o] = params[i] // create holes for the merge when necessary if (i < o) { delete params[i] } } return mixin(obj, params) }
javascript
function mergeParams(params, parent) { if (typeof parent !== 'object' || !parent) { return params } // make copy of parent for base var obj = mixin({}, parent) // simple non-numeric merging if (!(0 in params) || !(0 in parent)) { return mixin(obj, params) } var i = 0 var o = 0 // determine numeric gap in params while (i in params) { i++ } // determine numeric gap in parent while (o in parent) { o++ } // offset numeric indices in params before merge for (i--; i >= 0; i--) { params[i + o] = params[i] // create holes for the merge when necessary if (i < o) { delete params[i] } } return mixin(obj, params) }
[ "function", "mergeParams", "(", "params", ",", "parent", ")", "{", "if", "(", "typeof", "parent", "!==", "'object'", "||", "!", "parent", ")", "{", "return", "params", "}", "// make copy of parent for base", "var", "obj", "=", "mixin", "(", "{", "}", ",", "parent", ")", "// simple non-numeric merging", "if", "(", "!", "(", "0", "in", "params", ")", "||", "!", "(", "0", "in", "parent", ")", ")", "{", "return", "mixin", "(", "obj", ",", "params", ")", "}", "var", "i", "=", "0", "var", "o", "=", "0", "// determine numeric gap in params", "while", "(", "i", "in", "params", ")", "{", "i", "++", "}", "// determine numeric gap in parent", "while", "(", "o", "in", "parent", ")", "{", "o", "++", "}", "// offset numeric indices in params before merge", "for", "(", "i", "--", ";", "i", ">=", "0", ";", "i", "--", ")", "{", "params", "[", "i", "+", "o", "]", "=", "params", "[", "i", "]", "// create holes for the merge when necessary", "if", "(", "i", "<", "o", ")", "{", "delete", "params", "[", "i", "]", "}", "}", "return", "mixin", "(", "obj", ",", "params", ")", "}" ]
Merge params with parent params @private
[ "Merge", "params", "with", "parent", "params" ]
51c56e61b40ab486a936df7d6b09db006a3e9159
https://github.com/pillarjs/router/blob/51c56e61b40ab486a936df7d6b09db006a3e9159/index.js#L616-L653
13,158
pillarjs/router
index.js
restore
function restore(fn, obj) { var props = new Array(arguments.length - 2) var vals = new Array(arguments.length - 2) for (var i = 0; i < props.length; i++) { props[i] = arguments[i + 2] vals[i] = obj[props[i]] } return function(){ // restore vals for (var i = 0; i < props.length; i++) { obj[props[i]] = vals[i] } return fn.apply(this, arguments) } }
javascript
function restore(fn, obj) { var props = new Array(arguments.length - 2) var vals = new Array(arguments.length - 2) for (var i = 0; i < props.length; i++) { props[i] = arguments[i + 2] vals[i] = obj[props[i]] } return function(){ // restore vals for (var i = 0; i < props.length; i++) { obj[props[i]] = vals[i] } return fn.apply(this, arguments) } }
[ "function", "restore", "(", "fn", ",", "obj", ")", "{", "var", "props", "=", "new", "Array", "(", "arguments", ".", "length", "-", "2", ")", "var", "vals", "=", "new", "Array", "(", "arguments", ".", "length", "-", "2", ")", "for", "(", "var", "i", "=", "0", ";", "i", "<", "props", ".", "length", ";", "i", "++", ")", "{", "props", "[", "i", "]", "=", "arguments", "[", "i", "+", "2", "]", "vals", "[", "i", "]", "=", "obj", "[", "props", "[", "i", "]", "]", "}", "return", "function", "(", ")", "{", "// restore vals", "for", "(", "var", "i", "=", "0", ";", "i", "<", "props", ".", "length", ";", "i", "++", ")", "{", "obj", "[", "props", "[", "i", "]", "]", "=", "vals", "[", "i", "]", "}", "return", "fn", ".", "apply", "(", "this", ",", "arguments", ")", "}", "}" ]
Restore obj props after function @private
[ "Restore", "obj", "props", "after", "function" ]
51c56e61b40ab486a936df7d6b09db006a3e9159
https://github.com/pillarjs/router/blob/51c56e61b40ab486a936df7d6b09db006a3e9159/index.js#L661-L678
13,159
pillarjs/router
index.js
sendOptionsResponse
function sendOptionsResponse(res, methods) { var options = Object.create(null) // build unique method map for (var i = 0; i < methods.length; i++) { options[methods[i]] = true } // construct the allow list var allow = Object.keys(options).sort().join(', ') // send response res.setHeader('Allow', allow) res.setHeader('Content-Length', Buffer.byteLength(allow)) res.setHeader('Content-Type', 'text/plain') res.setHeader('X-Content-Type-Options', 'nosniff') res.end(allow) }
javascript
function sendOptionsResponse(res, methods) { var options = Object.create(null) // build unique method map for (var i = 0; i < methods.length; i++) { options[methods[i]] = true } // construct the allow list var allow = Object.keys(options).sort().join(', ') // send response res.setHeader('Allow', allow) res.setHeader('Content-Length', Buffer.byteLength(allow)) res.setHeader('Content-Type', 'text/plain') res.setHeader('X-Content-Type-Options', 'nosniff') res.end(allow) }
[ "function", "sendOptionsResponse", "(", "res", ",", "methods", ")", "{", "var", "options", "=", "Object", ".", "create", "(", "null", ")", "// build unique method map", "for", "(", "var", "i", "=", "0", ";", "i", "<", "methods", ".", "length", ";", "i", "++", ")", "{", "options", "[", "methods", "[", "i", "]", "]", "=", "true", "}", "// construct the allow list", "var", "allow", "=", "Object", ".", "keys", "(", "options", ")", ".", "sort", "(", ")", ".", "join", "(", "', '", ")", "// send response", "res", ".", "setHeader", "(", "'Allow'", ",", "allow", ")", "res", ".", "setHeader", "(", "'Content-Length'", ",", "Buffer", ".", "byteLength", "(", "allow", ")", ")", "res", ".", "setHeader", "(", "'Content-Type'", ",", "'text/plain'", ")", "res", ".", "setHeader", "(", "'X-Content-Type-Options'", ",", "'nosniff'", ")", "res", ".", "end", "(", "allow", ")", "}" ]
Send an OPTIONS response. @private
[ "Send", "an", "OPTIONS", "response", "." ]
51c56e61b40ab486a936df7d6b09db006a3e9159
https://github.com/pillarjs/router/blob/51c56e61b40ab486a936df7d6b09db006a3e9159/index.js#L686-L703
13,160
pillarjs/router
index.js
trySendOptionsResponse
function trySendOptionsResponse(res, methods, next) { try { sendOptionsResponse(res, methods) } catch (err) { next(err) } }
javascript
function trySendOptionsResponse(res, methods, next) { try { sendOptionsResponse(res, methods) } catch (err) { next(err) } }
[ "function", "trySendOptionsResponse", "(", "res", ",", "methods", ",", "next", ")", "{", "try", "{", "sendOptionsResponse", "(", "res", ",", "methods", ")", "}", "catch", "(", "err", ")", "{", "next", "(", "err", ")", "}", "}" ]
Try to send an OPTIONS response. @private
[ "Try", "to", "send", "an", "OPTIONS", "response", "." ]
51c56e61b40ab486a936df7d6b09db006a3e9159
https://github.com/pillarjs/router/blob/51c56e61b40ab486a936df7d6b09db006a3e9159/index.js#L711-L717
13,161
SC5/sc5-styleguide
lib/modules/section-references.js
reduceModifiers
function reduceModifiers (previousValue, currentValue) { return previousValue + currentValue[property].replace(modifierPlaceholder, currentValue.className); }
javascript
function reduceModifiers (previousValue, currentValue) { return previousValue + currentValue[property].replace(modifierPlaceholder, currentValue.className); }
[ "function", "reduceModifiers", "(", "previousValue", ",", "currentValue", ")", "{", "return", "previousValue", "+", "currentValue", "[", "property", "]", ".", "replace", "(", "modifierPlaceholder", ",", "currentValue", ".", "className", ")", ";", "}" ]
Concat all modifiers
[ "Concat", "all", "modifiers" ]
f573faba05643166f5c01c5faab3a4011c4173b7
https://github.com/SC5/sc5-styleguide/blob/f573faba05643166f5c01c5faab3a4011c4173b7/lib/modules/section-references.js#L13-L15
13,162
SC5/sc5-styleguide
lib/modules/kss-parser.js
jsonSections
function jsonSections(sections, block) { return sections.map(function(section) { // Temporary inserting of partial var partial = section; if (partial.markup() && partial.markup().toString().match(/^[^\n]+\.(html|hbs|pug)$/)) { partial.file = partial.markup().toString(); partial.name = path.basename(partial.file, path.extname(partial.file)); partial.file = path.dirname(block.filePath) + '/' + partial.file; partial.markupText = fs.readFileSync(partial.file, 'utf8'); section.markup = function() { return partial.markupText; }; } return { header: generateDescription(section.header(), {noWrapper: true}), description: generateDescription(section.description()), modifiers: jsonModifiers(section.modifiers()), deprecated: section.deprecated(), experimental: section.experimental(), reference: section.reference(), markup: section.markup() ? section.markup().toString() : null }; }); }
javascript
function jsonSections(sections, block) { return sections.map(function(section) { // Temporary inserting of partial var partial = section; if (partial.markup() && partial.markup().toString().match(/^[^\n]+\.(html|hbs|pug)$/)) { partial.file = partial.markup().toString(); partial.name = path.basename(partial.file, path.extname(partial.file)); partial.file = path.dirname(block.filePath) + '/' + partial.file; partial.markupText = fs.readFileSync(partial.file, 'utf8'); section.markup = function() { return partial.markupText; }; } return { header: generateDescription(section.header(), {noWrapper: true}), description: generateDescription(section.description()), modifiers: jsonModifiers(section.modifiers()), deprecated: section.deprecated(), experimental: section.experimental(), reference: section.reference(), markup: section.markup() ? section.markup().toString() : null }; }); }
[ "function", "jsonSections", "(", "sections", ",", "block", ")", "{", "return", "sections", ".", "map", "(", "function", "(", "section", ")", "{", "// Temporary inserting of partial", "var", "partial", "=", "section", ";", "if", "(", "partial", ".", "markup", "(", ")", "&&", "partial", ".", "markup", "(", ")", ".", "toString", "(", ")", ".", "match", "(", "/", "^[^\\n]+\\.(html|hbs|pug)$", "/", ")", ")", "{", "partial", ".", "file", "=", "partial", ".", "markup", "(", ")", ".", "toString", "(", ")", ";", "partial", ".", "name", "=", "path", ".", "basename", "(", "partial", ".", "file", ",", "path", ".", "extname", "(", "partial", ".", "file", ")", ")", ";", "partial", ".", "file", "=", "path", ".", "dirname", "(", "block", ".", "filePath", ")", "+", "'/'", "+", "partial", ".", "file", ";", "partial", ".", "markupText", "=", "fs", ".", "readFileSync", "(", "partial", ".", "file", ",", "'utf8'", ")", ";", "section", ".", "markup", "=", "function", "(", ")", "{", "return", "partial", ".", "markupText", ";", "}", ";", "}", "return", "{", "header", ":", "generateDescription", "(", "section", ".", "header", "(", ")", ",", "{", "noWrapper", ":", "true", "}", ")", ",", "description", ":", "generateDescription", "(", "section", ".", "description", "(", ")", ")", ",", "modifiers", ":", "jsonModifiers", "(", "section", ".", "modifiers", "(", ")", ")", ",", "deprecated", ":", "section", ".", "deprecated", "(", ")", ",", "experimental", ":", "section", ".", "experimental", "(", ")", ",", "reference", ":", "section", ".", "reference", "(", ")", ",", "markup", ":", "section", ".", "markup", "(", ")", "?", "section", ".", "markup", "(", ")", ".", "toString", "(", ")", ":", "null", "}", ";", "}", ")", ";", "}" ]
Parses kss.KssSection to JSON
[ "Parses", "kss", ".", "KssSection", "to", "JSON" ]
f573faba05643166f5c01c5faab3a4011c4173b7
https://github.com/SC5/sc5-styleguide/blob/f573faba05643166f5c01c5faab3a4011c4173b7/lib/modules/kss-parser.js#L14-L39
13,163
SC5/sc5-styleguide
lib/modules/kss-parser.js
jsonModifiers
function jsonModifiers(modifiers) { return modifiers.map(function(modifier, id) { return { id: id + 1, name: modifier.name(), description: modifier.description(), className: modifier.className(), markup: modifier.markup() ? modifier.markup().toString() : null }; }); }
javascript
function jsonModifiers(modifiers) { return modifiers.map(function(modifier, id) { return { id: id + 1, name: modifier.name(), description: modifier.description(), className: modifier.className(), markup: modifier.markup() ? modifier.markup().toString() : null }; }); }
[ "function", "jsonModifiers", "(", "modifiers", ")", "{", "return", "modifiers", ".", "map", "(", "function", "(", "modifier", ",", "id", ")", "{", "return", "{", "id", ":", "id", "+", "1", ",", "name", ":", "modifier", ".", "name", "(", ")", ",", "description", ":", "modifier", ".", "description", "(", ")", ",", "className", ":", "modifier", ".", "className", "(", ")", ",", "markup", ":", "modifier", ".", "markup", "(", ")", "?", "modifier", ".", "markup", "(", ")", ".", "toString", "(", ")", ":", "null", "}", ";", "}", ")", ";", "}" ]
Parses kss.KssModifier to JSON
[ "Parses", "kss", ".", "KssModifier", "to", "JSON" ]
f573faba05643166f5c01c5faab3a4011c4173b7
https://github.com/SC5/sc5-styleguide/blob/f573faba05643166f5c01c5faab3a4011c4173b7/lib/modules/kss-parser.js#L42-L52
13,164
dhotson/springy
springyui.js
intersect_line_line
function intersect_line_line(p1, p2, p3, p4) { var denom = ((p4.y - p3.y)*(p2.x - p1.x) - (p4.x - p3.x)*(p2.y - p1.y)); // lines are parallel if (denom === 0) { return false; } var ua = ((p4.x - p3.x)*(p1.y - p3.y) - (p4.y - p3.y)*(p1.x - p3.x)) / denom; var ub = ((p2.x - p1.x)*(p1.y - p3.y) - (p2.y - p1.y)*(p1.x - p3.x)) / denom; if (ua < 0 || ua > 1 || ub < 0 || ub > 1) { return false; } return new Springy.Vector(p1.x + ua * (p2.x - p1.x), p1.y + ua * (p2.y - p1.y)); }
javascript
function intersect_line_line(p1, p2, p3, p4) { var denom = ((p4.y - p3.y)*(p2.x - p1.x) - (p4.x - p3.x)*(p2.y - p1.y)); // lines are parallel if (denom === 0) { return false; } var ua = ((p4.x - p3.x)*(p1.y - p3.y) - (p4.y - p3.y)*(p1.x - p3.x)) / denom; var ub = ((p2.x - p1.x)*(p1.y - p3.y) - (p2.y - p1.y)*(p1.x - p3.x)) / denom; if (ua < 0 || ua > 1 || ub < 0 || ub > 1) { return false; } return new Springy.Vector(p1.x + ua * (p2.x - p1.x), p1.y + ua * (p2.y - p1.y)); }
[ "function", "intersect_line_line", "(", "p1", ",", "p2", ",", "p3", ",", "p4", ")", "{", "var", "denom", "=", "(", "(", "p4", ".", "y", "-", "p3", ".", "y", ")", "*", "(", "p2", ".", "x", "-", "p1", ".", "x", ")", "-", "(", "p4", ".", "x", "-", "p3", ".", "x", ")", "*", "(", "p2", ".", "y", "-", "p1", ".", "y", ")", ")", ";", "// lines are parallel", "if", "(", "denom", "===", "0", ")", "{", "return", "false", ";", "}", "var", "ua", "=", "(", "(", "p4", ".", "x", "-", "p3", ".", "x", ")", "*", "(", "p1", ".", "y", "-", "p3", ".", "y", ")", "-", "(", "p4", ".", "y", "-", "p3", ".", "y", ")", "*", "(", "p1", ".", "x", "-", "p3", ".", "x", ")", ")", "/", "denom", ";", "var", "ub", "=", "(", "(", "p2", ".", "x", "-", "p1", ".", "x", ")", "*", "(", "p1", ".", "y", "-", "p3", ".", "y", ")", "-", "(", "p2", ".", "y", "-", "p1", ".", "y", ")", "*", "(", "p1", ".", "x", "-", "p3", ".", "x", ")", ")", "/", "denom", ";", "if", "(", "ua", "<", "0", "||", "ua", ">", "1", "||", "ub", "<", "0", "||", "ub", ">", "1", ")", "{", "return", "false", ";", "}", "return", "new", "Springy", ".", "Vector", "(", "p1", ".", "x", "+", "ua", "*", "(", "p2", ".", "x", "-", "p1", ".", "x", ")", ",", "p1", ".", "y", "+", "ua", "*", "(", "p2", ".", "y", "-", "p1", ".", "y", ")", ")", ";", "}" ]
helpers for figuring out where to draw arrows
[ "helpers", "for", "figuring", "out", "where", "to", "draw", "arrows" ]
9654b64f85f7f35220eaafee80894d33a00ef5ac
https://github.com/dhotson/springy/blob/9654b64f85f7f35220eaafee80894d33a00ef5ac/springyui.js#L358-L374
13,165
fernando-mc/serverless-finch
lib/bucketUtils.js
emptyBucket
function emptyBucket(aws, bucketName, keyPrefix) { return listObjectsInBucket(aws, bucketName).then(resp => { const contents = resp.Contents; let testPrefix = false, prefixRegexp; if (!contents[0]) { return Promise.resolve(); } else { if (keyPrefix) { testPrefix = true; prefixRegexp = new RegExp('^' + keyPrefix); } const objects = contents.map(function(content) { return {Key: content.Key}; }).filter(content => !testPrefix || prefixRegexp.test(content.Key)); const params = { Bucket: bucketName, Delete: { Objects: objects } }; return aws.request('S3', 'deleteObjects', params); } }); }
javascript
function emptyBucket(aws, bucketName, keyPrefix) { return listObjectsInBucket(aws, bucketName).then(resp => { const contents = resp.Contents; let testPrefix = false, prefixRegexp; if (!contents[0]) { return Promise.resolve(); } else { if (keyPrefix) { testPrefix = true; prefixRegexp = new RegExp('^' + keyPrefix); } const objects = contents.map(function(content) { return {Key: content.Key}; }).filter(content => !testPrefix || prefixRegexp.test(content.Key)); const params = { Bucket: bucketName, Delete: { Objects: objects } }; return aws.request('S3', 'deleteObjects', params); } }); }
[ "function", "emptyBucket", "(", "aws", ",", "bucketName", ",", "keyPrefix", ")", "{", "return", "listObjectsInBucket", "(", "aws", ",", "bucketName", ")", ".", "then", "(", "resp", "=>", "{", "const", "contents", "=", "resp", ".", "Contents", ";", "let", "testPrefix", "=", "false", ",", "prefixRegexp", ";", "if", "(", "!", "contents", "[", "0", "]", ")", "{", "return", "Promise", ".", "resolve", "(", ")", ";", "}", "else", "{", "if", "(", "keyPrefix", ")", "{", "testPrefix", "=", "true", ";", "prefixRegexp", "=", "new", "RegExp", "(", "'^'", "+", "keyPrefix", ")", ";", "}", "const", "objects", "=", "contents", ".", "map", "(", "function", "(", "content", ")", "{", "return", "{", "Key", ":", "content", ".", "Key", "}", ";", "}", ")", ".", "filter", "(", "content", "=>", "!", "testPrefix", "||", "prefixRegexp", ".", "test", "(", "content", ".", "Key", ")", ")", ";", "const", "params", "=", "{", "Bucket", ":", "bucketName", ",", "Delete", ":", "{", "Objects", ":", "objects", "}", "}", ";", "return", "aws", ".", "request", "(", "'S3'", ",", "'deleteObjects'", ",", "params", ")", ";", "}", "}", ")", ";", "}" ]
Deletes all objects in an S3 bucket @param {Object} aws - AWS class @param {string} bucketName - Name of bucket to be deleted
[ "Deletes", "all", "objects", "in", "an", "S3", "bucket" ]
ccdc24b958385f65472fad19896b14279171de09
https://github.com/fernando-mc/serverless-finch/blob/ccdc24b958385f65472fad19896b14279171de09/lib/bucketUtils.js#L51-L76
13,166
fernando-mc/serverless-finch
lib/configure.js
configureBucket
function configureBucket( aws, bucketName, indexDocument, errorDocument, redirectAllRequestsTo, routingRules ) { const params = { Bucket: bucketName, WebsiteConfiguration: {} }; if (redirectAllRequestsTo) { params.WebsiteConfiguration.RedirectAllRequestsTo = {}; params.WebsiteConfiguration.RedirectAllRequestsTo.HostName = redirectAllRequestsTo.hostName; if (redirectAllRequestsTo.protocol) { params.WebsiteConfiguration.RedirectAllRequestsTo.Protocol = redirectAllRequestsTo.protocol; } } else { // AWS's terminology (Suffix/Key) here is weird. The following is how you specify // index and error documents for the bucket. See docs: // https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#putBucketWebsite-property params.WebsiteConfiguration.IndexDocument = { Suffix: indexDocument }; params.WebsiteConfiguration.ErrorDocument = { Key: errorDocument }; } if (routingRules) { params.WebsiteConfiguration.RoutingRules = []; routingRules.forEach(r => { const routingRule = { Redirect: {} }; const redirectProps = [ 'hostName', 'httpRedirectCode', 'protocol', 'replaceKeyPrefixWith', 'replaceKeyWith' ]; redirectProps.forEach(p => { if (r.redirect[p]) { if (p === 'httpRedirectCode') { r.redirect[p] = r.redirect[p].toString(); } // AWS expects the redirect properties to be PascalCase, while our API // uses camelCase. Converting here. routingRule.Redirect[p.charAt(0).toUpperCase() + p.slice(1)] = r.redirect[p]; } }); if (r.condition) { routingRule.Condition = {}; const conditionProps = ['httpErrorCodeReturnedEquals', 'keyPrefixEquals']; conditionProps.forEach(p => { if (r.condition[p]) { if (p === 'httpErrorCodeReturnedEquals') { r.condition[p] = r.condition[p].toString(); } // AWS expects the redirect conditions to be PascalCase, while our API // uses camelCase. Converting here. routingRule.Condition[p.charAt(0).toUpperCase() + p.slice(1)] = r.condition[p]; } }); } params.WebsiteConfiguration.RoutingRules.push(routingRule); }); } return aws.request('S3', 'putBucketWebsite', params); }
javascript
function configureBucket( aws, bucketName, indexDocument, errorDocument, redirectAllRequestsTo, routingRules ) { const params = { Bucket: bucketName, WebsiteConfiguration: {} }; if (redirectAllRequestsTo) { params.WebsiteConfiguration.RedirectAllRequestsTo = {}; params.WebsiteConfiguration.RedirectAllRequestsTo.HostName = redirectAllRequestsTo.hostName; if (redirectAllRequestsTo.protocol) { params.WebsiteConfiguration.RedirectAllRequestsTo.Protocol = redirectAllRequestsTo.protocol; } } else { // AWS's terminology (Suffix/Key) here is weird. The following is how you specify // index and error documents for the bucket. See docs: // https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#putBucketWebsite-property params.WebsiteConfiguration.IndexDocument = { Suffix: indexDocument }; params.WebsiteConfiguration.ErrorDocument = { Key: errorDocument }; } if (routingRules) { params.WebsiteConfiguration.RoutingRules = []; routingRules.forEach(r => { const routingRule = { Redirect: {} }; const redirectProps = [ 'hostName', 'httpRedirectCode', 'protocol', 'replaceKeyPrefixWith', 'replaceKeyWith' ]; redirectProps.forEach(p => { if (r.redirect[p]) { if (p === 'httpRedirectCode') { r.redirect[p] = r.redirect[p].toString(); } // AWS expects the redirect properties to be PascalCase, while our API // uses camelCase. Converting here. routingRule.Redirect[p.charAt(0).toUpperCase() + p.slice(1)] = r.redirect[p]; } }); if (r.condition) { routingRule.Condition = {}; const conditionProps = ['httpErrorCodeReturnedEquals', 'keyPrefixEquals']; conditionProps.forEach(p => { if (r.condition[p]) { if (p === 'httpErrorCodeReturnedEquals') { r.condition[p] = r.condition[p].toString(); } // AWS expects the redirect conditions to be PascalCase, while our API // uses camelCase. Converting here. routingRule.Condition[p.charAt(0).toUpperCase() + p.slice(1)] = r.condition[p]; } }); } params.WebsiteConfiguration.RoutingRules.push(routingRule); }); } return aws.request('S3', 'putBucketWebsite', params); }
[ "function", "configureBucket", "(", "aws", ",", "bucketName", ",", "indexDocument", ",", "errorDocument", ",", "redirectAllRequestsTo", ",", "routingRules", ")", "{", "const", "params", "=", "{", "Bucket", ":", "bucketName", ",", "WebsiteConfiguration", ":", "{", "}", "}", ";", "if", "(", "redirectAllRequestsTo", ")", "{", "params", ".", "WebsiteConfiguration", ".", "RedirectAllRequestsTo", "=", "{", "}", ";", "params", ".", "WebsiteConfiguration", ".", "RedirectAllRequestsTo", ".", "HostName", "=", "redirectAllRequestsTo", ".", "hostName", ";", "if", "(", "redirectAllRequestsTo", ".", "protocol", ")", "{", "params", ".", "WebsiteConfiguration", ".", "RedirectAllRequestsTo", ".", "Protocol", "=", "redirectAllRequestsTo", ".", "protocol", ";", "}", "}", "else", "{", "// AWS's terminology (Suffix/Key) here is weird. The following is how you specify", "// index and error documents for the bucket. See docs:", "// https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#putBucketWebsite-property", "params", ".", "WebsiteConfiguration", ".", "IndexDocument", "=", "{", "Suffix", ":", "indexDocument", "}", ";", "params", ".", "WebsiteConfiguration", ".", "ErrorDocument", "=", "{", "Key", ":", "errorDocument", "}", ";", "}", "if", "(", "routingRules", ")", "{", "params", ".", "WebsiteConfiguration", ".", "RoutingRules", "=", "[", "]", ";", "routingRules", ".", "forEach", "(", "r", "=>", "{", "const", "routingRule", "=", "{", "Redirect", ":", "{", "}", "}", ";", "const", "redirectProps", "=", "[", "'hostName'", ",", "'httpRedirectCode'", ",", "'protocol'", ",", "'replaceKeyPrefixWith'", ",", "'replaceKeyWith'", "]", ";", "redirectProps", ".", "forEach", "(", "p", "=>", "{", "if", "(", "r", ".", "redirect", "[", "p", "]", ")", "{", "if", "(", "p", "===", "'httpRedirectCode'", ")", "{", "r", ".", "redirect", "[", "p", "]", "=", "r", ".", "redirect", "[", "p", "]", ".", "toString", "(", ")", ";", "}", "// AWS expects the redirect properties to be PascalCase, while our API", "// uses camelCase. Converting here.", "routingRule", ".", "Redirect", "[", "p", ".", "charAt", "(", "0", ")", ".", "toUpperCase", "(", ")", "+", "p", ".", "slice", "(", "1", ")", "]", "=", "r", ".", "redirect", "[", "p", "]", ";", "}", "}", ")", ";", "if", "(", "r", ".", "condition", ")", "{", "routingRule", ".", "Condition", "=", "{", "}", ";", "const", "conditionProps", "=", "[", "'httpErrorCodeReturnedEquals'", ",", "'keyPrefixEquals'", "]", ";", "conditionProps", ".", "forEach", "(", "p", "=>", "{", "if", "(", "r", ".", "condition", "[", "p", "]", ")", "{", "if", "(", "p", "===", "'httpErrorCodeReturnedEquals'", ")", "{", "r", ".", "condition", "[", "p", "]", "=", "r", ".", "condition", "[", "p", "]", ".", "toString", "(", ")", ";", "}", "// AWS expects the redirect conditions to be PascalCase, while our API", "// uses camelCase. Converting here.", "routingRule", ".", "Condition", "[", "p", ".", "charAt", "(", "0", ")", ".", "toUpperCase", "(", ")", "+", "p", ".", "slice", "(", "1", ")", "]", "=", "r", ".", "condition", "[", "p", "]", ";", "}", "}", ")", ";", "}", "params", ".", "WebsiteConfiguration", ".", "RoutingRules", ".", "push", "(", "routingRule", ")", ";", "}", ")", ";", "}", "return", "aws", ".", "request", "(", "'S3'", ",", "'putBucketWebsite'", ",", "params", ")", ";", "}" ]
Sets website configuration parameters for given bucket @param {Object} aws - AWS class @param {string} bucketName - Name of bucket to be configured @param {string} indexDocument - Path to index document @param {string} errorDocument - Path to error document @param {Object} redirectAllRequestsTo - Configuration information for redirecting all requests @param {Object[]} routingRules - Rules for routing site traffic
[ "Sets", "website", "configuration", "parameters", "for", "given", "bucket" ]
ccdc24b958385f65472fad19896b14279171de09
https://github.com/fernando-mc/serverless-finch/blob/ccdc24b958385f65472fad19896b14279171de09/lib/configure.js#L12-L86
13,167
fernando-mc/serverless-finch
lib/configure.js
configurePolicyForBucket
function configurePolicyForBucket(aws, bucketName, customPolicy) { const policy = customPolicy || { Version: '2012-10-17', Statement: [ { Effect: 'Allow', Principal: { AWS: '*' }, Action: 's3:GetObject', Resource: `arn:aws:s3:::${bucketName}/*` } ] }; const params = { Bucket: bucketName, Policy: JSON.stringify(policy) }; return aws.request('S3', 'putBucketPolicy', params); }
javascript
function configurePolicyForBucket(aws, bucketName, customPolicy) { const policy = customPolicy || { Version: '2012-10-17', Statement: [ { Effect: 'Allow', Principal: { AWS: '*' }, Action: 's3:GetObject', Resource: `arn:aws:s3:::${bucketName}/*` } ] }; const params = { Bucket: bucketName, Policy: JSON.stringify(policy) }; return aws.request('S3', 'putBucketPolicy', params); }
[ "function", "configurePolicyForBucket", "(", "aws", ",", "bucketName", ",", "customPolicy", ")", "{", "const", "policy", "=", "customPolicy", "||", "{", "Version", ":", "'2012-10-17'", ",", "Statement", ":", "[", "{", "Effect", ":", "'Allow'", ",", "Principal", ":", "{", "AWS", ":", "'*'", "}", ",", "Action", ":", "'s3:GetObject'", ",", "Resource", ":", "`", "${", "bucketName", "}", "`", "}", "]", "}", ";", "const", "params", "=", "{", "Bucket", ":", "bucketName", ",", "Policy", ":", "JSON", ".", "stringify", "(", "policy", ")", "}", ";", "return", "aws", ".", "request", "(", "'S3'", ",", "'putBucketPolicy'", ",", "params", ")", ";", "}" ]
Configures policy for given bucket @param {Object} aws - AWS class @param {string} bucketName - Name of bucket to be configured
[ "Configures", "policy", "for", "given", "bucket" ]
ccdc24b958385f65472fad19896b14279171de09
https://github.com/fernando-mc/serverless-finch/blob/ccdc24b958385f65472fad19896b14279171de09/lib/configure.js#L93-L114
13,168
fernando-mc/serverless-finch
lib/configure.js
configureCorsForBucket
function configureCorsForBucket(aws, bucketName) { const params = { Bucket: bucketName, CORSConfiguration: require('./resources/CORSPolicy') }; return aws.request('S3', 'putBucketCors', params); }
javascript
function configureCorsForBucket(aws, bucketName) { const params = { Bucket: bucketName, CORSConfiguration: require('./resources/CORSPolicy') }; return aws.request('S3', 'putBucketCors', params); }
[ "function", "configureCorsForBucket", "(", "aws", ",", "bucketName", ")", "{", "const", "params", "=", "{", "Bucket", ":", "bucketName", ",", "CORSConfiguration", ":", "require", "(", "'./resources/CORSPolicy'", ")", "}", ";", "return", "aws", ".", "request", "(", "'S3'", ",", "'putBucketCors'", ",", "params", ")", ";", "}" ]
Configures CORS policy for given bucket @param {Object} aws - AWS class @param {string} bucketName - Name of bucket to be configured
[ "Configures", "CORS", "policy", "for", "given", "bucket" ]
ccdc24b958385f65472fad19896b14279171de09
https://github.com/fernando-mc/serverless-finch/blob/ccdc24b958385f65472fad19896b14279171de09/lib/configure.js#L121-L128
13,169
fernando-mc/serverless-finch
lib/upload.js
uploadDirectory
function uploadDirectory(aws, bucketName, clientRoot, headerSpec, orderSpec, keyPrefix) { const allFiles = getFileList(clientRoot); const filesGroupedByOrder = groupFilesByOrder(allFiles, orderSpec); return filesGroupedByOrder.reduce((existingUploads, files) => { return existingUploads.then(existingResults => { const uploadList = buildUploadList(files, clientRoot, headerSpec, keyPrefix); return Promise.all( uploadList.map(u => uploadFile(aws, bucketName, u.filePath, u.fileKey, u.headers)) ).then(currentResults => existingResults.concat(currentResults)); }); }, Promise.resolve([])); }
javascript
function uploadDirectory(aws, bucketName, clientRoot, headerSpec, orderSpec, keyPrefix) { const allFiles = getFileList(clientRoot); const filesGroupedByOrder = groupFilesByOrder(allFiles, orderSpec); return filesGroupedByOrder.reduce((existingUploads, files) => { return existingUploads.then(existingResults => { const uploadList = buildUploadList(files, clientRoot, headerSpec, keyPrefix); return Promise.all( uploadList.map(u => uploadFile(aws, bucketName, u.filePath, u.fileKey, u.headers)) ).then(currentResults => existingResults.concat(currentResults)); }); }, Promise.resolve([])); }
[ "function", "uploadDirectory", "(", "aws", ",", "bucketName", ",", "clientRoot", ",", "headerSpec", ",", "orderSpec", ",", "keyPrefix", ")", "{", "const", "allFiles", "=", "getFileList", "(", "clientRoot", ")", ";", "const", "filesGroupedByOrder", "=", "groupFilesByOrder", "(", "allFiles", ",", "orderSpec", ")", ";", "return", "filesGroupedByOrder", ".", "reduce", "(", "(", "existingUploads", ",", "files", ")", "=>", "{", "return", "existingUploads", ".", "then", "(", "existingResults", "=>", "{", "const", "uploadList", "=", "buildUploadList", "(", "files", ",", "clientRoot", ",", "headerSpec", ",", "keyPrefix", ")", ";", "return", "Promise", ".", "all", "(", "uploadList", ".", "map", "(", "u", "=>", "uploadFile", "(", "aws", ",", "bucketName", ",", "u", ".", "filePath", ",", "u", ".", "fileKey", ",", "u", ".", "headers", ")", ")", ")", ".", "then", "(", "currentResults", "=>", "existingResults", ".", "concat", "(", "currentResults", ")", ")", ";", "}", ")", ";", "}", ",", "Promise", ".", "resolve", "(", "[", "]", ")", ")", ";", "}" ]
Uploads client files to an S3 bucket @param {Object} aws - AWS class @param {string} bucketName - Name of bucket to be configured @param {string} clientRoot - Full path to the root directory of client files @param {Object[]} headerSpec - Array of header values to add to files @param {string[]} orderSpec - Array of regex's to order upload by @param {string} keyPrefix - A prefix for all files uploaded
[ "Uploads", "client", "files", "to", "an", "S3", "bucket" ]
ccdc24b958385f65472fad19896b14279171de09
https://github.com/fernando-mc/serverless-finch/blob/ccdc24b958385f65472fad19896b14279171de09/lib/upload.js#L22-L36
13,170
fernando-mc/serverless-finch
lib/upload.js
uploadFile
function uploadFile(aws, bucketName, filePath, fileKey, headers) { const baseHeaderKeys = [ 'Cache-Control', 'Content-Disposition', 'Content-Encoding', 'Content-Language', 'Content-Type', 'Expires', 'Website-Redirect-Location' ]; const fileBuffer = fs.readFileSync(filePath); const params = { Bucket: bucketName, Key: fileKey, Body: fileBuffer, ContentType: mime.lookup(filePath) }; Object.keys(headers).forEach(h => { if (baseHeaderKeys.includes(h)) { params[h.replace('-', '')] = headers[h]; } else { if (!params.Metadata) { params.Metadata = {}; } params.Metadata[h] = headers[h]; } }); return aws.request('S3', 'putObject', params); }
javascript
function uploadFile(aws, bucketName, filePath, fileKey, headers) { const baseHeaderKeys = [ 'Cache-Control', 'Content-Disposition', 'Content-Encoding', 'Content-Language', 'Content-Type', 'Expires', 'Website-Redirect-Location' ]; const fileBuffer = fs.readFileSync(filePath); const params = { Bucket: bucketName, Key: fileKey, Body: fileBuffer, ContentType: mime.lookup(filePath) }; Object.keys(headers).forEach(h => { if (baseHeaderKeys.includes(h)) { params[h.replace('-', '')] = headers[h]; } else { if (!params.Metadata) { params.Metadata = {}; } params.Metadata[h] = headers[h]; } }); return aws.request('S3', 'putObject', params); }
[ "function", "uploadFile", "(", "aws", ",", "bucketName", ",", "filePath", ",", "fileKey", ",", "headers", ")", "{", "const", "baseHeaderKeys", "=", "[", "'Cache-Control'", ",", "'Content-Disposition'", ",", "'Content-Encoding'", ",", "'Content-Language'", ",", "'Content-Type'", ",", "'Expires'", ",", "'Website-Redirect-Location'", "]", ";", "const", "fileBuffer", "=", "fs", ".", "readFileSync", "(", "filePath", ")", ";", "const", "params", "=", "{", "Bucket", ":", "bucketName", ",", "Key", ":", "fileKey", ",", "Body", ":", "fileBuffer", ",", "ContentType", ":", "mime", ".", "lookup", "(", "filePath", ")", "}", ";", "Object", ".", "keys", "(", "headers", ")", ".", "forEach", "(", "h", "=>", "{", "if", "(", "baseHeaderKeys", ".", "includes", "(", "h", ")", ")", "{", "params", "[", "h", ".", "replace", "(", "'-'", ",", "''", ")", "]", "=", "headers", "[", "h", "]", ";", "}", "else", "{", "if", "(", "!", "params", ".", "Metadata", ")", "{", "params", ".", "Metadata", "=", "{", "}", ";", "}", "params", ".", "Metadata", "[", "h", "]", "=", "headers", "[", "h", "]", ";", "}", "}", ")", ";", "return", "aws", ".", "request", "(", "'S3'", ",", "'putObject'", ",", "params", ")", ";", "}" ]
Uploads a file to an S3 bucket @param {Object} aws - AWS class @param {string} bucketName - Name of bucket to be configured @param {string} filePath - Full path to file to be uploaded @param {string} clientRoot - Full path to the root directory of client files
[ "Uploads", "a", "file", "to", "an", "S3", "bucket" ]
ccdc24b958385f65472fad19896b14279171de09
https://github.com/fernando-mc/serverless-finch/blob/ccdc24b958385f65472fad19896b14279171de09/lib/upload.js#L45-L77
13,171
livoras/list-diff
lib/diff.js
makeKeyIndexAndFree
function makeKeyIndexAndFree (list, key) { var keyIndex = {} var free = [] for (var i = 0, len = list.length; i < len; i++) { var item = list[i] var itemKey = getItemKey(item, key) if (itemKey) { keyIndex[itemKey] = i } else { free.push(item) } } return { keyIndex: keyIndex, free: free } }
javascript
function makeKeyIndexAndFree (list, key) { var keyIndex = {} var free = [] for (var i = 0, len = list.length; i < len; i++) { var item = list[i] var itemKey = getItemKey(item, key) if (itemKey) { keyIndex[itemKey] = i } else { free.push(item) } } return { keyIndex: keyIndex, free: free } }
[ "function", "makeKeyIndexAndFree", "(", "list", ",", "key", ")", "{", "var", "keyIndex", "=", "{", "}", "var", "free", "=", "[", "]", "for", "(", "var", "i", "=", "0", ",", "len", "=", "list", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "var", "item", "=", "list", "[", "i", "]", "var", "itemKey", "=", "getItemKey", "(", "item", ",", "key", ")", "if", "(", "itemKey", ")", "{", "keyIndex", "[", "itemKey", "]", "=", "i", "}", "else", "{", "free", ".", "push", "(", "item", ")", "}", "}", "return", "{", "keyIndex", ":", "keyIndex", ",", "free", ":", "free", "}", "}" ]
Convert list to key-item keyIndex object. @param {Array} list @param {String|Function} key
[ "Convert", "list", "to", "key", "-", "item", "keyIndex", "object", "." ]
7a35a1607e9f7baf3ab8c43bb68d424c6c0a7ca8
https://github.com/livoras/list-diff/blob/7a35a1607e9f7baf3ab8c43bb68d424c6c0a7ca8/lib/diff.js#L128-L144
13,172
Travelport-Ukraine/uapi-json
src/Services/Air/AirFormat.js
setIndexesForSegments
function setIndexesForSegments( segmentsObject = null, serviceSegmentsObject = null ) { const segments = segmentsObject ? Object.keys(segmentsObject).map(k => segmentsObject[k]) : null; const serviceSegments = serviceSegmentsObject ? Object.keys(serviceSegmentsObject).map(k => serviceSegmentsObject[k]) : null; if (segments === null && serviceSegments === null) { return { segments, serviceSegments }; } if (segments !== null && serviceSegments === null) { const segmentsNew = segments.map((segment, key) => ({ ...segment, index: key + 1, })); return { segments: segmentsNew, serviceSegments }; } if (segments === null && serviceSegments !== null) { const serviceSegmentsNew = serviceSegments.map( (segment, key) => ({ ...segment, index: key + 1, }) ); return { segments, serviceSegments: serviceSegmentsNew }; } const maxSegmentsTravelOrder = segments.reduce(travelOrderReducer, 0); const maxServiceSegmentsTravelOrder = serviceSegments.reduce(travelOrderReducer, 0); const maxOrder = Math.max( maxSegmentsTravelOrder, maxServiceSegmentsTravelOrder ); const allSegments = []; for (let i = 1; i <= maxOrder; i += 1) { segments.forEach(s => (Number(s.TravelOrder) === i ? allSegments.push(s) : null)); serviceSegments.forEach(s => (Number(s.TravelOrder) === i ? allSegments.push(s) : null)); } const indexedSegments = allSegments.map((s, k) => ({ ...s, index: k + 1 })); return { segments: indexedSegments.filter(s => s.SegmentType === undefined), serviceSegments: indexedSegments.filter(s => s.SegmentType === 'Service'), }; }
javascript
function setIndexesForSegments( segmentsObject = null, serviceSegmentsObject = null ) { const segments = segmentsObject ? Object.keys(segmentsObject).map(k => segmentsObject[k]) : null; const serviceSegments = serviceSegmentsObject ? Object.keys(serviceSegmentsObject).map(k => serviceSegmentsObject[k]) : null; if (segments === null && serviceSegments === null) { return { segments, serviceSegments }; } if (segments !== null && serviceSegments === null) { const segmentsNew = segments.map((segment, key) => ({ ...segment, index: key + 1, })); return { segments: segmentsNew, serviceSegments }; } if (segments === null && serviceSegments !== null) { const serviceSegmentsNew = serviceSegments.map( (segment, key) => ({ ...segment, index: key + 1, }) ); return { segments, serviceSegments: serviceSegmentsNew }; } const maxSegmentsTravelOrder = segments.reduce(travelOrderReducer, 0); const maxServiceSegmentsTravelOrder = serviceSegments.reduce(travelOrderReducer, 0); const maxOrder = Math.max( maxSegmentsTravelOrder, maxServiceSegmentsTravelOrder ); const allSegments = []; for (let i = 1; i <= maxOrder; i += 1) { segments.forEach(s => (Number(s.TravelOrder) === i ? allSegments.push(s) : null)); serviceSegments.forEach(s => (Number(s.TravelOrder) === i ? allSegments.push(s) : null)); } const indexedSegments = allSegments.map((s, k) => ({ ...s, index: k + 1 })); return { segments: indexedSegments.filter(s => s.SegmentType === undefined), serviceSegments: indexedSegments.filter(s => s.SegmentType === 'Service'), }; }
[ "function", "setIndexesForSegments", "(", "segmentsObject", "=", "null", ",", "serviceSegmentsObject", "=", "null", ")", "{", "const", "segments", "=", "segmentsObject", "?", "Object", ".", "keys", "(", "segmentsObject", ")", ".", "map", "(", "k", "=>", "segmentsObject", "[", "k", "]", ")", ":", "null", ";", "const", "serviceSegments", "=", "serviceSegmentsObject", "?", "Object", ".", "keys", "(", "serviceSegmentsObject", ")", ".", "map", "(", "k", "=>", "serviceSegmentsObject", "[", "k", "]", ")", ":", "null", ";", "if", "(", "segments", "===", "null", "&&", "serviceSegments", "===", "null", ")", "{", "return", "{", "segments", ",", "serviceSegments", "}", ";", "}", "if", "(", "segments", "!==", "null", "&&", "serviceSegments", "===", "null", ")", "{", "const", "segmentsNew", "=", "segments", ".", "map", "(", "(", "segment", ",", "key", ")", "=>", "(", "{", "...", "segment", ",", "index", ":", "key", "+", "1", ",", "}", ")", ")", ";", "return", "{", "segments", ":", "segmentsNew", ",", "serviceSegments", "}", ";", "}", "if", "(", "segments", "===", "null", "&&", "serviceSegments", "!==", "null", ")", "{", "const", "serviceSegmentsNew", "=", "serviceSegments", ".", "map", "(", "(", "segment", ",", "key", ")", "=>", "(", "{", "...", "segment", ",", "index", ":", "key", "+", "1", ",", "}", ")", ")", ";", "return", "{", "segments", ",", "serviceSegments", ":", "serviceSegmentsNew", "}", ";", "}", "const", "maxSegmentsTravelOrder", "=", "segments", ".", "reduce", "(", "travelOrderReducer", ",", "0", ")", ";", "const", "maxServiceSegmentsTravelOrder", "=", "serviceSegments", ".", "reduce", "(", "travelOrderReducer", ",", "0", ")", ";", "const", "maxOrder", "=", "Math", ".", "max", "(", "maxSegmentsTravelOrder", ",", "maxServiceSegmentsTravelOrder", ")", ";", "const", "allSegments", "=", "[", "]", ";", "for", "(", "let", "i", "=", "1", ";", "i", "<=", "maxOrder", ";", "i", "+=", "1", ")", "{", "segments", ".", "forEach", "(", "s", "=>", "(", "Number", "(", "s", ".", "TravelOrder", ")", "===", "i", "?", "allSegments", ".", "push", "(", "s", ")", ":", "null", ")", ")", ";", "serviceSegments", ".", "forEach", "(", "s", "=>", "(", "Number", "(", "s", ".", "TravelOrder", ")", "===", "i", "?", "allSegments", ".", "push", "(", "s", ")", ":", "null", ")", ")", ";", "}", "const", "indexedSegments", "=", "allSegments", ".", "map", "(", "(", "s", ",", "k", ")", "=>", "(", "{", "...", "s", ",", "index", ":", "k", "+", "1", "}", ")", ")", ";", "return", "{", "segments", ":", "indexedSegments", ".", "filter", "(", "s", "=>", "s", ".", "SegmentType", "===", "undefined", ")", ",", "serviceSegments", ":", "indexedSegments", ".", "filter", "(", "s", "=>", "s", ".", "SegmentType", "===", "'Service'", ")", ",", "}", ";", "}" ]
This function used to transform segments and service segments objects to arrays. After that this function try to set indexes with same as in terminal response order. So it needs to check `TravelOrder` field for that. @param segmentsObject @param serviceSegmentsObject @return {*}
[ "This", "function", "used", "to", "transform", "segments", "and", "service", "segments", "objects", "to", "arrays", ".", "After", "that", "this", "function", "try", "to", "set", "indexes", "with", "same", "as", "in", "terminal", "response", "order", ".", "So", "it", "needs", "to", "check", "TravelOrder", "field", "for", "that", "." ]
de43c1add967e7af629fe155505197dc55d637d4
https://github.com/Travelport-Ukraine/uapi-json/blob/de43c1add967e7af629fe155505197dc55d637d4/src/Services/Air/AirFormat.js#L244-L299
13,173
expressjs/cookie-parser
index.js
cookieParser
function cookieParser (secret, options) { var secrets = !secret || Array.isArray(secret) ? (secret || []) : [secret] return function cookieParser (req, res, next) { if (req.cookies) { return next() } var cookies = req.headers.cookie req.secret = secrets[0] req.cookies = Object.create(null) req.signedCookies = Object.create(null) // no cookies if (!cookies) { return next() } req.cookies = cookie.parse(cookies, options) // parse signed cookies if (secrets.length !== 0) { req.signedCookies = signedCookies(req.cookies, secrets) req.signedCookies = JSONCookies(req.signedCookies) } // parse JSON cookies req.cookies = JSONCookies(req.cookies) next() } }
javascript
function cookieParser (secret, options) { var secrets = !secret || Array.isArray(secret) ? (secret || []) : [secret] return function cookieParser (req, res, next) { if (req.cookies) { return next() } var cookies = req.headers.cookie req.secret = secrets[0] req.cookies = Object.create(null) req.signedCookies = Object.create(null) // no cookies if (!cookies) { return next() } req.cookies = cookie.parse(cookies, options) // parse signed cookies if (secrets.length !== 0) { req.signedCookies = signedCookies(req.cookies, secrets) req.signedCookies = JSONCookies(req.signedCookies) } // parse JSON cookies req.cookies = JSONCookies(req.cookies) next() } }
[ "function", "cookieParser", "(", "secret", ",", "options", ")", "{", "var", "secrets", "=", "!", "secret", "||", "Array", ".", "isArray", "(", "secret", ")", "?", "(", "secret", "||", "[", "]", ")", ":", "[", "secret", "]", "return", "function", "cookieParser", "(", "req", ",", "res", ",", "next", ")", "{", "if", "(", "req", ".", "cookies", ")", "{", "return", "next", "(", ")", "}", "var", "cookies", "=", "req", ".", "headers", ".", "cookie", "req", ".", "secret", "=", "secrets", "[", "0", "]", "req", ".", "cookies", "=", "Object", ".", "create", "(", "null", ")", "req", ".", "signedCookies", "=", "Object", ".", "create", "(", "null", ")", "// no cookies", "if", "(", "!", "cookies", ")", "{", "return", "next", "(", ")", "}", "req", ".", "cookies", "=", "cookie", ".", "parse", "(", "cookies", ",", "options", ")", "// parse signed cookies", "if", "(", "secrets", ".", "length", "!==", "0", ")", "{", "req", ".", "signedCookies", "=", "signedCookies", "(", "req", ".", "cookies", ",", "secrets", ")", "req", ".", "signedCookies", "=", "JSONCookies", "(", "req", ".", "signedCookies", ")", "}", "// parse JSON cookies", "req", ".", "cookies", "=", "JSONCookies", "(", "req", ".", "cookies", ")", "next", "(", ")", "}", "}" ]
Parse Cookie header and populate `req.cookies` with an object keyed by the cookie names. @param {string|array} [secret] A string (or array of strings) representing cookie signing secret(s). @param {Object} [options] @return {Function} @public
[ "Parse", "Cookie", "header", "and", "populate", "req", ".", "cookies", "with", "an", "object", "keyed", "by", "the", "cookie", "names", "." ]
26fd91a024c58bf2dbe0a05c6b8831b180c12d11
https://github.com/expressjs/cookie-parser/blob/26fd91a024c58bf2dbe0a05c6b8831b180c12d11/index.js#L39-L73
13,174
expressjs/cookie-parser
index.js
JSONCookie
function JSONCookie (str) { if (typeof str !== 'string' || str.substr(0, 2) !== 'j:') { return undefined } try { return JSON.parse(str.slice(2)) } catch (err) { return undefined } }
javascript
function JSONCookie (str) { if (typeof str !== 'string' || str.substr(0, 2) !== 'j:') { return undefined } try { return JSON.parse(str.slice(2)) } catch (err) { return undefined } }
[ "function", "JSONCookie", "(", "str", ")", "{", "if", "(", "typeof", "str", "!==", "'string'", "||", "str", ".", "substr", "(", "0", ",", "2", ")", "!==", "'j:'", ")", "{", "return", "undefined", "}", "try", "{", "return", "JSON", ".", "parse", "(", "str", ".", "slice", "(", "2", ")", ")", "}", "catch", "(", "err", ")", "{", "return", "undefined", "}", "}" ]
Parse JSON cookie string. @param {String} str @return {Object} Parsed object or undefined if not json cookie @public
[ "Parse", "JSON", "cookie", "string", "." ]
26fd91a024c58bf2dbe0a05c6b8831b180c12d11
https://github.com/expressjs/cookie-parser/blob/26fd91a024c58bf2dbe0a05c6b8831b180c12d11/index.js#L83-L93
13,175
expressjs/cookie-parser
index.js
JSONCookies
function JSONCookies (obj) { var cookies = Object.keys(obj) var key var val for (var i = 0; i < cookies.length; i++) { key = cookies[i] val = JSONCookie(obj[key]) if (val) { obj[key] = val } } return obj }
javascript
function JSONCookies (obj) { var cookies = Object.keys(obj) var key var val for (var i = 0; i < cookies.length; i++) { key = cookies[i] val = JSONCookie(obj[key]) if (val) { obj[key] = val } } return obj }
[ "function", "JSONCookies", "(", "obj", ")", "{", "var", "cookies", "=", "Object", ".", "keys", "(", "obj", ")", "var", "key", "var", "val", "for", "(", "var", "i", "=", "0", ";", "i", "<", "cookies", ".", "length", ";", "i", "++", ")", "{", "key", "=", "cookies", "[", "i", "]", "val", "=", "JSONCookie", "(", "obj", "[", "key", "]", ")", "if", "(", "val", ")", "{", "obj", "[", "key", "]", "=", "val", "}", "}", "return", "obj", "}" ]
Parse JSON cookies. @param {Object} obj @return {Object} @public
[ "Parse", "JSON", "cookies", "." ]
26fd91a024c58bf2dbe0a05c6b8831b180c12d11
https://github.com/expressjs/cookie-parser/blob/26fd91a024c58bf2dbe0a05c6b8831b180c12d11/index.js#L103-L118
13,176
Yaffle/EventSource
src/eventsource.js
function () { try { return new TextDecoder().decode(new TextEncoder().encode("test"), {stream: true}) === "test"; } catch (error) { console.log(error); } return false; }
javascript
function () { try { return new TextDecoder().decode(new TextEncoder().encode("test"), {stream: true}) === "test"; } catch (error) { console.log(error); } return false; }
[ "function", "(", ")", "{", "try", "{", "return", "new", "TextDecoder", "(", ")", ".", "decode", "(", "new", "TextEncoder", "(", ")", ".", "encode", "(", "\"test\"", ")", ",", "{", "stream", ":", "true", "}", ")", "===", "\"test\"", ";", "}", "catch", "(", "error", ")", "{", "console", ".", "log", "(", "error", ")", ";", "}", "return", "false", ";", "}" ]
Firefox < 38 throws an error with stream option
[ "Firefox", "<", "38", "throws", "an", "error", "with", "stream", "option" ]
c68b58eb7c35591af763fd704699ac8c9816defe
https://github.com/Yaffle/EventSource/blob/c68b58eb7c35591af763fd704699ac8c9816defe/src/eventsource.js#L148-L155
13,177
john-doherty/selenium-cucumber-js
page-objects/google-search.js
function (searchQuery) { var selector = page.googleSearch.elements.searchInput; // return a promise so the calling function knows the task has completed return driver.findElement(selector).sendKeys(searchQuery, selenium.Key.ENTER); }
javascript
function (searchQuery) { var selector = page.googleSearch.elements.searchInput; // return a promise so the calling function knows the task has completed return driver.findElement(selector).sendKeys(searchQuery, selenium.Key.ENTER); }
[ "function", "(", "searchQuery", ")", "{", "var", "selector", "=", "page", ".", "googleSearch", ".", "elements", ".", "searchInput", ";", "// return a promise so the calling function knows the task has completed", "return", "driver", ".", "findElement", "(", "selector", ")", ".", "sendKeys", "(", "searchQuery", ",", "selenium", ".", "Key", ".", "ENTER", ")", ";", "}" ]
enters a search term into Google's search box and presses enter @param {string} searchQuery @returns {Promise} a promise to enter the search values
[ "enters", "a", "search", "term", "into", "Google", "s", "search", "box", "and", "presses", "enter" ]
d29cd32ffafdc405fa5279fc9b50361d75c91e3c
https://github.com/john-doherty/selenium-cucumber-js/blob/d29cd32ffafdc405fa5279fc9b50361d75c91e3c/page-objects/google-search.js#L15-L21
13,178
john-doherty/selenium-cucumber-js
runtime/world.js
getDriverInstance
function getDriverInstance() { var driver; switch (browserName || '') { case 'firefox': { driver = new FireFoxDriver(); } break; case 'phantomjs': { driver = new PhantomJSDriver(); } break; case 'electron': { driver = new ElectronDriver(); } break; case 'chrome': { driver = new ChromeDriver(); } break; // try to load from file default: { var driverFileName = path.resolve(process.cwd(), browserName); if (!fs.isFileSync(driverFileName)) { throw new Error('Could not find driver file: ' + driverFileName); } driver = require(driverFileName)(); } } return driver; }
javascript
function getDriverInstance() { var driver; switch (browserName || '') { case 'firefox': { driver = new FireFoxDriver(); } break; case 'phantomjs': { driver = new PhantomJSDriver(); } break; case 'electron': { driver = new ElectronDriver(); } break; case 'chrome': { driver = new ChromeDriver(); } break; // try to load from file default: { var driverFileName = path.resolve(process.cwd(), browserName); if (!fs.isFileSync(driverFileName)) { throw new Error('Could not find driver file: ' + driverFileName); } driver = require(driverFileName)(); } } return driver; }
[ "function", "getDriverInstance", "(", ")", "{", "var", "driver", ";", "switch", "(", "browserName", "||", "''", ")", "{", "case", "'firefox'", ":", "{", "driver", "=", "new", "FireFoxDriver", "(", ")", ";", "}", "break", ";", "case", "'phantomjs'", ":", "{", "driver", "=", "new", "PhantomJSDriver", "(", ")", ";", "}", "break", ";", "case", "'electron'", ":", "{", "driver", "=", "new", "ElectronDriver", "(", ")", ";", "}", "break", ";", "case", "'chrome'", ":", "{", "driver", "=", "new", "ChromeDriver", "(", ")", ";", "}", "break", ";", "// try to load from file", "default", ":", "{", "var", "driverFileName", "=", "path", ".", "resolve", "(", "process", ".", "cwd", "(", ")", ",", "browserName", ")", ";", "if", "(", "!", "fs", ".", "isFileSync", "(", "driverFileName", ")", ")", "{", "throw", "new", "Error", "(", "'Could not find driver file: '", "+", "driverFileName", ")", ";", "}", "driver", "=", "require", "(", "driverFileName", ")", "(", ")", ";", "}", "}", "return", "driver", ";", "}" ]
create the selenium browser based on global var set in index.js @returns {ThenableWebDriver} selenium web driver
[ "create", "the", "selenium", "browser", "based", "on", "global", "var", "set", "in", "index", ".", "js" ]
d29cd32ffafdc405fa5279fc9b50361d75c91e3c
https://github.com/john-doherty/selenium-cucumber-js/blob/d29cd32ffafdc405fa5279fc9b50361d75c91e3c/runtime/world.js#L32-L71
13,179
john-doherty/selenium-cucumber-js
runtime/world.js
getEyesInstance
function getEyesInstance() { if (global.eyesKey) { var eyes = new Eyes(); // retrieve eyes api key from config file in the project root as defined by the user eyes.setApiKey(global.eyesKey); return eyes; } return null; }
javascript
function getEyesInstance() { if (global.eyesKey) { var eyes = new Eyes(); // retrieve eyes api key from config file in the project root as defined by the user eyes.setApiKey(global.eyesKey); return eyes; } return null; }
[ "function", "getEyesInstance", "(", ")", "{", "if", "(", "global", ".", "eyesKey", ")", "{", "var", "eyes", "=", "new", "Eyes", "(", ")", ";", "// retrieve eyes api key from config file in the project root as defined by the user", "eyes", ".", "setApiKey", "(", "global", ".", "eyesKey", ")", ";", "return", "eyes", ";", "}", "return", "null", ";", "}" ]
Initialize the eyes SDK and set your private API key via the config file.
[ "Initialize", "the", "eyes", "SDK", "and", "set", "your", "private", "API", "key", "via", "the", "config", "file", "." ]
d29cd32ffafdc405fa5279fc9b50361d75c91e3c
https://github.com/john-doherty/selenium-cucumber-js/blob/d29cd32ffafdc405fa5279fc9b50361d75c91e3c/runtime/world.js#L77-L90
13,180
john-doherty/selenium-cucumber-js
runtime/world.js
createWorld
function createWorld() { var runtime = { driver: null, // the browser object eyes: null, selenium: selenium, // the raw nodejs selenium driver By: selenium.By, // in keeping with Java expose selenium By by: selenium.By, // provide a javascript lowercase version until: selenium.until, // provide easy access to selenium until methods expect: expect, // expose chai expect to allow variable testing assert: assert, // expose chai assert to allow variable testing trace: consoleInfo, // expose an info method to log output to the console in a readable/visible format page: global.page || {}, // empty page objects placeholder shared: global.shared || {} // empty shared objects placeholder }; // expose properties to step definition methods via global variables Object.keys(runtime).forEach(function (key) { if (key === 'driver' && browserTeardownStrategy !== 'always') { return; } // make property/method available as a global (no this. prefix required) global[key] = runtime[key]; }); }
javascript
function createWorld() { var runtime = { driver: null, // the browser object eyes: null, selenium: selenium, // the raw nodejs selenium driver By: selenium.By, // in keeping with Java expose selenium By by: selenium.By, // provide a javascript lowercase version until: selenium.until, // provide easy access to selenium until methods expect: expect, // expose chai expect to allow variable testing assert: assert, // expose chai assert to allow variable testing trace: consoleInfo, // expose an info method to log output to the console in a readable/visible format page: global.page || {}, // empty page objects placeholder shared: global.shared || {} // empty shared objects placeholder }; // expose properties to step definition methods via global variables Object.keys(runtime).forEach(function (key) { if (key === 'driver' && browserTeardownStrategy !== 'always') { return; } // make property/method available as a global (no this. prefix required) global[key] = runtime[key]; }); }
[ "function", "createWorld", "(", ")", "{", "var", "runtime", "=", "{", "driver", ":", "null", ",", "// the browser object", "eyes", ":", "null", ",", "selenium", ":", "selenium", ",", "// the raw nodejs selenium driver", "By", ":", "selenium", ".", "By", ",", "// in keeping with Java expose selenium By", "by", ":", "selenium", ".", "By", ",", "// provide a javascript lowercase version", "until", ":", "selenium", ".", "until", ",", "// provide easy access to selenium until methods", "expect", ":", "expect", ",", "// expose chai expect to allow variable testing", "assert", ":", "assert", ",", "// expose chai assert to allow variable testing", "trace", ":", "consoleInfo", ",", "// expose an info method to log output to the console in a readable/visible format", "page", ":", "global", ".", "page", "||", "{", "}", ",", "// empty page objects placeholder", "shared", ":", "global", ".", "shared", "||", "{", "}", "// empty shared objects placeholder", "}", ";", "// expose properties to step definition methods via global variables", "Object", ".", "keys", "(", "runtime", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "if", "(", "key", "===", "'driver'", "&&", "browserTeardownStrategy", "!==", "'always'", ")", "{", "return", ";", "}", "// make property/method available as a global (no this. prefix required)", "global", "[", "key", "]", "=", "runtime", "[", "key", "]", ";", "}", ")", ";", "}" ]
Creates a list of variables to expose globally and therefore accessible within each step definition @returns {void}
[ "Creates", "a", "list", "of", "variables", "to", "expose", "globally", "and", "therefore", "accessible", "within", "each", "step", "definition" ]
d29cd32ffafdc405fa5279fc9b50361d75c91e3c
https://github.com/john-doherty/selenium-cucumber-js/blob/d29cd32ffafdc405fa5279fc9b50361d75c91e3c/runtime/world.js#L103-L128
13,181
john-doherty/selenium-cucumber-js
runtime/world.js
importSupportObjects
function importSupportObjects() { // import shared objects from multiple paths (after global vars have been created) if (global.sharedObjectPaths && Array.isArray(global.sharedObjectPaths) && global.sharedObjectPaths.length > 0) { var allDirs = {}; // first require directories into objects by directory global.sharedObjectPaths.forEach(function (itemPath) { if (fs.existsSync(itemPath)) { var dir = requireDir(itemPath, { camelcase: true, recurse: true }); merge(allDirs, dir); } }); // if we managed to import some directories, expose them if (Object.keys(allDirs).length > 0) { // expose globally global.shared = allDirs; } } // import page objects (after global vars have been created) if (global.pageObjectPath && fs.existsSync(global.pageObjectPath)) { // require all page objects using camel case as object names global.page = requireDir(global.pageObjectPath, { camelcase: true, recurse: true }); } // add helpers global.helpers = require('../runtime/helpers.js'); }
javascript
function importSupportObjects() { // import shared objects from multiple paths (after global vars have been created) if (global.sharedObjectPaths && Array.isArray(global.sharedObjectPaths) && global.sharedObjectPaths.length > 0) { var allDirs = {}; // first require directories into objects by directory global.sharedObjectPaths.forEach(function (itemPath) { if (fs.existsSync(itemPath)) { var dir = requireDir(itemPath, { camelcase: true, recurse: true }); merge(allDirs, dir); } }); // if we managed to import some directories, expose them if (Object.keys(allDirs).length > 0) { // expose globally global.shared = allDirs; } } // import page objects (after global vars have been created) if (global.pageObjectPath && fs.existsSync(global.pageObjectPath)) { // require all page objects using camel case as object names global.page = requireDir(global.pageObjectPath, { camelcase: true, recurse: true }); } // add helpers global.helpers = require('../runtime/helpers.js'); }
[ "function", "importSupportObjects", "(", ")", "{", "// import shared objects from multiple paths (after global vars have been created)", "if", "(", "global", ".", "sharedObjectPaths", "&&", "Array", ".", "isArray", "(", "global", ".", "sharedObjectPaths", ")", "&&", "global", ".", "sharedObjectPaths", ".", "length", ">", "0", ")", "{", "var", "allDirs", "=", "{", "}", ";", "// first require directories into objects by directory", "global", ".", "sharedObjectPaths", ".", "forEach", "(", "function", "(", "itemPath", ")", "{", "if", "(", "fs", ".", "existsSync", "(", "itemPath", ")", ")", "{", "var", "dir", "=", "requireDir", "(", "itemPath", ",", "{", "camelcase", ":", "true", ",", "recurse", ":", "true", "}", ")", ";", "merge", "(", "allDirs", ",", "dir", ")", ";", "}", "}", ")", ";", "// if we managed to import some directories, expose them", "if", "(", "Object", ".", "keys", "(", "allDirs", ")", ".", "length", ">", "0", ")", "{", "// expose globally", "global", ".", "shared", "=", "allDirs", ";", "}", "}", "// import page objects (after global vars have been created)", "if", "(", "global", ".", "pageObjectPath", "&&", "fs", ".", "existsSync", "(", "global", ".", "pageObjectPath", ")", ")", "{", "// require all page objects using camel case as object names", "global", ".", "page", "=", "requireDir", "(", "global", ".", "pageObjectPath", ",", "{", "camelcase", ":", "true", ",", "recurse", ":", "true", "}", ")", ";", "}", "// add helpers", "global", ".", "helpers", "=", "require", "(", "'../runtime/helpers.js'", ")", ";", "}" ]
Import shared objects, pages object and helpers into global scope @returns {void}
[ "Import", "shared", "objects", "pages", "object", "and", "helpers", "into", "global", "scope" ]
d29cd32ffafdc405fa5279fc9b50361d75c91e3c
https://github.com/john-doherty/selenium-cucumber-js/blob/d29cd32ffafdc405fa5279fc9b50361d75c91e3c/runtime/world.js#L134-L169
13,182
john-doherty/selenium-cucumber-js
runtime/helpers.js
function(url, waitInSeconds) { // use either passed in timeout or global default var timeout = (waitInSeconds) ? (waitInSeconds * 1000) : DEFAULT_TIMEOUT; // load the url and wait for it to complete return driver.get(url).then(function() { // now wait for the body element to be present return driver.wait(until.elementLocated(by.css('body')), timeout); }); }
javascript
function(url, waitInSeconds) { // use either passed in timeout or global default var timeout = (waitInSeconds) ? (waitInSeconds * 1000) : DEFAULT_TIMEOUT; // load the url and wait for it to complete return driver.get(url).then(function() { // now wait for the body element to be present return driver.wait(until.elementLocated(by.css('body')), timeout); }); }
[ "function", "(", "url", ",", "waitInSeconds", ")", "{", "// use either passed in timeout or global default", "var", "timeout", "=", "(", "waitInSeconds", ")", "?", "(", "waitInSeconds", "*", "1000", ")", ":", "DEFAULT_TIMEOUT", ";", "// load the url and wait for it to complete", "return", "driver", ".", "get", "(", "url", ")", ".", "then", "(", "function", "(", ")", "{", "// now wait for the body element to be present", "return", "driver", ".", "wait", "(", "until", ".", "elementLocated", "(", "by", ".", "css", "(", "'body'", ")", ")", ",", "timeout", ")", ";", "}", ")", ";", "}" ]
returns a promise that is called when the url has loaded and the body element is present @param {string} url - url to load @param {integer} waitInSeconds - number of seconds to wait for page to load @returns {Promise} resolved when url has loaded otherwise rejects @example helpers.loadPage('http://www.google.com');
[ "returns", "a", "promise", "that", "is", "called", "when", "the", "url", "has", "loaded", "and", "the", "body", "element", "is", "present" ]
d29cd32ffafdc405fa5279fc9b50361d75c91e3c
https://github.com/john-doherty/selenium-cucumber-js/blob/d29cd32ffafdc405fa5279fc9b50361d75c91e3c/runtime/helpers.js#L11-L22
13,183
john-doherty/selenium-cucumber-js
runtime/helpers.js
function (htmlCssSelector, attributeName) { // get the element from the page return driver.findElement(by.css(htmlCssSelector)).then(function(el) { return el.getAttribute(attributeName); }); }
javascript
function (htmlCssSelector, attributeName) { // get the element from the page return driver.findElement(by.css(htmlCssSelector)).then(function(el) { return el.getAttribute(attributeName); }); }
[ "function", "(", "htmlCssSelector", ",", "attributeName", ")", "{", "// get the element from the page", "return", "driver", ".", "findElement", "(", "by", ".", "css", "(", "htmlCssSelector", ")", ")", ".", "then", "(", "function", "(", "el", ")", "{", "return", "el", ".", "getAttribute", "(", "attributeName", ")", ";", "}", ")", ";", "}" ]
returns the value of an attribute on an element @param {string} htmlCssSelector - HTML css selector used to find the element @param {string} attributeName - attribute name to retrieve @returns {string} the value of the attribute or empty string if not found @example helpers.getAttributeValue('body', 'class');
[ "returns", "the", "value", "of", "an", "attribute", "on", "an", "element" ]
d29cd32ffafdc405fa5279fc9b50361d75c91e3c
https://github.com/john-doherty/selenium-cucumber-js/blob/d29cd32ffafdc405fa5279fc9b50361d75c91e3c/runtime/helpers.js#L32-L38
13,184
john-doherty/selenium-cucumber-js
runtime/helpers.js
function(elementSelector, attributeName, waitInMilliseconds) { // use either passed in timeout or global default var timeout = waitInMilliseconds || DEFAULT_TIMEOUT; // readable error message var timeoutMessage = attributeName + ' does not exists after ' + waitInMilliseconds + ' milliseconds'; // repeatedly execute the test until it's true or we timeout return driver.wait(function() { // get the html attribute value using helper method return helpers.getAttributeValue(elementSelector, attributeName).then(function(value) { // attribute exists if value is not null return value !== null; }); }, timeout, timeoutMessage); }
javascript
function(elementSelector, attributeName, waitInMilliseconds) { // use either passed in timeout or global default var timeout = waitInMilliseconds || DEFAULT_TIMEOUT; // readable error message var timeoutMessage = attributeName + ' does not exists after ' + waitInMilliseconds + ' milliseconds'; // repeatedly execute the test until it's true or we timeout return driver.wait(function() { // get the html attribute value using helper method return helpers.getAttributeValue(elementSelector, attributeName).then(function(value) { // attribute exists if value is not null return value !== null; }); }, timeout, timeoutMessage); }
[ "function", "(", "elementSelector", ",", "attributeName", ",", "waitInMilliseconds", ")", "{", "// use either passed in timeout or global default", "var", "timeout", "=", "waitInMilliseconds", "||", "DEFAULT_TIMEOUT", ";", "// readable error message", "var", "timeoutMessage", "=", "attributeName", "+", "' does not exists after '", "+", "waitInMilliseconds", "+", "' milliseconds'", ";", "// repeatedly execute the test until it's true or we timeout", "return", "driver", ".", "wait", "(", "function", "(", ")", "{", "// get the html attribute value using helper method", "return", "helpers", ".", "getAttributeValue", "(", "elementSelector", ",", "attributeName", ")", ".", "then", "(", "function", "(", "value", ")", "{", "// attribute exists if value is not null", "return", "value", "!==", "null", ";", "}", ")", ";", "}", ",", "timeout", ",", "timeoutMessage", ")", ";", "}" ]
Waits until a HTML attribute exists @param {string} elementSelector - HTML element CSS selector @param {string} attributeName - name of the attribute to inspect @param {integer} waitInMilliseconds - number of milliseconds to wait for page to load @returns {Promise} resolves if attribute exists within timeout, otherwise rejects @example helpers.waitUntilAttributeExists('html', 'data-busy', 5000);
[ "Waits", "until", "a", "HTML", "attribute", "exists" ]
d29cd32ffafdc405fa5279fc9b50361d75c91e3c
https://github.com/john-doherty/selenium-cucumber-js/blob/d29cd32ffafdc405fa5279fc9b50361d75c91e3c/runtime/helpers.js#L169-L188
13,185
ktquez/vue-head
vue-head.js
function () { if (!els.length) return els.map(function (el) { el.parentElement.removeChild(el) }) els = [] }
javascript
function () { if (!els.length) return els.map(function (el) { el.parentElement.removeChild(el) }) els = [] }
[ "function", "(", ")", "{", "if", "(", "!", "els", ".", "length", ")", "return", "els", ".", "map", "(", "function", "(", "el", ")", "{", "el", ".", "parentElement", ".", "removeChild", "(", "el", ")", "}", ")", "els", "=", "[", "]", "}" ]
Undo elements to its previous state @type {Function}
[ "Undo", "elements", "to", "its", "previous", "state" ]
0ff9d248cea22191539606e3009ab7591f6c2f11
https://github.com/ktquez/vue-head/blob/0ff9d248cea22191539606e3009ab7591f6c2f11/vue-head.js#L63-L69
13,186
ktquez/vue-head
vue-head.js
function (obj, el) { var self = this Object.keys(obj).map(function (prop) { var sh = self.shorthand[prop] || prop if (sh.match(/(body|undo|replace)/g)) return if (sh === 'inner') { el.textContent = obj[prop] return } el.setAttribute(sh, obj[prop]) }) return el }
javascript
function (obj, el) { var self = this Object.keys(obj).map(function (prop) { var sh = self.shorthand[prop] || prop if (sh.match(/(body|undo|replace)/g)) return if (sh === 'inner') { el.textContent = obj[prop] return } el.setAttribute(sh, obj[prop]) }) return el }
[ "function", "(", "obj", ",", "el", ")", "{", "var", "self", "=", "this", "Object", ".", "keys", "(", "obj", ")", ".", "map", "(", "function", "(", "prop", ")", "{", "var", "sh", "=", "self", ".", "shorthand", "[", "prop", "]", "||", "prop", "if", "(", "sh", ".", "match", "(", "/", "(body|undo|replace)", "/", "g", ")", ")", "return", "if", "(", "sh", "===", "'inner'", ")", "{", "el", ".", "textContent", "=", "obj", "[", "prop", "]", "return", "}", "el", ".", "setAttribute", "(", "sh", ",", "obj", "[", "prop", "]", ")", "}", ")", "return", "el", "}" ]
Set attributes in element @type {Function} @param {Object} obj @param {HTMLElement} el @return {HTMLElement} with defined attributes
[ "Set", "attributes", "in", "element" ]
0ff9d248cea22191539606e3009ab7591f6c2f11
https://github.com/ktquez/vue-head/blob/0ff9d248cea22191539606e3009ab7591f6c2f11/vue-head.js#L78-L90
13,187
ktquez/vue-head
vue-head.js
function (obj) { if (!obj) return diffTitle.before = opt.complement var title = obj.inner + ' ' + (obj.separator || opt.separator) + ' ' + (obj.complement || opt.complement) window.document.title = title.trim() }
javascript
function (obj) { if (!obj) return diffTitle.before = opt.complement var title = obj.inner + ' ' + (obj.separator || opt.separator) + ' ' + (obj.complement || opt.complement) window.document.title = title.trim() }
[ "function", "(", "obj", ")", "{", "if", "(", "!", "obj", ")", "return", "diffTitle", ".", "before", "=", "opt", ".", "complement", "var", "title", "=", "obj", ".", "inner", "+", "' '", "+", "(", "obj", ".", "separator", "||", "opt", ".", "separator", ")", "+", "' '", "+", "(", "obj", ".", "complement", "||", "opt", ".", "complement", ")", "window", ".", "document", ".", "title", "=", "title", ".", "trim", "(", ")", "}" ]
Change window.document title @type {Function} @param {Object} obj
[ "Change", "window", ".", "document", "title" ]
0ff9d248cea22191539606e3009ab7591f6c2f11
https://github.com/ktquez/vue-head/blob/0ff9d248cea22191539606e3009ab7591f6c2f11/vue-head.js#L97-L103
13,188
ktquez/vue-head
vue-head.js
function (arr, tag, place, update) { var self = this if (!arr) return arr.map(function (obj) { var parent = (obj.body) ? self.getPlace('body') : self.getPlace(place) var el = window.document.getElementById(obj.id) || window.document.createElement(tag) // Elements that will substitute data if (el.hasAttribute('id')) { self.prepareElement(obj, el) return } // Other elements el = self.prepareElement(obj, el) // Updated elements if (update) { diffEls.push(el) return } // Append Elements self.add(obj, el, parent) }) }
javascript
function (arr, tag, place, update) { var self = this if (!arr) return arr.map(function (obj) { var parent = (obj.body) ? self.getPlace('body') : self.getPlace(place) var el = window.document.getElementById(obj.id) || window.document.createElement(tag) // Elements that will substitute data if (el.hasAttribute('id')) { self.prepareElement(obj, el) return } // Other elements el = self.prepareElement(obj, el) // Updated elements if (update) { diffEls.push(el) return } // Append Elements self.add(obj, el, parent) }) }
[ "function", "(", "arr", ",", "tag", ",", "place", ",", "update", ")", "{", "var", "self", "=", "this", "if", "(", "!", "arr", ")", "return", "arr", ".", "map", "(", "function", "(", "obj", ")", "{", "var", "parent", "=", "(", "obj", ".", "body", ")", "?", "self", ".", "getPlace", "(", "'body'", ")", ":", "self", ".", "getPlace", "(", "place", ")", "var", "el", "=", "window", ".", "document", ".", "getElementById", "(", "obj", ".", "id", ")", "||", "window", ".", "document", ".", "createElement", "(", "tag", ")", "// Elements that will substitute data", "if", "(", "el", ".", "hasAttribute", "(", "'id'", ")", ")", "{", "self", ".", "prepareElement", "(", "obj", ",", "el", ")", "return", "}", "// Other elements", "el", "=", "self", ".", "prepareElement", "(", "obj", ",", "el", ")", "// Updated elements", "if", "(", "update", ")", "{", "diffEls", ".", "push", "(", "el", ")", "return", "}", "// Append Elements", "self", ".", "add", "(", "obj", ",", "el", ",", "parent", ")", "}", ")", "}" ]
Handle of create elements @type {Function} @param {Array} arr @param {String} tag - style, link, meta, script, base @param {String} place - Default 'head' @param {Boolean} update
[ "Handle", "of", "create", "elements" ]
0ff9d248cea22191539606e3009ab7591f6c2f11
https://github.com/ktquez/vue-head/blob/0ff9d248cea22191539606e3009ab7591f6c2f11/vue-head.js#L142-L163
13,189
ktquez/vue-head
vue-head.js
VueHead
function VueHead (Vue, options) { if (installed) return installed = true if (options) { Vue.util.extend(opt, options) } /** * Initializes and updates the elements in the head * @param {Boolean} update */ function init (update) { var self = this var head = (typeof self.$options.head === 'function') ? self.$options.head.bind(self)() : self.$options.head if (!head) return Object.keys(head).map(function (key) { var prop = head[key] if (!prop) return var obj = (typeof prop === 'function') ? head[key].bind(self)() : head[key] if (key === 'title') { util[key](obj) return } util.handle(obj, key, 'head', update) }) self.$emit('okHead') } /** * Remove the meta tags elements in the head */ function destroy () { if (!this.$options.head) return util.undoTitle(diffTitle) util.undo() } // v1 if (Vue.version.match(/[1].(.)+/g)) { Vue.mixin({ ready: function () { init.bind(this)() }, destroyed: function () { destroy.bind(this)() }, events: { updateHead: function () { init.bind(this)(true) util.update() } } }) } // v2 if (Vue.version.match(/[2].(.)+/g)) { Vue.mixin({ created: function () { var self = this self.$on('updateHead', function () { init.bind(self)(true) util.update() }) }, mounted: function () { init.bind(this)() }, beforeDestroy: function () { destroy.bind(this)() } }) } }
javascript
function VueHead (Vue, options) { if (installed) return installed = true if (options) { Vue.util.extend(opt, options) } /** * Initializes and updates the elements in the head * @param {Boolean} update */ function init (update) { var self = this var head = (typeof self.$options.head === 'function') ? self.$options.head.bind(self)() : self.$options.head if (!head) return Object.keys(head).map(function (key) { var prop = head[key] if (!prop) return var obj = (typeof prop === 'function') ? head[key].bind(self)() : head[key] if (key === 'title') { util[key](obj) return } util.handle(obj, key, 'head', update) }) self.$emit('okHead') } /** * Remove the meta tags elements in the head */ function destroy () { if (!this.$options.head) return util.undoTitle(diffTitle) util.undo() } // v1 if (Vue.version.match(/[1].(.)+/g)) { Vue.mixin({ ready: function () { init.bind(this)() }, destroyed: function () { destroy.bind(this)() }, events: { updateHead: function () { init.bind(this)(true) util.update() } } }) } // v2 if (Vue.version.match(/[2].(.)+/g)) { Vue.mixin({ created: function () { var self = this self.$on('updateHead', function () { init.bind(self)(true) util.update() }) }, mounted: function () { init.bind(this)() }, beforeDestroy: function () { destroy.bind(this)() } }) } }
[ "function", "VueHead", "(", "Vue", ",", "options", ")", "{", "if", "(", "installed", ")", "return", "installed", "=", "true", "if", "(", "options", ")", "{", "Vue", ".", "util", ".", "extend", "(", "opt", ",", "options", ")", "}", "/**\n * Initializes and updates the elements in the head\n * @param {Boolean} update\n */", "function", "init", "(", "update", ")", "{", "var", "self", "=", "this", "var", "head", "=", "(", "typeof", "self", ".", "$options", ".", "head", "===", "'function'", ")", "?", "self", ".", "$options", ".", "head", ".", "bind", "(", "self", ")", "(", ")", ":", "self", ".", "$options", ".", "head", "if", "(", "!", "head", ")", "return", "Object", ".", "keys", "(", "head", ")", ".", "map", "(", "function", "(", "key", ")", "{", "var", "prop", "=", "head", "[", "key", "]", "if", "(", "!", "prop", ")", "return", "var", "obj", "=", "(", "typeof", "prop", "===", "'function'", ")", "?", "head", "[", "key", "]", ".", "bind", "(", "self", ")", "(", ")", ":", "head", "[", "key", "]", "if", "(", "key", "===", "'title'", ")", "{", "util", "[", "key", "]", "(", "obj", ")", "return", "}", "util", ".", "handle", "(", "obj", ",", "key", ",", "'head'", ",", "update", ")", "}", ")", "self", ".", "$emit", "(", "'okHead'", ")", "}", "/**\n * Remove the meta tags elements in the head\n */", "function", "destroy", "(", ")", "{", "if", "(", "!", "this", ".", "$options", ".", "head", ")", "return", "util", ".", "undoTitle", "(", "diffTitle", ")", "util", ".", "undo", "(", ")", "}", "// v1", "if", "(", "Vue", ".", "version", ".", "match", "(", "/", "[1].(.)+", "/", "g", ")", ")", "{", "Vue", ".", "mixin", "(", "{", "ready", ":", "function", "(", ")", "{", "init", ".", "bind", "(", "this", ")", "(", ")", "}", ",", "destroyed", ":", "function", "(", ")", "{", "destroy", ".", "bind", "(", "this", ")", "(", ")", "}", ",", "events", ":", "{", "updateHead", ":", "function", "(", ")", "{", "init", ".", "bind", "(", "this", ")", "(", "true", ")", "util", ".", "update", "(", ")", "}", "}", "}", ")", "}", "// v2", "if", "(", "Vue", ".", "version", ".", "match", "(", "/", "[2].(.)+", "/", "g", ")", ")", "{", "Vue", ".", "mixin", "(", "{", "created", ":", "function", "(", ")", "{", "var", "self", "=", "this", "self", ".", "$on", "(", "'updateHead'", ",", "function", "(", ")", "{", "init", ".", "bind", "(", "self", ")", "(", "true", ")", "util", ".", "update", "(", ")", "}", ")", "}", ",", "mounted", ":", "function", "(", ")", "{", "init", ".", "bind", "(", "this", ")", "(", ")", "}", ",", "beforeDestroy", ":", "function", "(", ")", "{", "destroy", ".", "bind", "(", "this", ")", "(", ")", "}", "}", ")", "}", "}" ]
Plugin | vue-head @param {Function} Vue @param {Object} options
[ "Plugin", "|", "vue", "-", "head" ]
0ff9d248cea22191539606e3009ab7591f6c2f11
https://github.com/ktquez/vue-head/blob/0ff9d248cea22191539606e3009ab7591f6c2f11/vue-head.js#L171-L245
13,190
ktquez/vue-head
vue-head.js
init
function init (update) { var self = this var head = (typeof self.$options.head === 'function') ? self.$options.head.bind(self)() : self.$options.head if (!head) return Object.keys(head).map(function (key) { var prop = head[key] if (!prop) return var obj = (typeof prop === 'function') ? head[key].bind(self)() : head[key] if (key === 'title') { util[key](obj) return } util.handle(obj, key, 'head', update) }) self.$emit('okHead') }
javascript
function init (update) { var self = this var head = (typeof self.$options.head === 'function') ? self.$options.head.bind(self)() : self.$options.head if (!head) return Object.keys(head).map(function (key) { var prop = head[key] if (!prop) return var obj = (typeof prop === 'function') ? head[key].bind(self)() : head[key] if (key === 'title') { util[key](obj) return } util.handle(obj, key, 'head', update) }) self.$emit('okHead') }
[ "function", "init", "(", "update", ")", "{", "var", "self", "=", "this", "var", "head", "=", "(", "typeof", "self", ".", "$options", ".", "head", "===", "'function'", ")", "?", "self", ".", "$options", ".", "head", ".", "bind", "(", "self", ")", "(", ")", ":", "self", ".", "$options", ".", "head", "if", "(", "!", "head", ")", "return", "Object", ".", "keys", "(", "head", ")", ".", "map", "(", "function", "(", "key", ")", "{", "var", "prop", "=", "head", "[", "key", "]", "if", "(", "!", "prop", ")", "return", "var", "obj", "=", "(", "typeof", "prop", "===", "'function'", ")", "?", "head", "[", "key", "]", ".", "bind", "(", "self", ")", "(", ")", ":", "head", "[", "key", "]", "if", "(", "key", "===", "'title'", ")", "{", "util", "[", "key", "]", "(", "obj", ")", "return", "}", "util", ".", "handle", "(", "obj", ",", "key", ",", "'head'", ",", "update", ")", "}", ")", "self", ".", "$emit", "(", "'okHead'", ")", "}" ]
Initializes and updates the elements in the head @param {Boolean} update
[ "Initializes", "and", "updates", "the", "elements", "in", "the", "head" ]
0ff9d248cea22191539606e3009ab7591f6c2f11
https://github.com/ktquez/vue-head/blob/0ff9d248cea22191539606e3009ab7591f6c2f11/vue-head.js#L184-L199
13,191
C2FO/fast-csv
lib/formatter/formatter.js
gatherHeaders
function gatherHeaders(item) { var ret, i, l; if (isHashArray(item)) { //lets assume a multidimesional array with item 0 bing the title i = -1; l = item.length; ret = []; while (++i < l) { ret[i] = item[i][0]; } } else if (isArray(item)) { ret = item; } else { ret = keys(item); } return ret; }
javascript
function gatherHeaders(item) { var ret, i, l; if (isHashArray(item)) { //lets assume a multidimesional array with item 0 bing the title i = -1; l = item.length; ret = []; while (++i < l) { ret[i] = item[i][0]; } } else if (isArray(item)) { ret = item; } else { ret = keys(item); } return ret; }
[ "function", "gatherHeaders", "(", "item", ")", "{", "var", "ret", ",", "i", ",", "l", ";", "if", "(", "isHashArray", "(", "item", ")", ")", "{", "//lets assume a multidimesional array with item 0 bing the title", "i", "=", "-", "1", ";", "l", "=", "item", ".", "length", ";", "ret", "=", "[", "]", ";", "while", "(", "++", "i", "<", "l", ")", "{", "ret", "[", "i", "]", "=", "item", "[", "i", "]", "[", "0", "]", ";", "}", "}", "else", "if", "(", "isArray", "(", "item", ")", ")", "{", "ret", "=", "item", ";", "}", "else", "{", "ret", "=", "keys", "(", "item", ")", ";", "}", "return", "ret", ";", "}" ]
get headers from a row item
[ "get", "headers", "from", "a", "row", "item" ]
d4e33a2b5397afe188a08df01a1a3562efe8e3a1
https://github.com/C2FO/fast-csv/blob/d4e33a2b5397afe188a08df01a1a3562efe8e3a1/lib/formatter/formatter.js#L104-L120
13,192
C2FO/fast-csv
lib/formatter/formatter.js
transformHashData
function transformHashData(stream, item) { var vals = [], row = [], headers = stream.headers, i = -1, headersLength = stream.headersLength; if (stream.totalCount++) { row.push(stream.rowDelimiter); } while (++i < headersLength) { vals[i] = item[headers[i]]; } row.push(stream.formatter(vals)); return row.join(""); }
javascript
function transformHashData(stream, item) { var vals = [], row = [], headers = stream.headers, i = -1, headersLength = stream.headersLength; if (stream.totalCount++) { row.push(stream.rowDelimiter); } while (++i < headersLength) { vals[i] = item[headers[i]]; } row.push(stream.formatter(vals)); return row.join(""); }
[ "function", "transformHashData", "(", "stream", ",", "item", ")", "{", "var", "vals", "=", "[", "]", ",", "row", "=", "[", "]", ",", "headers", "=", "stream", ".", "headers", ",", "i", "=", "-", "1", ",", "headersLength", "=", "stream", ".", "headersLength", ";", "if", "(", "stream", ".", "totalCount", "++", ")", "{", "row", ".", "push", "(", "stream", ".", "rowDelimiter", ")", ";", "}", "while", "(", "++", "i", "<", "headersLength", ")", "{", "vals", "[", "i", "]", "=", "item", "[", "headers", "[", "i", "]", "]", ";", "}", "row", ".", "push", "(", "stream", ".", "formatter", "(", "vals", ")", ")", ";", "return", "row", ".", "join", "(", "\"\"", ")", ";", "}" ]
transform an object into a CSV row
[ "transform", "an", "object", "into", "a", "CSV", "row" ]
d4e33a2b5397afe188a08df01a1a3562efe8e3a1
https://github.com/C2FO/fast-csv/blob/d4e33a2b5397afe188a08df01a1a3562efe8e3a1/lib/formatter/formatter.js#L141-L151
13,193
C2FO/fast-csv
lib/formatter/formatter.js
transformArrayData
function transformArrayData(stream, item, cb) { var row = []; if (stream.totalCount++) { row.push(stream.rowDelimiter); } row.push(stream.formatter(item)); return row.join(""); }
javascript
function transformArrayData(stream, item, cb) { var row = []; if (stream.totalCount++) { row.push(stream.rowDelimiter); } row.push(stream.formatter(item)); return row.join(""); }
[ "function", "transformArrayData", "(", "stream", ",", "item", ",", "cb", ")", "{", "var", "row", "=", "[", "]", ";", "if", "(", "stream", ".", "totalCount", "++", ")", "{", "row", ".", "push", "(", "stream", ".", "rowDelimiter", ")", ";", "}", "row", ".", "push", "(", "stream", ".", "formatter", "(", "item", ")", ")", ";", "return", "row", ".", "join", "(", "\"\"", ")", ";", "}" ]
transform an array into a CSV row
[ "transform", "an", "array", "into", "a", "CSV", "row" ]
d4e33a2b5397afe188a08df01a1a3562efe8e3a1
https://github.com/C2FO/fast-csv/blob/d4e33a2b5397afe188a08df01a1a3562efe8e3a1/lib/formatter/formatter.js#L154-L161
13,194
C2FO/fast-csv
lib/formatter/formatter.js
transformHashArrayData
function transformHashArrayData(stream, item) { var vals = [], row = [], i = -1, headersLength = stream.headersLength; if (stream.totalCount++) { row.push(stream.rowDelimiter); } while (++i < headersLength) { vals[i] = item[i][1]; } row.push(stream.formatter(vals)); return row.join(""); }
javascript
function transformHashArrayData(stream, item) { var vals = [], row = [], i = -1, headersLength = stream.headersLength; if (stream.totalCount++) { row.push(stream.rowDelimiter); } while (++i < headersLength) { vals[i] = item[i][1]; } row.push(stream.formatter(vals)); return row.join(""); }
[ "function", "transformHashArrayData", "(", "stream", ",", "item", ")", "{", "var", "vals", "=", "[", "]", ",", "row", "=", "[", "]", ",", "i", "=", "-", "1", ",", "headersLength", "=", "stream", ".", "headersLength", ";", "if", "(", "stream", ".", "totalCount", "++", ")", "{", "row", ".", "push", "(", "stream", ".", "rowDelimiter", ")", ";", "}", "while", "(", "++", "i", "<", "headersLength", ")", "{", "vals", "[", "i", "]", "=", "item", "[", "i", "]", "[", "1", "]", ";", "}", "row", ".", "push", "(", "stream", ".", "formatter", "(", "vals", ")", ")", ";", "return", "row", ".", "join", "(", "\"\"", ")", ";", "}" ]
transform an array of two item arrays into a CSV row
[ "transform", "an", "array", "of", "two", "item", "arrays", "into", "a", "CSV", "row" ]
d4e33a2b5397afe188a08df01a1a3562efe8e3a1
https://github.com/C2FO/fast-csv/blob/d4e33a2b5397afe188a08df01a1a3562efe8e3a1/lib/formatter/formatter.js#L164-L174
13,195
C2FO/fast-csv
lib/formatter/formatter.js
transformItem
function transformItem(stream, item) { var ret; if (isArray(item)) { if (isHashArray(item)) { ret = transformHashArrayData(stream, item); } else { ret = transformArrayData(stream, item); } } else { ret = transformHashData(stream, item); } return ret; }
javascript
function transformItem(stream, item) { var ret; if (isArray(item)) { if (isHashArray(item)) { ret = transformHashArrayData(stream, item); } else { ret = transformArrayData(stream, item); } } else { ret = transformHashData(stream, item); } return ret; }
[ "function", "transformItem", "(", "stream", ",", "item", ")", "{", "var", "ret", ";", "if", "(", "isArray", "(", "item", ")", ")", "{", "if", "(", "isHashArray", "(", "item", ")", ")", "{", "ret", "=", "transformHashArrayData", "(", "stream", ",", "item", ")", ";", "}", "else", "{", "ret", "=", "transformArrayData", "(", "stream", ",", "item", ")", ";", "}", "}", "else", "{", "ret", "=", "transformHashData", "(", "stream", ",", "item", ")", ";", "}", "return", "ret", ";", "}" ]
wrapper to determin what transform to run
[ "wrapper", "to", "determin", "what", "transform", "to", "run" ]
d4e33a2b5397afe188a08df01a1a3562efe8e3a1
https://github.com/C2FO/fast-csv/blob/d4e33a2b5397afe188a08df01a1a3562efe8e3a1/lib/formatter/formatter.js#L177-L189
13,196
andybelldesign/beedle
bundler.js
bundleJavaScript
async function bundleJavaScript() { const bundle = await rollup.rollup({ input: `${__dirname}/src/beedle.js`, plugins: [ uglify() ] }); await bundle.write({ format: 'umd', name: 'beedle', file: 'beedle.js', dir: `${__dirname}/dist/`, }); }
javascript
async function bundleJavaScript() { const bundle = await rollup.rollup({ input: `${__dirname}/src/beedle.js`, plugins: [ uglify() ] }); await bundle.write({ format: 'umd', name: 'beedle', file: 'beedle.js', dir: `${__dirname}/dist/`, }); }
[ "async", "function", "bundleJavaScript", "(", ")", "{", "const", "bundle", "=", "await", "rollup", ".", "rollup", "(", "{", "input", ":", "`", "${", "__dirname", "}", "`", ",", "plugins", ":", "[", "uglify", "(", ")", "]", "}", ")", ";", "await", "bundle", ".", "write", "(", "{", "format", ":", "'umd'", ",", "name", ":", "'beedle'", ",", "file", ":", "'beedle.js'", ",", "dir", ":", "`", "${", "__dirname", "}", "`", ",", "}", ")", ";", "}" ]
Bundle the JavaScript components together and smoosh them with uglify
[ "Bundle", "the", "JavaScript", "components", "together", "and", "smoosh", "them", "with", "uglify" ]
84f02075a8c144bfdbb877d7b615487807c742cb
https://github.com/andybelldesign/beedle/blob/84f02075a8c144bfdbb877d7b615487807c742cb/bundler.js#L7-L21
13,197
posthtml/posthtml
lib/index.js
_next
function _next (res) { if (res && !options.skipParse) { res = [].concat(res) } return next(res || result, cb) }
javascript
function _next (res) { if (res && !options.skipParse) { res = [].concat(res) } return next(res || result, cb) }
[ "function", "_next", "(", "res", ")", "{", "if", "(", "res", "&&", "!", "options", ".", "skipParse", ")", "{", "res", "=", "[", "]", ".", "concat", "(", "res", ")", "}", "return", "next", "(", "res", "||", "result", ",", "cb", ")", "}" ]
little helper to go to the next iteration
[ "little", "helper", "to", "go", "to", "the", "next", "iteration" ]
881d4a5b170109789a5245a379229afb4793e21a
https://github.com/posthtml/posthtml/blob/881d4a5b170109789a5245a379229afb4793e21a/lib/index.js#L165-L171
13,198
posthtml/posthtml
lib/index.js
lazyResult
function lazyResult (render, tree) { return { get html () { return render(tree, tree.options) }, tree: tree, messages: tree.messages } }
javascript
function lazyResult (render, tree) { return { get html () { return render(tree, tree.options) }, tree: tree, messages: tree.messages } }
[ "function", "lazyResult", "(", "render", ",", "tree", ")", "{", "return", "{", "get", "html", "(", ")", "{", "return", "render", "(", "tree", ",", "tree", ".", "options", ")", "}", ",", "tree", ":", "tree", ",", "messages", ":", "tree", ".", "messages", "}", "}" ]
Wraps the PostHTMLTree within an object using a getter to render HTML on demand. @private @param {Function} render @param {Array} tree @returns {Object<{html: String, tree: Array}>}
[ "Wraps", "the", "PostHTMLTree", "within", "an", "object", "using", "a", "getter", "to", "render", "HTML", "on", "demand", "." ]
881d4a5b170109789a5245a379229afb4793e21a
https://github.com/posthtml/posthtml/blob/881d4a5b170109789a5245a379229afb4793e21a/lib/index.js#L286-L294
13,199
posthtml/posthtml
lib/api.js
match
function match (expression, cb) { return Array.isArray(expression) ? traverse(this, function (node) { for (var i = 0; i < expression.length; i++) { if (compare(expression[i], node)) return cb(node) } return node }) : traverse(this, function (node) { if (compare(expression, node)) return cb(node) return node }) }
javascript
function match (expression, cb) { return Array.isArray(expression) ? traverse(this, function (node) { for (var i = 0; i < expression.length; i++) { if (compare(expression[i], node)) return cb(node) } return node }) : traverse(this, function (node) { if (compare(expression, node)) return cb(node) return node }) }
[ "function", "match", "(", "expression", ",", "cb", ")", "{", "return", "Array", ".", "isArray", "(", "expression", ")", "?", "traverse", "(", "this", ",", "function", "(", "node", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "expression", ".", "length", ";", "i", "++", ")", "{", "if", "(", "compare", "(", "expression", "[", "i", "]", ",", "node", ")", ")", "return", "cb", "(", "node", ")", "}", "return", "node", "}", ")", ":", "traverse", "(", "this", ",", "function", "(", "node", ")", "{", "if", "(", "compare", "(", "expression", ",", "node", ")", ")", "return", "cb", "(", "node", ")", "return", "node", "}", ")", "}" ]
Matches an expression to search for nodes in the tree @memberof tree @param {String|RegExp|Object|Array} expression - Matcher(s) to search @param {Function} cb Callback @return {Function} Callback(node) @example ```js export const match = (tree) => { // Single matcher tree.match({ tag: 'custom-tag' }, (node) => { let tag = node.tag Object.assign(node, { tag: 'div', attrs: {class: tag} }) return node }) // Multiple matchers tree.match([{ tag: 'b' }, { tag: 'strong' }], (node) => { let style = 'font-weight: bold;' node.tag = 'span' node.attrs ? ( node.attrs.style ? ( node.attrs.style += style ) : node.attrs.style = style ) : node.attrs = { style: style } return node }) } ```
[ "Matches", "an", "expression", "to", "search", "for", "nodes", "in", "the", "tree" ]
881d4a5b170109789a5245a379229afb4793e21a
https://github.com/posthtml/posthtml/blob/881d4a5b170109789a5245a379229afb4793e21a/lib/api.js#L81-L95