repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
partition
stringclasses
1 value
lovell/sharp
lib/output.js
toFormat
function toFormat (format, options) { if (is.object(format) && is.string(format.id)) { format = format.id; } if (format === 'jpg') format = 'jpeg'; if (!is.inArray(format, ['jpeg', 'png', 'webp', 'tiff', 'raw'])) { throw new Error('Unsupported output format ' + format); } return this[format](options); }
javascript
function toFormat (format, options) { if (is.object(format) && is.string(format.id)) { format = format.id; } if (format === 'jpg') format = 'jpeg'; if (!is.inArray(format, ['jpeg', 'png', 'webp', 'tiff', 'raw'])) { throw new Error('Unsupported output format ' + format); } return this[format](options); }
[ "function", "toFormat", "(", "format", ",", "options", ")", "{", "if", "(", "is", ".", "object", "(", "format", ")", "&&", "is", ".", "string", "(", "format", ".", "id", ")", ")", "{", "format", "=", "format", ".", "id", ";", "}", "if", "(", "format", "===", "'jpg'", ")", "format", "=", "'jpeg'", ";", "if", "(", "!", "is", ".", "inArray", "(", "format", ",", "[", "'jpeg'", ",", "'png'", ",", "'webp'", ",", "'tiff'", ",", "'raw'", "]", ")", ")", "{", "throw", "new", "Error", "(", "'Unsupported output format '", "+", "format", ")", ";", "}", "return", "this", "[", "format", "]", "(", "options", ")", ";", "}" ]
Force output to a given format. @example // Convert any input to PNG output const data = await sharp(input) .toFormat('png') .toBuffer(); @param {(String|Object)} format - as a String or an Object with an 'id' attribute @param {Object} options - output options @returns {Sharp} @throws {Error} unsupported format or options
[ "Force", "output", "to", "a", "given", "format", "." ]
05d76eeadfe54713606a615185b2da047923406b
https://github.com/lovell/sharp/blob/05d76eeadfe54713606a615185b2da047923406b/lib/output.js#L461-L470
train
lovell/sharp
lib/output.js
_updateFormatOut
function _updateFormatOut (formatOut, options) { if (!(is.object(options) && options.force === false)) { this.options.formatOut = formatOut; } return this; }
javascript
function _updateFormatOut (formatOut, options) { if (!(is.object(options) && options.force === false)) { this.options.formatOut = formatOut; } return this; }
[ "function", "_updateFormatOut", "(", "formatOut", ",", "options", ")", "{", "if", "(", "!", "(", "is", ".", "object", "(", "options", ")", "&&", "options", ".", "force", "===", "false", ")", ")", "{", "this", ".", "options", ".", "formatOut", "=", "formatOut", ";", "}", "return", "this", ";", "}" ]
Update the output format unless options.force is false, in which case revert to input format. @private @param {String} formatOut @param {Object} [options] @param {Boolean} [options.force=true] - force output format, otherwise attempt to use input format @returns {Sharp}
[ "Update", "the", "output", "format", "unless", "options", ".", "force", "is", "false", "in", "which", "case", "revert", "to", "input", "format", "." ]
05d76eeadfe54713606a615185b2da047923406b
https://github.com/lovell/sharp/blob/05d76eeadfe54713606a615185b2da047923406b/lib/output.js#L575-L580
train
lovell/sharp
lib/output.js
_setBooleanOption
function _setBooleanOption (key, val) { if (is.bool(val)) { this.options[key] = val; } else { throw new Error('Invalid ' + key + ' (boolean) ' + val); } }
javascript
function _setBooleanOption (key, val) { if (is.bool(val)) { this.options[key] = val; } else { throw new Error('Invalid ' + key + ' (boolean) ' + val); } }
[ "function", "_setBooleanOption", "(", "key", ",", "val", ")", "{", "if", "(", "is", ".", "bool", "(", "val", ")", ")", "{", "this", ".", "options", "[", "key", "]", "=", "val", ";", "}", "else", "{", "throw", "new", "Error", "(", "'Invalid '", "+", "key", "+", "' (boolean) '", "+", "val", ")", ";", "}", "}" ]
Update a Boolean attribute of the this.options Object. @private @param {String} key @param {Boolean} val @throws {Error} Invalid key
[ "Update", "a", "Boolean", "attribute", "of", "the", "this", ".", "options", "Object", "." ]
05d76eeadfe54713606a615185b2da047923406b
https://github.com/lovell/sharp/blob/05d76eeadfe54713606a615185b2da047923406b/lib/output.js#L589-L595
train
lovell/sharp
lib/colour.js
tint
function tint (rgb) { const colour = color(rgb); this.options.tintA = colour.a(); this.options.tintB = colour.b(); return this; }
javascript
function tint (rgb) { const colour = color(rgb); this.options.tintA = colour.a(); this.options.tintB = colour.b(); return this; }
[ "function", "tint", "(", "rgb", ")", "{", "const", "colour", "=", "color", "(", "rgb", ")", ";", "this", ".", "options", ".", "tintA", "=", "colour", ".", "a", "(", ")", ";", "this", ".", "options", ".", "tintB", "=", "colour", ".", "b", "(", ")", ";", "return", "this", ";", "}" ]
Tint the image using the provided chroma while preserving the image luminance. An alpha channel may be present and will be unchanged by the operation. @param {String|Object} rgb - parsed by the [color](https://www.npmjs.org/package/color) module to extract chroma values. @returns {Sharp} @throws {Error} Invalid parameter
[ "Tint", "the", "image", "using", "the", "provided", "chroma", "while", "preserving", "the", "image", "luminance", ".", "An", "alpha", "channel", "may", "be", "present", "and", "will", "be", "unchanged", "by", "the", "operation", "." ]
05d76eeadfe54713606a615185b2da047923406b
https://github.com/lovell/sharp/blob/05d76eeadfe54713606a615185b2da047923406b/lib/colour.js#L26-L31
train
lovell/sharp
lib/colour.js
toColourspace
function toColourspace (colourspace) { if (!is.string(colourspace)) { throw new Error('Invalid output colourspace ' + colourspace); } this.options.colourspace = colourspace; return this; }
javascript
function toColourspace (colourspace) { if (!is.string(colourspace)) { throw new Error('Invalid output colourspace ' + colourspace); } this.options.colourspace = colourspace; return this; }
[ "function", "toColourspace", "(", "colourspace", ")", "{", "if", "(", "!", "is", ".", "string", "(", "colourspace", ")", ")", "{", "throw", "new", "Error", "(", "'Invalid output colourspace '", "+", "colourspace", ")", ";", "}", "this", ".", "options", ".", "colourspace", "=", "colourspace", ";", "return", "this", ";", "}" ]
Set the output colourspace. By default output image will be web-friendly sRGB, with additional channels interpreted as alpha channels. @param {String} [colourspace] - output colourspace e.g. `srgb`, `rgb`, `cmyk`, `lab`, `b-w` [...](https://github.com/libvips/libvips/blob/master/libvips/iofuncs/enumtypes.c#L568) @returns {Sharp} @throws {Error} Invalid parameters
[ "Set", "the", "output", "colourspace", ".", "By", "default", "output", "image", "will", "be", "web", "-", "friendly", "sRGB", "with", "additional", "channels", "interpreted", "as", "alpha", "channels", "." ]
05d76eeadfe54713606a615185b2da047923406b
https://github.com/lovell/sharp/blob/05d76eeadfe54713606a615185b2da047923406b/lib/colour.js#L64-L70
train
lovell/sharp
lib/colour.js
_setColourOption
function _setColourOption (key, val) { if (is.object(val) || is.string(val)) { const colour = color(val); this.options[key] = [ colour.red(), colour.green(), colour.blue(), Math.round(colour.alpha() * 255) ]; } }
javascript
function _setColourOption (key, val) { if (is.object(val) || is.string(val)) { const colour = color(val); this.options[key] = [ colour.red(), colour.green(), colour.blue(), Math.round(colour.alpha() * 255) ]; } }
[ "function", "_setColourOption", "(", "key", ",", "val", ")", "{", "if", "(", "is", ".", "object", "(", "val", ")", "||", "is", ".", "string", "(", "val", ")", ")", "{", "const", "colour", "=", "color", "(", "val", ")", ";", "this", ".", "options", "[", "key", "]", "=", "[", "colour", ".", "red", "(", ")", ",", "colour", ".", "green", "(", ")", ",", "colour", ".", "blue", "(", ")", ",", "Math", ".", "round", "(", "colour", ".", "alpha", "(", ")", "*", "255", ")", "]", ";", "}", "}" ]
Update a colour attribute of the this.options Object. @private @param {String} key @param {String|Object} val @throws {Error} Invalid key
[ "Update", "a", "colour", "attribute", "of", "the", "this", ".", "options", "Object", "." ]
05d76eeadfe54713606a615185b2da047923406b
https://github.com/lovell/sharp/blob/05d76eeadfe54713606a615185b2da047923406b/lib/colour.js#L89-L99
train
lovell/sharp
lib/resize.js
extract
function extract (options) { const suffix = this.options.width === -1 && this.options.height === -1 ? 'Pre' : 'Post'; ['left', 'top', 'width', 'height'].forEach(function (name) { const value = options[name]; if (is.integer(value) && value >= 0) { this.options[name + (name === 'left' || name === 'top' ? 'Offset' : '') + suffix] = value; } else { throw new Error('Non-integer value for ' + name + ' of ' + value); } }, this); // Ensure existing rotation occurs before pre-resize extraction if (suffix === 'Pre' && ((this.options.angle % 360) !== 0 || this.options.useExifOrientation === true)) { this.options.rotateBeforePreExtract = true; } return this; }
javascript
function extract (options) { const suffix = this.options.width === -1 && this.options.height === -1 ? 'Pre' : 'Post'; ['left', 'top', 'width', 'height'].forEach(function (name) { const value = options[name]; if (is.integer(value) && value >= 0) { this.options[name + (name === 'left' || name === 'top' ? 'Offset' : '') + suffix] = value; } else { throw new Error('Non-integer value for ' + name + ' of ' + value); } }, this); // Ensure existing rotation occurs before pre-resize extraction if (suffix === 'Pre' && ((this.options.angle % 360) !== 0 || this.options.useExifOrientation === true)) { this.options.rotateBeforePreExtract = true; } return this; }
[ "function", "extract", "(", "options", ")", "{", "const", "suffix", "=", "this", ".", "options", ".", "width", "===", "-", "1", "&&", "this", ".", "options", ".", "height", "===", "-", "1", "?", "'Pre'", ":", "'Post'", ";", "[", "'left'", ",", "'top'", ",", "'width'", ",", "'height'", "]", ".", "forEach", "(", "function", "(", "name", ")", "{", "const", "value", "=", "options", "[", "name", "]", ";", "if", "(", "is", ".", "integer", "(", "value", ")", "&&", "value", ">=", "0", ")", "{", "this", ".", "options", "[", "name", "+", "(", "name", "===", "'left'", "||", "name", "===", "'top'", "?", "'Offset'", ":", "''", ")", "+", "suffix", "]", "=", "value", ";", "}", "else", "{", "throw", "new", "Error", "(", "'Non-integer value for '", "+", "name", "+", "' of '", "+", "value", ")", ";", "}", "}", ",", "this", ")", ";", "if", "(", "suffix", "===", "'Pre'", "&&", "(", "(", "this", ".", "options", ".", "angle", "%", "360", ")", "!==", "0", "||", "this", ".", "options", ".", "useExifOrientation", "===", "true", ")", ")", "{", "this", ".", "options", ".", "rotateBeforePreExtract", "=", "true", ";", "}", "return", "this", ";", "}" ]
Extract a region of the image. - Use `extract` before `resize` for pre-resize extraction. - Use `extract` after `resize` for post-resize extraction. - Use `extract` before and after for both. @example sharp(input) .extract({ left: left, top: top, width: width, height: height }) .toFile(output, function(err) { // Extract a region of the input image, saving in the same format. }); @example sharp(input) .extract({ left: leftOffsetPre, top: topOffsetPre, width: widthPre, height: heightPre }) .resize(width, height) .extract({ left: leftOffsetPost, top: topOffsetPost, width: widthPost, height: heightPost }) .toFile(output, function(err) { // Extract a region, resize, then extract from the resized image }); @param {Object} options - describes the region to extract using integral pixel values @param {Number} options.left - zero-indexed offset from left edge @param {Number} options.top - zero-indexed offset from top edge @param {Number} options.width - width of region to extract @param {Number} options.height - height of region to extract @returns {Sharp} @throws {Error} Invalid parameters
[ "Extract", "a", "region", "of", "the", "image", "." ]
05d76eeadfe54713606a615185b2da047923406b
https://github.com/lovell/sharp/blob/05d76eeadfe54713606a615185b2da047923406b/lib/resize.js#L345-L360
train
lovell/sharp
lib/resize.js
trim
function trim (threshold) { if (!is.defined(threshold)) { this.options.trimThreshold = 10; } else if (is.number(threshold) && threshold > 0) { this.options.trimThreshold = threshold; } else { throw is.invalidParameterError('threshold', 'number greater than zero', threshold); } return this; }
javascript
function trim (threshold) { if (!is.defined(threshold)) { this.options.trimThreshold = 10; } else if (is.number(threshold) && threshold > 0) { this.options.trimThreshold = threshold; } else { throw is.invalidParameterError('threshold', 'number greater than zero', threshold); } return this; }
[ "function", "trim", "(", "threshold", ")", "{", "if", "(", "!", "is", ".", "defined", "(", "threshold", ")", ")", "{", "this", ".", "options", ".", "trimThreshold", "=", "10", ";", "}", "else", "if", "(", "is", ".", "number", "(", "threshold", ")", "&&", "threshold", ">", "0", ")", "{", "this", ".", "options", ".", "trimThreshold", "=", "threshold", ";", "}", "else", "{", "throw", "is", ".", "invalidParameterError", "(", "'threshold'", ",", "'number greater than zero'", ",", "threshold", ")", ";", "}", "return", "this", ";", "}" ]
Trim "boring" pixels from all edges that contain values similar to the top-left pixel. The `info` response Object will contain `trimOffsetLeft` and `trimOffsetTop` properties. @param {Number} [threshold=10] the allowed difference from the top-left pixel, a number greater than zero. @returns {Sharp} @throws {Error} Invalid parameters
[ "Trim", "boring", "pixels", "from", "all", "edges", "that", "contain", "values", "similar", "to", "the", "top", "-", "left", "pixel", ".", "The", "info", "response", "Object", "will", "contain", "trimOffsetLeft", "and", "trimOffsetTop", "properties", "." ]
05d76eeadfe54713606a615185b2da047923406b
https://github.com/lovell/sharp/blob/05d76eeadfe54713606a615185b2da047923406b/lib/resize.js#L369-L378
train
lovell/sharp
lib/operation.js
rotate
function rotate (angle, options) { if (!is.defined(angle)) { this.options.useExifOrientation = true; } else if (is.integer(angle) && !(angle % 90)) { this.options.angle = angle; } else if (is.number(angle)) { this.options.rotationAngle = angle; if (is.object(options) && options.background) { const backgroundColour = color(options.background); this.options.rotationBackground = [ backgroundColour.red(), backgroundColour.green(), backgroundColour.blue(), Math.round(backgroundColour.alpha() * 255) ]; } } else { throw new Error('Unsupported angle: must be a number.'); } return this; }
javascript
function rotate (angle, options) { if (!is.defined(angle)) { this.options.useExifOrientation = true; } else if (is.integer(angle) && !(angle % 90)) { this.options.angle = angle; } else if (is.number(angle)) { this.options.rotationAngle = angle; if (is.object(options) && options.background) { const backgroundColour = color(options.background); this.options.rotationBackground = [ backgroundColour.red(), backgroundColour.green(), backgroundColour.blue(), Math.round(backgroundColour.alpha() * 255) ]; } } else { throw new Error('Unsupported angle: must be a number.'); } return this; }
[ "function", "rotate", "(", "angle", ",", "options", ")", "{", "if", "(", "!", "is", ".", "defined", "(", "angle", ")", ")", "{", "this", ".", "options", ".", "useExifOrientation", "=", "true", ";", "}", "else", "if", "(", "is", ".", "integer", "(", "angle", ")", "&&", "!", "(", "angle", "%", "90", ")", ")", "{", "this", ".", "options", ".", "angle", "=", "angle", ";", "}", "else", "if", "(", "is", ".", "number", "(", "angle", ")", ")", "{", "this", ".", "options", ".", "rotationAngle", "=", "angle", ";", "if", "(", "is", ".", "object", "(", "options", ")", "&&", "options", ".", "background", ")", "{", "const", "backgroundColour", "=", "color", "(", "options", ".", "background", ")", ";", "this", ".", "options", ".", "rotationBackground", "=", "[", "backgroundColour", ".", "red", "(", ")", ",", "backgroundColour", ".", "green", "(", ")", ",", "backgroundColour", ".", "blue", "(", ")", ",", "Math", ".", "round", "(", "backgroundColour", ".", "alpha", "(", ")", "*", "255", ")", "]", ";", "}", "}", "else", "{", "throw", "new", "Error", "(", "'Unsupported angle: must be a number.'", ")", ";", "}", "return", "this", ";", "}" ]
Rotate the output image by either an explicit angle or auto-orient based on the EXIF `Orientation` tag. If an angle is provided, it is converted to a valid positive degree rotation. For example, `-450` will produce a 270deg rotation. When rotating by an angle other than a multiple of 90, the background colour can be provided with the `background` option. If no angle is provided, it is determined from the EXIF data. Mirroring is supported and may infer the use of a flip operation. The use of `rotate` implies the removal of the EXIF `Orientation` tag, if any. Method order is important when both rotating and extracting regions, for example `rotate(x).extract(y)` will produce a different result to `extract(y).rotate(x)`. @example const pipeline = sharp() .rotate() .resize(null, 200) .toBuffer(function (err, outputBuffer, info) { // outputBuffer contains 200px high JPEG image data, // auto-rotated using EXIF Orientation tag // info.width and info.height contain the dimensions of the resized image }); readableStream.pipe(pipeline); @param {Number} [angle=auto] angle of rotation. @param {Object} [options] - if present, is an Object with optional attributes. @param {String|Object} [options.background="#000000"] parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha. @returns {Sharp} @throws {Error} Invalid parameters
[ "Rotate", "the", "output", "image", "by", "either", "an", "explicit", "angle", "or", "auto", "-", "orient", "based", "on", "the", "EXIF", "Orientation", "tag", "." ]
05d76eeadfe54713606a615185b2da047923406b
https://github.com/lovell/sharp/blob/05d76eeadfe54713606a615185b2da047923406b/lib/operation.js#L41-L61
train
lovell/sharp
lib/operation.js
sharpen
function sharpen (sigma, flat, jagged) { if (!is.defined(sigma)) { // No arguments: default to mild sharpen this.options.sharpenSigma = -1; } else if (is.bool(sigma)) { // Boolean argument: apply mild sharpen? this.options.sharpenSigma = sigma ? -1 : 0; } else if (is.number(sigma) && is.inRange(sigma, 0.01, 10000)) { // Numeric argument: specific sigma this.options.sharpenSigma = sigma; // Control over flat areas if (is.defined(flat)) { if (is.number(flat) && is.inRange(flat, 0, 10000)) { this.options.sharpenFlat = flat; } else { throw new Error('Invalid sharpen level for flat areas (0.0 - 10000.0) ' + flat); } } // Control over jagged areas if (is.defined(jagged)) { if (is.number(jagged) && is.inRange(jagged, 0, 10000)) { this.options.sharpenJagged = jagged; } else { throw new Error('Invalid sharpen level for jagged areas (0.0 - 10000.0) ' + jagged); } } } else { throw new Error('Invalid sharpen sigma (0.01 - 10000) ' + sigma); } return this; }
javascript
function sharpen (sigma, flat, jagged) { if (!is.defined(sigma)) { // No arguments: default to mild sharpen this.options.sharpenSigma = -1; } else if (is.bool(sigma)) { // Boolean argument: apply mild sharpen? this.options.sharpenSigma = sigma ? -1 : 0; } else if (is.number(sigma) && is.inRange(sigma, 0.01, 10000)) { // Numeric argument: specific sigma this.options.sharpenSigma = sigma; // Control over flat areas if (is.defined(flat)) { if (is.number(flat) && is.inRange(flat, 0, 10000)) { this.options.sharpenFlat = flat; } else { throw new Error('Invalid sharpen level for flat areas (0.0 - 10000.0) ' + flat); } } // Control over jagged areas if (is.defined(jagged)) { if (is.number(jagged) && is.inRange(jagged, 0, 10000)) { this.options.sharpenJagged = jagged; } else { throw new Error('Invalid sharpen level for jagged areas (0.0 - 10000.0) ' + jagged); } } } else { throw new Error('Invalid sharpen sigma (0.01 - 10000) ' + sigma); } return this; }
[ "function", "sharpen", "(", "sigma", ",", "flat", ",", "jagged", ")", "{", "if", "(", "!", "is", ".", "defined", "(", "sigma", ")", ")", "{", "this", ".", "options", ".", "sharpenSigma", "=", "-", "1", ";", "}", "else", "if", "(", "is", ".", "bool", "(", "sigma", ")", ")", "{", "this", ".", "options", ".", "sharpenSigma", "=", "sigma", "?", "-", "1", ":", "0", ";", "}", "else", "if", "(", "is", ".", "number", "(", "sigma", ")", "&&", "is", ".", "inRange", "(", "sigma", ",", "0.01", ",", "10000", ")", ")", "{", "this", ".", "options", ".", "sharpenSigma", "=", "sigma", ";", "if", "(", "is", ".", "defined", "(", "flat", ")", ")", "{", "if", "(", "is", ".", "number", "(", "flat", ")", "&&", "is", ".", "inRange", "(", "flat", ",", "0", ",", "10000", ")", ")", "{", "this", ".", "options", ".", "sharpenFlat", "=", "flat", ";", "}", "else", "{", "throw", "new", "Error", "(", "'Invalid sharpen level for flat areas (0.0 - 10000.0) '", "+", "flat", ")", ";", "}", "}", "if", "(", "is", ".", "defined", "(", "jagged", ")", ")", "{", "if", "(", "is", ".", "number", "(", "jagged", ")", "&&", "is", ".", "inRange", "(", "jagged", ",", "0", ",", "10000", ")", ")", "{", "this", ".", "options", ".", "sharpenJagged", "=", "jagged", ";", "}", "else", "{", "throw", "new", "Error", "(", "'Invalid sharpen level for jagged areas (0.0 - 10000.0) '", "+", "jagged", ")", ";", "}", "}", "}", "else", "{", "throw", "new", "Error", "(", "'Invalid sharpen sigma (0.01 - 10000) '", "+", "sigma", ")", ";", "}", "return", "this", ";", "}" ]
Sharpen the image. When used without parameters, performs a fast, mild sharpen of the output image. When a `sigma` is provided, performs a slower, more accurate sharpen of the L channel in the LAB colour space. Separate control over the level of sharpening in "flat" and "jagged" areas is available. @param {Number} [sigma] - the sigma of the Gaussian mask, where `sigma = 1 + radius / 2`. @param {Number} [flat=1.0] - the level of sharpening to apply to "flat" areas. @param {Number} [jagged=2.0] - the level of sharpening to apply to "jagged" areas. @returns {Sharp} @throws {Error} Invalid parameters
[ "Sharpen", "the", "image", ".", "When", "used", "without", "parameters", "performs", "a", "fast", "mild", "sharpen", "of", "the", "output", "image", ".", "When", "a", "sigma", "is", "provided", "performs", "a", "slower", "more", "accurate", "sharpen", "of", "the", "L", "channel", "in", "the", "LAB", "colour", "space", ".", "Separate", "control", "over", "the", "level", "of", "sharpening", "in", "flat", "and", "jagged", "areas", "is", "available", "." ]
05d76eeadfe54713606a615185b2da047923406b
https://github.com/lovell/sharp/blob/05d76eeadfe54713606a615185b2da047923406b/lib/operation.js#L97-L127
train
lovell/sharp
lib/operation.js
median
function median (size) { if (!is.defined(size)) { // No arguments: default to 3x3 this.options.medianSize = 3; } else if (is.integer(size) && is.inRange(size, 1, 1000)) { // Numeric argument: specific sigma this.options.medianSize = size; } else { throw new Error('Invalid median size ' + size); } return this; }
javascript
function median (size) { if (!is.defined(size)) { // No arguments: default to 3x3 this.options.medianSize = 3; } else if (is.integer(size) && is.inRange(size, 1, 1000)) { // Numeric argument: specific sigma this.options.medianSize = size; } else { throw new Error('Invalid median size ' + size); } return this; }
[ "function", "median", "(", "size", ")", "{", "if", "(", "!", "is", ".", "defined", "(", "size", ")", ")", "{", "this", ".", "options", ".", "medianSize", "=", "3", ";", "}", "else", "if", "(", "is", ".", "integer", "(", "size", ")", "&&", "is", ".", "inRange", "(", "size", ",", "1", ",", "1000", ")", ")", "{", "this", ".", "options", ".", "medianSize", "=", "size", ";", "}", "else", "{", "throw", "new", "Error", "(", "'Invalid median size '", "+", "size", ")", ";", "}", "return", "this", ";", "}" ]
Apply median filter. When used without parameters the default window is 3x3. @param {Number} [size=3] square mask size: size x size @returns {Sharp} @throws {Error} Invalid parameters
[ "Apply", "median", "filter", ".", "When", "used", "without", "parameters", "the", "default", "window", "is", "3x3", "." ]
05d76eeadfe54713606a615185b2da047923406b
https://github.com/lovell/sharp/blob/05d76eeadfe54713606a615185b2da047923406b/lib/operation.js#L136-L147
train
lovell/sharp
lib/operation.js
blur
function blur (sigma) { if (!is.defined(sigma)) { // No arguments: default to mild blur this.options.blurSigma = -1; } else if (is.bool(sigma)) { // Boolean argument: apply mild blur? this.options.blurSigma = sigma ? -1 : 0; } else if (is.number(sigma) && is.inRange(sigma, 0.3, 1000)) { // Numeric argument: specific sigma this.options.blurSigma = sigma; } else { throw new Error('Invalid blur sigma (0.3 - 1000.0) ' + sigma); } return this; }
javascript
function blur (sigma) { if (!is.defined(sigma)) { // No arguments: default to mild blur this.options.blurSigma = -1; } else if (is.bool(sigma)) { // Boolean argument: apply mild blur? this.options.blurSigma = sigma ? -1 : 0; } else if (is.number(sigma) && is.inRange(sigma, 0.3, 1000)) { // Numeric argument: specific sigma this.options.blurSigma = sigma; } else { throw new Error('Invalid blur sigma (0.3 - 1000.0) ' + sigma); } return this; }
[ "function", "blur", "(", "sigma", ")", "{", "if", "(", "!", "is", ".", "defined", "(", "sigma", ")", ")", "{", "this", ".", "options", ".", "blurSigma", "=", "-", "1", ";", "}", "else", "if", "(", "is", ".", "bool", "(", "sigma", ")", ")", "{", "this", ".", "options", ".", "blurSigma", "=", "sigma", "?", "-", "1", ":", "0", ";", "}", "else", "if", "(", "is", ".", "number", "(", "sigma", ")", "&&", "is", ".", "inRange", "(", "sigma", ",", "0.3", ",", "1000", ")", ")", "{", "this", ".", "options", ".", "blurSigma", "=", "sigma", ";", "}", "else", "{", "throw", "new", "Error", "(", "'Invalid blur sigma (0.3 - 1000.0) '", "+", "sigma", ")", ";", "}", "return", "this", ";", "}" ]
Blur the image. When used without parameters, performs a fast, mild blur of the output image. When a `sigma` is provided, performs a slower, more accurate Gaussian blur. @param {Number} [sigma] a value between 0.3 and 1000 representing the sigma of the Gaussian mask, where `sigma = 1 + radius / 2`. @returns {Sharp} @throws {Error} Invalid parameters
[ "Blur", "the", "image", ".", "When", "used", "without", "parameters", "performs", "a", "fast", "mild", "blur", "of", "the", "output", "image", ".", "When", "a", "sigma", "is", "provided", "performs", "a", "slower", "more", "accurate", "Gaussian", "blur", "." ]
05d76eeadfe54713606a615185b2da047923406b
https://github.com/lovell/sharp/blob/05d76eeadfe54713606a615185b2da047923406b/lib/operation.js#L157-L171
train
lovell/sharp
lib/operation.js
flatten
function flatten (options) { this.options.flatten = is.bool(options) ? options : true; if (is.object(options)) { this._setColourOption('flattenBackground', options.background); } return this; }
javascript
function flatten (options) { this.options.flatten = is.bool(options) ? options : true; if (is.object(options)) { this._setColourOption('flattenBackground', options.background); } return this; }
[ "function", "flatten", "(", "options", ")", "{", "this", ".", "options", ".", "flatten", "=", "is", ".", "bool", "(", "options", ")", "?", "options", ":", "true", ";", "if", "(", "is", ".", "object", "(", "options", ")", ")", "{", "this", ".", "_setColourOption", "(", "'flattenBackground'", ",", "options", ".", "background", ")", ";", "}", "return", "this", ";", "}" ]
Merge alpha transparency channel, if any, with a background. @param {Object} [options] @param {String|Object} [options.background={r: 0, g: 0, b: 0}] - background colour, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to black. @returns {Sharp}
[ "Merge", "alpha", "transparency", "channel", "if", "any", "with", "a", "background", "." ]
05d76eeadfe54713606a615185b2da047923406b
https://github.com/lovell/sharp/blob/05d76eeadfe54713606a615185b2da047923406b/lib/operation.js#L179-L185
train
lovell/sharp
lib/operation.js
convolve
function convolve (kernel) { if (!is.object(kernel) || !Array.isArray(kernel.kernel) || !is.integer(kernel.width) || !is.integer(kernel.height) || !is.inRange(kernel.width, 3, 1001) || !is.inRange(kernel.height, 3, 1001) || kernel.height * kernel.width !== kernel.kernel.length ) { // must pass in a kernel throw new Error('Invalid convolution kernel'); } // Default scale is sum of kernel values if (!is.integer(kernel.scale)) { kernel.scale = kernel.kernel.reduce(function (a, b) { return a + b; }, 0); } // Clip scale to a minimum value of 1 if (kernel.scale < 1) { kernel.scale = 1; } if (!is.integer(kernel.offset)) { kernel.offset = 0; } this.options.convKernel = kernel; return this; }
javascript
function convolve (kernel) { if (!is.object(kernel) || !Array.isArray(kernel.kernel) || !is.integer(kernel.width) || !is.integer(kernel.height) || !is.inRange(kernel.width, 3, 1001) || !is.inRange(kernel.height, 3, 1001) || kernel.height * kernel.width !== kernel.kernel.length ) { // must pass in a kernel throw new Error('Invalid convolution kernel'); } // Default scale is sum of kernel values if (!is.integer(kernel.scale)) { kernel.scale = kernel.kernel.reduce(function (a, b) { return a + b; }, 0); } // Clip scale to a minimum value of 1 if (kernel.scale < 1) { kernel.scale = 1; } if (!is.integer(kernel.offset)) { kernel.offset = 0; } this.options.convKernel = kernel; return this; }
[ "function", "convolve", "(", "kernel", ")", "{", "if", "(", "!", "is", ".", "object", "(", "kernel", ")", "||", "!", "Array", ".", "isArray", "(", "kernel", ".", "kernel", ")", "||", "!", "is", ".", "integer", "(", "kernel", ".", "width", ")", "||", "!", "is", ".", "integer", "(", "kernel", ".", "height", ")", "||", "!", "is", ".", "inRange", "(", "kernel", ".", "width", ",", "3", ",", "1001", ")", "||", "!", "is", ".", "inRange", "(", "kernel", ".", "height", ",", "3", ",", "1001", ")", "||", "kernel", ".", "height", "*", "kernel", ".", "width", "!==", "kernel", ".", "kernel", ".", "length", ")", "{", "throw", "new", "Error", "(", "'Invalid convolution kernel'", ")", ";", "}", "if", "(", "!", "is", ".", "integer", "(", "kernel", ".", "scale", ")", ")", "{", "kernel", ".", "scale", "=", "kernel", ".", "kernel", ".", "reduce", "(", "function", "(", "a", ",", "b", ")", "{", "return", "a", "+", "b", ";", "}", ",", "0", ")", ";", "}", "if", "(", "kernel", ".", "scale", "<", "1", ")", "{", "kernel", ".", "scale", "=", "1", ";", "}", "if", "(", "!", "is", ".", "integer", "(", "kernel", ".", "offset", ")", ")", "{", "kernel", ".", "offset", "=", "0", ";", "}", "this", ".", "options", ".", "convKernel", "=", "kernel", ";", "return", "this", ";", "}" ]
Convolve the image with the specified kernel. @example sharp(input) .convolve({ width: 3, height: 3, kernel: [-1, 0, 1, -2, 0, 2, -1, 0, 1] }) .raw() .toBuffer(function(err, data, info) { // data contains the raw pixel data representing the convolution // of the input image with the horizontal Sobel operator }); @param {Object} kernel @param {Number} kernel.width - width of the kernel in pixels. @param {Number} kernel.height - width of the kernel in pixels. @param {Array<Number>} kernel.kernel - Array of length `width*height` containing the kernel values. @param {Number} [kernel.scale=sum] - the scale of the kernel in pixels. @param {Number} [kernel.offset=0] - the offset of the kernel in pixels. @returns {Sharp} @throws {Error} Invalid parameters
[ "Convolve", "the", "image", "with", "the", "specified", "kernel", "." ]
05d76eeadfe54713606a615185b2da047923406b
https://github.com/lovell/sharp/blob/05d76eeadfe54713606a615185b2da047923406b/lib/operation.js#L275-L299
train
lovell/sharp
lib/operation.js
threshold
function threshold (threshold, options) { if (!is.defined(threshold)) { this.options.threshold = 128; } else if (is.bool(threshold)) { this.options.threshold = threshold ? 128 : 0; } else if (is.integer(threshold) && is.inRange(threshold, 0, 255)) { this.options.threshold = threshold; } else { throw new Error('Invalid threshold (0 to 255) ' + threshold); } if (!is.object(options) || options.greyscale === true || options.grayscale === true) { this.options.thresholdGrayscale = true; } else { this.options.thresholdGrayscale = false; } return this; }
javascript
function threshold (threshold, options) { if (!is.defined(threshold)) { this.options.threshold = 128; } else if (is.bool(threshold)) { this.options.threshold = threshold ? 128 : 0; } else if (is.integer(threshold) && is.inRange(threshold, 0, 255)) { this.options.threshold = threshold; } else { throw new Error('Invalid threshold (0 to 255) ' + threshold); } if (!is.object(options) || options.greyscale === true || options.grayscale === true) { this.options.thresholdGrayscale = true; } else { this.options.thresholdGrayscale = false; } return this; }
[ "function", "threshold", "(", "threshold", ",", "options", ")", "{", "if", "(", "!", "is", ".", "defined", "(", "threshold", ")", ")", "{", "this", ".", "options", ".", "threshold", "=", "128", ";", "}", "else", "if", "(", "is", ".", "bool", "(", "threshold", ")", ")", "{", "this", ".", "options", ".", "threshold", "=", "threshold", "?", "128", ":", "0", ";", "}", "else", "if", "(", "is", ".", "integer", "(", "threshold", ")", "&&", "is", ".", "inRange", "(", "threshold", ",", "0", ",", "255", ")", ")", "{", "this", ".", "options", ".", "threshold", "=", "threshold", ";", "}", "else", "{", "throw", "new", "Error", "(", "'Invalid threshold (0 to 255) '", "+", "threshold", ")", ";", "}", "if", "(", "!", "is", ".", "object", "(", "options", ")", "||", "options", ".", "greyscale", "===", "true", "||", "options", ".", "grayscale", "===", "true", ")", "{", "this", ".", "options", ".", "thresholdGrayscale", "=", "true", ";", "}", "else", "{", "this", ".", "options", ".", "thresholdGrayscale", "=", "false", ";", "}", "return", "this", ";", "}" ]
Any pixel value greather than or equal to the threshold value will be set to 255, otherwise it will be set to 0. @param {Number} [threshold=128] - a value in the range 0-255 representing the level at which the threshold will be applied. @param {Object} [options] @param {Boolean} [options.greyscale=true] - convert to single channel greyscale. @param {Boolean} [options.grayscale=true] - alternative spelling for greyscale. @returns {Sharp} @throws {Error} Invalid parameters
[ "Any", "pixel", "value", "greather", "than", "or", "equal", "to", "the", "threshold", "value", "will", "be", "set", "to", "255", "otherwise", "it", "will", "be", "set", "to", "0", "." ]
05d76eeadfe54713606a615185b2da047923406b
https://github.com/lovell/sharp/blob/05d76eeadfe54713606a615185b2da047923406b/lib/operation.js#L310-L326
train
lovell/sharp
lib/operation.js
boolean
function boolean (operand, operator, options) { this.options.boolean = this._createInputDescriptor(operand, options); if (is.string(operator) && is.inArray(operator, ['and', 'or', 'eor'])) { this.options.booleanOp = operator; } else { throw new Error('Invalid boolean operator ' + operator); } return this; }
javascript
function boolean (operand, operator, options) { this.options.boolean = this._createInputDescriptor(operand, options); if (is.string(operator) && is.inArray(operator, ['and', 'or', 'eor'])) { this.options.booleanOp = operator; } else { throw new Error('Invalid boolean operator ' + operator); } return this; }
[ "function", "boolean", "(", "operand", ",", "operator", ",", "options", ")", "{", "this", ".", "options", ".", "boolean", "=", "this", ".", "_createInputDescriptor", "(", "operand", ",", "options", ")", ";", "if", "(", "is", ".", "string", "(", "operator", ")", "&&", "is", ".", "inArray", "(", "operator", ",", "[", "'and'", ",", "'or'", ",", "'eor'", "]", ")", ")", "{", "this", ".", "options", ".", "booleanOp", "=", "operator", ";", "}", "else", "{", "throw", "new", "Error", "(", "'Invalid boolean operator '", "+", "operator", ")", ";", "}", "return", "this", ";", "}" ]
Perform a bitwise boolean operation with operand image. This operation creates an output image where each pixel is the result of the selected bitwise boolean `operation` between the corresponding pixels of the input images. @param {Buffer|String} operand - Buffer containing image data or String containing the path to an image file. @param {String} operator - one of `and`, `or` or `eor` to perform that bitwise operation, like the C logic operators `&`, `|` and `^` respectively. @param {Object} [options] @param {Object} [options.raw] - describes operand when using raw pixel data. @param {Number} [options.raw.width] @param {Number} [options.raw.height] @param {Number} [options.raw.channels] @returns {Sharp} @throws {Error} Invalid parameters
[ "Perform", "a", "bitwise", "boolean", "operation", "with", "operand", "image", "." ]
05d76eeadfe54713606a615185b2da047923406b
https://github.com/lovell/sharp/blob/05d76eeadfe54713606a615185b2da047923406b/lib/operation.js#L344-L352
train
lovell/sharp
lib/operation.js
recomb
function recomb (inputMatrix) { if (!Array.isArray(inputMatrix) || inputMatrix.length !== 3 || inputMatrix[0].length !== 3 || inputMatrix[1].length !== 3 || inputMatrix[2].length !== 3 ) { // must pass in a kernel throw new Error('Invalid Recomb Matrix'); } this.options.recombMatrix = [ inputMatrix[0][0], inputMatrix[0][1], inputMatrix[0][2], inputMatrix[1][0], inputMatrix[1][1], inputMatrix[1][2], inputMatrix[2][0], inputMatrix[2][1], inputMatrix[2][2] ].map(Number); return this; }
javascript
function recomb (inputMatrix) { if (!Array.isArray(inputMatrix) || inputMatrix.length !== 3 || inputMatrix[0].length !== 3 || inputMatrix[1].length !== 3 || inputMatrix[2].length !== 3 ) { // must pass in a kernel throw new Error('Invalid Recomb Matrix'); } this.options.recombMatrix = [ inputMatrix[0][0], inputMatrix[0][1], inputMatrix[0][2], inputMatrix[1][0], inputMatrix[1][1], inputMatrix[1][2], inputMatrix[2][0], inputMatrix[2][1], inputMatrix[2][2] ].map(Number); return this; }
[ "function", "recomb", "(", "inputMatrix", ")", "{", "if", "(", "!", "Array", ".", "isArray", "(", "inputMatrix", ")", "||", "inputMatrix", ".", "length", "!==", "3", "||", "inputMatrix", "[", "0", "]", ".", "length", "!==", "3", "||", "inputMatrix", "[", "1", "]", ".", "length", "!==", "3", "||", "inputMatrix", "[", "2", "]", ".", "length", "!==", "3", ")", "{", "throw", "new", "Error", "(", "'Invalid Recomb Matrix'", ")", ";", "}", "this", ".", "options", ".", "recombMatrix", "=", "[", "inputMatrix", "[", "0", "]", "[", "0", "]", ",", "inputMatrix", "[", "0", "]", "[", "1", "]", ",", "inputMatrix", "[", "0", "]", "[", "2", "]", ",", "inputMatrix", "[", "1", "]", "[", "0", "]", ",", "inputMatrix", "[", "1", "]", "[", "1", "]", ",", "inputMatrix", "[", "1", "]", "[", "2", "]", ",", "inputMatrix", "[", "2", "]", "[", "0", "]", ",", "inputMatrix", "[", "2", "]", "[", "1", "]", ",", "inputMatrix", "[", "2", "]", "[", "2", "]", "]", ".", "map", "(", "Number", ")", ";", "return", "this", ";", "}" ]
Recomb the image with the specified matrix. @example sharp(input) .recomb([ [0.3588, 0.7044, 0.1368], [0.2990, 0.5870, 0.1140], [0.2392, 0.4696, 0.0912], ]) .raw() .toBuffer(function(err, data, info) { // data contains the raw pixel data after applying the recomb // With this example input, a sepia filter has been applied }); @param {Array<Array<Number>>} 3x3 Recombination matrix @returns {Sharp} @throws {Error} Invalid parameters
[ "Recomb", "the", "image", "with", "the", "specified", "matrix", "." ]
05d76eeadfe54713606a615185b2da047923406b
https://github.com/lovell/sharp/blob/05d76eeadfe54713606a615185b2da047923406b/lib/operation.js#L401-L416
train
lovell/sharp
lib/operation.js
modulate
function modulate (options) { if (!is.plainObject(options)) { throw is.invalidParameterError('options', 'plain object', options); } if ('brightness' in options) { if (is.number(options.brightness) && options.brightness >= 0) { this.options.brightness = options.brightness; } else { throw is.invalidParameterError('brightness', 'number above zero', options.brightness); } } if ('saturation' in options) { if (is.number(options.saturation) && options.saturation >= 0) { this.options.saturation = options.saturation; } else { throw is.invalidParameterError('saturation', 'number above zero', options.saturation); } } if ('hue' in options) { if (is.integer(options.hue)) { this.options.hue = options.hue % 360; } else { throw is.invalidParameterError('hue', 'number', options.hue); } } return this; }
javascript
function modulate (options) { if (!is.plainObject(options)) { throw is.invalidParameterError('options', 'plain object', options); } if ('brightness' in options) { if (is.number(options.brightness) && options.brightness >= 0) { this.options.brightness = options.brightness; } else { throw is.invalidParameterError('brightness', 'number above zero', options.brightness); } } if ('saturation' in options) { if (is.number(options.saturation) && options.saturation >= 0) { this.options.saturation = options.saturation; } else { throw is.invalidParameterError('saturation', 'number above zero', options.saturation); } } if ('hue' in options) { if (is.integer(options.hue)) { this.options.hue = options.hue % 360; } else { throw is.invalidParameterError('hue', 'number', options.hue); } } return this; }
[ "function", "modulate", "(", "options", ")", "{", "if", "(", "!", "is", ".", "plainObject", "(", "options", ")", ")", "{", "throw", "is", ".", "invalidParameterError", "(", "'options'", ",", "'plain object'", ",", "options", ")", ";", "}", "if", "(", "'brightness'", "in", "options", ")", "{", "if", "(", "is", ".", "number", "(", "options", ".", "brightness", ")", "&&", "options", ".", "brightness", ">=", "0", ")", "{", "this", ".", "options", ".", "brightness", "=", "options", ".", "brightness", ";", "}", "else", "{", "throw", "is", ".", "invalidParameterError", "(", "'brightness'", ",", "'number above zero'", ",", "options", ".", "brightness", ")", ";", "}", "}", "if", "(", "'saturation'", "in", "options", ")", "{", "if", "(", "is", ".", "number", "(", "options", ".", "saturation", ")", "&&", "options", ".", "saturation", ">=", "0", ")", "{", "this", ".", "options", ".", "saturation", "=", "options", ".", "saturation", ";", "}", "else", "{", "throw", "is", ".", "invalidParameterError", "(", "'saturation'", ",", "'number above zero'", ",", "options", ".", "saturation", ")", ";", "}", "}", "if", "(", "'hue'", "in", "options", ")", "{", "if", "(", "is", ".", "integer", "(", "options", ".", "hue", ")", ")", "{", "this", ".", "options", ".", "hue", "=", "options", ".", "hue", "%", "360", ";", "}", "else", "{", "throw", "is", ".", "invalidParameterError", "(", "'hue'", ",", "'number'", ",", "options", ".", "hue", ")", ";", "}", "}", "return", "this", ";", "}" ]
Transforms the image using brightness, saturation and hue rotation. @example sharp(input) .modulate({ brightness: 2 // increase lightness by a factor of 2 }); sharp(input) .modulate({ hue: 180 // hue-rotate by 180 degrees }); // decreate brightness and saturation while also hue-rotating by 90 degrees sharp(input) .modulate({ brightness: 0.5, saturation: 0.5, hue: 90 }); @param {Object} [options] @param {Number} [options.brightness] Brightness multiplier @param {Number} [options.saturation] Saturation multiplier @param {Number} [options.hue] Degrees for hue rotation @returns {Sharp}
[ "Transforms", "the", "image", "using", "brightness", "saturation", "and", "hue", "rotation", "." ]
05d76eeadfe54713606a615185b2da047923406b
https://github.com/lovell/sharp/blob/05d76eeadfe54713606a615185b2da047923406b/lib/operation.js#L446-L472
train
airbnb/enzyme
packages/enzyme/src/ShallowWrapper.js
findWhereUnwrapped
function findWhereUnwrapped(wrapper, predicate, filter = treeFilter) { return wrapper.flatMap(n => filter(n.getNodeInternal(), predicate)); }
javascript
function findWhereUnwrapped(wrapper, predicate, filter = treeFilter) { return wrapper.flatMap(n => filter(n.getNodeInternal(), predicate)); }
[ "function", "findWhereUnwrapped", "(", "wrapper", ",", "predicate", ",", "filter", "=", "treeFilter", ")", "{", "return", "wrapper", ".", "flatMap", "(", "n", "=>", "filter", "(", "n", ".", "getNodeInternal", "(", ")", ",", "predicate", ")", ")", ";", "}" ]
Finds all nodes in the current wrapper nodes' render trees that match the provided predicate function. @param {ShallowWrapper} wrapper @param {Function} predicate @param {Function} filter @returns {ShallowWrapper}
[ "Finds", "all", "nodes", "in", "the", "current", "wrapper", "nodes", "render", "trees", "that", "match", "the", "provided", "predicate", "function", "." ]
cd430eae95eba151f17e970ee77c18f09476de0e
https://github.com/airbnb/enzyme/blob/cd430eae95eba151f17e970ee77c18f09476de0e/packages/enzyme/src/ShallowWrapper.js#L59-L61
train
airbnb/enzyme
packages/enzyme/src/ShallowWrapper.js
filterWhereUnwrapped
function filterWhereUnwrapped(wrapper, predicate) { return wrapper.wrap(wrapper.getNodesInternal().filter(predicate).filter(Boolean)); }
javascript
function filterWhereUnwrapped(wrapper, predicate) { return wrapper.wrap(wrapper.getNodesInternal().filter(predicate).filter(Boolean)); }
[ "function", "filterWhereUnwrapped", "(", "wrapper", ",", "predicate", ")", "{", "return", "wrapper", ".", "wrap", "(", "wrapper", ".", "getNodesInternal", "(", ")", ".", "filter", "(", "predicate", ")", ".", "filter", "(", "Boolean", ")", ")", ";", "}" ]
Returns a new wrapper instance with only the nodes of the current wrapper instance that match the provided predicate function. @param {ShallowWrapper} wrapper @param {Function} predicate @returns {ShallowWrapper}
[ "Returns", "a", "new", "wrapper", "instance", "with", "only", "the", "nodes", "of", "the", "current", "wrapper", "instance", "that", "match", "the", "provided", "predicate", "function", "." ]
cd430eae95eba151f17e970ee77c18f09476de0e
https://github.com/airbnb/enzyme/blob/cd430eae95eba151f17e970ee77c18f09476de0e/packages/enzyme/src/ShallowWrapper.js#L71-L73
train
airbnb/enzyme
packages/enzyme/src/ShallowWrapper.js
validateOptions
function validateOptions(options) { const { lifecycleExperimental, disableLifecycleMethods, enableComponentDidUpdateOnSetState, supportPrevContextArgumentOfComponentDidUpdate, lifecycles, } = options; if (typeof lifecycleExperimental !== 'undefined' && typeof lifecycleExperimental !== 'boolean') { throw new Error('lifecycleExperimental must be either true or false if provided'); } if (typeof disableLifecycleMethods !== 'undefined' && typeof disableLifecycleMethods !== 'boolean') { throw new Error('disableLifecycleMethods must be either true or false if provided'); } if ( lifecycleExperimental != null && disableLifecycleMethods != null && lifecycleExperimental === disableLifecycleMethods ) { throw new Error('lifecycleExperimental and disableLifecycleMethods cannot be set to the same value'); } if ( typeof enableComponentDidUpdateOnSetState !== 'undefined' && lifecycles.componentDidUpdate && lifecycles.componentDidUpdate.onSetState !== enableComponentDidUpdateOnSetState ) { throw new TypeError('the legacy enableComponentDidUpdateOnSetState option should be matched by `lifecycles: { componentDidUpdate: { onSetState: true } }`, for compatibility'); } if ( typeof supportPrevContextArgumentOfComponentDidUpdate !== 'undefined' && lifecycles.componentDidUpdate && lifecycles.componentDidUpdate.prevContext !== supportPrevContextArgumentOfComponentDidUpdate ) { throw new TypeError('the legacy supportPrevContextArgumentOfComponentDidUpdate option should be matched by `lifecycles: { componentDidUpdate: { prevContext: true } }`, for compatibility'); } }
javascript
function validateOptions(options) { const { lifecycleExperimental, disableLifecycleMethods, enableComponentDidUpdateOnSetState, supportPrevContextArgumentOfComponentDidUpdate, lifecycles, } = options; if (typeof lifecycleExperimental !== 'undefined' && typeof lifecycleExperimental !== 'boolean') { throw new Error('lifecycleExperimental must be either true or false if provided'); } if (typeof disableLifecycleMethods !== 'undefined' && typeof disableLifecycleMethods !== 'boolean') { throw new Error('disableLifecycleMethods must be either true or false if provided'); } if ( lifecycleExperimental != null && disableLifecycleMethods != null && lifecycleExperimental === disableLifecycleMethods ) { throw new Error('lifecycleExperimental and disableLifecycleMethods cannot be set to the same value'); } if ( typeof enableComponentDidUpdateOnSetState !== 'undefined' && lifecycles.componentDidUpdate && lifecycles.componentDidUpdate.onSetState !== enableComponentDidUpdateOnSetState ) { throw new TypeError('the legacy enableComponentDidUpdateOnSetState option should be matched by `lifecycles: { componentDidUpdate: { onSetState: true } }`, for compatibility'); } if ( typeof supportPrevContextArgumentOfComponentDidUpdate !== 'undefined' && lifecycles.componentDidUpdate && lifecycles.componentDidUpdate.prevContext !== supportPrevContextArgumentOfComponentDidUpdate ) { throw new TypeError('the legacy supportPrevContextArgumentOfComponentDidUpdate option should be matched by `lifecycles: { componentDidUpdate: { prevContext: true } }`, for compatibility'); } }
[ "function", "validateOptions", "(", "options", ")", "{", "const", "{", "lifecycleExperimental", ",", "disableLifecycleMethods", ",", "enableComponentDidUpdateOnSetState", ",", "supportPrevContextArgumentOfComponentDidUpdate", ",", "lifecycles", ",", "}", "=", "options", ";", "if", "(", "typeof", "lifecycleExperimental", "!==", "'undefined'", "&&", "typeof", "lifecycleExperimental", "!==", "'boolean'", ")", "{", "throw", "new", "Error", "(", "'lifecycleExperimental must be either true or false if provided'", ")", ";", "}", "if", "(", "typeof", "disableLifecycleMethods", "!==", "'undefined'", "&&", "typeof", "disableLifecycleMethods", "!==", "'boolean'", ")", "{", "throw", "new", "Error", "(", "'disableLifecycleMethods must be either true or false if provided'", ")", ";", "}", "if", "(", "lifecycleExperimental", "!=", "null", "&&", "disableLifecycleMethods", "!=", "null", "&&", "lifecycleExperimental", "===", "disableLifecycleMethods", ")", "{", "throw", "new", "Error", "(", "'lifecycleExperimental and disableLifecycleMethods cannot be set to the same value'", ")", ";", "}", "if", "(", "typeof", "enableComponentDidUpdateOnSetState", "!==", "'undefined'", "&&", "lifecycles", ".", "componentDidUpdate", "&&", "lifecycles", ".", "componentDidUpdate", ".", "onSetState", "!==", "enableComponentDidUpdateOnSetState", ")", "{", "throw", "new", "TypeError", "(", "'the legacy enableComponentDidUpdateOnSetState option should be matched by `lifecycles: { componentDidUpdate: { onSetState: true } }`, for compatibility'", ")", ";", "}", "if", "(", "typeof", "supportPrevContextArgumentOfComponentDidUpdate", "!==", "'undefined'", "&&", "lifecycles", ".", "componentDidUpdate", "&&", "lifecycles", ".", "componentDidUpdate", ".", "prevContext", "!==", "supportPrevContextArgumentOfComponentDidUpdate", ")", "{", "throw", "new", "TypeError", "(", "'the legacy supportPrevContextArgumentOfComponentDidUpdate option should be matched by `lifecycles: { componentDidUpdate: { prevContext: true } }`, for compatibility'", ")", ";", "}", "}" ]
Ensure options passed to ShallowWrapper are valid. Throws otherwise. @param {Object} options
[ "Ensure", "options", "passed", "to", "ShallowWrapper", "are", "valid", ".", "Throws", "otherwise", "." ]
cd430eae95eba151f17e970ee77c18f09476de0e
https://github.com/airbnb/enzyme/blob/cd430eae95eba151f17e970ee77c18f09476de0e/packages/enzyme/src/ShallowWrapper.js#L79-L118
train
airbnb/enzyme
packages/enzyme/src/ShallowWrapper.js
getContextFromWrappingComponent
function getContextFromWrappingComponent(wrapper, adapter) { const rootFinder = deepRender(wrapper, wrapper[ROOT_FINDER], adapter); if (!rootFinder) { throw new Error('`wrappingComponent` must render its children!'); } return { legacyContext: rootFinder[OPTIONS].context, providerValues: rootFinder[PROVIDER_VALUES], }; }
javascript
function getContextFromWrappingComponent(wrapper, adapter) { const rootFinder = deepRender(wrapper, wrapper[ROOT_FINDER], adapter); if (!rootFinder) { throw new Error('`wrappingComponent` must render its children!'); } return { legacyContext: rootFinder[OPTIONS].context, providerValues: rootFinder[PROVIDER_VALUES], }; }
[ "function", "getContextFromWrappingComponent", "(", "wrapper", ",", "adapter", ")", "{", "const", "rootFinder", "=", "deepRender", "(", "wrapper", ",", "wrapper", "[", "ROOT_FINDER", "]", ",", "adapter", ")", ";", "if", "(", "!", "rootFinder", ")", "{", "throw", "new", "Error", "(", "'`wrappingComponent` must render its children!'", ")", ";", "}", "return", "{", "legacyContext", ":", "rootFinder", "[", "OPTIONS", "]", ".", "context", ",", "providerValues", ":", "rootFinder", "[", "PROVIDER_VALUES", "]", ",", "}", ";", "}" ]
Deep-renders the `wrappingComponent` and returns the context that should be accessible to the primary wrapper. @param {WrappingComponentWrapper} wrapper The `WrappingComponentWrapper` for a `wrappingComponent` @param {Adapter} adapter An Enzyme adapter @returns {object} An object containing an object of legacy context values and a Map of `createContext()` Provider values.
[ "Deep", "-", "renders", "the", "wrappingComponent", "and", "returns", "the", "context", "that", "should", "be", "accessible", "to", "the", "primary", "wrapper", "." ]
cd430eae95eba151f17e970ee77c18f09476de0e
https://github.com/airbnb/enzyme/blob/cd430eae95eba151f17e970ee77c18f09476de0e/packages/enzyme/src/ShallowWrapper.js#L320-L329
train
airbnb/enzyme
packages/enzyme/src/ShallowWrapper.js
updatePrimaryRootContext
function updatePrimaryRootContext(wrappingComponent) { const adapter = getAdapter(wrappingComponent[OPTIONS]); const primaryWrapper = wrappingComponent[PRIMARY_WRAPPER]; const primaryRenderer = primaryWrapper[RENDERER]; const primaryNode = primaryRenderer.getNode(); const { legacyContext, providerValues, } = getContextFromWrappingComponent(wrappingComponent, adapter); const prevProviderValues = primaryWrapper[PROVIDER_VALUES]; primaryWrapper.setContext({ ...wrappingComponent[PRIMARY_WRAPPER][OPTIONS].context, ...legacyContext, }); primaryWrapper[PROVIDER_VALUES] = new Map([...prevProviderValues, ...providerValues]); if (typeof adapter.isContextConsumer === 'function' && adapter.isContextConsumer(primaryNode.type)) { const Consumer = primaryNode.type; // Adapters with an `isContextConsumer` method will definitely have a `getProviderFromConsumer` // method. const Provider = adapter.getProviderFromConsumer(Consumer); const newValue = providerValues.get(Provider); const oldValue = prevProviderValues.get(Provider); // Use referential comparison like React if (newValue !== oldValue) { primaryWrapper.rerender(); } } }
javascript
function updatePrimaryRootContext(wrappingComponent) { const adapter = getAdapter(wrappingComponent[OPTIONS]); const primaryWrapper = wrappingComponent[PRIMARY_WRAPPER]; const primaryRenderer = primaryWrapper[RENDERER]; const primaryNode = primaryRenderer.getNode(); const { legacyContext, providerValues, } = getContextFromWrappingComponent(wrappingComponent, adapter); const prevProviderValues = primaryWrapper[PROVIDER_VALUES]; primaryWrapper.setContext({ ...wrappingComponent[PRIMARY_WRAPPER][OPTIONS].context, ...legacyContext, }); primaryWrapper[PROVIDER_VALUES] = new Map([...prevProviderValues, ...providerValues]); if (typeof adapter.isContextConsumer === 'function' && adapter.isContextConsumer(primaryNode.type)) { const Consumer = primaryNode.type; // Adapters with an `isContextConsumer` method will definitely have a `getProviderFromConsumer` // method. const Provider = adapter.getProviderFromConsumer(Consumer); const newValue = providerValues.get(Provider); const oldValue = prevProviderValues.get(Provider); // Use referential comparison like React if (newValue !== oldValue) { primaryWrapper.rerender(); } } }
[ "function", "updatePrimaryRootContext", "(", "wrappingComponent", ")", "{", "const", "adapter", "=", "getAdapter", "(", "wrappingComponent", "[", "OPTIONS", "]", ")", ";", "const", "primaryWrapper", "=", "wrappingComponent", "[", "PRIMARY_WRAPPER", "]", ";", "const", "primaryRenderer", "=", "primaryWrapper", "[", "RENDERER", "]", ";", "const", "primaryNode", "=", "primaryRenderer", ".", "getNode", "(", ")", ";", "const", "{", "legacyContext", ",", "providerValues", ",", "}", "=", "getContextFromWrappingComponent", "(", "wrappingComponent", ",", "adapter", ")", ";", "const", "prevProviderValues", "=", "primaryWrapper", "[", "PROVIDER_VALUES", "]", ";", "primaryWrapper", ".", "setContext", "(", "{", "...", "wrappingComponent", "[", "PRIMARY_WRAPPER", "]", "[", "OPTIONS", "]", ".", "context", ",", "...", "legacyContext", ",", "}", ")", ";", "primaryWrapper", "[", "PROVIDER_VALUES", "]", "=", "new", "Map", "(", "[", "...", "prevProviderValues", ",", "...", "providerValues", "]", ")", ";", "if", "(", "typeof", "adapter", ".", "isContextConsumer", "===", "'function'", "&&", "adapter", ".", "isContextConsumer", "(", "primaryNode", ".", "type", ")", ")", "{", "const", "Consumer", "=", "primaryNode", ".", "type", ";", "const", "Provider", "=", "adapter", ".", "getProviderFromConsumer", "(", "Consumer", ")", ";", "const", "newValue", "=", "providerValues", ".", "get", "(", "Provider", ")", ";", "const", "oldValue", "=", "prevProviderValues", ".", "get", "(", "Provider", ")", ";", "if", "(", "newValue", "!==", "oldValue", ")", "{", "primaryWrapper", ".", "rerender", "(", ")", ";", "}", "}", "}" ]
Updates the context of the primary wrapper when the `wrappingComponent` re-renders.
[ "Updates", "the", "context", "of", "the", "primary", "wrapper", "when", "the", "wrappingComponent", "re", "-", "renders", "." ]
cd430eae95eba151f17e970ee77c18f09476de0e
https://github.com/airbnb/enzyme/blob/cd430eae95eba151f17e970ee77c18f09476de0e/packages/enzyme/src/ShallowWrapper.js#L1724-L1754
train
airbnb/enzyme
packages/enzyme/src/selectors.js
nodeMatchesToken
function nodeMatchesToken(node, token, root) { if (node === null || typeof node === 'string') { return false; } switch (token.type) { /** * Match every node * @example '*' matches every node */ case UNIVERSAL_SELECTOR: return true; /** * Match against the className prop * @example '.active' matches <div className='active' /> */ case CLASS_SELECTOR: return hasClassName(node, token.name); /** * Simple type matching * @example 'div' matches <div /> */ case TYPE_SELECTOR: return nodeHasType(node, token.name); /** * Match against the `id` prop * @example '#nav' matches <ul id="nav" /> */ case ID_SELECTOR: return nodeHasId(node, token.name); /** * Matches if an attribute is present, regardless * of its value * @example '[disabled]' matches <a disabled /> */ case ATTRIBUTE_PRESENCE: return matchAttributeSelector(node, token); /** * Matches if an attribute is present with the * provided value * @example '[data-foo=foo]' matches <div data-foo="foo" /> */ case ATTRIBUTE_VALUE: return matchAttributeSelector(node, token); case PSEUDO_ELEMENT: case PSEUDO_CLASS: return matchPseudoSelector(node, token, root); default: throw new Error(`Unknown token type: ${token.type}`); } }
javascript
function nodeMatchesToken(node, token, root) { if (node === null || typeof node === 'string') { return false; } switch (token.type) { /** * Match every node * @example '*' matches every node */ case UNIVERSAL_SELECTOR: return true; /** * Match against the className prop * @example '.active' matches <div className='active' /> */ case CLASS_SELECTOR: return hasClassName(node, token.name); /** * Simple type matching * @example 'div' matches <div /> */ case TYPE_SELECTOR: return nodeHasType(node, token.name); /** * Match against the `id` prop * @example '#nav' matches <ul id="nav" /> */ case ID_SELECTOR: return nodeHasId(node, token.name); /** * Matches if an attribute is present, regardless * of its value * @example '[disabled]' matches <a disabled /> */ case ATTRIBUTE_PRESENCE: return matchAttributeSelector(node, token); /** * Matches if an attribute is present with the * provided value * @example '[data-foo=foo]' matches <div data-foo="foo" /> */ case ATTRIBUTE_VALUE: return matchAttributeSelector(node, token); case PSEUDO_ELEMENT: case PSEUDO_CLASS: return matchPseudoSelector(node, token, root); default: throw new Error(`Unknown token type: ${token.type}`); } }
[ "function", "nodeMatchesToken", "(", "node", ",", "token", ",", "root", ")", "{", "if", "(", "node", "===", "null", "||", "typeof", "node", "===", "'string'", ")", "{", "return", "false", ";", "}", "switch", "(", "token", ".", "type", ")", "{", "case", "UNIVERSAL_SELECTOR", ":", "return", "true", ";", "case", "CLASS_SELECTOR", ":", "return", "hasClassName", "(", "node", ",", "token", ".", "name", ")", ";", "case", "TYPE_SELECTOR", ":", "return", "nodeHasType", "(", "node", ",", "token", ".", "name", ")", ";", "case", "ID_SELECTOR", ":", "return", "nodeHasId", "(", "node", ",", "token", ".", "name", ")", ";", "case", "ATTRIBUTE_PRESENCE", ":", "return", "matchAttributeSelector", "(", "node", ",", "token", ")", ";", "case", "ATTRIBUTE_VALUE", ":", "return", "matchAttributeSelector", "(", "node", ",", "token", ")", ";", "case", "PSEUDO_ELEMENT", ":", "case", "PSEUDO_CLASS", ":", "return", "matchPseudoSelector", "(", "node", ",", "token", ",", "root", ")", ";", "default", ":", "throw", "new", "Error", "(", "`", "${", "token", ".", "type", "}", "`", ")", ";", "}", "}" ]
Takes a node and a token and determines if the node matches the predicate defined by the token. @param {Node} node @param {Token} token
[ "Takes", "a", "node", "and", "a", "token", "and", "determines", "if", "the", "node", "matches", "the", "predicate", "defined", "by", "the", "token", "." ]
cd430eae95eba151f17e970ee77c18f09476de0e
https://github.com/airbnb/enzyme/blob/cd430eae95eba151f17e970ee77c18f09476de0e/packages/enzyme/src/selectors.js#L183-L232
train
airbnb/enzyme
packages/enzyme/src/selectors.js
buildPredicateFromToken
function buildPredicateFromToken(token, root) { return node => token.body.every(bodyToken => nodeMatchesToken(node, bodyToken, root)); }
javascript
function buildPredicateFromToken(token, root) { return node => token.body.every(bodyToken => nodeMatchesToken(node, bodyToken, root)); }
[ "function", "buildPredicateFromToken", "(", "token", ",", "root", ")", "{", "return", "node", "=>", "token", ".", "body", ".", "every", "(", "bodyToken", "=>", "nodeMatchesToken", "(", "node", ",", "bodyToken", ",", "root", ")", ")", ";", "}" ]
Returns a predicate function that checks if a node matches every token in the body of a selector token. @param {Token} token
[ "Returns", "a", "predicate", "function", "that", "checks", "if", "a", "node", "matches", "every", "token", "in", "the", "body", "of", "a", "selector", "token", "." ]
cd430eae95eba151f17e970ee77c18f09476de0e
https://github.com/airbnb/enzyme/blob/cd430eae95eba151f17e970ee77c18f09476de0e/packages/enzyme/src/selectors.js#L240-L242
train
airbnb/enzyme
packages/enzyme/src/selectors.js
matchDescendant
function matchDescendant(nodes, predicate) { return uniqueReduce( (matches, node) => matches.concat(treeFilter(node, predicate)), flat(nodes.map(childrenOfNode)), ); }
javascript
function matchDescendant(nodes, predicate) { return uniqueReduce( (matches, node) => matches.concat(treeFilter(node, predicate)), flat(nodes.map(childrenOfNode)), ); }
[ "function", "matchDescendant", "(", "nodes", ",", "predicate", ")", "{", "return", "uniqueReduce", "(", "(", "matches", ",", "node", ")", "=>", "matches", ".", "concat", "(", "treeFilter", "(", "node", ",", "predicate", ")", ")", ",", "flat", "(", "nodes", ".", "map", "(", "childrenOfNode", ")", ")", ",", ")", ";", "}" ]
Matches all descendant nodes against a predicate, returning those that match. @param {Array<Node>} nodes @param {Function} predicate
[ "Matches", "all", "descendant", "nodes", "against", "a", "predicate", "returning", "those", "that", "match", "." ]
cd430eae95eba151f17e970ee77c18f09476de0e
https://github.com/airbnb/enzyme/blob/cd430eae95eba151f17e970ee77c18f09476de0e/packages/enzyme/src/selectors.js#L361-L366
train
GoogleChrome/workbox
packages/workbox-webpack-plugin/src/lib/get-manifest-entries-from-compilation.js
getEntry
function getEntry(knownHashes, url, revision) { // We're assuming that if the URL contains any of the known hashes // (either the short or full chunk hash or compilation hash) then it's // already revisioned, and we don't need additional out-of-band revisioning. if (!revision || knownHashes.some((hash) => url.includes(hash))) { return {url}; } return {revision, url}; }
javascript
function getEntry(knownHashes, url, revision) { // We're assuming that if the URL contains any of the known hashes // (either the short or full chunk hash or compilation hash) then it's // already revisioned, and we don't need additional out-of-band revisioning. if (!revision || knownHashes.some((hash) => url.includes(hash))) { return {url}; } return {revision, url}; }
[ "function", "getEntry", "(", "knownHashes", ",", "url", ",", "revision", ")", "{", "if", "(", "!", "revision", "||", "knownHashes", ".", "some", "(", "(", "hash", ")", "=>", "url", ".", "includes", "(", "hash", ")", ")", ")", "{", "return", "{", "url", "}", ";", "}", "return", "{", "revision", ",", "url", "}", ";", "}" ]
A single manifest entry that Workbox can precache. When possible, we leave out the revision information, which tells Workbox that the URL contains enough info to uniquely version the asset. @param {Array<string>} knownHashes All of the hashes that are associated with this webpack build. @param {string} url webpack asset url path @param {string} [revision] A revision hash for the entry @return {module:workbox-build.ManifestEntry} A single manifest entry @private
[ "A", "single", "manifest", "entry", "that", "Workbox", "can", "precache", ".", "When", "possible", "we", "leave", "out", "the", "revision", "information", "which", "tells", "Workbox", "that", "the", "URL", "contains", "enough", "info", "to", "uniquely", "version", "the", "asset", "." ]
8379c51b6deaf52faed5879206fe84579cae41f0
https://github.com/GoogleChrome/workbox/blob/8379c51b6deaf52faed5879206fe84579cae41f0/packages/workbox-webpack-plugin/src/lib/get-manifest-entries-from-compilation.js#L27-L35
train
GoogleChrome/workbox
packages/workbox-webpack-plugin/src/lib/get-manifest-entries-from-compilation.js
getKnownHashesFromAssets
function getKnownHashesFromAssets(assetMetadata) { const knownHashes = new Set(); for (const metadata of Object.values(assetMetadata)) { knownHashes.add(metadata.hash); } return knownHashes; }
javascript
function getKnownHashesFromAssets(assetMetadata) { const knownHashes = new Set(); for (const metadata of Object.values(assetMetadata)) { knownHashes.add(metadata.hash); } return knownHashes; }
[ "function", "getKnownHashesFromAssets", "(", "assetMetadata", ")", "{", "const", "knownHashes", "=", "new", "Set", "(", ")", ";", "for", "(", "const", "metadata", "of", "Object", ".", "values", "(", "assetMetadata", ")", ")", "{", "knownHashes", ".", "add", "(", "metadata", ".", "hash", ")", ";", "}", "return", "knownHashes", ";", "}" ]
Given an assetMetadata mapping, returns a Set of all of the hashes that are associated with at least one asset. @param {Object<string, Object>} assetMetadata Mapping of asset paths to chunk name and hash metadata. @return {Set} The known hashes associated with an asset. @private
[ "Given", "an", "assetMetadata", "mapping", "returns", "a", "Set", "of", "all", "of", "the", "hashes", "that", "are", "associated", "with", "at", "least", "one", "asset", "." ]
8379c51b6deaf52faed5879206fe84579cae41f0
https://github.com/GoogleChrome/workbox/blob/8379c51b6deaf52faed5879206fe84579cae41f0/packages/workbox-webpack-plugin/src/lib/get-manifest-entries-from-compilation.js#L139-L145
train
GoogleChrome/workbox
packages/workbox-webpack-plugin/src/lib/get-manifest-entries-from-compilation.js
getManifestEntriesFromCompilation
function getManifestEntriesFromCompilation(compilation, config) { const blacklistedChunkNames = config.excludeChunks; const whitelistedChunkNames = config.chunks; const {assets, chunks} = compilation; const {publicPath} = compilation.options.output; const assetMetadata = generateMetadataForAssets(assets, chunks); const filteredAssetMetadata = filterAssets(assetMetadata, whitelistedChunkNames, blacklistedChunkNames); const knownHashes = [ compilation.hash, compilation.fullHash, ...getKnownHashesFromAssets(filteredAssetMetadata), ].filter((hash) => !!hash); const manifestEntries = []; for (const [file, metadata] of Object.entries(filteredAssetMetadata)) { // Filter based on test/include/exclude options set in the config, // following webpack's conventions. // This matches the behavior of, e.g., UglifyJS's webpack plugin. if (!ModuleFilenameHelpers.matchObject(config, file)) { continue; } const publicURL = resolveWebpackURL(publicPath, file); const manifestEntry = getEntry(knownHashes, publicURL, metadata.hash); manifestEntries.push(manifestEntry); } return manifestEntries; }
javascript
function getManifestEntriesFromCompilation(compilation, config) { const blacklistedChunkNames = config.excludeChunks; const whitelistedChunkNames = config.chunks; const {assets, chunks} = compilation; const {publicPath} = compilation.options.output; const assetMetadata = generateMetadataForAssets(assets, chunks); const filteredAssetMetadata = filterAssets(assetMetadata, whitelistedChunkNames, blacklistedChunkNames); const knownHashes = [ compilation.hash, compilation.fullHash, ...getKnownHashesFromAssets(filteredAssetMetadata), ].filter((hash) => !!hash); const manifestEntries = []; for (const [file, metadata] of Object.entries(filteredAssetMetadata)) { // Filter based on test/include/exclude options set in the config, // following webpack's conventions. // This matches the behavior of, e.g., UglifyJS's webpack plugin. if (!ModuleFilenameHelpers.matchObject(config, file)) { continue; } const publicURL = resolveWebpackURL(publicPath, file); const manifestEntry = getEntry(knownHashes, publicURL, metadata.hash); manifestEntries.push(manifestEntry); } return manifestEntries; }
[ "function", "getManifestEntriesFromCompilation", "(", "compilation", ",", "config", ")", "{", "const", "blacklistedChunkNames", "=", "config", ".", "excludeChunks", ";", "const", "whitelistedChunkNames", "=", "config", ".", "chunks", ";", "const", "{", "assets", ",", "chunks", "}", "=", "compilation", ";", "const", "{", "publicPath", "}", "=", "compilation", ".", "options", ".", "output", ";", "const", "assetMetadata", "=", "generateMetadataForAssets", "(", "assets", ",", "chunks", ")", ";", "const", "filteredAssetMetadata", "=", "filterAssets", "(", "assetMetadata", ",", "whitelistedChunkNames", ",", "blacklistedChunkNames", ")", ";", "const", "knownHashes", "=", "[", "compilation", ".", "hash", ",", "compilation", ".", "fullHash", ",", "...", "getKnownHashesFromAssets", "(", "filteredAssetMetadata", ")", ",", "]", ".", "filter", "(", "(", "hash", ")", "=>", "!", "!", "hash", ")", ";", "const", "manifestEntries", "=", "[", "]", ";", "for", "(", "const", "[", "file", ",", "metadata", "]", "of", "Object", ".", "entries", "(", "filteredAssetMetadata", ")", ")", "{", "if", "(", "!", "ModuleFilenameHelpers", ".", "matchObject", "(", "config", ",", "file", ")", ")", "{", "continue", ";", "}", "const", "publicURL", "=", "resolveWebpackURL", "(", "publicPath", ",", "file", ")", ";", "const", "manifestEntry", "=", "getEntry", "(", "knownHashes", ",", "publicURL", ",", "metadata", ".", "hash", ")", ";", "manifestEntries", ".", "push", "(", "manifestEntry", ")", ";", "}", "return", "manifestEntries", ";", "}" ]
Generate an array of manifest entries using webpack's compilation data. @param {Object} compilation webpack compilation @param {Object} config @return {Array<workbox.build.ManifestEntry>} @private
[ "Generate", "an", "array", "of", "manifest", "entries", "using", "webpack", "s", "compilation", "data", "." ]
8379c51b6deaf52faed5879206fe84579cae41f0
https://github.com/GoogleChrome/workbox/blob/8379c51b6deaf52faed5879206fe84579cae41f0/packages/workbox-webpack-plugin/src/lib/get-manifest-entries-from-compilation.js#L156-L186
train
GoogleChrome/workbox
packages/workbox-build/src/lib/runtime-caching-converter.js
getOptionsString
function getOptionsString(options = {}) { let plugins = []; if (options.plugins) { // Using libs because JSON.stringify won't handle functions. plugins = options.plugins.map(stringifyWithoutComments); delete options.plugins; } // Pull handler-specific config from the options object, since they are // not directly used to construct a Plugin instance. If set, need to be // passed as options to the handler constructor instead. const handlerOptionKeys = [ 'cacheName', 'networkTimeoutSeconds', 'fetchOptions', 'matchOptions', ]; const handlerOptions = {}; for (const key of handlerOptionKeys) { if (key in options) { handlerOptions[key] = options[key]; delete options[key]; } } const pluginsMapping = { backgroundSync: 'workbox.backgroundSync.Plugin', broadcastUpdate: 'workbox.broadcastUpdate.Plugin', expiration: 'workbox.expiration.Plugin', cacheableResponse: 'workbox.cacheableResponse.Plugin', }; for (const [pluginName, pluginConfig] of Object.entries(options)) { // Ensure that we have some valid configuration to pass to Plugin(). if (Object.keys(pluginConfig).length === 0) { continue; } const pluginString = pluginsMapping[pluginName]; if (!pluginString) { throw new Error(`${errors['bad-runtime-caching-config']} ${pluginName}`); } let pluginCode; switch (pluginName) { // Special case logic for plugins that have a required parameter, and then // an additional optional config parameter. case 'backgroundSync': { const name = pluginConfig.name; pluginCode = `new ${pluginString}(${JSON.stringify(name)}`; if ('options' in pluginConfig) { pluginCode += `, ${stringifyWithoutComments(pluginConfig.options)}`; } pluginCode += `)`; break; } case 'broadcastUpdate': { const channelName = pluginConfig.channelName; const opts = Object.assign({channelName}, pluginConfig.options); pluginCode = `new ${pluginString}(${stringifyWithoutComments(opts)})`; break; } // For plugins that just pass in an Object to the constructor, like // expiration and cacheableResponse default: { pluginCode = `new ${pluginString}(${stringifyWithoutComments( pluginConfig )})`; } } plugins.push(pluginCode); } if (Object.keys(handlerOptions).length > 0 || plugins.length > 0) { const optionsString = JSON.stringify(handlerOptions).slice(1, -1); return ol`{ ${optionsString ? optionsString + ',' : ''} plugins: [${plugins.join(', ')}] }`; } else { return ''; } }
javascript
function getOptionsString(options = {}) { let plugins = []; if (options.plugins) { // Using libs because JSON.stringify won't handle functions. plugins = options.plugins.map(stringifyWithoutComments); delete options.plugins; } // Pull handler-specific config from the options object, since they are // not directly used to construct a Plugin instance. If set, need to be // passed as options to the handler constructor instead. const handlerOptionKeys = [ 'cacheName', 'networkTimeoutSeconds', 'fetchOptions', 'matchOptions', ]; const handlerOptions = {}; for (const key of handlerOptionKeys) { if (key in options) { handlerOptions[key] = options[key]; delete options[key]; } } const pluginsMapping = { backgroundSync: 'workbox.backgroundSync.Plugin', broadcastUpdate: 'workbox.broadcastUpdate.Plugin', expiration: 'workbox.expiration.Plugin', cacheableResponse: 'workbox.cacheableResponse.Plugin', }; for (const [pluginName, pluginConfig] of Object.entries(options)) { // Ensure that we have some valid configuration to pass to Plugin(). if (Object.keys(pluginConfig).length === 0) { continue; } const pluginString = pluginsMapping[pluginName]; if (!pluginString) { throw new Error(`${errors['bad-runtime-caching-config']} ${pluginName}`); } let pluginCode; switch (pluginName) { // Special case logic for plugins that have a required parameter, and then // an additional optional config parameter. case 'backgroundSync': { const name = pluginConfig.name; pluginCode = `new ${pluginString}(${JSON.stringify(name)}`; if ('options' in pluginConfig) { pluginCode += `, ${stringifyWithoutComments(pluginConfig.options)}`; } pluginCode += `)`; break; } case 'broadcastUpdate': { const channelName = pluginConfig.channelName; const opts = Object.assign({channelName}, pluginConfig.options); pluginCode = `new ${pluginString}(${stringifyWithoutComments(opts)})`; break; } // For plugins that just pass in an Object to the constructor, like // expiration and cacheableResponse default: { pluginCode = `new ${pluginString}(${stringifyWithoutComments( pluginConfig )})`; } } plugins.push(pluginCode); } if (Object.keys(handlerOptions).length > 0 || plugins.length > 0) { const optionsString = JSON.stringify(handlerOptions).slice(1, -1); return ol`{ ${optionsString ? optionsString + ',' : ''} plugins: [${plugins.join(', ')}] }`; } else { return ''; } }
[ "function", "getOptionsString", "(", "options", "=", "{", "}", ")", "{", "let", "plugins", "=", "[", "]", ";", "if", "(", "options", ".", "plugins", ")", "{", "plugins", "=", "options", ".", "plugins", ".", "map", "(", "stringifyWithoutComments", ")", ";", "delete", "options", ".", "plugins", ";", "}", "const", "handlerOptionKeys", "=", "[", "'cacheName'", ",", "'networkTimeoutSeconds'", ",", "'fetchOptions'", ",", "'matchOptions'", ",", "]", ";", "const", "handlerOptions", "=", "{", "}", ";", "for", "(", "const", "key", "of", "handlerOptionKeys", ")", "{", "if", "(", "key", "in", "options", ")", "{", "handlerOptions", "[", "key", "]", "=", "options", "[", "key", "]", ";", "delete", "options", "[", "key", "]", ";", "}", "}", "const", "pluginsMapping", "=", "{", "backgroundSync", ":", "'workbox.backgroundSync.Plugin'", ",", "broadcastUpdate", ":", "'workbox.broadcastUpdate.Plugin'", ",", "expiration", ":", "'workbox.expiration.Plugin'", ",", "cacheableResponse", ":", "'workbox.cacheableResponse.Plugin'", ",", "}", ";", "for", "(", "const", "[", "pluginName", ",", "pluginConfig", "]", "of", "Object", ".", "entries", "(", "options", ")", ")", "{", "if", "(", "Object", ".", "keys", "(", "pluginConfig", ")", ".", "length", "===", "0", ")", "{", "continue", ";", "}", "const", "pluginString", "=", "pluginsMapping", "[", "pluginName", "]", ";", "if", "(", "!", "pluginString", ")", "{", "throw", "new", "Error", "(", "`", "${", "errors", "[", "'bad-runtime-caching-config'", "]", "}", "${", "pluginName", "}", "`", ")", ";", "}", "let", "pluginCode", ";", "switch", "(", "pluginName", ")", "{", "case", "'backgroundSync'", ":", "{", "const", "name", "=", "pluginConfig", ".", "name", ";", "pluginCode", "=", "`", "${", "pluginString", "}", "${", "JSON", ".", "stringify", "(", "name", ")", "}", "`", ";", "if", "(", "'options'", "in", "pluginConfig", ")", "{", "pluginCode", "+=", "`", "${", "stringifyWithoutComments", "(", "pluginConfig", ".", "options", ")", "}", "`", ";", "}", "pluginCode", "+=", "`", "`", ";", "break", ";", "}", "case", "'broadcastUpdate'", ":", "{", "const", "channelName", "=", "pluginConfig", ".", "channelName", ";", "const", "opts", "=", "Object", ".", "assign", "(", "{", "channelName", "}", ",", "pluginConfig", ".", "options", ")", ";", "pluginCode", "=", "`", "${", "pluginString", "}", "${", "stringifyWithoutComments", "(", "opts", ")", "}", "`", ";", "break", ";", "}", "default", ":", "{", "pluginCode", "=", "`", "${", "pluginString", "}", "${", "stringifyWithoutComments", "(", "pluginConfig", ")", "}", "`", ";", "}", "}", "plugins", ".", "push", "(", "pluginCode", ")", ";", "}", "if", "(", "Object", ".", "keys", "(", "handlerOptions", ")", ".", "length", ">", "0", "||", "plugins", ".", "length", ">", "0", ")", "{", "const", "optionsString", "=", "JSON", ".", "stringify", "(", "handlerOptions", ")", ".", "slice", "(", "1", ",", "-", "1", ")", ";", "return", "ol", "`", "${", "optionsString", "?", "optionsString", "+", "','", ":", "''", "}", "${", "plugins", ".", "join", "(", "', '", ")", "}", "`", ";", "}", "else", "{", "return", "''", ";", "}", "}" ]
Given a set of options that configures `sw-toolbox`'s behavior, convert it into a string that would configure equivalent `workbox-sw` behavior. @param {Object} options See https://googlechromelabs.github.io/sw-toolbox/api.html#options @return {string} A JSON string representing the equivalent options. @private
[ "Given", "a", "set", "of", "options", "that", "configures", "sw", "-", "toolbox", "s", "behavior", "convert", "it", "into", "a", "string", "that", "would", "configure", "equivalent", "workbox", "-", "sw", "behavior", "." ]
8379c51b6deaf52faed5879206fe84579cae41f0
https://github.com/GoogleChrome/workbox/blob/8379c51b6deaf52faed5879206fe84579cae41f0/packages/workbox-build/src/lib/runtime-caching-converter.js#L24-L111
train
GoogleChrome/workbox
packages/workbox-build/src/entry-points/generate-sw-string.js
generateSWString
async function generateSWString(config) { // This check needs to be done before validation, since the deprecated options // will be renamed. const deprecationWarnings = checkForDeprecatedOptions(config); const options = validate(config, generateSWStringSchema); const {manifestEntries, warnings} = await getFileManifestEntries(options); const swString = await populateSWTemplate(Object.assign({ manifestEntries, }, options)); // Add in any deprecation warnings. warnings.push(...deprecationWarnings); return {swString, warnings}; }
javascript
async function generateSWString(config) { // This check needs to be done before validation, since the deprecated options // will be renamed. const deprecationWarnings = checkForDeprecatedOptions(config); const options = validate(config, generateSWStringSchema); const {manifestEntries, warnings} = await getFileManifestEntries(options); const swString = await populateSWTemplate(Object.assign({ manifestEntries, }, options)); // Add in any deprecation warnings. warnings.push(...deprecationWarnings); return {swString, warnings}; }
[ "async", "function", "generateSWString", "(", "config", ")", "{", "const", "deprecationWarnings", "=", "checkForDeprecatedOptions", "(", "config", ")", ";", "const", "options", "=", "validate", "(", "config", ",", "generateSWStringSchema", ")", ";", "const", "{", "manifestEntries", ",", "warnings", "}", "=", "await", "getFileManifestEntries", "(", "options", ")", ";", "const", "swString", "=", "await", "populateSWTemplate", "(", "Object", ".", "assign", "(", "{", "manifestEntries", ",", "}", ",", "options", ")", ")", ";", "warnings", ".", "push", "(", "...", "deprecationWarnings", ")", ";", "return", "{", "swString", ",", "warnings", "}", ";", "}" ]
This method generates a service worker based on the configuration options provided. @param {Object} config Please refer to the [configuration guide](https://developers.google.com/web/tools/workbox/modules/workbox-build#generateswstring_mode). @return {Promise<{swString: string, warnings: Array<string>}>} A promise that resolves once the service worker template is populated. The `swString` property contains a string representation of the full service worker code. Any non-fatal warning messages will be returned via `warnings`. @memberof module:workbox-build
[ "This", "method", "generates", "a", "service", "worker", "based", "on", "the", "configuration", "options", "provided", "." ]
8379c51b6deaf52faed5879206fe84579cae41f0
https://github.com/GoogleChrome/workbox/blob/8379c51b6deaf52faed5879206fe84579cae41f0/packages/workbox-build/src/entry-points/generate-sw-string.js#L29-L46
train
GoogleChrome/workbox
packages/workbox-cli/src/app.js
runBuildCommand
async function runBuildCommand({command, config, watch}) { try { const {size, count, warnings} = await workboxBuild[command](config); for (const warning of warnings) { logger.warn(warning); } logger.log(`The service worker was written to ${config.swDest}\n` + `${count} files will be precached, totalling ${prettyBytes(size)}.`); if (watch) { logger.log(`\nWatching for changes...`); } } catch (error) { // See https://github.com/hapijs/joi/blob/v11.3.4/API.md#errors if (typeof error.annotate === 'function') { throw new Error( `${errors['config-validation-failed']}\n${error.annotate()}`); } logger.error(errors['workbox-build-runtime-error']); throw error; } }
javascript
async function runBuildCommand({command, config, watch}) { try { const {size, count, warnings} = await workboxBuild[command](config); for (const warning of warnings) { logger.warn(warning); } logger.log(`The service worker was written to ${config.swDest}\n` + `${count} files will be precached, totalling ${prettyBytes(size)}.`); if (watch) { logger.log(`\nWatching for changes...`); } } catch (error) { // See https://github.com/hapijs/joi/blob/v11.3.4/API.md#errors if (typeof error.annotate === 'function') { throw new Error( `${errors['config-validation-failed']}\n${error.annotate()}`); } logger.error(errors['workbox-build-runtime-error']); throw error; } }
[ "async", "function", "runBuildCommand", "(", "{", "command", ",", "config", ",", "watch", "}", ")", "{", "try", "{", "const", "{", "size", ",", "count", ",", "warnings", "}", "=", "await", "workboxBuild", "[", "command", "]", "(", "config", ")", ";", "for", "(", "const", "warning", "of", "warnings", ")", "{", "logger", ".", "warn", "(", "warning", ")", ";", "}", "logger", ".", "log", "(", "`", "${", "config", ".", "swDest", "}", "\\n", "`", "+", "`", "${", "count", "}", "${", "prettyBytes", "(", "size", ")", "}", "`", ")", ";", "if", "(", "watch", ")", "{", "logger", ".", "log", "(", "`", "\\n", "`", ")", ";", "}", "}", "catch", "(", "error", ")", "{", "if", "(", "typeof", "error", ".", "annotate", "===", "'function'", ")", "{", "throw", "new", "Error", "(", "`", "${", "errors", "[", "'config-validation-failed'", "]", "}", "\\n", "${", "error", ".", "annotate", "(", ")", "}", "`", ")", ";", "}", "logger", ".", "error", "(", "errors", "[", "'workbox-build-runtime-error'", "]", ")", ";", "throw", "error", ";", "}", "}" ]
Runs the specified build command with the provided configuration. @param {Object} options
[ "Runs", "the", "specified", "build", "command", "with", "the", "provided", "configuration", "." ]
8379c51b6deaf52faed5879206fe84579cae41f0
https://github.com/GoogleChrome/workbox/blob/8379c51b6deaf52faed5879206fe84579cae41f0/packages/workbox-cli/src/app.js#L27-L50
train
GoogleChrome/workbox
packages/workbox-build/src/entry-points/get-manifest.js
getManifest
async function getManifest(config) { // This check needs to be done before validation, since the deprecated options // will be renamed. const deprecationWarnings = checkForDeprecatedOptions(config); const options = validate(config, getManifestSchema); const {manifestEntries, count, size, warnings} = await getFileManifestEntries(options); // Add in any deprecation warnings. warnings.push(...deprecationWarnings); return {manifestEntries, count, size, warnings}; }
javascript
async function getManifest(config) { // This check needs to be done before validation, since the deprecated options // will be renamed. const deprecationWarnings = checkForDeprecatedOptions(config); const options = validate(config, getManifestSchema); const {manifestEntries, count, size, warnings} = await getFileManifestEntries(options); // Add in any deprecation warnings. warnings.push(...deprecationWarnings); return {manifestEntries, count, size, warnings}; }
[ "async", "function", "getManifest", "(", "config", ")", "{", "const", "deprecationWarnings", "=", "checkForDeprecatedOptions", "(", "config", ")", ";", "const", "options", "=", "validate", "(", "config", ",", "getManifestSchema", ")", ";", "const", "{", "manifestEntries", ",", "count", ",", "size", ",", "warnings", "}", "=", "await", "getFileManifestEntries", "(", "options", ")", ";", "warnings", ".", "push", "(", "...", "deprecationWarnings", ")", ";", "return", "{", "manifestEntries", ",", "count", ",", "size", ",", "warnings", "}", ";", "}" ]
This method returns a list of URLs to precache, referred to as a "precache manifest", along with details about the number of entries and their size, based on the options you provide. @param {Object} config Please refer to the [configuration guide](https://developers.google.com/web/tools/workbox/modules/workbox-build#getmanifest_mode). @return {Promise<{manifestEntries: Array<ManifestEntry>, count: number, size: number, warnings: Array<string>}>} A promise that resolves once the precache manifest is determined. The `size` property contains the aggregate size of all the precached entries, in bytes, the `count` property contains the total number of precached entries, and the `manifestEntries` property contains all the `ManifestEntry` items. Any non-fatal warning messages will be returned via `warnings`. @memberof module:workbox-build
[ "This", "method", "returns", "a", "list", "of", "URLs", "to", "precache", "referred", "to", "as", "a", "precache", "manifest", "along", "with", "details", "about", "the", "number", "of", "entries", "and", "their", "size", "based", "on", "the", "options", "you", "provide", "." ]
8379c51b6deaf52faed5879206fe84579cae41f0
https://github.com/GoogleChrome/workbox/blob/8379c51b6deaf52faed5879206fe84579cae41f0/packages/workbox-build/src/entry-points/get-manifest.js#L32-L46
train
tgriesser/knex
src/seed/Seeder.js
Seeder
function Seeder(knex) { this.knex = knex; this.config = this.setConfig(knex.client.config.seeds); }
javascript
function Seeder(knex) { this.knex = knex; this.config = this.setConfig(knex.client.config.seeds); }
[ "function", "Seeder", "(", "knex", ")", "{", "this", ".", "knex", "=", "knex", ";", "this", ".", "config", "=", "this", ".", "setConfig", "(", "knex", ".", "client", ".", "config", ".", "seeds", ")", ";", "}" ]
The new seeds we're performing, typically called from the `knex.seed` interface on the main `knex` object. Passes the `knex` instance performing the seeds.
[ "The", "new", "seeds", "we", "re", "performing", "typically", "called", "from", "the", "knex", ".", "seed", "interface", "on", "the", "main", "knex", "object", ".", "Passes", "the", "knex", "instance", "performing", "the", "seeds", "." ]
6a4fecfe7822442ee5c43d924958eadfe6e17a93
https://github.com/tgriesser/knex/blob/6a4fecfe7822442ee5c43d924958eadfe6e17a93/src/seed/Seeder.js#L13-L16
train
tgriesser/knex
src/query/joinclause.js
JoinClause
function JoinClause(table, type, schema) { this.schema = schema; this.table = table; this.joinType = type; this.and = this; this.clauses = []; }
javascript
function JoinClause(table, type, schema) { this.schema = schema; this.table = table; this.joinType = type; this.and = this; this.clauses = []; }
[ "function", "JoinClause", "(", "table", ",", "type", ",", "schema", ")", "{", "this", ".", "schema", "=", "schema", ";", "this", ".", "table", "=", "table", ";", "this", ".", "joinType", "=", "type", ";", "this", ".", "and", "=", "this", ";", "this", ".", "clauses", "=", "[", "]", ";", "}" ]
The "JoinClause" is an object holding any necessary info about a join, including the type, and any associated tables & columns being joined.
[ "The", "JoinClause", "is", "an", "object", "holding", "any", "necessary", "info", "about", "a", "join", "including", "the", "type", "and", "any", "associated", "tables", "&", "columns", "being", "joined", "." ]
6a4fecfe7822442ee5c43d924958eadfe6e17a93
https://github.com/tgriesser/knex/blob/6a4fecfe7822442ee5c43d924958eadfe6e17a93/src/query/joinclause.js#L9-L15
train
tgriesser/knex
src/migrate/MigrationGenerator.js
yyyymmddhhmmss
function yyyymmddhhmmss() { const d = new Date(); return ( d.getFullYear().toString() + padDate(d.getMonth() + 1) + padDate(d.getDate()) + padDate(d.getHours()) + padDate(d.getMinutes()) + padDate(d.getSeconds()) ); }
javascript
function yyyymmddhhmmss() { const d = new Date(); return ( d.getFullYear().toString() + padDate(d.getMonth() + 1) + padDate(d.getDate()) + padDate(d.getHours()) + padDate(d.getMinutes()) + padDate(d.getSeconds()) ); }
[ "function", "yyyymmddhhmmss", "(", ")", "{", "const", "d", "=", "new", "Date", "(", ")", ";", "return", "(", "d", ".", "getFullYear", "(", ")", ".", "toString", "(", ")", "+", "padDate", "(", "d", ".", "getMonth", "(", ")", "+", "1", ")", "+", "padDate", "(", "d", ".", "getDate", "(", ")", ")", "+", "padDate", "(", "d", ".", "getHours", "(", ")", ")", "+", "padDate", "(", "d", ".", "getMinutes", "(", ")", ")", "+", "padDate", "(", "d", ".", "getSeconds", "(", ")", ")", ")", ";", "}" ]
Get a date object in the correct format, without requiring a full out library like "moment.js".
[ "Get", "a", "date", "object", "in", "the", "correct", "format", "without", "requiring", "a", "full", "out", "library", "like", "moment", ".", "js", "." ]
6a4fecfe7822442ee5c43d924958eadfe6e17a93
https://github.com/tgriesser/knex/blob/6a4fecfe7822442ee5c43d924958eadfe6e17a93/src/migrate/MigrationGenerator.js#L87-L97
train
tgriesser/knex
src/schema/builder.js
SchemaBuilder
function SchemaBuilder(client) { this.client = client; this._sequence = []; if (client.config) { this._debug = client.config.debug; saveAsyncStack(this, 4); } }
javascript
function SchemaBuilder(client) { this.client = client; this._sequence = []; if (client.config) { this._debug = client.config.debug; saveAsyncStack(this, 4); } }
[ "function", "SchemaBuilder", "(", "client", ")", "{", "this", ".", "client", "=", "client", ";", "this", ".", "_sequence", "=", "[", "]", ";", "if", "(", "client", ".", "config", ")", "{", "this", ".", "_debug", "=", "client", ".", "config", ".", "debug", ";", "saveAsyncStack", "(", "this", ",", "4", ")", ";", "}", "}" ]
Constructor for the builder instance, typically called from `knex.builder`, accepting the current `knex` instance, and pulling out the `client` and `grammar` from the current knex instance.
[ "Constructor", "for", "the", "builder", "instance", "typically", "called", "from", "knex", ".", "builder", "accepting", "the", "current", "knex", "instance", "and", "pulling", "out", "the", "client", "and", "grammar", "from", "the", "current", "knex", "instance", "." ]
6a4fecfe7822442ee5c43d924958eadfe6e17a93
https://github.com/tgriesser/knex/blob/6a4fecfe7822442ee5c43d924958eadfe6e17a93/src/schema/builder.js#L11-L19
train
tgriesser/knex
src/client.js
Client
function Client(config = {}) { this.config = config; this.logger = new Logger(config); //Client is a required field, so throw error if it's not supplied. //If 'this.dialect' is set, then this is a 'super()' call, in which case //'client' does not have to be set as it's already assigned on the client prototype. if (this.dialect && !this.config.client) { this.logger.warn( `Using 'this.dialect' to identify the client is deprecated and support for it will be removed in the future. Please use configuration option 'client' instead.` ); } const dbClient = this.config.client || this.dialect; if (!dbClient) { throw new Error(`knex: Required configuration option 'client' is missing.`); } if (config.version) { this.version = config.version; } this.connectionSettings = cloneDeep(config.connection || {}); if (this.driverName && config.connection) { this.initializeDriver(); if (!config.pool || (config.pool && config.pool.max !== 0)) { this.initializePool(config); } } this.valueForUndefined = this.raw('DEFAULT'); if (config.useNullAsDefault) { this.valueForUndefined = null; } }
javascript
function Client(config = {}) { this.config = config; this.logger = new Logger(config); //Client is a required field, so throw error if it's not supplied. //If 'this.dialect' is set, then this is a 'super()' call, in which case //'client' does not have to be set as it's already assigned on the client prototype. if (this.dialect && !this.config.client) { this.logger.warn( `Using 'this.dialect' to identify the client is deprecated and support for it will be removed in the future. Please use configuration option 'client' instead.` ); } const dbClient = this.config.client || this.dialect; if (!dbClient) { throw new Error(`knex: Required configuration option 'client' is missing.`); } if (config.version) { this.version = config.version; } this.connectionSettings = cloneDeep(config.connection || {}); if (this.driverName && config.connection) { this.initializeDriver(); if (!config.pool || (config.pool && config.pool.max !== 0)) { this.initializePool(config); } } this.valueForUndefined = this.raw('DEFAULT'); if (config.useNullAsDefault) { this.valueForUndefined = null; } }
[ "function", "Client", "(", "config", "=", "{", "}", ")", "{", "this", ".", "config", "=", "config", ";", "this", ".", "logger", "=", "new", "Logger", "(", "config", ")", ";", "if", "(", "this", ".", "dialect", "&&", "!", "this", ".", "config", ".", "client", ")", "{", "this", ".", "logger", ".", "warn", "(", "`", "`", ")", ";", "}", "const", "dbClient", "=", "this", ".", "config", ".", "client", "||", "this", ".", "dialect", ";", "if", "(", "!", "dbClient", ")", "{", "throw", "new", "Error", "(", "`", "`", ")", ";", "}", "if", "(", "config", ".", "version", ")", "{", "this", ".", "version", "=", "config", ".", "version", ";", "}", "this", ".", "connectionSettings", "=", "cloneDeep", "(", "config", ".", "connection", "||", "{", "}", ")", ";", "if", "(", "this", ".", "driverName", "&&", "config", ".", "connection", ")", "{", "this", ".", "initializeDriver", "(", ")", ";", "if", "(", "!", "config", ".", "pool", "||", "(", "config", ".", "pool", "&&", "config", ".", "pool", ".", "max", "!==", "0", ")", ")", "{", "this", ".", "initializePool", "(", "config", ")", ";", "}", "}", "this", ".", "valueForUndefined", "=", "this", ".", "raw", "(", "'DEFAULT'", ")", ";", "if", "(", "config", ".", "useNullAsDefault", ")", "{", "this", ".", "valueForUndefined", "=", "null", ";", "}", "}" ]
The base client provides the general structure for a dialect specific client object.
[ "The", "base", "client", "provides", "the", "general", "structure", "for", "a", "dialect", "specific", "client", "object", "." ]
6a4fecfe7822442ee5c43d924958eadfe6e17a93
https://github.com/tgriesser/knex/blob/6a4fecfe7822442ee5c43d924958eadfe6e17a93/src/client.js#L35-L68
train
tgriesser/knex
src/dialects/sqlite3/schema/ddl.js
SQLite3_DDL
function SQLite3_DDL(client, tableCompiler, pragma, connection) { this.client = client; this.tableCompiler = tableCompiler; this.pragma = pragma; this.tableNameRaw = this.tableCompiler.tableNameRaw; this.alteredName = uniqueId('_knex_temp_alter'); this.connection = connection; this.formatter = client && client.config && client.config.wrapIdentifier ? client.config.wrapIdentifier : (value) => value; }
javascript
function SQLite3_DDL(client, tableCompiler, pragma, connection) { this.client = client; this.tableCompiler = tableCompiler; this.pragma = pragma; this.tableNameRaw = this.tableCompiler.tableNameRaw; this.alteredName = uniqueId('_knex_temp_alter'); this.connection = connection; this.formatter = client && client.config && client.config.wrapIdentifier ? client.config.wrapIdentifier : (value) => value; }
[ "function", "SQLite3_DDL", "(", "client", ",", "tableCompiler", ",", "pragma", ",", "connection", ")", "{", "this", ".", "client", "=", "client", ";", "this", ".", "tableCompiler", "=", "tableCompiler", ";", "this", ".", "pragma", "=", "pragma", ";", "this", ".", "tableNameRaw", "=", "this", ".", "tableCompiler", ".", "tableNameRaw", ";", "this", ".", "alteredName", "=", "uniqueId", "(", "'_knex_temp_alter'", ")", ";", "this", ".", "connection", "=", "connection", ";", "this", ".", "formatter", "=", "client", "&&", "client", ".", "config", "&&", "client", ".", "config", ".", "wrapIdentifier", "?", "client", ".", "config", ".", "wrapIdentifier", ":", "(", "value", ")", "=>", "value", ";", "}" ]
So altering the schema in SQLite3 is a major pain. We have our own object to deal with the renaming and altering the types for sqlite3 things.
[ "So", "altering", "the", "schema", "in", "SQLite3", "is", "a", "major", "pain", ".", "We", "have", "our", "own", "object", "to", "deal", "with", "the", "renaming", "and", "altering", "the", "types", "for", "sqlite3", "things", "." ]
6a4fecfe7822442ee5c43d924958eadfe6e17a93
https://github.com/tgriesser/knex/blob/6a4fecfe7822442ee5c43d924958eadfe6e17a93/src/dialects/sqlite3/schema/ddl.js#L22-L33
train
tgriesser/knex
src/transaction.js
makeTransactor
function makeTransactor(trx, connection, trxClient) { const transactor = makeKnex(trxClient); transactor.withUserParams = () => { throw new Error( 'Cannot set user params on a transaction - it can only inherit params from main knex instance' ); }; transactor.isTransaction = true; transactor.userParams = trx.userParams || {}; transactor.transaction = function(container, options) { return trxClient.transaction(container, options, trx); }; transactor.savepoint = function(container, options) { return transactor.transaction(container, options); }; if (trx.client.transacting) { transactor.commit = (value) => trx.release(connection, value); transactor.rollback = (error) => trx.rollbackTo(connection, error); } else { transactor.commit = (value) => trx.commit(connection, value); transactor.rollback = (error) => trx.rollback(connection, error); } return transactor; }
javascript
function makeTransactor(trx, connection, trxClient) { const transactor = makeKnex(trxClient); transactor.withUserParams = () => { throw new Error( 'Cannot set user params on a transaction - it can only inherit params from main knex instance' ); }; transactor.isTransaction = true; transactor.userParams = trx.userParams || {}; transactor.transaction = function(container, options) { return trxClient.transaction(container, options, trx); }; transactor.savepoint = function(container, options) { return transactor.transaction(container, options); }; if (trx.client.transacting) { transactor.commit = (value) => trx.release(connection, value); transactor.rollback = (error) => trx.rollbackTo(connection, error); } else { transactor.commit = (value) => trx.commit(connection, value); transactor.rollback = (error) => trx.rollback(connection, error); } return transactor; }
[ "function", "makeTransactor", "(", "trx", ",", "connection", ",", "trxClient", ")", "{", "const", "transactor", "=", "makeKnex", "(", "trxClient", ")", ";", "transactor", ".", "withUserParams", "=", "(", ")", "=>", "{", "throw", "new", "Error", "(", "'Cannot set user params on a transaction - it can only inherit params from main knex instance'", ")", ";", "}", ";", "transactor", ".", "isTransaction", "=", "true", ";", "transactor", ".", "userParams", "=", "trx", ".", "userParams", "||", "{", "}", ";", "transactor", ".", "transaction", "=", "function", "(", "container", ",", "options", ")", "{", "return", "trxClient", ".", "transaction", "(", "container", ",", "options", ",", "trx", ")", ";", "}", ";", "transactor", ".", "savepoint", "=", "function", "(", "container", ",", "options", ")", "{", "return", "transactor", ".", "transaction", "(", "container", ",", "options", ")", ";", "}", ";", "if", "(", "trx", ".", "client", ".", "transacting", ")", "{", "transactor", ".", "commit", "=", "(", "value", ")", "=>", "trx", ".", "release", "(", "connection", ",", "value", ")", ";", "transactor", ".", "rollback", "=", "(", "error", ")", "=>", "trx", ".", "rollbackTo", "(", "connection", ",", "error", ")", ";", "}", "else", "{", "transactor", ".", "commit", "=", "(", "value", ")", "=>", "trx", ".", "commit", "(", "connection", ",", "value", ")", ";", "transactor", ".", "rollback", "=", "(", "error", ")", "=>", "trx", ".", "rollback", "(", "connection", ",", "error", ")", ";", "}", "return", "transactor", ";", "}" ]
The transactor is a full featured knex object, with a "commit", a "rollback" and a "savepoint" function. The "savepoint" is just sugar for creating a new transaction. If the rollback is run inside a savepoint, it rolls back to the last savepoint - otherwise it rolls back the transaction.
[ "The", "transactor", "is", "a", "full", "featured", "knex", "object", "with", "a", "commit", "a", "rollback", "and", "a", "savepoint", "function", ".", "The", "savepoint", "is", "just", "sugar", "for", "creating", "a", "new", "transaction", ".", "If", "the", "rollback", "is", "run", "inside", "a", "savepoint", "it", "rolls", "back", "to", "the", "last", "savepoint", "-", "otherwise", "it", "rolls", "back", "the", "transaction", "." ]
6a4fecfe7822442ee5c43d924958eadfe6e17a93
https://github.com/tgriesser/knex/blob/6a4fecfe7822442ee5c43d924958eadfe6e17a93/src/transaction.js#L187-L215
train
tgriesser/knex
src/transaction.js
makeTxClient
function makeTxClient(trx, client, connection) { const trxClient = Object.create(client.constructor.prototype); trxClient.version = client.version; trxClient.config = client.config; trxClient.driver = client.driver; trxClient.connectionSettings = client.connectionSettings; trxClient.transacting = true; trxClient.valueForUndefined = client.valueForUndefined; trxClient.logger = client.logger; trxClient.on('query', function(arg) { trx.emit('query', arg); client.emit('query', arg); }); trxClient.on('query-error', function(err, obj) { trx.emit('query-error', err, obj); client.emit('query-error', err, obj); }); trxClient.on('query-response', function(response, obj, builder) { trx.emit('query-response', response, obj, builder); client.emit('query-response', response, obj, builder); }); const _query = trxClient.query; trxClient.query = function(conn, obj) { const completed = trx.isCompleted(); return Promise.try(function() { if (conn !== connection) throw new Error('Invalid connection for transaction query.'); if (completed) completedError(trx, obj); return _query.call(trxClient, conn, obj); }); }; const _stream = trxClient.stream; trxClient.stream = function(conn, obj, stream, options) { const completed = trx.isCompleted(); return Promise.try(function() { if (conn !== connection) throw new Error('Invalid connection for transaction query.'); if (completed) completedError(trx, obj); return _stream.call(trxClient, conn, obj, stream, options); }); }; trxClient.acquireConnection = function() { return Promise.resolve(connection); }; trxClient.releaseConnection = function() { return Promise.resolve(); }; return trxClient; }
javascript
function makeTxClient(trx, client, connection) { const trxClient = Object.create(client.constructor.prototype); trxClient.version = client.version; trxClient.config = client.config; trxClient.driver = client.driver; trxClient.connectionSettings = client.connectionSettings; trxClient.transacting = true; trxClient.valueForUndefined = client.valueForUndefined; trxClient.logger = client.logger; trxClient.on('query', function(arg) { trx.emit('query', arg); client.emit('query', arg); }); trxClient.on('query-error', function(err, obj) { trx.emit('query-error', err, obj); client.emit('query-error', err, obj); }); trxClient.on('query-response', function(response, obj, builder) { trx.emit('query-response', response, obj, builder); client.emit('query-response', response, obj, builder); }); const _query = trxClient.query; trxClient.query = function(conn, obj) { const completed = trx.isCompleted(); return Promise.try(function() { if (conn !== connection) throw new Error('Invalid connection for transaction query.'); if (completed) completedError(trx, obj); return _query.call(trxClient, conn, obj); }); }; const _stream = trxClient.stream; trxClient.stream = function(conn, obj, stream, options) { const completed = trx.isCompleted(); return Promise.try(function() { if (conn !== connection) throw new Error('Invalid connection for transaction query.'); if (completed) completedError(trx, obj); return _stream.call(trxClient, conn, obj, stream, options); }); }; trxClient.acquireConnection = function() { return Promise.resolve(connection); }; trxClient.releaseConnection = function() { return Promise.resolve(); }; return trxClient; }
[ "function", "makeTxClient", "(", "trx", ",", "client", ",", "connection", ")", "{", "const", "trxClient", "=", "Object", ".", "create", "(", "client", ".", "constructor", ".", "prototype", ")", ";", "trxClient", ".", "version", "=", "client", ".", "version", ";", "trxClient", ".", "config", "=", "client", ".", "config", ";", "trxClient", ".", "driver", "=", "client", ".", "driver", ";", "trxClient", ".", "connectionSettings", "=", "client", ".", "connectionSettings", ";", "trxClient", ".", "transacting", "=", "true", ";", "trxClient", ".", "valueForUndefined", "=", "client", ".", "valueForUndefined", ";", "trxClient", ".", "logger", "=", "client", ".", "logger", ";", "trxClient", ".", "on", "(", "'query'", ",", "function", "(", "arg", ")", "{", "trx", ".", "emit", "(", "'query'", ",", "arg", ")", ";", "client", ".", "emit", "(", "'query'", ",", "arg", ")", ";", "}", ")", ";", "trxClient", ".", "on", "(", "'query-error'", ",", "function", "(", "err", ",", "obj", ")", "{", "trx", ".", "emit", "(", "'query-error'", ",", "err", ",", "obj", ")", ";", "client", ".", "emit", "(", "'query-error'", ",", "err", ",", "obj", ")", ";", "}", ")", ";", "trxClient", ".", "on", "(", "'query-response'", ",", "function", "(", "response", ",", "obj", ",", "builder", ")", "{", "trx", ".", "emit", "(", "'query-response'", ",", "response", ",", "obj", ",", "builder", ")", ";", "client", ".", "emit", "(", "'query-response'", ",", "response", ",", "obj", ",", "builder", ")", ";", "}", ")", ";", "const", "_query", "=", "trxClient", ".", "query", ";", "trxClient", ".", "query", "=", "function", "(", "conn", ",", "obj", ")", "{", "const", "completed", "=", "trx", ".", "isCompleted", "(", ")", ";", "return", "Promise", ".", "try", "(", "function", "(", ")", "{", "if", "(", "conn", "!==", "connection", ")", "throw", "new", "Error", "(", "'Invalid connection for transaction query.'", ")", ";", "if", "(", "completed", ")", "completedError", "(", "trx", ",", "obj", ")", ";", "return", "_query", ".", "call", "(", "trxClient", ",", "conn", ",", "obj", ")", ";", "}", ")", ";", "}", ";", "const", "_stream", "=", "trxClient", ".", "stream", ";", "trxClient", ".", "stream", "=", "function", "(", "conn", ",", "obj", ",", "stream", ",", "options", ")", "{", "const", "completed", "=", "trx", ".", "isCompleted", "(", ")", ";", "return", "Promise", ".", "try", "(", "function", "(", ")", "{", "if", "(", "conn", "!==", "connection", ")", "throw", "new", "Error", "(", "'Invalid connection for transaction query.'", ")", ";", "if", "(", "completed", ")", "completedError", "(", "trx", ",", "obj", ")", ";", "return", "_stream", ".", "call", "(", "trxClient", ",", "conn", ",", "obj", ",", "stream", ",", "options", ")", ";", "}", ")", ";", "}", ";", "trxClient", ".", "acquireConnection", "=", "function", "(", ")", "{", "return", "Promise", ".", "resolve", "(", "connection", ")", ";", "}", ";", "trxClient", ".", "releaseConnection", "=", "function", "(", ")", "{", "return", "Promise", ".", "resolve", "(", ")", ";", "}", ";", "return", "trxClient", ";", "}" ]
We need to make a client object which always acquires the same connection and does not release back into the pool.
[ "We", "need", "to", "make", "a", "client", "object", "which", "always", "acquires", "the", "same", "connection", "and", "does", "not", "release", "back", "into", "the", "pool", "." ]
6a4fecfe7822442ee5c43d924958eadfe6e17a93
https://github.com/tgriesser/knex/blob/6a4fecfe7822442ee5c43d924958eadfe6e17a93/src/transaction.js#L219-L272
train
tgriesser/knex
src/migrate/table-resolver.js
getTable
function getTable(trxOrKnex, tableName, schemaName) { return schemaName ? trxOrKnex(tableName).withSchema(schemaName) : trxOrKnex(tableName); }
javascript
function getTable(trxOrKnex, tableName, schemaName) { return schemaName ? trxOrKnex(tableName).withSchema(schemaName) : trxOrKnex(tableName); }
[ "function", "getTable", "(", "trxOrKnex", ",", "tableName", ",", "schemaName", ")", "{", "return", "schemaName", "?", "trxOrKnex", "(", "tableName", ")", ".", "withSchema", "(", "schemaName", ")", ":", "trxOrKnex", "(", "tableName", ")", ";", "}" ]
Get schema-aware query builder for a given table and schema name
[ "Get", "schema", "-", "aware", "query", "builder", "for", "a", "given", "table", "and", "schema", "name" ]
6a4fecfe7822442ee5c43d924958eadfe6e17a93
https://github.com/tgriesser/knex/blob/6a4fecfe7822442ee5c43d924958eadfe6e17a93/src/migrate/table-resolver.js#L7-L11
train
tgriesser/knex
src/migrate/Migrator.js
validateMigrationList
function validateMigrationList(migrationSource, migrations) { const all = migrations[0]; const completed = migrations[1]; const diff = getMissingMigrations(migrationSource, completed, all); if (!isEmpty(diff)) { throw new Error( `The migration directory is corrupt, the following files are missing: ${diff.join( ', ' )}` ); } }
javascript
function validateMigrationList(migrationSource, migrations) { const all = migrations[0]; const completed = migrations[1]; const diff = getMissingMigrations(migrationSource, completed, all); if (!isEmpty(diff)) { throw new Error( `The migration directory is corrupt, the following files are missing: ${diff.join( ', ' )}` ); } }
[ "function", "validateMigrationList", "(", "migrationSource", ",", "migrations", ")", "{", "const", "all", "=", "migrations", "[", "0", "]", ";", "const", "completed", "=", "migrations", "[", "1", "]", ";", "const", "diff", "=", "getMissingMigrations", "(", "migrationSource", ",", "completed", ",", "all", ")", ";", "if", "(", "!", "isEmpty", "(", "diff", ")", ")", "{", "throw", "new", "Error", "(", "`", "${", "diff", ".", "join", "(", "', '", ")", "}", "`", ")", ";", "}", "}" ]
Validates that migrations are present in the appropriate directories.
[ "Validates", "that", "migrations", "are", "present", "in", "the", "appropriate", "directories", "." ]
6a4fecfe7822442ee5c43d924958eadfe6e17a93
https://github.com/tgriesser/knex/blob/6a4fecfe7822442ee5c43d924958eadfe6e17a93/src/migrate/Migrator.js#L459-L470
train
nodejs/node-gyp
lib/configure.js
findAccessibleSync
function findAccessibleSync (logprefix, dir, candidates) { for (var next = 0; next < candidates.length; next++) { var candidate = path.resolve(dir, candidates[next]) try { var fd = fs.openSync(candidate, 'r') } catch (e) { // this candidate was not found or not readable, do nothing log.silly(logprefix, 'Could not open %s: %s', candidate, e.message) continue } fs.closeSync(fd) log.silly(logprefix, 'Found readable %s', candidate) return candidate } return undefined }
javascript
function findAccessibleSync (logprefix, dir, candidates) { for (var next = 0; next < candidates.length; next++) { var candidate = path.resolve(dir, candidates[next]) try { var fd = fs.openSync(candidate, 'r') } catch (e) { // this candidate was not found or not readable, do nothing log.silly(logprefix, 'Could not open %s: %s', candidate, e.message) continue } fs.closeSync(fd) log.silly(logprefix, 'Found readable %s', candidate) return candidate } return undefined }
[ "function", "findAccessibleSync", "(", "logprefix", ",", "dir", ",", "candidates", ")", "{", "for", "(", "var", "next", "=", "0", ";", "next", "<", "candidates", ".", "length", ";", "next", "++", ")", "{", "var", "candidate", "=", "path", ".", "resolve", "(", "dir", ",", "candidates", "[", "next", "]", ")", "try", "{", "var", "fd", "=", "fs", ".", "openSync", "(", "candidate", ",", "'r'", ")", "}", "catch", "(", "e", ")", "{", "log", ".", "silly", "(", "logprefix", ",", "'Could not open %s: %s'", ",", "candidate", ",", "e", ".", "message", ")", "continue", "}", "fs", ".", "closeSync", "(", "fd", ")", "log", ".", "silly", "(", "logprefix", ",", "'Found readable %s'", ",", "candidate", ")", "return", "candidate", "}", "return", "undefined", "}" ]
Returns the first file or directory from an array of candidates that is readable by the current user, or undefined if none of the candidates are readable.
[ "Returns", "the", "first", "file", "or", "directory", "from", "an", "array", "of", "candidates", "that", "is", "readable", "by", "the", "current", "user", "or", "undefined", "if", "none", "of", "the", "candidates", "are", "readable", "." ]
721eb691cf15556cc2700eda0558d5bad5f84232
https://github.com/nodejs/node-gyp/blob/721eb691cf15556cc2700eda0558d5bad5f84232/lib/configure.js#L350-L366
train
nodejs/node-gyp
lib/configure.js
findPython
function findPython() { const SKIP=0, FAIL=1 const toCheck = [ { before: () => { if (!this.configPython) { this.addLog( 'Python is not set from command line or npm configuration') return SKIP } this.addLog('checking Python explicitly set from command line or ' + 'npm configuration') this.addLog('- "--python=" or "npm config get python" is ' + `"${this.configPython}"`) }, check: this.checkCommand, arg: this.configPython, }, { before: () => { if (!this.env.PYTHON) { this.addLog('Python is not set from environment variable PYTHON') return SKIP } this.addLog( 'checking Python explicitly set from environment variable PYTHON') this.addLog(`- process.env.PYTHON is "${this.env.PYTHON}"`) }, check: this.checkCommand, arg: this.env.PYTHON, }, { before: () => { this.addLog('checking if "python2" can be used') }, check: this.checkCommand, arg: 'python2', }, { before: () => { this.addLog('checking if "python" can be used') }, check: this.checkCommand, arg: 'python', }, { before: () => { if (!this.win) { // Everything after this is Windows specific return FAIL } this.addLog( 'checking if the py launcher can be used to find Python 2') }, check: this.checkPyLauncher, }, { before: () => { this.addLog( 'checking if Python 2 is installed in the default location') }, check: this.checkExecPath, arg: this.defaultLocation, }, ] function runChecks(err) { this.log.silly('runChecks: err = %j', err && err.stack || err) const check = toCheck.shift() if (!check) { return this.fail() } const before = check.before.apply(this) if (before === SKIP) { return runChecks.apply(this) } if (before === FAIL) { return this.fail() } const args = [ runChecks.bind(this) ] if (check.arg) { args.unshift(check.arg) } check.check.apply(this, args) } runChecks.apply(this) }
javascript
function findPython() { const SKIP=0, FAIL=1 const toCheck = [ { before: () => { if (!this.configPython) { this.addLog( 'Python is not set from command line or npm configuration') return SKIP } this.addLog('checking Python explicitly set from command line or ' + 'npm configuration') this.addLog('- "--python=" or "npm config get python" is ' + `"${this.configPython}"`) }, check: this.checkCommand, arg: this.configPython, }, { before: () => { if (!this.env.PYTHON) { this.addLog('Python is not set from environment variable PYTHON') return SKIP } this.addLog( 'checking Python explicitly set from environment variable PYTHON') this.addLog(`- process.env.PYTHON is "${this.env.PYTHON}"`) }, check: this.checkCommand, arg: this.env.PYTHON, }, { before: () => { this.addLog('checking if "python2" can be used') }, check: this.checkCommand, arg: 'python2', }, { before: () => { this.addLog('checking if "python" can be used') }, check: this.checkCommand, arg: 'python', }, { before: () => { if (!this.win) { // Everything after this is Windows specific return FAIL } this.addLog( 'checking if the py launcher can be used to find Python 2') }, check: this.checkPyLauncher, }, { before: () => { this.addLog( 'checking if Python 2 is installed in the default location') }, check: this.checkExecPath, arg: this.defaultLocation, }, ] function runChecks(err) { this.log.silly('runChecks: err = %j', err && err.stack || err) const check = toCheck.shift() if (!check) { return this.fail() } const before = check.before.apply(this) if (before === SKIP) { return runChecks.apply(this) } if (before === FAIL) { return this.fail() } const args = [ runChecks.bind(this) ] if (check.arg) { args.unshift(check.arg) } check.check.apply(this, args) } runChecks.apply(this) }
[ "function", "findPython", "(", ")", "{", "const", "SKIP", "=", "0", ",", "FAIL", "=", "1", "const", "toCheck", "=", "[", "{", "before", ":", "(", ")", "=>", "{", "if", "(", "!", "this", ".", "configPython", ")", "{", "this", ".", "addLog", "(", "'Python is not set from command line or npm configuration'", ")", "return", "SKIP", "}", "this", ".", "addLog", "(", "'checking Python explicitly set from command line or '", "+", "'npm configuration'", ")", "this", ".", "addLog", "(", "'- \"--python=\" or \"npm config get python\" is '", "+", "`", "${", "this", ".", "configPython", "}", "`", ")", "}", ",", "check", ":", "this", ".", "checkCommand", ",", "arg", ":", "this", ".", "configPython", ",", "}", ",", "{", "before", ":", "(", ")", "=>", "{", "if", "(", "!", "this", ".", "env", ".", "PYTHON", ")", "{", "this", ".", "addLog", "(", "'Python is not set from environment variable PYTHON'", ")", "return", "SKIP", "}", "this", ".", "addLog", "(", "'checking Python explicitly set from environment variable PYTHON'", ")", "this", ".", "addLog", "(", "`", "${", "this", ".", "env", ".", "PYTHON", "}", "`", ")", "}", ",", "check", ":", "this", ".", "checkCommand", ",", "arg", ":", "this", ".", "env", ".", "PYTHON", ",", "}", ",", "{", "before", ":", "(", ")", "=>", "{", "this", ".", "addLog", "(", "'checking if \"python2\" can be used'", ")", "}", ",", "check", ":", "this", ".", "checkCommand", ",", "arg", ":", "'python2'", ",", "}", ",", "{", "before", ":", "(", ")", "=>", "{", "this", ".", "addLog", "(", "'checking if \"python\" can be used'", ")", "}", ",", "check", ":", "this", ".", "checkCommand", ",", "arg", ":", "'python'", ",", "}", ",", "{", "before", ":", "(", ")", "=>", "{", "if", "(", "!", "this", ".", "win", ")", "{", "return", "FAIL", "}", "this", ".", "addLog", "(", "'checking if the py launcher can be used to find Python 2'", ")", "}", ",", "check", ":", "this", ".", "checkPyLauncher", ",", "}", ",", "{", "before", ":", "(", ")", "=>", "{", "this", ".", "addLog", "(", "'checking if Python 2 is installed in the default location'", ")", "}", ",", "check", ":", "this", ".", "checkExecPath", ",", "arg", ":", "this", ".", "defaultLocation", ",", "}", ",", "]", "function", "runChecks", "(", "err", ")", "{", "this", ".", "log", ".", "silly", "(", "'runChecks: err = %j'", ",", "err", "&&", "err", ".", "stack", "||", "err", ")", "const", "check", "=", "toCheck", ".", "shift", "(", ")", "if", "(", "!", "check", ")", "{", "return", "this", ".", "fail", "(", ")", "}", "const", "before", "=", "check", ".", "before", ".", "apply", "(", "this", ")", "if", "(", "before", "===", "SKIP", ")", "{", "return", "runChecks", ".", "apply", "(", "this", ")", "}", "if", "(", "before", "===", "FAIL", ")", "{", "return", "this", ".", "fail", "(", ")", "}", "const", "args", "=", "[", "runChecks", ".", "bind", "(", "this", ")", "]", "if", "(", "check", ".", "arg", ")", "{", "args", ".", "unshift", "(", "check", ".", "arg", ")", "}", "check", ".", "check", ".", "apply", "(", "this", ",", "args", ")", "}", "runChecks", ".", "apply", "(", "this", ")", "}" ]
Find Python by trying a sequence of possibilities. Ignore errors, keep trying until Python is found.
[ "Find", "Python", "by", "trying", "a", "sequence", "of", "possibilities", ".", "Ignore", "errors", "keep", "trying", "until", "Python", "is", "found", "." ]
721eb691cf15556cc2700eda0558d5bad5f84232
https://github.com/nodejs/node-gyp/blob/721eb691cf15556cc2700eda0558d5bad5f84232/lib/configure.js#L398-L484
train
nodejs/node-gyp
lib/configure.js
checkExecPath
function checkExecPath (execPath, errorCallback) { this.log.verbose(`- executing "${execPath}" to get version`) this.run(execPath, this.argsVersion, false, function (err, version) { // Possible outcomes: // - Error: executable can not be run (likely meaning the command wasn't // a Python executable and the previous command produced gibberish) // - Gibberish: somehow the last command produced an executable path, // this will fail when verifying the version // - Version of the Python executable if (err) { this.addLog(`- "${execPath}" could not be run`) return errorCallback(err) } this.addLog(`- version is "${version}"`) const range = semver.Range(this.semverRange) var valid = false try { valid = range.test(version) } catch (err) { this.log.silly('range.test() threw:\n%s', err.stack) this.addLog(`- "${execPath}" does not have a valid version`) this.addLog('- is it a Python executable?') return errorCallback(err) } if (!valid) { this.addLog(`- version is ${version} - should be ${this.semverRange}`) this.addLog('- THIS VERSION OF PYTHON IS NOT SUPPORTED') return errorCallback(new Error( `Found unsupported Python version ${version}`)) } this.succeed(execPath, version) }.bind(this)) }
javascript
function checkExecPath (execPath, errorCallback) { this.log.verbose(`- executing "${execPath}" to get version`) this.run(execPath, this.argsVersion, false, function (err, version) { // Possible outcomes: // - Error: executable can not be run (likely meaning the command wasn't // a Python executable and the previous command produced gibberish) // - Gibberish: somehow the last command produced an executable path, // this will fail when verifying the version // - Version of the Python executable if (err) { this.addLog(`- "${execPath}" could not be run`) return errorCallback(err) } this.addLog(`- version is "${version}"`) const range = semver.Range(this.semverRange) var valid = false try { valid = range.test(version) } catch (err) { this.log.silly('range.test() threw:\n%s', err.stack) this.addLog(`- "${execPath}" does not have a valid version`) this.addLog('- is it a Python executable?') return errorCallback(err) } if (!valid) { this.addLog(`- version is ${version} - should be ${this.semverRange}`) this.addLog('- THIS VERSION OF PYTHON IS NOT SUPPORTED') return errorCallback(new Error( `Found unsupported Python version ${version}`)) } this.succeed(execPath, version) }.bind(this)) }
[ "function", "checkExecPath", "(", "execPath", ",", "errorCallback", ")", "{", "this", ".", "log", ".", "verbose", "(", "`", "${", "execPath", "}", "`", ")", "this", ".", "run", "(", "execPath", ",", "this", ".", "argsVersion", ",", "false", ",", "function", "(", "err", ",", "version", ")", "{", "if", "(", "err", ")", "{", "this", ".", "addLog", "(", "`", "${", "execPath", "}", "`", ")", "return", "errorCallback", "(", "err", ")", "}", "this", ".", "addLog", "(", "`", "${", "version", "}", "`", ")", "const", "range", "=", "semver", ".", "Range", "(", "this", ".", "semverRange", ")", "var", "valid", "=", "false", "try", "{", "valid", "=", "range", ".", "test", "(", "version", ")", "}", "catch", "(", "err", ")", "{", "this", ".", "log", ".", "silly", "(", "'range.test() threw:\\n%s'", ",", "\\n", ")", "err", ".", "stack", "this", ".", "addLog", "(", "`", "${", "execPath", "}", "`", ")", "this", ".", "addLog", "(", "'- is it a Python executable?'", ")", "}", "return", "errorCallback", "(", "err", ")", "if", "(", "!", "valid", ")", "{", "this", ".", "addLog", "(", "`", "${", "version", "}", "${", "this", ".", "semverRange", "}", "`", ")", "this", ".", "addLog", "(", "'- THIS VERSION OF PYTHON IS NOT SUPPORTED'", ")", "return", "errorCallback", "(", "new", "Error", "(", "`", "${", "version", "}", "`", ")", ")", "}", "}", ".", "this", ".", "succeed", "(", "execPath", ",", "version", ")", "bind", ")", "}" ]
Check if a Python executable is the correct version to use. Will exit the Python finder on success.
[ "Check", "if", "a", "Python", "executable", "is", "the", "correct", "version", "to", "use", ".", "Will", "exit", "the", "Python", "finder", "on", "success", "." ]
721eb691cf15556cc2700eda0558d5bad5f84232
https://github.com/nodejs/node-gyp/blob/721eb691cf15556cc2700eda0558d5bad5f84232/lib/configure.js#L544-L578
train
nodejs/node-gyp
lib/configure.js
run
function run(exec, args, shell, callback) { var env = extend({}, this.env) env.TERM = 'dumb' const opts = { env: env, shell: shell } this.log.silly('execFile: exec = %j', exec) this.log.silly('execFile: args = %j', args) this.log.silly('execFile: opts = %j', opts) try { this.execFile(exec, args, opts, execFileCallback.bind(this)) } catch (err) { this.log.silly('execFile: threw:\n%s', err.stack) return callback(err) } function execFileCallback(err, stdout, stderr) { this.log.silly('execFile result: err = %j', err && err.stack || err) this.log.silly('execFile result: stdout = %j', stdout) this.log.silly('execFile result: stderr = %j', stderr) if (err) { return callback(err) } const execPath = stdout.trim() callback(null, execPath) } }
javascript
function run(exec, args, shell, callback) { var env = extend({}, this.env) env.TERM = 'dumb' const opts = { env: env, shell: shell } this.log.silly('execFile: exec = %j', exec) this.log.silly('execFile: args = %j', args) this.log.silly('execFile: opts = %j', opts) try { this.execFile(exec, args, opts, execFileCallback.bind(this)) } catch (err) { this.log.silly('execFile: threw:\n%s', err.stack) return callback(err) } function execFileCallback(err, stdout, stderr) { this.log.silly('execFile result: err = %j', err && err.stack || err) this.log.silly('execFile result: stdout = %j', stdout) this.log.silly('execFile result: stderr = %j', stderr) if (err) { return callback(err) } const execPath = stdout.trim() callback(null, execPath) } }
[ "function", "run", "(", "exec", ",", "args", ",", "shell", ",", "callback", ")", "{", "var", "env", "=", "extend", "(", "{", "}", ",", "this", ".", "env", ")", "env", ".", "TERM", "=", "'dumb'", "const", "opts", "=", "{", "env", ":", "env", ",", "shell", ":", "shell", "}", "this", ".", "log", ".", "silly", "(", "'execFile: exec = %j'", ",", "exec", ")", "this", ".", "log", ".", "silly", "(", "'execFile: args = %j'", ",", "args", ")", "this", ".", "log", ".", "silly", "(", "'execFile: opts = %j'", ",", "opts", ")", "try", "{", "this", ".", "execFile", "(", "exec", ",", "args", ",", "opts", ",", "execFileCallback", ".", "bind", "(", "this", ")", ")", "}", "catch", "(", "err", ")", "{", "this", ".", "log", ".", "silly", "(", "'execFile: threw:\\n%s'", ",", "\\n", ")", "err", ".", "stack", "}", "return", "callback", "(", "err", ")", "}" ]
Run an executable or shell command, trimming the output.
[ "Run", "an", "executable", "or", "shell", "command", "trimming", "the", "output", "." ]
721eb691cf15556cc2700eda0558d5bad5f84232
https://github.com/nodejs/node-gyp/blob/721eb691cf15556cc2700eda0558d5bad5f84232/lib/configure.js#L581-L606
train
nodejs/node-gyp
lib/install.js
cb
function cb (err) { if (cb.done) return cb.done = true if (err) { log.warn('install', 'got an error, rolling back install') // roll-back the install if anything went wrong gyp.commands.remove([ release.versionDir ], function () { callback(err) }) } else { callback(null, release.version) } }
javascript
function cb (err) { if (cb.done) return cb.done = true if (err) { log.warn('install', 'got an error, rolling back install') // roll-back the install if anything went wrong gyp.commands.remove([ release.versionDir ], function () { callback(err) }) } else { callback(null, release.version) } }
[ "function", "cb", "(", "err", ")", "{", "if", "(", "cb", ".", "done", ")", "return", "cb", ".", "done", "=", "true", "if", "(", "err", ")", "{", "log", ".", "warn", "(", "'install'", ",", "'got an error, rolling back install'", ")", "gyp", ".", "commands", ".", "remove", "(", "[", "release", ".", "versionDir", "]", ",", "function", "(", ")", "{", "callback", "(", "err", ")", "}", ")", "}", "else", "{", "callback", "(", "null", ",", "release", ".", "version", ")", "}", "}" ]
ensure no double-callbacks happen
[ "ensure", "no", "double", "-", "callbacks", "happen" ]
721eb691cf15556cc2700eda0558d5bad5f84232
https://github.com/nodejs/node-gyp/blob/721eb691cf15556cc2700eda0558d5bad5f84232/lib/install.js#L29-L41
train
nodejs/node-gyp
lib/install.js
afterTarball
function afterTarball () { if (badDownload) return if (extractCount === 0) { return cb(new Error('There was a fatal problem while downloading/extracting the tarball')) } log.verbose('tarball', 'done parsing tarball') var async = 0 if (win) { // need to download node.lib async++ downloadNodeLib(deref) } // write the "installVersion" file async++ var installVersionPath = path.resolve(devDir, 'installVersion') fs.writeFile(installVersionPath, gyp.package.installVersion + '\n', deref) // Only download SHASUMS.txt if not using tarPath override if (!tarPath) { // download SHASUMS.txt async++ downloadShasums(deref) } if (async === 0) { // no async tasks required cb() } function deref (err) { if (err) return cb(err) async-- if (!async) { log.verbose('download contents checksum', JSON.stringify(contentShasums)) // check content shasums for (var k in contentShasums) { log.verbose('validating download checksum for ' + k, '(%s == %s)', contentShasums[k], expectShasums[k]) if (contentShasums[k] !== expectShasums[k]) { cb(new Error(k + ' local checksum ' + contentShasums[k] + ' not match remote ' + expectShasums[k])) return } } cb() } } }
javascript
function afterTarball () { if (badDownload) return if (extractCount === 0) { return cb(new Error('There was a fatal problem while downloading/extracting the tarball')) } log.verbose('tarball', 'done parsing tarball') var async = 0 if (win) { // need to download node.lib async++ downloadNodeLib(deref) } // write the "installVersion" file async++ var installVersionPath = path.resolve(devDir, 'installVersion') fs.writeFile(installVersionPath, gyp.package.installVersion + '\n', deref) // Only download SHASUMS.txt if not using tarPath override if (!tarPath) { // download SHASUMS.txt async++ downloadShasums(deref) } if (async === 0) { // no async tasks required cb() } function deref (err) { if (err) return cb(err) async-- if (!async) { log.verbose('download contents checksum', JSON.stringify(contentShasums)) // check content shasums for (var k in contentShasums) { log.verbose('validating download checksum for ' + k, '(%s == %s)', contentShasums[k], expectShasums[k]) if (contentShasums[k] !== expectShasums[k]) { cb(new Error(k + ' local checksum ' + contentShasums[k] + ' not match remote ' + expectShasums[k])) return } } cb() } } }
[ "function", "afterTarball", "(", ")", "{", "if", "(", "badDownload", ")", "return", "if", "(", "extractCount", "===", "0", ")", "{", "return", "cb", "(", "new", "Error", "(", "'There was a fatal problem while downloading/extracting the tarball'", ")", ")", "}", "log", ".", "verbose", "(", "'tarball'", ",", "'done parsing tarball'", ")", "var", "async", "=", "0", "if", "(", "win", ")", "{", "async", "++", "downloadNodeLib", "(", "deref", ")", "}", "async", "++", "var", "installVersionPath", "=", "path", ".", "resolve", "(", "devDir", ",", "'installVersion'", ")", "fs", ".", "writeFile", "(", "installVersionPath", ",", "gyp", ".", "package", ".", "installVersion", "+", "'\\n'", ",", "\\n", ")", "deref", "if", "(", "!", "tarPath", ")", "{", "async", "++", "downloadShasums", "(", "deref", ")", "}", "if", "(", "async", "===", "0", ")", "{", "cb", "(", ")", "}", "}" ]
invoked after the tarball has finished being extracted
[ "invoked", "after", "the", "tarball", "has", "finished", "being", "extracted" ]
721eb691cf15556cc2700eda0558d5bad5f84232
https://github.com/nodejs/node-gyp/blob/721eb691cf15556cc2700eda0558d5bad5f84232/lib/install.js#L215-L263
train
nodejs/node-gyp
lib/build.js
loadConfigGypi
function loadConfigGypi () { var configPath = path.resolve('build', 'config.gypi') fs.readFile(configPath, 'utf8', function (err, data) { if (err) { if (err.code == 'ENOENT') { callback(new Error('You must run `node-gyp configure` first!')) } else { callback(err) } return } config = JSON.parse(data.replace(/\#.+\n/, '')) // get the 'arch', 'buildType', and 'nodeDir' vars from the config buildType = config.target_defaults.default_configuration arch = config.variables.target_arch nodeDir = config.variables.nodedir if ('debug' in gyp.opts) { buildType = gyp.opts.debug ? 'Debug' : 'Release' } if (!buildType) { buildType = 'Release' } log.verbose('build type', buildType) log.verbose('architecture', arch) log.verbose('node dev dir', nodeDir) if (win) { findSolutionFile() } else { doWhich() } }) }
javascript
function loadConfigGypi () { var configPath = path.resolve('build', 'config.gypi') fs.readFile(configPath, 'utf8', function (err, data) { if (err) { if (err.code == 'ENOENT') { callback(new Error('You must run `node-gyp configure` first!')) } else { callback(err) } return } config = JSON.parse(data.replace(/\#.+\n/, '')) // get the 'arch', 'buildType', and 'nodeDir' vars from the config buildType = config.target_defaults.default_configuration arch = config.variables.target_arch nodeDir = config.variables.nodedir if ('debug' in gyp.opts) { buildType = gyp.opts.debug ? 'Debug' : 'Release' } if (!buildType) { buildType = 'Release' } log.verbose('build type', buildType) log.verbose('architecture', arch) log.verbose('node dev dir', nodeDir) if (win) { findSolutionFile() } else { doWhich() } }) }
[ "function", "loadConfigGypi", "(", ")", "{", "var", "configPath", "=", "path", ".", "resolve", "(", "'build'", ",", "'config.gypi'", ")", "fs", ".", "readFile", "(", "configPath", ",", "'utf8'", ",", "function", "(", "err", ",", "data", ")", "{", "if", "(", "err", ")", "{", "if", "(", "err", ".", "code", "==", "'ENOENT'", ")", "{", "callback", "(", "new", "Error", "(", "'You must run `node-gyp configure` first!'", ")", ")", "}", "else", "{", "callback", "(", "err", ")", "}", "return", "}", "config", "=", "JSON", ".", "parse", "(", "data", ".", "replace", "(", "/", "\\#.+\\n", "/", ",", "''", ")", ")", "buildType", "=", "config", ".", "target_defaults", ".", "default_configuration", "arch", "=", "config", ".", "variables", ".", "target_arch", "nodeDir", "=", "config", ".", "variables", ".", "nodedir", "if", "(", "'debug'", "in", "gyp", ".", "opts", ")", "{", "buildType", "=", "gyp", ".", "opts", ".", "debug", "?", "'Debug'", ":", "'Release'", "}", "if", "(", "!", "buildType", ")", "{", "buildType", "=", "'Release'", "}", "log", ".", "verbose", "(", "'build type'", ",", "buildType", ")", "log", ".", "verbose", "(", "'architecture'", ",", "arch", ")", "log", ".", "verbose", "(", "'node dev dir'", ",", "nodeDir", ")", "if", "(", "win", ")", "{", "findSolutionFile", "(", ")", "}", "else", "{", "doWhich", "(", ")", "}", "}", ")", "}" ]
Load the "config.gypi" file that was generated during "configure".
[ "Load", "the", "config", ".", "gypi", "file", "that", "was", "generated", "during", "configure", "." ]
721eb691cf15556cc2700eda0558d5bad5f84232
https://github.com/nodejs/node-gyp/blob/721eb691cf15556cc2700eda0558d5bad5f84232/lib/build.js#L40-L75
train
nodejs/node-gyp
lib/build.js
findMsbuild
function findMsbuild () { log.verbose('could not find "msbuild.exe" in PATH - finding location in registry') var notfoundErr = 'Can\'t find "msbuild.exe". Do you have Microsoft Visual Studio C++ 2008+ installed?' var cmd = 'reg query "HKLM\\Software\\Microsoft\\MSBuild\\ToolsVersions" /s' if (process.arch !== 'ia32') cmd += ' /reg:32' exec(cmd, function (err, stdout) { if (err) { return callback(new Error(err.message + '\n' + notfoundErr)) } var reVers = /ToolsVersions\\([^\\]+)$/i , rePath = /\r\n[ \t]+MSBuildToolsPath[ \t]+REG_SZ[ \t]+([^\r]+)/i , msbuilds = [] , r , msbuildPath stdout.split('\r\n\r\n').forEach(function(l) { if (!l) return l = l.trim() if (r = reVers.exec(l.substring(0, l.indexOf('\r\n')))) { var ver = parseFloat(r[1], 10) if (ver >= 3.5) { if (r = rePath.exec(l)) { msbuilds.push({ version: ver, path: r[1] }) } } } }) msbuilds.sort(function (x, y) { return (x.version < y.version ? -1 : 1) }) ;(function verifyMsbuild () { if (!msbuilds.length) return callback(new Error(notfoundErr)) msbuildPath = path.resolve(msbuilds.pop().path, 'msbuild.exe') fs.stat(msbuildPath, function (err) { if (err) { if (err.code == 'ENOENT') { if (msbuilds.length) { return verifyMsbuild() } else { callback(new Error(notfoundErr)) } } else { callback(err) } return } command = msbuildPath doBuild() }) })() }) }
javascript
function findMsbuild () { log.verbose('could not find "msbuild.exe" in PATH - finding location in registry') var notfoundErr = 'Can\'t find "msbuild.exe". Do you have Microsoft Visual Studio C++ 2008+ installed?' var cmd = 'reg query "HKLM\\Software\\Microsoft\\MSBuild\\ToolsVersions" /s' if (process.arch !== 'ia32') cmd += ' /reg:32' exec(cmd, function (err, stdout) { if (err) { return callback(new Error(err.message + '\n' + notfoundErr)) } var reVers = /ToolsVersions\\([^\\]+)$/i , rePath = /\r\n[ \t]+MSBuildToolsPath[ \t]+REG_SZ[ \t]+([^\r]+)/i , msbuilds = [] , r , msbuildPath stdout.split('\r\n\r\n').forEach(function(l) { if (!l) return l = l.trim() if (r = reVers.exec(l.substring(0, l.indexOf('\r\n')))) { var ver = parseFloat(r[1], 10) if (ver >= 3.5) { if (r = rePath.exec(l)) { msbuilds.push({ version: ver, path: r[1] }) } } } }) msbuilds.sort(function (x, y) { return (x.version < y.version ? -1 : 1) }) ;(function verifyMsbuild () { if (!msbuilds.length) return callback(new Error(notfoundErr)) msbuildPath = path.resolve(msbuilds.pop().path, 'msbuild.exe') fs.stat(msbuildPath, function (err) { if (err) { if (err.code == 'ENOENT') { if (msbuilds.length) { return verifyMsbuild() } else { callback(new Error(notfoundErr)) } } else { callback(err) } return } command = msbuildPath doBuild() }) })() }) }
[ "function", "findMsbuild", "(", ")", "{", "log", ".", "verbose", "(", "'could not find \"msbuild.exe\" in PATH - finding location in registry'", ")", "var", "notfoundErr", "=", "'Can\\'t find \"msbuild.exe\". Do you have Microsoft Visual Studio C++ 2008+ installed?'", "\\'", "var", "cmd", "=", "'reg query \"HKLM\\\\Software\\\\Microsoft\\\\MSBuild\\\\ToolsVersions\" /s'", "\\\\", "}" ]
Search for the location of "msbuild.exe" file on Windows.
[ "Search", "for", "the", "location", "of", "msbuild", ".", "exe", "file", "on", "Windows", "." ]
721eb691cf15556cc2700eda0558d5bad5f84232
https://github.com/nodejs/node-gyp/blob/721eb691cf15556cc2700eda0558d5bad5f84232/lib/build.js#L126-L180
train
nodejs/node-gyp
lib/build.js
doBuild
function doBuild () { // Enable Verbose build var verbose = log.levels[log.level] <= log.levels.verbose if (!win && verbose) { argv.push('V=1') } if (win && !verbose) { argv.push('/clp:Verbosity=minimal') } if (win) { // Turn off the Microsoft logo on Windows argv.push('/nologo') } // Specify the build type, Release by default if (win) { // Convert .gypi config target_arch to MSBuild /Platform // Since there are many ways to state '32-bit Intel', default to it. // N.B. msbuild's Condition string equality tests are case-insensitive. var archLower = arch.toLowerCase() var p = archLower === 'x64' ? 'x64' : (archLower === 'arm' ? 'ARM' : (archLower === 'arm64' ? 'ARM64' : 'Win32')) argv.push('/p:Configuration=' + buildType + ';Platform=' + p) if (jobs) { var j = parseInt(jobs, 10) if (!isNaN(j) && j > 0) { argv.push('/m:' + j) } else if (jobs.toUpperCase() === 'MAX') { argv.push('/m:' + require('os').cpus().length) } } } else { argv.push('BUILDTYPE=' + buildType) // Invoke the Makefile in the 'build' dir. argv.push('-C') argv.push('build') if (jobs) { var j = parseInt(jobs, 10) if (!isNaN(j) && j > 0) { argv.push('--jobs') argv.push(j) } else if (jobs.toUpperCase() === 'MAX') { argv.push('--jobs') argv.push(require('os').cpus().length) } } } if (win) { // did the user specify their own .sln file? var hasSln = argv.some(function (arg) { return path.extname(arg) == '.sln' }) if (!hasSln) { argv.unshift(gyp.opts.solution || guessedSolution) } } var proc = gyp.spawn(command, argv) proc.on('exit', onExit) }
javascript
function doBuild () { // Enable Verbose build var verbose = log.levels[log.level] <= log.levels.verbose if (!win && verbose) { argv.push('V=1') } if (win && !verbose) { argv.push('/clp:Verbosity=minimal') } if (win) { // Turn off the Microsoft logo on Windows argv.push('/nologo') } // Specify the build type, Release by default if (win) { // Convert .gypi config target_arch to MSBuild /Platform // Since there are many ways to state '32-bit Intel', default to it. // N.B. msbuild's Condition string equality tests are case-insensitive. var archLower = arch.toLowerCase() var p = archLower === 'x64' ? 'x64' : (archLower === 'arm' ? 'ARM' : (archLower === 'arm64' ? 'ARM64' : 'Win32')) argv.push('/p:Configuration=' + buildType + ';Platform=' + p) if (jobs) { var j = parseInt(jobs, 10) if (!isNaN(j) && j > 0) { argv.push('/m:' + j) } else if (jobs.toUpperCase() === 'MAX') { argv.push('/m:' + require('os').cpus().length) } } } else { argv.push('BUILDTYPE=' + buildType) // Invoke the Makefile in the 'build' dir. argv.push('-C') argv.push('build') if (jobs) { var j = parseInt(jobs, 10) if (!isNaN(j) && j > 0) { argv.push('--jobs') argv.push(j) } else if (jobs.toUpperCase() === 'MAX') { argv.push('--jobs') argv.push(require('os').cpus().length) } } } if (win) { // did the user specify their own .sln file? var hasSln = argv.some(function (arg) { return path.extname(arg) == '.sln' }) if (!hasSln) { argv.unshift(gyp.opts.solution || guessedSolution) } } var proc = gyp.spawn(command, argv) proc.on('exit', onExit) }
[ "function", "doBuild", "(", ")", "{", "var", "verbose", "=", "log", ".", "levels", "[", "log", ".", "level", "]", "<=", "log", ".", "levels", ".", "verbose", "if", "(", "!", "win", "&&", "verbose", ")", "{", "argv", ".", "push", "(", "'V=1'", ")", "}", "if", "(", "win", "&&", "!", "verbose", ")", "{", "argv", ".", "push", "(", "'/clp:Verbosity=minimal'", ")", "}", "if", "(", "win", ")", "{", "argv", ".", "push", "(", "'/nologo'", ")", "}", "if", "(", "win", ")", "{", "var", "archLower", "=", "arch", ".", "toLowerCase", "(", ")", "var", "p", "=", "archLower", "===", "'x64'", "?", "'x64'", ":", "(", "archLower", "===", "'arm'", "?", "'ARM'", ":", "(", "archLower", "===", "'arm64'", "?", "'ARM64'", ":", "'Win32'", ")", ")", "argv", ".", "push", "(", "'/p:Configuration='", "+", "buildType", "+", "';Platform='", "+", "p", ")", "if", "(", "jobs", ")", "{", "var", "j", "=", "parseInt", "(", "jobs", ",", "10", ")", "if", "(", "!", "isNaN", "(", "j", ")", "&&", "j", ">", "0", ")", "{", "argv", ".", "push", "(", "'/m:'", "+", "j", ")", "}", "else", "if", "(", "jobs", ".", "toUpperCase", "(", ")", "===", "'MAX'", ")", "{", "argv", ".", "push", "(", "'/m:'", "+", "require", "(", "'os'", ")", ".", "cpus", "(", ")", ".", "length", ")", "}", "}", "}", "else", "{", "argv", ".", "push", "(", "'BUILDTYPE='", "+", "buildType", ")", "argv", ".", "push", "(", "'-C'", ")", "argv", ".", "push", "(", "'build'", ")", "if", "(", "jobs", ")", "{", "var", "j", "=", "parseInt", "(", "jobs", ",", "10", ")", "if", "(", "!", "isNaN", "(", "j", ")", "&&", "j", ">", "0", ")", "{", "argv", ".", "push", "(", "'--jobs'", ")", "argv", ".", "push", "(", "j", ")", "}", "else", "if", "(", "jobs", ".", "toUpperCase", "(", ")", "===", "'MAX'", ")", "{", "argv", ".", "push", "(", "'--jobs'", ")", "argv", ".", "push", "(", "require", "(", "'os'", ")", ".", "cpus", "(", ")", ".", "length", ")", "}", "}", "}", "if", "(", "win", ")", "{", "var", "hasSln", "=", "argv", ".", "some", "(", "function", "(", "arg", ")", "{", "return", "path", ".", "extname", "(", "arg", ")", "==", "'.sln'", "}", ")", "if", "(", "!", "hasSln", ")", "{", "argv", ".", "unshift", "(", "gyp", ".", "opts", ".", "solution", "||", "guessedSolution", ")", "}", "}", "var", "proc", "=", "gyp", ".", "spawn", "(", "command", ",", "argv", ")", "proc", ".", "on", "(", "'exit'", ",", "onExit", ")", "}" ]
Actually spawn the process and compile the module.
[ "Actually", "spawn", "the", "process", "and", "compile", "the", "module", "." ]
721eb691cf15556cc2700eda0558d5bad5f84232
https://github.com/nodejs/node-gyp/blob/721eb691cf15556cc2700eda0558d5bad5f84232/lib/build.js#L186-L248
train
websockets/ws
lib/permessage-deflate.js
inflateOnData
function inflateOnData(chunk) { this[kTotalLength] += chunk.length; if ( this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload ) { this[kBuffers].push(chunk); return; } this[kError] = new RangeError('Max payload size exceeded'); this[kError][kStatusCode] = 1009; this.removeListener('data', inflateOnData); this.reset(); }
javascript
function inflateOnData(chunk) { this[kTotalLength] += chunk.length; if ( this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload ) { this[kBuffers].push(chunk); return; } this[kError] = new RangeError('Max payload size exceeded'); this[kError][kStatusCode] = 1009; this.removeListener('data', inflateOnData); this.reset(); }
[ "function", "inflateOnData", "(", "chunk", ")", "{", "this", "[", "kTotalLength", "]", "+=", "chunk", ".", "length", ";", "if", "(", "this", "[", "kPerMessageDeflate", "]", ".", "_maxPayload", "<", "1", "||", "this", "[", "kTotalLength", "]", "<=", "this", "[", "kPerMessageDeflate", "]", ".", "_maxPayload", ")", "{", "this", "[", "kBuffers", "]", ".", "push", "(", "chunk", ")", ";", "return", ";", "}", "this", "[", "kError", "]", "=", "new", "RangeError", "(", "'Max payload size exceeded'", ")", ";", "this", "[", "kError", "]", "[", "kStatusCode", "]", "=", "1009", ";", "this", ".", "removeListener", "(", "'data'", ",", "inflateOnData", ")", ";", "this", ".", "reset", "(", ")", ";", "}" ]
The listener of the `zlib.InflateRaw` stream `'data'` event. @param {Buffer} chunk A chunk of data @private
[ "The", "listener", "of", "the", "zlib", ".", "InflateRaw", "stream", "data", "event", "." ]
995c527c87d0d4833d8093c18dcfa2e4a41d9582
https://github.com/websockets/ws/blob/995c527c87d0d4833d8093c18dcfa2e4a41d9582/lib/permessage-deflate.js#L473-L488
train
websockets/ws
lib/receiver.js
error
function error(ErrorCtor, message, prefix, statusCode) { const err = new ErrorCtor( prefix ? `Invalid WebSocket frame: ${message}` : message ); Error.captureStackTrace(err, error); err[kStatusCode] = statusCode; return err; }
javascript
function error(ErrorCtor, message, prefix, statusCode) { const err = new ErrorCtor( prefix ? `Invalid WebSocket frame: ${message}` : message ); Error.captureStackTrace(err, error); err[kStatusCode] = statusCode; return err; }
[ "function", "error", "(", "ErrorCtor", ",", "message", ",", "prefix", ",", "statusCode", ")", "{", "const", "err", "=", "new", "ErrorCtor", "(", "prefix", "?", "`", "${", "message", "}", "`", ":", "message", ")", ";", "Error", ".", "captureStackTrace", "(", "err", ",", "error", ")", ";", "err", "[", "kStatusCode", "]", "=", "statusCode", ";", "return", "err", ";", "}" ]
Builds an error object. @param {(Error|RangeError)} ErrorCtor The error constructor @param {String} message The error message @param {Boolean} prefix Specifies whether or not to add a default prefix to `message` @param {Number} statusCode The status code @return {(Error|RangeError)} The error @private
[ "Builds", "an", "error", "object", "." ]
995c527c87d0d4833d8093c18dcfa2e4a41d9582
https://github.com/websockets/ws/blob/995c527c87d0d4833d8093c18dcfa2e4a41d9582/lib/receiver.js#L484-L492
train
websockets/ws
lib/buffer-util.js
concat
function concat(list, totalLength) { if (list.length === 0) return EMPTY_BUFFER; if (list.length === 1) return list[0]; const target = Buffer.allocUnsafe(totalLength); let offset = 0; for (let i = 0; i < list.length; i++) { const buf = list[i]; buf.copy(target, offset); offset += buf.length; } return target; }
javascript
function concat(list, totalLength) { if (list.length === 0) return EMPTY_BUFFER; if (list.length === 1) return list[0]; const target = Buffer.allocUnsafe(totalLength); let offset = 0; for (let i = 0; i < list.length; i++) { const buf = list[i]; buf.copy(target, offset); offset += buf.length; } return target; }
[ "function", "concat", "(", "list", ",", "totalLength", ")", "{", "if", "(", "list", ".", "length", "===", "0", ")", "return", "EMPTY_BUFFER", ";", "if", "(", "list", ".", "length", "===", "1", ")", "return", "list", "[", "0", "]", ";", "const", "target", "=", "Buffer", ".", "allocUnsafe", "(", "totalLength", ")", ";", "let", "offset", "=", "0", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "list", ".", "length", ";", "i", "++", ")", "{", "const", "buf", "=", "list", "[", "i", "]", ";", "buf", ".", "copy", "(", "target", ",", "offset", ")", ";", "offset", "+=", "buf", ".", "length", ";", "}", "return", "target", ";", "}" ]
Merges an array of buffers into a new buffer. @param {Buffer[]} list The array of buffers to concat @param {Number} totalLength The total length of buffers in the list @return {Buffer} The resulting buffer @public
[ "Merges", "an", "array", "of", "buffers", "into", "a", "new", "buffer", "." ]
995c527c87d0d4833d8093c18dcfa2e4a41d9582
https://github.com/websockets/ws/blob/995c527c87d0d4833d8093c18dcfa2e4a41d9582/lib/buffer-util.js#L13-L27
train
websockets/ws
lib/buffer-util.js
_mask
function _mask(source, mask, output, offset, length) { for (let i = 0; i < length; i++) { output[offset + i] = source[i] ^ mask[i & 3]; } }
javascript
function _mask(source, mask, output, offset, length) { for (let i = 0; i < length; i++) { output[offset + i] = source[i] ^ mask[i & 3]; } }
[ "function", "_mask", "(", "source", ",", "mask", ",", "output", ",", "offset", ",", "length", ")", "{", "for", "(", "let", "i", "=", "0", ";", "i", "<", "length", ";", "i", "++", ")", "{", "output", "[", "offset", "+", "i", "]", "=", "source", "[", "i", "]", "^", "mask", "[", "i", "&", "3", "]", ";", "}", "}" ]
Masks a buffer using the given mask. @param {Buffer} source The buffer to mask @param {Buffer} mask The mask to use @param {Buffer} output The buffer where to store the result @param {Number} offset The offset at which to start writing @param {Number} length The number of bytes to mask. @public
[ "Masks", "a", "buffer", "using", "the", "given", "mask", "." ]
995c527c87d0d4833d8093c18dcfa2e4a41d9582
https://github.com/websockets/ws/blob/995c527c87d0d4833d8093c18dcfa2e4a41d9582/lib/buffer-util.js#L39-L43
train
websockets/ws
lib/buffer-util.js
_unmask
function _unmask(buffer, mask) { // Required until https://github.com/nodejs/node/issues/9006 is resolved. const length = buffer.length; for (let i = 0; i < length; i++) { buffer[i] ^= mask[i & 3]; } }
javascript
function _unmask(buffer, mask) { // Required until https://github.com/nodejs/node/issues/9006 is resolved. const length = buffer.length; for (let i = 0; i < length; i++) { buffer[i] ^= mask[i & 3]; } }
[ "function", "_unmask", "(", "buffer", ",", "mask", ")", "{", "const", "length", "=", "buffer", ".", "length", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "length", ";", "i", "++", ")", "{", "buffer", "[", "i", "]", "^=", "mask", "[", "i", "&", "3", "]", ";", "}", "}" ]
Unmasks a buffer using the given mask. @param {Buffer} buffer The buffer to unmask @param {Buffer} mask The mask to use @public
[ "Unmasks", "a", "buffer", "using", "the", "given", "mask", "." ]
995c527c87d0d4833d8093c18dcfa2e4a41d9582
https://github.com/websockets/ws/blob/995c527c87d0d4833d8093c18dcfa2e4a41d9582/lib/buffer-util.js#L52-L58
train
websockets/ws
lib/buffer-util.js
toArrayBuffer
function toArrayBuffer(buf) { if (buf.byteLength === buf.buffer.byteLength) { return buf.buffer; } return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); }
javascript
function toArrayBuffer(buf) { if (buf.byteLength === buf.buffer.byteLength) { return buf.buffer; } return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); }
[ "function", "toArrayBuffer", "(", "buf", ")", "{", "if", "(", "buf", ".", "byteLength", "===", "buf", ".", "buffer", ".", "byteLength", ")", "{", "return", "buf", ".", "buffer", ";", "}", "return", "buf", ".", "buffer", ".", "slice", "(", "buf", ".", "byteOffset", ",", "buf", ".", "byteOffset", "+", "buf", ".", "byteLength", ")", ";", "}" ]
Converts a buffer to an `ArrayBuffer`. @param {Buffer} buf The buffer to convert @return {ArrayBuffer} Converted buffer @public
[ "Converts", "a", "buffer", "to", "an", "ArrayBuffer", "." ]
995c527c87d0d4833d8093c18dcfa2e4a41d9582
https://github.com/websockets/ws/blob/995c527c87d0d4833d8093c18dcfa2e4a41d9582/lib/buffer-util.js#L67-L73
train
websockets/ws
lib/buffer-util.js
toBuffer
function toBuffer(data) { toBuffer.readOnly = true; if (Buffer.isBuffer(data)) return data; let buf; if (data instanceof ArrayBuffer) { buf = Buffer.from(data); } else if (ArrayBuffer.isView(data)) { buf = viewToBuffer(data); } else { buf = Buffer.from(data); toBuffer.readOnly = false; } return buf; }
javascript
function toBuffer(data) { toBuffer.readOnly = true; if (Buffer.isBuffer(data)) return data; let buf; if (data instanceof ArrayBuffer) { buf = Buffer.from(data); } else if (ArrayBuffer.isView(data)) { buf = viewToBuffer(data); } else { buf = Buffer.from(data); toBuffer.readOnly = false; } return buf; }
[ "function", "toBuffer", "(", "data", ")", "{", "toBuffer", ".", "readOnly", "=", "true", ";", "if", "(", "Buffer", ".", "isBuffer", "(", "data", ")", ")", "return", "data", ";", "let", "buf", ";", "if", "(", "data", "instanceof", "ArrayBuffer", ")", "{", "buf", "=", "Buffer", ".", "from", "(", "data", ")", ";", "}", "else", "if", "(", "ArrayBuffer", ".", "isView", "(", "data", ")", ")", "{", "buf", "=", "viewToBuffer", "(", "data", ")", ";", "}", "else", "{", "buf", "=", "Buffer", ".", "from", "(", "data", ")", ";", "toBuffer", ".", "readOnly", "=", "false", ";", "}", "return", "buf", ";", "}" ]
Converts `data` to a `Buffer`. @param {*} data The data to convert @return {Buffer} The buffer @throws {TypeError} @public
[ "Converts", "data", "to", "a", "Buffer", "." ]
995c527c87d0d4833d8093c18dcfa2e4a41d9582
https://github.com/websockets/ws/blob/995c527c87d0d4833d8093c18dcfa2e4a41d9582/lib/buffer-util.js#L83-L100
train
websockets/ws
lib/buffer-util.js
viewToBuffer
function viewToBuffer(view) { const buf = Buffer.from(view.buffer); if (view.byteLength !== view.buffer.byteLength) { return buf.slice(view.byteOffset, view.byteOffset + view.byteLength); } return buf; }
javascript
function viewToBuffer(view) { const buf = Buffer.from(view.buffer); if (view.byteLength !== view.buffer.byteLength) { return buf.slice(view.byteOffset, view.byteOffset + view.byteLength); } return buf; }
[ "function", "viewToBuffer", "(", "view", ")", "{", "const", "buf", "=", "Buffer", ".", "from", "(", "view", ".", "buffer", ")", ";", "if", "(", "view", ".", "byteLength", "!==", "view", ".", "buffer", ".", "byteLength", ")", "{", "return", "buf", ".", "slice", "(", "view", ".", "byteOffset", ",", "view", ".", "byteOffset", "+", "view", ".", "byteLength", ")", ";", "}", "return", "buf", ";", "}" ]
Converts an `ArrayBuffer` view into a buffer. @param {(DataView|TypedArray)} view The view to convert @return {Buffer} Converted view @private
[ "Converts", "an", "ArrayBuffer", "view", "into", "a", "buffer", "." ]
995c527c87d0d4833d8093c18dcfa2e4a41d9582
https://github.com/websockets/ws/blob/995c527c87d0d4833d8093c18dcfa2e4a41d9582/lib/buffer-util.js#L109-L117
train
websockets/ws
lib/websocket-server.js
abortHandshake
function abortHandshake(socket, code, message, headers) { if (socket.writable) { message = message || STATUS_CODES[code]; headers = { Connection: 'close', 'Content-type': 'text/html', 'Content-Length': Buffer.byteLength(message), ...headers }; socket.write( `HTTP/1.1 ${code} ${STATUS_CODES[code]}\r\n` + Object.keys(headers) .map((h) => `${h}: ${headers[h]}`) .join('\r\n') + '\r\n\r\n' + message ); } socket.removeListener('error', socketOnError); socket.destroy(); }
javascript
function abortHandshake(socket, code, message, headers) { if (socket.writable) { message = message || STATUS_CODES[code]; headers = { Connection: 'close', 'Content-type': 'text/html', 'Content-Length': Buffer.byteLength(message), ...headers }; socket.write( `HTTP/1.1 ${code} ${STATUS_CODES[code]}\r\n` + Object.keys(headers) .map((h) => `${h}: ${headers[h]}`) .join('\r\n') + '\r\n\r\n' + message ); } socket.removeListener('error', socketOnError); socket.destroy(); }
[ "function", "abortHandshake", "(", "socket", ",", "code", ",", "message", ",", "headers", ")", "{", "if", "(", "socket", ".", "writable", ")", "{", "message", "=", "message", "||", "STATUS_CODES", "[", "code", "]", ";", "headers", "=", "{", "Connection", ":", "'close'", ",", "'Content-type'", ":", "'text/html'", ",", "'Content-Length'", ":", "Buffer", ".", "byteLength", "(", "message", ")", ",", "...", "headers", "}", ";", "socket", ".", "write", "(", "`", "${", "code", "}", "${", "STATUS_CODES", "[", "code", "]", "}", "\\r", "\\n", "`", "+", "Object", ".", "keys", "(", "headers", ")", ".", "map", "(", "(", "h", ")", "=>", "`", "${", "h", "}", "${", "headers", "[", "h", "]", "}", "`", ")", ".", "join", "(", "'\\r\\n'", ")", "+", "\\r", "+", "\\n", ")", ";", "}", "'\\r\\n\\r\\n'", "\\r", "}" ]
Close the connection when preconditions are not fulfilled. @param {net.Socket} socket The socket of the upgrade request @param {Number} code The HTTP response status code @param {String} [message] The HTTP response body @param {Object} [headers] Additional HTTP response headers @private
[ "Close", "the", "connection", "when", "preconditions", "are", "not", "fulfilled", "." ]
995c527c87d0d4833d8093c18dcfa2e4a41d9582
https://github.com/websockets/ws/blob/995c527c87d0d4833d8093c18dcfa2e4a41d9582/lib/websocket-server.js#L374-L396
train
websockets/ws
lib/extension.js
push
function push(dest, name, elem) { if (dest[name] === undefined) dest[name] = [elem]; else dest[name].push(elem); }
javascript
function push(dest, name, elem) { if (dest[name] === undefined) dest[name] = [elem]; else dest[name].push(elem); }
[ "function", "push", "(", "dest", ",", "name", ",", "elem", ")", "{", "if", "(", "dest", "[", "name", "]", "===", "undefined", ")", "dest", "[", "name", "]", "=", "[", "elem", "]", ";", "else", "dest", "[", "name", "]", ".", "push", "(", "elem", ")", ";", "}" ]
Adds an offer to the map of extension offers or a parameter to the map of parameters. @param {Object} dest The map of extension offers or parameters @param {String} name The extension or parameter name @param {(Object|Boolean|String)} elem The extension parameters or the parameter value @private
[ "Adds", "an", "offer", "to", "the", "map", "of", "extension", "offers", "or", "a", "parameter", "to", "the", "map", "of", "parameters", "." ]
995c527c87d0d4833d8093c18dcfa2e4a41d9582
https://github.com/websockets/ws/blob/995c527c87d0d4833d8093c18dcfa2e4a41d9582/lib/extension.js#L36-L39
train
websockets/ws
lib/extension.js
format
function format(extensions) { return Object.keys(extensions) .map((extension) => { let configurations = extensions[extension]; if (!Array.isArray(configurations)) configurations = [configurations]; return configurations .map((params) => { return [extension] .concat( Object.keys(params).map((k) => { let values = params[k]; if (!Array.isArray(values)) values = [values]; return values .map((v) => (v === true ? k : `${k}=${v}`)) .join('; '); }) ) .join('; '); }) .join(', '); }) .join(', '); }
javascript
function format(extensions) { return Object.keys(extensions) .map((extension) => { let configurations = extensions[extension]; if (!Array.isArray(configurations)) configurations = [configurations]; return configurations .map((params) => { return [extension] .concat( Object.keys(params).map((k) => { let values = params[k]; if (!Array.isArray(values)) values = [values]; return values .map((v) => (v === true ? k : `${k}=${v}`)) .join('; '); }) ) .join('; '); }) .join(', '); }) .join(', '); }
[ "function", "format", "(", "extensions", ")", "{", "return", "Object", ".", "keys", "(", "extensions", ")", ".", "map", "(", "(", "extension", ")", "=>", "{", "let", "configurations", "=", "extensions", "[", "extension", "]", ";", "if", "(", "!", "Array", ".", "isArray", "(", "configurations", ")", ")", "configurations", "=", "[", "configurations", "]", ";", "return", "configurations", ".", "map", "(", "(", "params", ")", "=>", "{", "return", "[", "extension", "]", ".", "concat", "(", "Object", ".", "keys", "(", "params", ")", ".", "map", "(", "(", "k", ")", "=>", "{", "let", "values", "=", "params", "[", "k", "]", ";", "if", "(", "!", "Array", ".", "isArray", "(", "values", ")", ")", "values", "=", "[", "values", "]", ";", "return", "values", ".", "map", "(", "(", "v", ")", "=>", "(", "v", "===", "true", "?", "k", ":", "`", "${", "k", "}", "${", "v", "}", "`", ")", ")", ".", "join", "(", "'; '", ")", ";", "}", ")", ")", ".", "join", "(", "'; '", ")", ";", "}", ")", ".", "join", "(", "', '", ")", ";", "}", ")", ".", "join", "(", "', '", ")", ";", "}" ]
Builds the `Sec-WebSocket-Extensions` header field value. @param {Object} extensions The map of extensions and parameters to format @return {String} A string representing the given object @public
[ "Builds", "the", "Sec", "-", "WebSocket", "-", "Extensions", "header", "field", "value", "." ]
995c527c87d0d4833d8093c18dcfa2e4a41d9582
https://github.com/websockets/ws/blob/995c527c87d0d4833d8093c18dcfa2e4a41d9582/lib/extension.js#L199-L221
train
websockets/ws
lib/websocket.js
tlsConnect
function tlsConnect(options) { options.path = undefined; options.servername = options.servername || options.host; return tls.connect(options); }
javascript
function tlsConnect(options) { options.path = undefined; options.servername = options.servername || options.host; return tls.connect(options); }
[ "function", "tlsConnect", "(", "options", ")", "{", "options", ".", "path", "=", "undefined", ";", "options", ".", "servername", "=", "options", ".", "servername", "||", "options", ".", "host", ";", "return", "tls", ".", "connect", "(", "options", ")", ";", "}" ]
Create a `tls.TLSSocket` and initiate a connection. @param {Object} options Connection options @return {tls.TLSSocket} The newly created socket used to start the connection @private
[ "Create", "a", "tls", ".", "TLSSocket", "and", "initiate", "a", "connection", "." ]
995c527c87d0d4833d8093c18dcfa2e4a41d9582
https://github.com/websockets/ws/blob/995c527c87d0d4833d8093c18dcfa2e4a41d9582/lib/websocket.js#L669-L673
train
websockets/ws
lib/websocket.js
abortHandshake
function abortHandshake(websocket, stream, message) { websocket.readyState = WebSocket.CLOSING; const err = new Error(message); Error.captureStackTrace(err, abortHandshake); if (stream.setHeader) { stream.abort(); stream.once('abort', websocket.emitClose.bind(websocket)); websocket.emit('error', err); } else { stream.destroy(err); stream.once('error', websocket.emit.bind(websocket, 'error')); stream.once('close', websocket.emitClose.bind(websocket)); } }
javascript
function abortHandshake(websocket, stream, message) { websocket.readyState = WebSocket.CLOSING; const err = new Error(message); Error.captureStackTrace(err, abortHandshake); if (stream.setHeader) { stream.abort(); stream.once('abort', websocket.emitClose.bind(websocket)); websocket.emit('error', err); } else { stream.destroy(err); stream.once('error', websocket.emit.bind(websocket, 'error')); stream.once('close', websocket.emitClose.bind(websocket)); } }
[ "function", "abortHandshake", "(", "websocket", ",", "stream", ",", "message", ")", "{", "websocket", ".", "readyState", "=", "WebSocket", ".", "CLOSING", ";", "const", "err", "=", "new", "Error", "(", "message", ")", ";", "Error", ".", "captureStackTrace", "(", "err", ",", "abortHandshake", ")", ";", "if", "(", "stream", ".", "setHeader", ")", "{", "stream", ".", "abort", "(", ")", ";", "stream", ".", "once", "(", "'abort'", ",", "websocket", ".", "emitClose", ".", "bind", "(", "websocket", ")", ")", ";", "websocket", ".", "emit", "(", "'error'", ",", "err", ")", ";", "}", "else", "{", "stream", ".", "destroy", "(", "err", ")", ";", "stream", ".", "once", "(", "'error'", ",", "websocket", ".", "emit", ".", "bind", "(", "websocket", ",", "'error'", ")", ")", ";", "stream", ".", "once", "(", "'close'", ",", "websocket", ".", "emitClose", ".", "bind", "(", "websocket", ")", ")", ";", "}", "}" ]
Abort the handshake and emit an error. @param {WebSocket} websocket The WebSocket instance @param {(http.ClientRequest|net.Socket)} stream The request to abort or the socket to destroy @param {String} message The error message @private
[ "Abort", "the", "handshake", "and", "emit", "an", "error", "." ]
995c527c87d0d4833d8093c18dcfa2e4a41d9582
https://github.com/websockets/ws/blob/995c527c87d0d4833d8093c18dcfa2e4a41d9582/lib/websocket.js#L684-L699
train
websockets/ws
lib/websocket.js
receiverOnConclude
function receiverOnConclude(code, reason) { const websocket = this[kWebSocket]; websocket._socket.removeListener('data', socketOnData); websocket._socket.resume(); websocket._closeFrameReceived = true; websocket._closeMessage = reason; websocket._closeCode = code; if (code === 1005) websocket.close(); else websocket.close(code, reason); }
javascript
function receiverOnConclude(code, reason) { const websocket = this[kWebSocket]; websocket._socket.removeListener('data', socketOnData); websocket._socket.resume(); websocket._closeFrameReceived = true; websocket._closeMessage = reason; websocket._closeCode = code; if (code === 1005) websocket.close(); else websocket.close(code, reason); }
[ "function", "receiverOnConclude", "(", "code", ",", "reason", ")", "{", "const", "websocket", "=", "this", "[", "kWebSocket", "]", ";", "websocket", ".", "_socket", ".", "removeListener", "(", "'data'", ",", "socketOnData", ")", ";", "websocket", ".", "_socket", ".", "resume", "(", ")", ";", "websocket", ".", "_closeFrameReceived", "=", "true", ";", "websocket", ".", "_closeMessage", "=", "reason", ";", "websocket", ".", "_closeCode", "=", "code", ";", "if", "(", "code", "===", "1005", ")", "websocket", ".", "close", "(", ")", ";", "else", "websocket", ".", "close", "(", "code", ",", "reason", ")", ";", "}" ]
The listener of the `Receiver` `'conclude'` event. @param {Number} code The status code @param {String} reason The reason for closing @private
[ "The", "listener", "of", "the", "Receiver", "conclude", "event", "." ]
995c527c87d0d4833d8093c18dcfa2e4a41d9582
https://github.com/websockets/ws/blob/995c527c87d0d4833d8093c18dcfa2e4a41d9582/lib/websocket.js#L740-L752
train
websockets/ws
lib/websocket.js
receiverOnError
function receiverOnError(err) { const websocket = this[kWebSocket]; websocket._socket.removeListener('data', socketOnData); websocket.readyState = WebSocket.CLOSING; websocket._closeCode = err[kStatusCode]; websocket.emit('error', err); websocket._socket.destroy(); }
javascript
function receiverOnError(err) { const websocket = this[kWebSocket]; websocket._socket.removeListener('data', socketOnData); websocket.readyState = WebSocket.CLOSING; websocket._closeCode = err[kStatusCode]; websocket.emit('error', err); websocket._socket.destroy(); }
[ "function", "receiverOnError", "(", "err", ")", "{", "const", "websocket", "=", "this", "[", "kWebSocket", "]", ";", "websocket", ".", "_socket", ".", "removeListener", "(", "'data'", ",", "socketOnData", ")", ";", "websocket", ".", "readyState", "=", "WebSocket", ".", "CLOSING", ";", "websocket", ".", "_closeCode", "=", "err", "[", "kStatusCode", "]", ";", "websocket", ".", "emit", "(", "'error'", ",", "err", ")", ";", "websocket", ".", "_socket", ".", "destroy", "(", ")", ";", "}" ]
The listener of the `Receiver` `'error'` event. @param {(RangeError|Error)} err The emitted error @private
[ "The", "listener", "of", "the", "Receiver", "error", "event", "." ]
995c527c87d0d4833d8093c18dcfa2e4a41d9582
https://github.com/websockets/ws/blob/995c527c87d0d4833d8093c18dcfa2e4a41d9582/lib/websocket.js#L769-L778
train
websockets/ws
lib/websocket.js
receiverOnPing
function receiverOnPing(data) { const websocket = this[kWebSocket]; websocket.pong(data, !websocket._isServer, NOOP); websocket.emit('ping', data); }
javascript
function receiverOnPing(data) { const websocket = this[kWebSocket]; websocket.pong(data, !websocket._isServer, NOOP); websocket.emit('ping', data); }
[ "function", "receiverOnPing", "(", "data", ")", "{", "const", "websocket", "=", "this", "[", "kWebSocket", "]", ";", "websocket", ".", "pong", "(", "data", ",", "!", "websocket", ".", "_isServer", ",", "NOOP", ")", ";", "websocket", ".", "emit", "(", "'ping'", ",", "data", ")", ";", "}" ]
The listener of the `Receiver` `'ping'` event. @param {Buffer} data The data included in the ping frame @private
[ "The", "listener", "of", "the", "Receiver", "ping", "event", "." ]
995c527c87d0d4833d8093c18dcfa2e4a41d9582
https://github.com/websockets/ws/blob/995c527c87d0d4833d8093c18dcfa2e4a41d9582/lib/websocket.js#L805-L810
train
websockets/ws
lib/websocket.js
socketOnClose
function socketOnClose() { const websocket = this[kWebSocket]; this.removeListener('close', socketOnClose); this.removeListener('end', socketOnEnd); websocket.readyState = WebSocket.CLOSING; // // The close frame might not have been received or the `'end'` event emitted, // for example, if the socket was destroyed due to an error. Ensure that the // `receiver` stream is closed after writing any remaining buffered data to // it. If the readable side of the socket is in flowing mode then there is no // buffered data as everything has been already written and `readable.read()` // will return `null`. If instead, the socket is paused, any possible buffered // data will be read as a single chunk and emitted synchronously in a single // `'data'` event. // websocket._socket.read(); websocket._receiver.end(); this.removeListener('data', socketOnData); this[kWebSocket] = undefined; clearTimeout(websocket._closeTimer); if ( websocket._receiver._writableState.finished || websocket._receiver._writableState.errorEmitted ) { websocket.emitClose(); } else { websocket._receiver.on('error', receiverOnFinish); websocket._receiver.on('finish', receiverOnFinish); } }
javascript
function socketOnClose() { const websocket = this[kWebSocket]; this.removeListener('close', socketOnClose); this.removeListener('end', socketOnEnd); websocket.readyState = WebSocket.CLOSING; // // The close frame might not have been received or the `'end'` event emitted, // for example, if the socket was destroyed due to an error. Ensure that the // `receiver` stream is closed after writing any remaining buffered data to // it. If the readable side of the socket is in flowing mode then there is no // buffered data as everything has been already written and `readable.read()` // will return `null`. If instead, the socket is paused, any possible buffered // data will be read as a single chunk and emitted synchronously in a single // `'data'` event. // websocket._socket.read(); websocket._receiver.end(); this.removeListener('data', socketOnData); this[kWebSocket] = undefined; clearTimeout(websocket._closeTimer); if ( websocket._receiver._writableState.finished || websocket._receiver._writableState.errorEmitted ) { websocket.emitClose(); } else { websocket._receiver.on('error', receiverOnFinish); websocket._receiver.on('finish', receiverOnFinish); } }
[ "function", "socketOnClose", "(", ")", "{", "const", "websocket", "=", "this", "[", "kWebSocket", "]", ";", "this", ".", "removeListener", "(", "'close'", ",", "socketOnClose", ")", ";", "this", ".", "removeListener", "(", "'end'", ",", "socketOnEnd", ")", ";", "websocket", ".", "readyState", "=", "WebSocket", ".", "CLOSING", ";", "websocket", ".", "_socket", ".", "read", "(", ")", ";", "websocket", ".", "_receiver", ".", "end", "(", ")", ";", "this", ".", "removeListener", "(", "'data'", ",", "socketOnData", ")", ";", "this", "[", "kWebSocket", "]", "=", "undefined", ";", "clearTimeout", "(", "websocket", ".", "_closeTimer", ")", ";", "if", "(", "websocket", ".", "_receiver", ".", "_writableState", ".", "finished", "||", "websocket", ".", "_receiver", ".", "_writableState", ".", "errorEmitted", ")", "{", "websocket", ".", "emitClose", "(", ")", ";", "}", "else", "{", "websocket", ".", "_receiver", ".", "on", "(", "'error'", ",", "receiverOnFinish", ")", ";", "websocket", ".", "_receiver", ".", "on", "(", "'finish'", ",", "receiverOnFinish", ")", ";", "}", "}" ]
The listener of the `net.Socket` `'close'` event. @private
[ "The", "listener", "of", "the", "net", ".", "Socket", "close", "event", "." ]
995c527c87d0d4833d8093c18dcfa2e4a41d9582
https://github.com/websockets/ws/blob/995c527c87d0d4833d8093c18dcfa2e4a41d9582/lib/websocket.js#L827-L862
train
websockets/ws
lib/websocket.js
socketOnEnd
function socketOnEnd() { const websocket = this[kWebSocket]; websocket.readyState = WebSocket.CLOSING; websocket._receiver.end(); this.end(); }
javascript
function socketOnEnd() { const websocket = this[kWebSocket]; websocket.readyState = WebSocket.CLOSING; websocket._receiver.end(); this.end(); }
[ "function", "socketOnEnd", "(", ")", "{", "const", "websocket", "=", "this", "[", "kWebSocket", "]", ";", "websocket", ".", "readyState", "=", "WebSocket", ".", "CLOSING", ";", "websocket", ".", "_receiver", ".", "end", "(", ")", ";", "this", ".", "end", "(", ")", ";", "}" ]
The listener of the `net.Socket` `'end'` event. @private
[ "The", "listener", "of", "the", "net", ".", "Socket", "end", "event", "." ]
995c527c87d0d4833d8093c18dcfa2e4a41d9582
https://github.com/websockets/ws/blob/995c527c87d0d4833d8093c18dcfa2e4a41d9582/lib/websocket.js#L881-L887
train
websockets/ws
lib/websocket.js
socketOnError
function socketOnError() { const websocket = this[kWebSocket]; this.removeListener('error', socketOnError); this.on('error', NOOP); websocket.readyState = WebSocket.CLOSING; this.destroy(); }
javascript
function socketOnError() { const websocket = this[kWebSocket]; this.removeListener('error', socketOnError); this.on('error', NOOP); websocket.readyState = WebSocket.CLOSING; this.destroy(); }
[ "function", "socketOnError", "(", ")", "{", "const", "websocket", "=", "this", "[", "kWebSocket", "]", ";", "this", ".", "removeListener", "(", "'error'", ",", "socketOnError", ")", ";", "this", ".", "on", "(", "'error'", ",", "NOOP", ")", ";", "websocket", ".", "readyState", "=", "WebSocket", ".", "CLOSING", ";", "this", ".", "destroy", "(", ")", ";", "}" ]
The listener of the `net.Socket` `'error'` event. @private
[ "The", "listener", "of", "the", "net", ".", "Socket", "error", "event", "." ]
995c527c87d0d4833d8093c18dcfa2e4a41d9582
https://github.com/websockets/ws/blob/995c527c87d0d4833d8093c18dcfa2e4a41d9582/lib/websocket.js#L894-L902
train
summernote/summernote
src/js/base/core/lists.js
all
function all(array, pred) { for (let idx = 0, len = array.length; idx < len; idx++) { if (!pred(array[idx])) { return false; } } return true; }
javascript
function all(array, pred) { for (let idx = 0, len = array.length; idx < len; idx++) { if (!pred(array[idx])) { return false; } } return true; }
[ "function", "all", "(", "array", ",", "pred", ")", "{", "for", "(", "let", "idx", "=", "0", ",", "len", "=", "array", ".", "length", ";", "idx", "<", "len", ";", "idx", "++", ")", "{", "if", "(", "!", "pred", "(", "array", "[", "idx", "]", ")", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
returns true if all of the values in the array pass the predicate truth test.
[ "returns", "true", "if", "all", "of", "the", "values", "in", "the", "array", "pass", "the", "predicate", "truth", "test", "." ]
8dcafb8107453006b905ef697a529c42e76beb3f
https://github.com/summernote/summernote/blob/8dcafb8107453006b905ef697a529c42e76beb3f/src/js/base/core/lists.js#L54-L61
train
summernote/summernote
src/js/base/core/lists.js
contains
function contains(array, item) { if (array && array.length && item) { return array.indexOf(item) !== -1; } return false; }
javascript
function contains(array, item) { if (array && array.length && item) { return array.indexOf(item) !== -1; } return false; }
[ "function", "contains", "(", "array", ",", "item", ")", "{", "if", "(", "array", "&&", "array", ".", "length", "&&", "item", ")", "{", "return", "array", ".", "indexOf", "(", "item", ")", "!==", "-", "1", ";", "}", "return", "false", ";", "}" ]
returns true if the value is present in the list.
[ "returns", "true", "if", "the", "value", "is", "present", "in", "the", "list", "." ]
8dcafb8107453006b905ef697a529c42e76beb3f
https://github.com/summernote/summernote/blob/8dcafb8107453006b905ef697a529c42e76beb3f/src/js/base/core/lists.js#L66-L71
train
summernote/summernote
src/js/base/core/lists.js
sum
function sum(array, fn) { fn = fn || func.self; return array.reduce(function(memo, v) { return memo + fn(v); }, 0); }
javascript
function sum(array, fn) { fn = fn || func.self; return array.reduce(function(memo, v) { return memo + fn(v); }, 0); }
[ "function", "sum", "(", "array", ",", "fn", ")", "{", "fn", "=", "fn", "||", "func", ".", "self", ";", "return", "array", ".", "reduce", "(", "function", "(", "memo", ",", "v", ")", "{", "return", "memo", "+", "fn", "(", "v", ")", ";", "}", ",", "0", ")", ";", "}" ]
get sum from a list @param {Array} array - array @param {Function} fn - iterator
[ "get", "sum", "from", "a", "list" ]
8dcafb8107453006b905ef697a529c42e76beb3f
https://github.com/summernote/summernote/blob/8dcafb8107453006b905ef697a529c42e76beb3f/src/js/base/core/lists.js#L79-L84
train
summernote/summernote
src/js/base/core/lists.js
from
function from(collection) { const result = []; const length = collection.length; let idx = -1; while (++idx < length) { result[idx] = collection[idx]; } return result; }
javascript
function from(collection) { const result = []; const length = collection.length; let idx = -1; while (++idx < length) { result[idx] = collection[idx]; } return result; }
[ "function", "from", "(", "collection", ")", "{", "const", "result", "=", "[", "]", ";", "const", "length", "=", "collection", ".", "length", ";", "let", "idx", "=", "-", "1", ";", "while", "(", "++", "idx", "<", "length", ")", "{", "result", "[", "idx", "]", "=", "collection", "[", "idx", "]", ";", "}", "return", "result", ";", "}" ]
returns a copy of the collection with array type. @param {Collection} collection - collection eg) node.childNodes, ...
[ "returns", "a", "copy", "of", "the", "collection", "with", "array", "type", "." ]
8dcafb8107453006b905ef697a529c42e76beb3f
https://github.com/summernote/summernote/blob/8dcafb8107453006b905ef697a529c42e76beb3f/src/js/base/core/lists.js#L90-L98
train
summernote/summernote
src/js/base/core/lists.js
compact
function compact(array) { const aResult = []; for (let idx = 0, len = array.length; idx < len; idx++) { if (array[idx]) { aResult.push(array[idx]); } } return aResult; }
javascript
function compact(array) { const aResult = []; for (let idx = 0, len = array.length; idx < len; idx++) { if (array[idx]) { aResult.push(array[idx]); } } return aResult; }
[ "function", "compact", "(", "array", ")", "{", "const", "aResult", "=", "[", "]", ";", "for", "(", "let", "idx", "=", "0", ",", "len", "=", "array", ".", "length", ";", "idx", "<", "len", ";", "idx", "++", ")", "{", "if", "(", "array", "[", "idx", "]", ")", "{", "aResult", ".", "push", "(", "array", "[", "idx", "]", ")", ";", "}", "}", "return", "aResult", ";", "}" ]
returns a copy of the array with all false values removed @param {Array} array - array @param {Function} fn - predicate function for cluster rule
[ "returns", "a", "copy", "of", "the", "array", "with", "all", "false", "values", "removed" ]
8dcafb8107453006b905ef697a529c42e76beb3f
https://github.com/summernote/summernote/blob/8dcafb8107453006b905ef697a529c42e76beb3f/src/js/base/core/lists.js#L134-L140
train
summernote/summernote
src/js/base/core/lists.js
unique
function unique(array) { const results = []; for (let idx = 0, len = array.length; idx < len; idx++) { if (!contains(results, array[idx])) { results.push(array[idx]); } } return results; }
javascript
function unique(array) { const results = []; for (let idx = 0, len = array.length; idx < len; idx++) { if (!contains(results, array[idx])) { results.push(array[idx]); } } return results; }
[ "function", "unique", "(", "array", ")", "{", "const", "results", "=", "[", "]", ";", "for", "(", "let", "idx", "=", "0", ",", "len", "=", "array", ".", "length", ";", "idx", "<", "len", ";", "idx", "++", ")", "{", "if", "(", "!", "contains", "(", "results", ",", "array", "[", "idx", "]", ")", ")", "{", "results", ".", "push", "(", "array", "[", "idx", "]", ")", ";", "}", "}", "return", "results", ";", "}" ]
produces a duplicate-free version of the array @param {Array} array
[ "produces", "a", "duplicate", "-", "free", "version", "of", "the", "array" ]
8dcafb8107453006b905ef697a529c42e76beb3f
https://github.com/summernote/summernote/blob/8dcafb8107453006b905ef697a529c42e76beb3f/src/js/base/core/lists.js#L147-L157
train
summernote/summernote
src/js/base/core/lists.js
prev
function prev(array, item) { if (array && array.length && item) { const idx = array.indexOf(item); return idx === -1 ? null : array[idx - 1]; } return null; }
javascript
function prev(array, item) { if (array && array.length && item) { const idx = array.indexOf(item); return idx === -1 ? null : array[idx - 1]; } return null; }
[ "function", "prev", "(", "array", ",", "item", ")", "{", "if", "(", "array", "&&", "array", ".", "length", "&&", "item", ")", "{", "const", "idx", "=", "array", ".", "indexOf", "(", "item", ")", ";", "return", "idx", "===", "-", "1", "?", "null", ":", "array", "[", "idx", "-", "1", "]", ";", "}", "return", "null", ";", "}" ]
returns prev item. @param {Array} array
[ "returns", "prev", "item", "." ]
8dcafb8107453006b905ef697a529c42e76beb3f
https://github.com/summernote/summernote/blob/8dcafb8107453006b905ef697a529c42e76beb3f/src/js/base/core/lists.js#L175-L181
train
summernote/summernote
src/js/base/core/dom.js
listDescendant
function listDescendant(node, pred) { const descendants = []; pred = pred || func.ok; // start DFS(depth first search) with node (function fnWalk(current) { if (node !== current && pred(current)) { descendants.push(current); } for (let idx = 0, len = current.childNodes.length; idx < len; idx++) { fnWalk(current.childNodes[idx]); } })(node); return descendants; }
javascript
function listDescendant(node, pred) { const descendants = []; pred = pred || func.ok; // start DFS(depth first search) with node (function fnWalk(current) { if (node !== current && pred(current)) { descendants.push(current); } for (let idx = 0, len = current.childNodes.length; idx < len; idx++) { fnWalk(current.childNodes[idx]); } })(node); return descendants; }
[ "function", "listDescendant", "(", "node", ",", "pred", ")", "{", "const", "descendants", "=", "[", "]", ";", "pred", "=", "pred", "||", "func", ".", "ok", ";", "(", "function", "fnWalk", "(", "current", ")", "{", "if", "(", "node", "!==", "current", "&&", "pred", "(", "current", ")", ")", "{", "descendants", ".", "push", "(", "current", ")", ";", "}", "for", "(", "let", "idx", "=", "0", ",", "len", "=", "current", ".", "childNodes", ".", "length", ";", "idx", "<", "len", ";", "idx", "++", ")", "{", "fnWalk", "(", "current", ".", "childNodes", "[", "idx", "]", ")", ";", "}", "}", ")", "(", "node", ")", ";", "return", "descendants", ";", "}" ]
listing descendant nodes @param {Node} node @param {Function} [pred] - predicate function
[ "listing", "descendant", "nodes" ]
8dcafb8107453006b905ef697a529c42e76beb3f
https://github.com/summernote/summernote/blob/8dcafb8107453006b905ef697a529c42e76beb3f/src/js/base/core/dom.js#L352-L367
train
summernote/summernote
src/js/base/core/dom.js
isLeftEdgeOf
function isLeftEdgeOf(node, ancestor) { while (node && node !== ancestor) { if (position(node) !== 0) { return false; } node = node.parentNode; } return true; }
javascript
function isLeftEdgeOf(node, ancestor) { while (node && node !== ancestor) { if (position(node) !== 0) { return false; } node = node.parentNode; } return true; }
[ "function", "isLeftEdgeOf", "(", "node", ",", "ancestor", ")", "{", "while", "(", "node", "&&", "node", "!==", "ancestor", ")", "{", "if", "(", "position", "(", "node", ")", "!==", "0", ")", "{", "return", "false", ";", "}", "node", "=", "node", ".", "parentNode", ";", "}", "return", "true", ";", "}" ]
returns whether node is left edge of ancestor or not. @param {Node} node @param {Node} ancestor @return {Boolean}
[ "returns", "whether", "node", "is", "left", "edge", "of", "ancestor", "or", "not", "." ]
8dcafb8107453006b905ef697a529c42e76beb3f
https://github.com/summernote/summernote/blob/8dcafb8107453006b905ef697a529c42e76beb3f/src/js/base/core/dom.js#L453-L462
train
summernote/summernote
src/js/base/core/dom.js
prevPoint
function prevPoint(point, isSkipInnerOffset) { let node; let offset; if (point.offset === 0) { if (isEditable(point.node)) { return null; } node = point.node.parentNode; offset = position(point.node); } else if (hasChildren(point.node)) { node = point.node.childNodes[point.offset - 1]; offset = nodeLength(node); } else { node = point.node; offset = isSkipInnerOffset ? 0 : point.offset - 1; } return { node: node, offset: offset, }; }
javascript
function prevPoint(point, isSkipInnerOffset) { let node; let offset; if (point.offset === 0) { if (isEditable(point.node)) { return null; } node = point.node.parentNode; offset = position(point.node); } else if (hasChildren(point.node)) { node = point.node.childNodes[point.offset - 1]; offset = nodeLength(node); } else { node = point.node; offset = isSkipInnerOffset ? 0 : point.offset - 1; } return { node: node, offset: offset, }; }
[ "function", "prevPoint", "(", "point", ",", "isSkipInnerOffset", ")", "{", "let", "node", ";", "let", "offset", ";", "if", "(", "point", ".", "offset", "===", "0", ")", "{", "if", "(", "isEditable", "(", "point", ".", "node", ")", ")", "{", "return", "null", ";", "}", "node", "=", "point", ".", "node", ".", "parentNode", ";", "offset", "=", "position", "(", "point", ".", "node", ")", ";", "}", "else", "if", "(", "hasChildren", "(", "point", ".", "node", ")", ")", "{", "node", "=", "point", ".", "node", ".", "childNodes", "[", "point", ".", "offset", "-", "1", "]", ";", "offset", "=", "nodeLength", "(", "node", ")", ";", "}", "else", "{", "node", "=", "point", ".", "node", ";", "offset", "=", "isSkipInnerOffset", "?", "0", ":", "point", ".", "offset", "-", "1", ";", "}", "return", "{", "node", ":", "node", ",", "offset", ":", "offset", ",", "}", ";", "}" ]
returns previous boundaryPoint @param {BoundaryPoint} point @param {Boolean} isSkipInnerOffset @return {BoundaryPoint}
[ "returns", "previous", "boundaryPoint" ]
8dcafb8107453006b905ef697a529c42e76beb3f
https://github.com/summernote/summernote/blob/8dcafb8107453006b905ef697a529c42e76beb3f/src/js/base/core/dom.js#L529-L552
train
summernote/summernote
src/js/base/core/dom.js
isSamePoint
function isSamePoint(pointA, pointB) { return pointA.node === pointB.node && pointA.offset === pointB.offset; }
javascript
function isSamePoint(pointA, pointB) { return pointA.node === pointB.node && pointA.offset === pointB.offset; }
[ "function", "isSamePoint", "(", "pointA", ",", "pointB", ")", "{", "return", "pointA", ".", "node", "===", "pointB", ".", "node", "&&", "pointA", ".", "offset", "===", "pointB", ".", "offset", ";", "}" ]
returns whether pointA and pointB is same or not. @param {BoundaryPoint} pointA @param {BoundaryPoint} pointB @return {Boolean}
[ "returns", "whether", "pointA", "and", "pointB", "is", "same", "or", "not", "." ]
8dcafb8107453006b905ef697a529c42e76beb3f
https://github.com/summernote/summernote/blob/8dcafb8107453006b905ef697a529c42e76beb3f/src/js/base/core/dom.js#L592-L594
train
summernote/summernote
src/js/base/core/range.js
textRangeToPoint
function textRangeToPoint(textRange, isStart) { let container = textRange.parentElement(); let offset; const tester = document.body.createTextRange(); let prevContainer; const childNodes = lists.from(container.childNodes); for (offset = 0; offset < childNodes.length; offset++) { if (dom.isText(childNodes[offset])) { continue; } tester.moveToElementText(childNodes[offset]); if (tester.compareEndPoints('StartToStart', textRange) >= 0) { break; } prevContainer = childNodes[offset]; } if (offset !== 0 && dom.isText(childNodes[offset - 1])) { const textRangeStart = document.body.createTextRange(); let curTextNode = null; textRangeStart.moveToElementText(prevContainer || container); textRangeStart.collapse(!prevContainer); curTextNode = prevContainer ? prevContainer.nextSibling : container.firstChild; const pointTester = textRange.duplicate(); pointTester.setEndPoint('StartToStart', textRangeStart); let textCount = pointTester.text.replace(/[\r\n]/g, '').length; while (textCount > curTextNode.nodeValue.length && curTextNode.nextSibling) { textCount -= curTextNode.nodeValue.length; curTextNode = curTextNode.nextSibling; } // [workaround] enforce IE to re-reference curTextNode, hack const dummy = curTextNode.nodeValue; // eslint-disable-line if (isStart && curTextNode.nextSibling && dom.isText(curTextNode.nextSibling) && textCount === curTextNode.nodeValue.length) { textCount -= curTextNode.nodeValue.length; curTextNode = curTextNode.nextSibling; } container = curTextNode; offset = textCount; } return { cont: container, offset: offset, }; }
javascript
function textRangeToPoint(textRange, isStart) { let container = textRange.parentElement(); let offset; const tester = document.body.createTextRange(); let prevContainer; const childNodes = lists.from(container.childNodes); for (offset = 0; offset < childNodes.length; offset++) { if (dom.isText(childNodes[offset])) { continue; } tester.moveToElementText(childNodes[offset]); if (tester.compareEndPoints('StartToStart', textRange) >= 0) { break; } prevContainer = childNodes[offset]; } if (offset !== 0 && dom.isText(childNodes[offset - 1])) { const textRangeStart = document.body.createTextRange(); let curTextNode = null; textRangeStart.moveToElementText(prevContainer || container); textRangeStart.collapse(!prevContainer); curTextNode = prevContainer ? prevContainer.nextSibling : container.firstChild; const pointTester = textRange.duplicate(); pointTester.setEndPoint('StartToStart', textRangeStart); let textCount = pointTester.text.replace(/[\r\n]/g, '').length; while (textCount > curTextNode.nodeValue.length && curTextNode.nextSibling) { textCount -= curTextNode.nodeValue.length; curTextNode = curTextNode.nextSibling; } // [workaround] enforce IE to re-reference curTextNode, hack const dummy = curTextNode.nodeValue; // eslint-disable-line if (isStart && curTextNode.nextSibling && dom.isText(curTextNode.nextSibling) && textCount === curTextNode.nodeValue.length) { textCount -= curTextNode.nodeValue.length; curTextNode = curTextNode.nextSibling; } container = curTextNode; offset = textCount; } return { cont: container, offset: offset, }; }
[ "function", "textRangeToPoint", "(", "textRange", ",", "isStart", ")", "{", "let", "container", "=", "textRange", ".", "parentElement", "(", ")", ";", "let", "offset", ";", "const", "tester", "=", "document", ".", "body", ".", "createTextRange", "(", ")", ";", "let", "prevContainer", ";", "const", "childNodes", "=", "lists", ".", "from", "(", "container", ".", "childNodes", ")", ";", "for", "(", "offset", "=", "0", ";", "offset", "<", "childNodes", ".", "length", ";", "offset", "++", ")", "{", "if", "(", "dom", ".", "isText", "(", "childNodes", "[", "offset", "]", ")", ")", "{", "continue", ";", "}", "tester", ".", "moveToElementText", "(", "childNodes", "[", "offset", "]", ")", ";", "if", "(", "tester", ".", "compareEndPoints", "(", "'StartToStart'", ",", "textRange", ")", ">=", "0", ")", "{", "break", ";", "}", "prevContainer", "=", "childNodes", "[", "offset", "]", ";", "}", "if", "(", "offset", "!==", "0", "&&", "dom", ".", "isText", "(", "childNodes", "[", "offset", "-", "1", "]", ")", ")", "{", "const", "textRangeStart", "=", "document", ".", "body", ".", "createTextRange", "(", ")", ";", "let", "curTextNode", "=", "null", ";", "textRangeStart", ".", "moveToElementText", "(", "prevContainer", "||", "container", ")", ";", "textRangeStart", ".", "collapse", "(", "!", "prevContainer", ")", ";", "curTextNode", "=", "prevContainer", "?", "prevContainer", ".", "nextSibling", ":", "container", ".", "firstChild", ";", "const", "pointTester", "=", "textRange", ".", "duplicate", "(", ")", ";", "pointTester", ".", "setEndPoint", "(", "'StartToStart'", ",", "textRangeStart", ")", ";", "let", "textCount", "=", "pointTester", ".", "text", ".", "replace", "(", "/", "[\\r\\n]", "/", "g", ",", "''", ")", ".", "length", ";", "while", "(", "textCount", ">", "curTextNode", ".", "nodeValue", ".", "length", "&&", "curTextNode", ".", "nextSibling", ")", "{", "textCount", "-=", "curTextNode", ".", "nodeValue", ".", "length", ";", "curTextNode", "=", "curTextNode", ".", "nextSibling", ";", "}", "const", "dummy", "=", "curTextNode", ".", "nodeValue", ";", "if", "(", "isStart", "&&", "curTextNode", ".", "nextSibling", "&&", "dom", ".", "isText", "(", "curTextNode", ".", "nextSibling", ")", "&&", "textCount", "===", "curTextNode", ".", "nodeValue", ".", "length", ")", "{", "textCount", "-=", "curTextNode", ".", "nodeValue", ".", "length", ";", "curTextNode", "=", "curTextNode", ".", "nextSibling", ";", "}", "container", "=", "curTextNode", ";", "offset", "=", "textCount", ";", "}", "return", "{", "cont", ":", "container", ",", "offset", ":", "offset", ",", "}", ";", "}" ]
return boundaryPoint from TextRange, inspired by Andy Na's HuskyRange.js @param {TextRange} textRange @param {Boolean} isStart @return {BoundaryPoint} @see http://msdn.microsoft.com/en-us/library/ie/ms535872(v=vs.85).aspx
[ "return", "boundaryPoint", "from", "TextRange", "inspired", "by", "Andy", "Na", "s", "HuskyRange", ".", "js" ]
8dcafb8107453006b905ef697a529c42e76beb3f
https://github.com/summernote/summernote/blob/8dcafb8107453006b905ef697a529c42e76beb3f/src/js/base/core/range.js#L16-L67
train
summernote/summernote
src/js/base/core/env.js
isFontInstalled
function isFontInstalled(fontName) { const testFontName = fontName === 'Comic Sans MS' ? 'Courier New' : 'Comic Sans MS'; const testText = 'mmmmmmmmmmwwwww'; const testSize = '200px'; var canvas = document.createElement('canvas'); var context = canvas.getContext('2d'); context.font = testSize + " '" + testFontName + "'"; const originalWidth = context.measureText(testText).width; context.font = testSize + " '" + fontName + "', '" + testFontName + "'"; const width = context.measureText(testText).width; return originalWidth !== width; }
javascript
function isFontInstalled(fontName) { const testFontName = fontName === 'Comic Sans MS' ? 'Courier New' : 'Comic Sans MS'; const testText = 'mmmmmmmmmmwwwww'; const testSize = '200px'; var canvas = document.createElement('canvas'); var context = canvas.getContext('2d'); context.font = testSize + " '" + testFontName + "'"; const originalWidth = context.measureText(testText).width; context.font = testSize + " '" + fontName + "', '" + testFontName + "'"; const width = context.measureText(testText).width; return originalWidth !== width; }
[ "function", "isFontInstalled", "(", "fontName", ")", "{", "const", "testFontName", "=", "fontName", "===", "'Comic Sans MS'", "?", "'Courier New'", ":", "'Comic Sans MS'", ";", "const", "testText", "=", "'mmmmmmmmmmwwwww'", ";", "const", "testSize", "=", "'200px'", ";", "var", "canvas", "=", "document", ".", "createElement", "(", "'canvas'", ")", ";", "var", "context", "=", "canvas", ".", "getContext", "(", "'2d'", ")", ";", "context", ".", "font", "=", "testSize", "+", "\" '\"", "+", "testFontName", "+", "\"'\"", ";", "const", "originalWidth", "=", "context", ".", "measureText", "(", "testText", ")", ".", "width", ";", "context", ".", "font", "=", "testSize", "+", "\" '\"", "+", "fontName", "+", "\"', '\"", "+", "testFontName", "+", "\"'\"", ";", "const", "width", "=", "context", ".", "measureText", "(", "testText", ")", ".", "width", ";", "return", "originalWidth", "!==", "width", ";", "}" ]
eslint-disable-line returns whether font is installed or not. @param {String} fontName @return {Boolean}
[ "eslint", "-", "disable", "-", "line", "returns", "whether", "font", "is", "installed", "or", "not", "." ]
8dcafb8107453006b905ef697a529c42e76beb3f
https://github.com/summernote/summernote/blob/8dcafb8107453006b905ef697a529c42e76beb3f/src/js/base/core/env.js#L10-L25
train
ramda/ramda
source/applySpec.js
mapValues
function mapValues(fn, obj) { return keys(obj).reduce(function(acc, key) { acc[key] = fn(obj[key]); return acc; }, {}); }
javascript
function mapValues(fn, obj) { return keys(obj).reduce(function(acc, key) { acc[key] = fn(obj[key]); return acc; }, {}); }
[ "function", "mapValues", "(", "fn", ",", "obj", ")", "{", "return", "keys", "(", "obj", ")", ".", "reduce", "(", "function", "(", "acc", ",", "key", ")", "{", "acc", "[", "key", "]", "=", "fn", "(", "obj", "[", "key", "]", ")", ";", "return", "acc", ";", "}", ",", "{", "}", ")", ";", "}" ]
Use custom mapValues function to avoid issues with specs that include a "map" key and R.map delegating calls to .map
[ "Use", "custom", "mapValues", "function", "to", "avoid", "issues", "with", "specs", "that", "include", "a", "map", "key", "and", "R", ".", "map", "delegating", "calls", "to", ".", "map" ]
072d417a345e7087a95466a9825d43b6ca3a4941
https://github.com/ramda/ramda/blob/072d417a345e7087a95466a9825d43b6ca3a4941/source/applySpec.js#L12-L17
train
uikit/uikit
src/js/components/parallax.js
getOffsetElement
function getOffsetElement(el) { return el ? 'offsetTop' in el ? el : getOffsetElement(el.parentNode) : document.body; }
javascript
function getOffsetElement(el) { return el ? 'offsetTop' in el ? el : getOffsetElement(el.parentNode) : document.body; }
[ "function", "getOffsetElement", "(", "el", ")", "{", "return", "el", "?", "'offsetTop'", "in", "el", "?", "el", ":", "getOffsetElement", "(", "el", ".", "parentNode", ")", ":", "document", ".", "body", ";", "}" ]
SVG elements do not inherit from HTMLElement
[ "SVG", "elements", "do", "not", "inherit", "from", "HTMLElement" ]
b7760008135313b6a81f645c750db6f285a89488
https://github.com/uikit/uikit/blob/b7760008135313b6a81f645c750db6f285a89488/src/js/components/parallax.js#L70-L76
train
pagekit/vue-resource
dist/vue-resource.esm.js
root
function root (options$$1, next) { var url = next(options$$1); if (isString(options$$1.root) && !/^(https?:)?\//.test(url)) { url = trimEnd(options$$1.root, '/') + '/' + url; } return url; }
javascript
function root (options$$1, next) { var url = next(options$$1); if (isString(options$$1.root) && !/^(https?:)?\//.test(url)) { url = trimEnd(options$$1.root, '/') + '/' + url; } return url; }
[ "function", "root", "(", "options$$1", ",", "next", ")", "{", "var", "url", "=", "next", "(", "options$$1", ")", ";", "if", "(", "isString", "(", "options$$1", ".", "root", ")", "&&", "!", "/", "^(https?:)?\\/", "/", ".", "test", "(", "url", ")", ")", "{", "url", "=", "trimEnd", "(", "options$$1", ".", "root", ",", "'/'", ")", "+", "'/'", "+", "url", ";", "}", "return", "url", ";", "}" ]
Root Prefix Transform.
[ "Root", "Prefix", "Transform", "." ]
fe268fa1d6053ede5f34aef9a11e1a424a70446c
https://github.com/pagekit/vue-resource/blob/fe268fa1d6053ede5f34aef9a11e1a424a70446c/dist/vue-resource.esm.js#L448-L457
train
pagekit/vue-resource
dist/vue-resource.esm.js
query
function query (options$$1, next) { var urlParams = Object.keys(Url.options.params), query = {}, url = next(options$$1); each(options$$1.params, function (value, key) { if (urlParams.indexOf(key) === -1) { query[key] = value; } }); query = Url.params(query); if (query) { url += (url.indexOf('?') == -1 ? '?' : '&') + query; } return url; }
javascript
function query (options$$1, next) { var urlParams = Object.keys(Url.options.params), query = {}, url = next(options$$1); each(options$$1.params, function (value, key) { if (urlParams.indexOf(key) === -1) { query[key] = value; } }); query = Url.params(query); if (query) { url += (url.indexOf('?') == -1 ? '?' : '&') + query; } return url; }
[ "function", "query", "(", "options$$1", ",", "next", ")", "{", "var", "urlParams", "=", "Object", ".", "keys", "(", "Url", ".", "options", ".", "params", ")", ",", "query", "=", "{", "}", ",", "url", "=", "next", "(", "options$$1", ")", ";", "each", "(", "options$$1", ".", "params", ",", "function", "(", "value", ",", "key", ")", "{", "if", "(", "urlParams", ".", "indexOf", "(", "key", ")", "===", "-", "1", ")", "{", "query", "[", "key", "]", "=", "value", ";", "}", "}", ")", ";", "query", "=", "Url", ".", "params", "(", "query", ")", ";", "if", "(", "query", ")", "{", "url", "+=", "(", "url", ".", "indexOf", "(", "'?'", ")", "==", "-", "1", "?", "'?'", ":", "'&'", ")", "+", "query", ";", "}", "return", "url", ";", "}" ]
Query Parameter Transform.
[ "Query", "Parameter", "Transform", "." ]
fe268fa1d6053ede5f34aef9a11e1a424a70446c
https://github.com/pagekit/vue-resource/blob/fe268fa1d6053ede5f34aef9a11e1a424a70446c/dist/vue-resource.esm.js#L463-L480
train
pagekit/vue-resource
dist/vue-resource.esm.js
form
function form (request) { if (isFormData(request.body)) { request.headers.delete('Content-Type'); } else if (isObject(request.body) && request.emulateJSON) { request.body = Url.params(request.body); request.headers.set('Content-Type', 'application/x-www-form-urlencoded'); } }
javascript
function form (request) { if (isFormData(request.body)) { request.headers.delete('Content-Type'); } else if (isObject(request.body) && request.emulateJSON) { request.body = Url.params(request.body); request.headers.set('Content-Type', 'application/x-www-form-urlencoded'); } }
[ "function", "form", "(", "request", ")", "{", "if", "(", "isFormData", "(", "request", ".", "body", ")", ")", "{", "request", ".", "headers", ".", "delete", "(", "'Content-Type'", ")", ";", "}", "else", "if", "(", "isObject", "(", "request", ".", "body", ")", "&&", "request", ".", "emulateJSON", ")", "{", "request", ".", "body", "=", "Url", ".", "params", "(", "request", ".", "body", ")", ";", "request", ".", "headers", ".", "set", "(", "'Content-Type'", ",", "'application/x-www-form-urlencoded'", ")", ";", "}", "}" ]
Form data Interceptor.
[ "Form", "data", "Interceptor", "." ]
fe268fa1d6053ede5f34aef9a11e1a424a70446c
https://github.com/pagekit/vue-resource/blob/fe268fa1d6053ede5f34aef9a11e1a424a70446c/dist/vue-resource.esm.js#L848-L857
train
pagekit/vue-resource
dist/vue-resource.esm.js
json
function json (request) { var type = request.headers.get('Content-Type') || ''; if (isObject(request.body) && type.indexOf('application/json') === 0) { request.body = JSON.stringify(request.body); } return function (response) { return response.bodyText ? when(response.text(), function (text) { var type = response.headers.get('Content-Type') || ''; if (type.indexOf('application/json') === 0 || isJson(text)) { try { response.body = JSON.parse(text); } catch (e) { response.body = null; } } else { response.body = text; } return response; }) : response; }; }
javascript
function json (request) { var type = request.headers.get('Content-Type') || ''; if (isObject(request.body) && type.indexOf('application/json') === 0) { request.body = JSON.stringify(request.body); } return function (response) { return response.bodyText ? when(response.text(), function (text) { var type = response.headers.get('Content-Type') || ''; if (type.indexOf('application/json') === 0 || isJson(text)) { try { response.body = JSON.parse(text); } catch (e) { response.body = null; } } else { response.body = text; } return response; }) : response; }; }
[ "function", "json", "(", "request", ")", "{", "var", "type", "=", "request", ".", "headers", ".", "get", "(", "'Content-Type'", ")", "||", "''", ";", "if", "(", "isObject", "(", "request", ".", "body", ")", "&&", "type", ".", "indexOf", "(", "'application/json'", ")", "===", "0", ")", "{", "request", ".", "body", "=", "JSON", ".", "stringify", "(", "request", ".", "body", ")", ";", "}", "return", "function", "(", "response", ")", "{", "return", "response", ".", "bodyText", "?", "when", "(", "response", ".", "text", "(", ")", ",", "function", "(", "text", ")", "{", "var", "type", "=", "response", ".", "headers", ".", "get", "(", "'Content-Type'", ")", "||", "''", ";", "if", "(", "type", ".", "indexOf", "(", "'application/json'", ")", "===", "0", "||", "isJson", "(", "text", ")", ")", "{", "try", "{", "response", ".", "body", "=", "JSON", ".", "parse", "(", "text", ")", ";", "}", "catch", "(", "e", ")", "{", "response", ".", "body", "=", "null", ";", "}", "}", "else", "{", "response", ".", "body", "=", "text", ";", "}", "return", "response", ";", "}", ")", ":", "response", ";", "}", ";", "}" ]
JSON Interceptor.
[ "JSON", "Interceptor", "." ]
fe268fa1d6053ede5f34aef9a11e1a424a70446c
https://github.com/pagekit/vue-resource/blob/fe268fa1d6053ede5f34aef9a11e1a424a70446c/dist/vue-resource.esm.js#L863-L894
train
pagekit/vue-resource
dist/vue-resource.esm.js
method
function method (request) { if (request.emulateHTTP && /^(PUT|PATCH|DELETE)$/i.test(request.method)) { request.headers.set('X-HTTP-Method-Override', request.method); request.method = 'POST'; } }
javascript
function method (request) { if (request.emulateHTTP && /^(PUT|PATCH|DELETE)$/i.test(request.method)) { request.headers.set('X-HTTP-Method-Override', request.method); request.method = 'POST'; } }
[ "function", "method", "(", "request", ")", "{", "if", "(", "request", ".", "emulateHTTP", "&&", "/", "^(PUT|PATCH|DELETE)$", "/", "i", ".", "test", "(", "request", ".", "method", ")", ")", "{", "request", ".", "headers", ".", "set", "(", "'X-HTTP-Method-Override'", ",", "request", ".", "method", ")", ";", "request", ".", "method", "=", "'POST'", ";", "}", "}" ]
HTTP method override Interceptor.
[ "HTTP", "method", "override", "Interceptor", "." ]
fe268fa1d6053ede5f34aef9a11e1a424a70446c
https://github.com/pagekit/vue-resource/blob/fe268fa1d6053ede5f34aef9a11e1a424a70446c/dist/vue-resource.esm.js#L986-L993
train
pagekit/vue-resource
dist/vue-resource.esm.js
header
function header (request) { var headers = assign({}, Http.headers.common, !request.crossOrigin ? Http.headers.custom : {}, Http.headers[toLower(request.method)] ); each(headers, function (value, name) { if (!request.headers.has(name)) { request.headers.set(name, value); } }); }
javascript
function header (request) { var headers = assign({}, Http.headers.common, !request.crossOrigin ? Http.headers.custom : {}, Http.headers[toLower(request.method)] ); each(headers, function (value, name) { if (!request.headers.has(name)) { request.headers.set(name, value); } }); }
[ "function", "header", "(", "request", ")", "{", "var", "headers", "=", "assign", "(", "{", "}", ",", "Http", ".", "headers", ".", "common", ",", "!", "request", ".", "crossOrigin", "?", "Http", ".", "headers", ".", "custom", ":", "{", "}", ",", "Http", ".", "headers", "[", "toLower", "(", "request", ".", "method", ")", "]", ")", ";", "each", "(", "headers", ",", "function", "(", "value", ",", "name", ")", "{", "if", "(", "!", "request", ".", "headers", ".", "has", "(", "name", ")", ")", "{", "request", ".", "headers", ".", "set", "(", "name", ",", "value", ")", ";", "}", "}", ")", ";", "}" ]
Header Interceptor.
[ "Header", "Interceptor", "." ]
fe268fa1d6053ede5f34aef9a11e1a424a70446c
https://github.com/pagekit/vue-resource/blob/fe268fa1d6053ede5f34aef9a11e1a424a70446c/dist/vue-resource.esm.js#L999-L1012
train
pagekit/vue-resource
dist/vue-resource.esm.js
Client
function Client (context) { var reqHandlers = [sendRequest], resHandlers = []; if (!isObject(context)) { context = null; } function Client(request) { while (reqHandlers.length) { var handler = reqHandlers.pop(); if (isFunction(handler)) { var response = (void 0), next = (void 0); response = handler.call(context, request, function (val) { return next = val; }) || next; if (isObject(response)) { return new PromiseObj(function (resolve, reject) { resHandlers.forEach(function (handler) { response = when(response, function (response) { return handler.call(context, response) || response; }, reject); }); when(response, resolve, reject); }, context); } if (isFunction(response)) { resHandlers.unshift(response); } } else { warn(("Invalid interceptor of type " + (typeof handler) + ", must be a function")); } } } Client.use = function (handler) { reqHandlers.push(handler); }; return Client; }
javascript
function Client (context) { var reqHandlers = [sendRequest], resHandlers = []; if (!isObject(context)) { context = null; } function Client(request) { while (reqHandlers.length) { var handler = reqHandlers.pop(); if (isFunction(handler)) { var response = (void 0), next = (void 0); response = handler.call(context, request, function (val) { return next = val; }) || next; if (isObject(response)) { return new PromiseObj(function (resolve, reject) { resHandlers.forEach(function (handler) { response = when(response, function (response) { return handler.call(context, response) || response; }, reject); }); when(response, resolve, reject); }, context); } if (isFunction(response)) { resHandlers.unshift(response); } } else { warn(("Invalid interceptor of type " + (typeof handler) + ", must be a function")); } } } Client.use = function (handler) { reqHandlers.push(handler); }; return Client; }
[ "function", "Client", "(", "context", ")", "{", "var", "reqHandlers", "=", "[", "sendRequest", "]", ",", "resHandlers", "=", "[", "]", ";", "if", "(", "!", "isObject", "(", "context", ")", ")", "{", "context", "=", "null", ";", "}", "function", "Client", "(", "request", ")", "{", "while", "(", "reqHandlers", ".", "length", ")", "{", "var", "handler", "=", "reqHandlers", ".", "pop", "(", ")", ";", "if", "(", "isFunction", "(", "handler", ")", ")", "{", "var", "response", "=", "(", "void", "0", ")", ",", "next", "=", "(", "void", "0", ")", ";", "response", "=", "handler", ".", "call", "(", "context", ",", "request", ",", "function", "(", "val", ")", "{", "return", "next", "=", "val", ";", "}", ")", "||", "next", ";", "if", "(", "isObject", "(", "response", ")", ")", "{", "return", "new", "PromiseObj", "(", "function", "(", "resolve", ",", "reject", ")", "{", "resHandlers", ".", "forEach", "(", "function", "(", "handler", ")", "{", "response", "=", "when", "(", "response", ",", "function", "(", "response", ")", "{", "return", "handler", ".", "call", "(", "context", ",", "response", ")", "||", "response", ";", "}", ",", "reject", ")", ";", "}", ")", ";", "when", "(", "response", ",", "resolve", ",", "reject", ")", ";", "}", ",", "context", ")", ";", "}", "if", "(", "isFunction", "(", "response", ")", ")", "{", "resHandlers", ".", "unshift", "(", "response", ")", ";", "}", "}", "else", "{", "warn", "(", "(", "\"Invalid interceptor of type \"", "+", "(", "typeof", "handler", ")", "+", "\", must be a function\"", ")", ")", ";", "}", "}", "}", "Client", ".", "use", "=", "function", "(", "handler", ")", "{", "reqHandlers", ".", "push", "(", "handler", ")", ";", "}", ";", "return", "Client", ";", "}" ]
Base client.
[ "Base", "client", "." ]
fe268fa1d6053ede5f34aef9a11e1a424a70446c
https://github.com/pagekit/vue-resource/blob/fe268fa1d6053ede5f34aef9a11e1a424a70446c/dist/vue-resource.esm.js#L1126-L1174
train
pagekit/vue-resource
dist/vue-resource.esm.js
Headers
function Headers(headers) { var this$1 = this; this.map = {}; each(headers, function (value, name) { return this$1.append(name, value); }); }
javascript
function Headers(headers) { var this$1 = this; this.map = {}; each(headers, function (value, name) { return this$1.append(name, value); }); }
[ "function", "Headers", "(", "headers", ")", "{", "var", "this$1", "=", "this", ";", "this", ".", "map", "=", "{", "}", ";", "each", "(", "headers", ",", "function", "(", "value", ",", "name", ")", "{", "return", "this$1", ".", "append", "(", "name", ",", "value", ")", ";", "}", ")", ";", "}" ]
HTTP Headers.
[ "HTTP", "Headers", "." ]
fe268fa1d6053ede5f34aef9a11e1a424a70446c
https://github.com/pagekit/vue-resource/blob/fe268fa1d6053ede5f34aef9a11e1a424a70446c/dist/vue-resource.esm.js#L1187-L1194
train
pagekit/vue-resource
dist/vue-resource.esm.js
Response
function Response(body, ref) { var url = ref.url; var headers = ref.headers; var status = ref.status; var statusText = ref.statusText; this.url = url; this.ok = status >= 200 && status < 300; this.status = status || 0; this.statusText = statusText || ''; this.headers = new Headers(headers); this.body = body; if (isString(body)) { this.bodyText = body; } else if (isBlob(body)) { this.bodyBlob = body; if (isBlobText(body)) { this.bodyText = blobText(body); } } }
javascript
function Response(body, ref) { var url = ref.url; var headers = ref.headers; var status = ref.status; var statusText = ref.statusText; this.url = url; this.ok = status >= 200 && status < 300; this.status = status || 0; this.statusText = statusText || ''; this.headers = new Headers(headers); this.body = body; if (isString(body)) { this.bodyText = body; } else if (isBlob(body)) { this.bodyBlob = body; if (isBlobText(body)) { this.bodyText = blobText(body); } } }
[ "function", "Response", "(", "body", ",", "ref", ")", "{", "var", "url", "=", "ref", ".", "url", ";", "var", "headers", "=", "ref", ".", "headers", ";", "var", "status", "=", "ref", ".", "status", ";", "var", "statusText", "=", "ref", ".", "statusText", ";", "this", ".", "url", "=", "url", ";", "this", ".", "ok", "=", "status", ">=", "200", "&&", "status", "<", "300", ";", "this", ".", "status", "=", "status", "||", "0", ";", "this", ".", "statusText", "=", "statusText", "||", "''", ";", "this", ".", "headers", "=", "new", "Headers", "(", "headers", ")", ";", "this", ".", "body", "=", "body", ";", "if", "(", "isString", "(", "body", ")", ")", "{", "this", ".", "bodyText", "=", "body", ";", "}", "else", "if", "(", "isBlob", "(", "body", ")", ")", "{", "this", ".", "bodyBlob", "=", "body", ";", "if", "(", "isBlobText", "(", "body", ")", ")", "{", "this", ".", "bodyText", "=", "blobText", "(", "body", ")", ";", "}", "}", "}" ]
HTTP Response.
[ "HTTP", "Response", "." ]
fe268fa1d6053ede5f34aef9a11e1a424a70446c
https://github.com/pagekit/vue-resource/blob/fe268fa1d6053ede5f34aef9a11e1a424a70446c/dist/vue-resource.esm.js#L1261-L1287
train
pagekit/vue-resource
dist/vue-resource.esm.js
Request
function Request(options$$1) { this.body = null; this.params = {}; assign(this, options$$1, { method: toUpper(options$$1.method || 'GET') }); if (!(this.headers instanceof Headers)) { this.headers = new Headers(this.headers); } }
javascript
function Request(options$$1) { this.body = null; this.params = {}; assign(this, options$$1, { method: toUpper(options$$1.method || 'GET') }); if (!(this.headers instanceof Headers)) { this.headers = new Headers(this.headers); } }
[ "function", "Request", "(", "options$$1", ")", "{", "this", ".", "body", "=", "null", ";", "this", ".", "params", "=", "{", "}", ";", "assign", "(", "this", ",", "options$$1", ",", "{", "method", ":", "toUpper", "(", "options$$1", ".", "method", "||", "'GET'", ")", "}", ")", ";", "if", "(", "!", "(", "this", ".", "headers", "instanceof", "Headers", ")", ")", "{", "this", ".", "headers", "=", "new", "Headers", "(", "this", ".", "headers", ")", ";", "}", "}" ]
HTTP Request.
[ "HTTP", "Request", "." ]
fe268fa1d6053ede5f34aef9a11e1a424a70446c
https://github.com/pagekit/vue-resource/blob/fe268fa1d6053ede5f34aef9a11e1a424a70446c/dist/vue-resource.esm.js#L1334-L1346
train
pagekit/vue-resource
dist/vue-resource.esm.js
Resource
function Resource(url, params, actions, options$$1) { var self = this || {}, resource = {}; actions = assign({}, Resource.actions, actions ); each(actions, function (action, name) { action = merge({url: url, params: assign({}, params)}, options$$1, action); resource[name] = function () { return (self.$http || Http)(opts(action, arguments)); }; }); return resource; }
javascript
function Resource(url, params, actions, options$$1) { var self = this || {}, resource = {}; actions = assign({}, Resource.actions, actions ); each(actions, function (action, name) { action = merge({url: url, params: assign({}, params)}, options$$1, action); resource[name] = function () { return (self.$http || Http)(opts(action, arguments)); }; }); return resource; }
[ "function", "Resource", "(", "url", ",", "params", ",", "actions", ",", "options$$1", ")", "{", "var", "self", "=", "this", "||", "{", "}", ",", "resource", "=", "{", "}", ";", "actions", "=", "assign", "(", "{", "}", ",", "Resource", ".", "actions", ",", "actions", ")", ";", "each", "(", "actions", ",", "function", "(", "action", ",", "name", ")", "{", "action", "=", "merge", "(", "{", "url", ":", "url", ",", "params", ":", "assign", "(", "{", "}", ",", "params", ")", "}", ",", "options$$1", ",", "action", ")", ";", "resource", "[", "name", "]", "=", "function", "(", ")", "{", "return", "(", "self", ".", "$http", "||", "Http", ")", "(", "opts", "(", "action", ",", "arguments", ")", ")", ";", "}", ";", "}", ")", ";", "return", "resource", ";", "}" ]
Service for interacting with RESTful services.
[ "Service", "for", "interacting", "with", "RESTful", "services", "." ]
fe268fa1d6053ede5f34aef9a11e1a424a70446c
https://github.com/pagekit/vue-resource/blob/fe268fa1d6053ede5f34aef9a11e1a424a70446c/dist/vue-resource.esm.js#L1433-L1452
train
pagekit/vue-resource
dist/vue-resource.esm.js
plugin
function plugin(Vue) { if (plugin.installed) { return; } Util(Vue); Vue.url = Url; Vue.http = Http; Vue.resource = Resource; Vue.Promise = PromiseObj; Object.defineProperties(Vue.prototype, { $url: { get: function get() { return options(Vue.url, this, this.$options.url); } }, $http: { get: function get() { return options(Vue.http, this, this.$options.http); } }, $resource: { get: function get() { return Vue.resource.bind(this); } }, $promise: { get: function get() { var this$1 = this; return function (executor) { return new Vue.Promise(executor, this$1); }; } } }); }
javascript
function plugin(Vue) { if (plugin.installed) { return; } Util(Vue); Vue.url = Url; Vue.http = Http; Vue.resource = Resource; Vue.Promise = PromiseObj; Object.defineProperties(Vue.prototype, { $url: { get: function get() { return options(Vue.url, this, this.$options.url); } }, $http: { get: function get() { return options(Vue.http, this, this.$options.http); } }, $resource: { get: function get() { return Vue.resource.bind(this); } }, $promise: { get: function get() { var this$1 = this; return function (executor) { return new Vue.Promise(executor, this$1); }; } } }); }
[ "function", "plugin", "(", "Vue", ")", "{", "if", "(", "plugin", ".", "installed", ")", "{", "return", ";", "}", "Util", "(", "Vue", ")", ";", "Vue", ".", "url", "=", "Url", ";", "Vue", ".", "http", "=", "Http", ";", "Vue", ".", "resource", "=", "Resource", ";", "Vue", ".", "Promise", "=", "PromiseObj", ";", "Object", ".", "defineProperties", "(", "Vue", ".", "prototype", ",", "{", "$url", ":", "{", "get", ":", "function", "get", "(", ")", "{", "return", "options", "(", "Vue", ".", "url", ",", "this", ",", "this", ".", "$options", ".", "url", ")", ";", "}", "}", ",", "$http", ":", "{", "get", ":", "function", "get", "(", ")", "{", "return", "options", "(", "Vue", ".", "http", ",", "this", ",", "this", ".", "$options", ".", "http", ")", ";", "}", "}", ",", "$resource", ":", "{", "get", ":", "function", "get", "(", ")", "{", "return", "Vue", ".", "resource", ".", "bind", "(", "this", ")", ";", "}", "}", ",", "$promise", ":", "{", "get", ":", "function", "get", "(", ")", "{", "var", "this$1", "=", "this", ";", "return", "function", "(", "executor", ")", "{", "return", "new", "Vue", ".", "Promise", "(", "executor", ",", "this$1", ")", ";", "}", ";", "}", "}", "}", ")", ";", "}" ]
Install plugin.
[ "Install", "plugin", "." ]
fe268fa1d6053ede5f34aef9a11e1a424a70446c
https://github.com/pagekit/vue-resource/blob/fe268fa1d6053ede5f34aef9a11e1a424a70446c/dist/vue-resource.esm.js#L1507-L1549
train
kriasoft/react-starter-kit
src/client.js
onLocationChange
async function onLocationChange(location, action) { // Remember the latest scroll position for the previous location scrollPositionsHistory[currentLocation.key] = { scrollX: window.pageXOffset, scrollY: window.pageYOffset, }; // Delete stored scroll position for next page if any if (action === 'PUSH') { delete scrollPositionsHistory[location.key]; } currentLocation = location; const isInitialRender = !action; try { context.pathname = location.pathname; context.query = queryString.parse(location.search); // Traverses the list of routes in the order they are defined until // it finds the first route that matches provided URL path string // and whose action method returns anything other than `undefined`. const route = await router.resolve(context); // Prevent multiple page renders during the routing process if (currentLocation.key !== location.key) { return; } if (route.redirect) { history.replace(route.redirect); return; } const renderReactApp = isInitialRender ? ReactDOM.hydrate : ReactDOM.render; appInstance = renderReactApp( <App context={context}>{route.component}</App>, container, () => { if (isInitialRender) { // Switch off the native scroll restoration behavior and handle it manually // https://developers.google.com/web/updates/2015/09/history-api-scroll-restoration if (window.history && 'scrollRestoration' in window.history) { window.history.scrollRestoration = 'manual'; } const elem = document.getElementById('css'); if (elem) elem.parentNode.removeChild(elem); return; } document.title = route.title; updateMeta('description', route.description); // Update necessary tags in <head> at runtime here, ie: // updateMeta('keywords', route.keywords); // updateCustomMeta('og:url', route.canonicalUrl); // updateCustomMeta('og:image', route.imageUrl); // updateLink('canonical', route.canonicalUrl); // etc. let scrollX = 0; let scrollY = 0; const pos = scrollPositionsHistory[location.key]; if (pos) { scrollX = pos.scrollX; scrollY = pos.scrollY; } else { const targetHash = location.hash.substr(1); if (targetHash) { const target = document.getElementById(targetHash); if (target) { scrollY = window.pageYOffset + target.getBoundingClientRect().top; } } } // Restore the scroll position if it was saved into the state // or scroll to the given #hash anchor // or scroll to top of the page window.scrollTo(scrollX, scrollY); // Google Analytics tracking. Don't send 'pageview' event after // the initial rendering, as it was already sent if (window.ga) { window.ga('send', 'pageview', createPath(location)); } }, ); } catch (error) { if (__DEV__) { throw error; } console.error(error); // Do a full page reload if error occurs during client-side navigation if (!isInitialRender && currentLocation.key === location.key) { console.error('RSK will reload your page after error'); window.location.reload(); } } }
javascript
async function onLocationChange(location, action) { // Remember the latest scroll position for the previous location scrollPositionsHistory[currentLocation.key] = { scrollX: window.pageXOffset, scrollY: window.pageYOffset, }; // Delete stored scroll position for next page if any if (action === 'PUSH') { delete scrollPositionsHistory[location.key]; } currentLocation = location; const isInitialRender = !action; try { context.pathname = location.pathname; context.query = queryString.parse(location.search); // Traverses the list of routes in the order they are defined until // it finds the first route that matches provided URL path string // and whose action method returns anything other than `undefined`. const route = await router.resolve(context); // Prevent multiple page renders during the routing process if (currentLocation.key !== location.key) { return; } if (route.redirect) { history.replace(route.redirect); return; } const renderReactApp = isInitialRender ? ReactDOM.hydrate : ReactDOM.render; appInstance = renderReactApp( <App context={context}>{route.component}</App>, container, () => { if (isInitialRender) { // Switch off the native scroll restoration behavior and handle it manually // https://developers.google.com/web/updates/2015/09/history-api-scroll-restoration if (window.history && 'scrollRestoration' in window.history) { window.history.scrollRestoration = 'manual'; } const elem = document.getElementById('css'); if (elem) elem.parentNode.removeChild(elem); return; } document.title = route.title; updateMeta('description', route.description); // Update necessary tags in <head> at runtime here, ie: // updateMeta('keywords', route.keywords); // updateCustomMeta('og:url', route.canonicalUrl); // updateCustomMeta('og:image', route.imageUrl); // updateLink('canonical', route.canonicalUrl); // etc. let scrollX = 0; let scrollY = 0; const pos = scrollPositionsHistory[location.key]; if (pos) { scrollX = pos.scrollX; scrollY = pos.scrollY; } else { const targetHash = location.hash.substr(1); if (targetHash) { const target = document.getElementById(targetHash); if (target) { scrollY = window.pageYOffset + target.getBoundingClientRect().top; } } } // Restore the scroll position if it was saved into the state // or scroll to the given #hash anchor // or scroll to top of the page window.scrollTo(scrollX, scrollY); // Google Analytics tracking. Don't send 'pageview' event after // the initial rendering, as it was already sent if (window.ga) { window.ga('send', 'pageview', createPath(location)); } }, ); } catch (error) { if (__DEV__) { throw error; } console.error(error); // Do a full page reload if error occurs during client-side navigation if (!isInitialRender && currentLocation.key === location.key) { console.error('RSK will reload your page after error'); window.location.reload(); } } }
[ "async", "function", "onLocationChange", "(", "location", ",", "action", ")", "{", "scrollPositionsHistory", "[", "currentLocation", ".", "key", "]", "=", "{", "scrollX", ":", "window", ".", "pageXOffset", ",", "scrollY", ":", "window", ".", "pageYOffset", ",", "}", ";", "if", "(", "action", "===", "'PUSH'", ")", "{", "delete", "scrollPositionsHistory", "[", "location", ".", "key", "]", ";", "}", "currentLocation", "=", "location", ";", "const", "isInitialRender", "=", "!", "action", ";", "try", "{", "context", ".", "pathname", "=", "location", ".", "pathname", ";", "context", ".", "query", "=", "queryString", ".", "parse", "(", "location", ".", "search", ")", ";", "const", "route", "=", "await", "router", ".", "resolve", "(", "context", ")", ";", "if", "(", "currentLocation", ".", "key", "!==", "location", ".", "key", ")", "{", "return", ";", "}", "if", "(", "route", ".", "redirect", ")", "{", "history", ".", "replace", "(", "route", ".", "redirect", ")", ";", "return", ";", "}", "const", "renderReactApp", "=", "isInitialRender", "?", "ReactDOM", ".", "hydrate", ":", "ReactDOM", ".", "render", ";", "appInstance", "=", "renderReactApp", "(", "<", "App", "context", "=", "{", "context", "}", ">", "{", "route", ".", "component", "}", "<", "/", "App", ">", ",", "container", ",", "(", ")", "=>", "{", "if", "(", "isInitialRender", ")", "{", "if", "(", "window", ".", "history", "&&", "'scrollRestoration'", "in", "window", ".", "history", ")", "{", "window", ".", "history", ".", "scrollRestoration", "=", "'manual'", ";", "}", "const", "elem", "=", "document", ".", "getElementById", "(", "'css'", ")", ";", "if", "(", "elem", ")", "elem", ".", "parentNode", ".", "removeChild", "(", "elem", ")", ";", "return", ";", "}", "document", ".", "title", "=", "route", ".", "title", ";", "updateMeta", "(", "'description'", ",", "route", ".", "description", ")", ";", "let", "scrollX", "=", "0", ";", "let", "scrollY", "=", "0", ";", "const", "pos", "=", "scrollPositionsHistory", "[", "location", ".", "key", "]", ";", "if", "(", "pos", ")", "{", "scrollX", "=", "pos", ".", "scrollX", ";", "scrollY", "=", "pos", ".", "scrollY", ";", "}", "else", "{", "const", "targetHash", "=", "location", ".", "hash", ".", "substr", "(", "1", ")", ";", "if", "(", "targetHash", ")", "{", "const", "target", "=", "document", ".", "getElementById", "(", "targetHash", ")", ";", "if", "(", "target", ")", "{", "scrollY", "=", "window", ".", "pageYOffset", "+", "target", ".", "getBoundingClientRect", "(", ")", ".", "top", ";", "}", "}", "}", "window", ".", "scrollTo", "(", "scrollX", ",", "scrollY", ")", ";", "if", "(", "window", ".", "ga", ")", "{", "window", ".", "ga", "(", "'send'", ",", "'pageview'", ",", "createPath", "(", "location", ")", ")", ";", "}", "}", ",", ")", ";", "}", "catch", "(", "error", ")", "{", "if", "(", "__DEV__", ")", "{", "throw", "error", ";", "}", "console", ".", "error", "(", "error", ")", ";", "if", "(", "!", "isInitialRender", "&&", "currentLocation", ".", "key", "===", "location", ".", "key", ")", "{", "console", ".", "error", "(", "'RSK will reload your page after error'", ")", ";", "window", ".", "location", ".", "reload", "(", ")", ";", "}", "}", "}" ]
Re-render the app when window.location changes
[ "Re", "-", "render", "the", "app", "when", "window", ".", "location", "changes" ]
8d6c018f3198dec2a580ecafb011a32f06e38dbf
https://github.com/kriasoft/react-starter-kit/blob/8d6c018f3198dec2a580ecafb011a32f06e38dbf/src/client.js#L47-L147
train
bokeh/bokeh
examples/custom/gears/gear_utils.js
involuteXbez
function involuteXbez(t) { // map t (0 <= t <= 1) onto x (where -1 <= x <= 1) var x = t*2-1; //map theta (where ts <= theta <= te) from x (-1 <=x <= 1) var theta = x*(te-ts)/2 + (ts + te)/2; return Rb*(Math.cos(theta)+theta*Math.sin(theta)); }
javascript
function involuteXbez(t) { // map t (0 <= t <= 1) onto x (where -1 <= x <= 1) var x = t*2-1; //map theta (where ts <= theta <= te) from x (-1 <=x <= 1) var theta = x*(te-ts)/2 + (ts + te)/2; return Rb*(Math.cos(theta)+theta*Math.sin(theta)); }
[ "function", "involuteXbez", "(", "t", ")", "{", "var", "x", "=", "t", "*", "2", "-", "1", ";", "var", "theta", "=", "x", "*", "(", "te", "-", "ts", ")", "/", "2", "+", "(", "ts", "+", "te", ")", "/", "2", ";", "return", "Rb", "*", "(", "Math", ".", "cos", "(", "theta", ")", "+", "theta", "*", "Math", ".", "sin", "(", "theta", ")", ")", ";", "}" ]
Equation of involute using the Bezier parameter t as variable
[ "Equation", "of", "involute", "using", "the", "Bezier", "parameter", "t", "as", "variable" ]
c3a9d4d5ab5662ea34813fd72de50e1bdaae714d
https://github.com/bokeh/bokeh/blob/c3a9d4d5ab5662ea34813fd72de50e1bdaae714d/examples/custom/gears/gear_utils.js#L128-L135
train