repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
sequence
docstring
stringlengths
4
11.8k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
86
226
partition
stringclasses
1 value
recharts/recharts-scale
src/getNiceTickValues.js
getTickOfSingleValue
function getTickOfSingleValue(value, tickCount, allowDecimals) { let step = 1; // calculate the middle value of ticks let middle = new Decimal(value); if (!middle.isint() && allowDecimals) { const absVal = Math.abs(value); if (absVal < 1) { // The step should be a float number when the difference is smaller than 1 step = new Decimal(10).pow(Arithmetic.getDigitCount(value) - 1); middle = new Decimal(Math.floor(middle.div(step).toNumber())).mul(step); } else if (absVal > 1) { // Return the maximum integer which is smaller than 'value' when 'value' is greater than 1 middle = new Decimal(Math.floor(value)); } } else if (value === 0) { middle = new Decimal(Math.floor((tickCount - 1) / 2)); } else if (!allowDecimals) { middle = new Decimal(Math.floor(value)); } const middleIndex = Math.floor((tickCount - 1) / 2); const fn = compose( map(n => middle.add(new Decimal(n - middleIndex).mul(step)).toNumber()), range, ); return fn(0, tickCount); }
javascript
function getTickOfSingleValue(value, tickCount, allowDecimals) { let step = 1; // calculate the middle value of ticks let middle = new Decimal(value); if (!middle.isint() && allowDecimals) { const absVal = Math.abs(value); if (absVal < 1) { // The step should be a float number when the difference is smaller than 1 step = new Decimal(10).pow(Arithmetic.getDigitCount(value) - 1); middle = new Decimal(Math.floor(middle.div(step).toNumber())).mul(step); } else if (absVal > 1) { // Return the maximum integer which is smaller than 'value' when 'value' is greater than 1 middle = new Decimal(Math.floor(value)); } } else if (value === 0) { middle = new Decimal(Math.floor((tickCount - 1) / 2)); } else if (!allowDecimals) { middle = new Decimal(Math.floor(value)); } const middleIndex = Math.floor((tickCount - 1) / 2); const fn = compose( map(n => middle.add(new Decimal(n - middleIndex).mul(step)).toNumber()), range, ); return fn(0, tickCount); }
[ "function", "getTickOfSingleValue", "(", "value", ",", "tickCount", ",", "allowDecimals", ")", "{", "let", "step", "=", "1", ";", "let", "middle", "=", "new", "Decimal", "(", "value", ")", ";", "if", "(", "!", "middle", ".", "isint", "(", ")", "&&", "allowDecimals", ")", "{", "const", "absVal", "=", "Math", ".", "abs", "(", "value", ")", ";", "if", "(", "absVal", "<", "1", ")", "{", "step", "=", "new", "Decimal", "(", "10", ")", ".", "pow", "(", "Arithmetic", ".", "getDigitCount", "(", "value", ")", "-", "1", ")", ";", "middle", "=", "new", "Decimal", "(", "Math", ".", "floor", "(", "middle", ".", "div", "(", "step", ")", ".", "toNumber", "(", ")", ")", ")", ".", "mul", "(", "step", ")", ";", "}", "else", "if", "(", "absVal", ">", "1", ")", "{", "middle", "=", "new", "Decimal", "(", "Math", ".", "floor", "(", "value", ")", ")", ";", "}", "}", "else", "if", "(", "value", "===", "0", ")", "{", "middle", "=", "new", "Decimal", "(", "Math", ".", "floor", "(", "(", "tickCount", "-", "1", ")", "/", "2", ")", ")", ";", "}", "else", "if", "(", "!", "allowDecimals", ")", "{", "middle", "=", "new", "Decimal", "(", "Math", ".", "floor", "(", "value", ")", ")", ";", "}", "const", "middleIndex", "=", "Math", ".", "floor", "(", "(", "tickCount", "-", "1", ")", "/", "2", ")", ";", "const", "fn", "=", "compose", "(", "map", "(", "n", "=>", "middle", ".", "add", "(", "new", "Decimal", "(", "n", "-", "middleIndex", ")", ".", "mul", "(", "step", ")", ")", ".", "toNumber", "(", ")", ")", ",", "range", ",", ")", ";", "return", "fn", "(", "0", ",", "tickCount", ")", ";", "}" ]
calculate the ticks when the minimum value equals to the maximum value @param {Number} value The minimum valuue which is also the maximum value @param {Integer} tickCount The count of ticks @param {Boolean} allowDecimals Allow the ticks to be decimals or not @return {Array} ticks
[ "calculate", "the", "ticks", "when", "the", "minimum", "value", "equals", "to", "the", "maximum", "value" ]
8fdf6d32d24cdabf6da75f1cd9d0a3e33336dc2a
https://github.com/recharts/recharts-scale/blob/8fdf6d32d24cdabf6da75f1cd9d0a3e33336dc2a/src/getNiceTickValues.js#L66-L97
train
recharts/recharts-scale
src/getNiceTickValues.js
calculateStep
function calculateStep(min, max, tickCount, allowDecimals, correctionFactor = 0) { // dirty hack (for recharts' test) if (!Number.isFinite((max - min) / (tickCount - 1))) { return { step: new Decimal(0), tickMin: new Decimal(0), tickMax: new Decimal(0), }; } // The step which is easy to understand between two ticks const step = getFormatStep( new Decimal(max).sub(min).div(tickCount - 1), allowDecimals, correctionFactor, ); // A medial value of ticks let middle; // When 0 is inside the interval, 0 should be a tick if (min <= 0 && max >= 0) { middle = new Decimal(0); } else { // calculate the middle value middle = new Decimal(min).add(max).div(2); // minus modulo value middle = middle.sub(new Decimal(middle).mod(step)); } let belowCount = Math.ceil(middle.sub(min).div(step).toNumber()); let upCount = Math.ceil(new Decimal(max).sub(middle).div(step) .toNumber()); const scaleCount = belowCount + upCount + 1; if (scaleCount > tickCount) { // When more ticks need to cover the interval, step should be bigger. return calculateStep(min, max, tickCount, allowDecimals, correctionFactor + 1); } if (scaleCount < tickCount) { // When less ticks can cover the interval, we should add some additional ticks upCount = max > 0 ? upCount + (tickCount - scaleCount) : upCount; belowCount = max > 0 ? belowCount : belowCount + (tickCount - scaleCount); } return { step, tickMin: middle.sub(new Decimal(belowCount).mul(step)), tickMax: middle.add(new Decimal(upCount).mul(step)), }; }
javascript
function calculateStep(min, max, tickCount, allowDecimals, correctionFactor = 0) { // dirty hack (for recharts' test) if (!Number.isFinite((max - min) / (tickCount - 1))) { return { step: new Decimal(0), tickMin: new Decimal(0), tickMax: new Decimal(0), }; } // The step which is easy to understand between two ticks const step = getFormatStep( new Decimal(max).sub(min).div(tickCount - 1), allowDecimals, correctionFactor, ); // A medial value of ticks let middle; // When 0 is inside the interval, 0 should be a tick if (min <= 0 && max >= 0) { middle = new Decimal(0); } else { // calculate the middle value middle = new Decimal(min).add(max).div(2); // minus modulo value middle = middle.sub(new Decimal(middle).mod(step)); } let belowCount = Math.ceil(middle.sub(min).div(step).toNumber()); let upCount = Math.ceil(new Decimal(max).sub(middle).div(step) .toNumber()); const scaleCount = belowCount + upCount + 1; if (scaleCount > tickCount) { // When more ticks need to cover the interval, step should be bigger. return calculateStep(min, max, tickCount, allowDecimals, correctionFactor + 1); } if (scaleCount < tickCount) { // When less ticks can cover the interval, we should add some additional ticks upCount = max > 0 ? upCount + (tickCount - scaleCount) : upCount; belowCount = max > 0 ? belowCount : belowCount + (tickCount - scaleCount); } return { step, tickMin: middle.sub(new Decimal(belowCount).mul(step)), tickMax: middle.add(new Decimal(upCount).mul(step)), }; }
[ "function", "calculateStep", "(", "min", ",", "max", ",", "tickCount", ",", "allowDecimals", ",", "correctionFactor", "=", "0", ")", "{", "if", "(", "!", "Number", ".", "isFinite", "(", "(", "max", "-", "min", ")", "/", "(", "tickCount", "-", "1", ")", ")", ")", "{", "return", "{", "step", ":", "new", "Decimal", "(", "0", ")", ",", "tickMin", ":", "new", "Decimal", "(", "0", ")", ",", "tickMax", ":", "new", "Decimal", "(", "0", ")", ",", "}", ";", "}", "const", "step", "=", "getFormatStep", "(", "new", "Decimal", "(", "max", ")", ".", "sub", "(", "min", ")", ".", "div", "(", "tickCount", "-", "1", ")", ",", "allowDecimals", ",", "correctionFactor", ",", ")", ";", "let", "middle", ";", "if", "(", "min", "<=", "0", "&&", "max", ">=", "0", ")", "{", "middle", "=", "new", "Decimal", "(", "0", ")", ";", "}", "else", "{", "middle", "=", "new", "Decimal", "(", "min", ")", ".", "add", "(", "max", ")", ".", "div", "(", "2", ")", ";", "middle", "=", "middle", ".", "sub", "(", "new", "Decimal", "(", "middle", ")", ".", "mod", "(", "step", ")", ")", ";", "}", "let", "belowCount", "=", "Math", ".", "ceil", "(", "middle", ".", "sub", "(", "min", ")", ".", "div", "(", "step", ")", ".", "toNumber", "(", ")", ")", ";", "let", "upCount", "=", "Math", ".", "ceil", "(", "new", "Decimal", "(", "max", ")", ".", "sub", "(", "middle", ")", ".", "div", "(", "step", ")", ".", "toNumber", "(", ")", ")", ";", "const", "scaleCount", "=", "belowCount", "+", "upCount", "+", "1", ";", "if", "(", "scaleCount", ">", "tickCount", ")", "{", "return", "calculateStep", "(", "min", ",", "max", ",", "tickCount", ",", "allowDecimals", ",", "correctionFactor", "+", "1", ")", ";", "}", "if", "(", "scaleCount", "<", "tickCount", ")", "{", "upCount", "=", "max", ">", "0", "?", "upCount", "+", "(", "tickCount", "-", "scaleCount", ")", ":", "upCount", ";", "belowCount", "=", "max", ">", "0", "?", "belowCount", ":", "belowCount", "+", "(", "tickCount", "-", "scaleCount", ")", ";", "}", "return", "{", "step", ",", "tickMin", ":", "middle", ".", "sub", "(", "new", "Decimal", "(", "belowCount", ")", ".", "mul", "(", "step", ")", ")", ",", "tickMax", ":", "middle", ".", "add", "(", "new", "Decimal", "(", "upCount", ")", ".", "mul", "(", "step", ")", ")", ",", "}", ";", "}" ]
Calculate the step @param {Number} min The minimum value of an interval @param {Number} max The maximum value of an interval @param {Integer} tickCount The count of ticks @param {Boolean} allowDecimals Allow the ticks to be decimals or not @param {Number} correctionFactor A correction factor @return {Object} The step, minimum value of ticks, maximum value of ticks
[ "Calculate", "the", "step" ]
8fdf6d32d24cdabf6da75f1cd9d0a3e33336dc2a
https://github.com/recharts/recharts-scale/blob/8fdf6d32d24cdabf6da75f1cd9d0a3e33336dc2a/src/getNiceTickValues.js#L109-L158
train
recharts/recharts-scale
src/getNiceTickValues.js
getNiceTickValuesFn
function getNiceTickValuesFn([min, max], tickCount = 6, allowDecimals = true) { // More than two ticks should be return const count = Math.max(tickCount, 2); const [cormin, cormax] = getValidInterval([min, max]); if (cormin === -Infinity || cormax === Infinity) { const values = cormax === Infinity ? [cormin, ...range(0, tickCount - 1).map(() => Infinity)] : [...range(0, tickCount - 1).map(() => -Infinity), cormax]; return min > max ? reverse(values) : values; } if (cormin === cormax) { return getTickOfSingleValue(cormin, tickCount, allowDecimals); } // Get the step between two ticks const { step, tickMin, tickMax } = calculateStep(cormin, cormax, count, allowDecimals); const values = Arithmetic.rangeStep(tickMin, tickMax.add(new Decimal(0.1).mul(step)), step); return min > max ? reverse(values) : values; }
javascript
function getNiceTickValuesFn([min, max], tickCount = 6, allowDecimals = true) { // More than two ticks should be return const count = Math.max(tickCount, 2); const [cormin, cormax] = getValidInterval([min, max]); if (cormin === -Infinity || cormax === Infinity) { const values = cormax === Infinity ? [cormin, ...range(0, tickCount - 1).map(() => Infinity)] : [...range(0, tickCount - 1).map(() => -Infinity), cormax]; return min > max ? reverse(values) : values; } if (cormin === cormax) { return getTickOfSingleValue(cormin, tickCount, allowDecimals); } // Get the step between two ticks const { step, tickMin, tickMax } = calculateStep(cormin, cormax, count, allowDecimals); const values = Arithmetic.rangeStep(tickMin, tickMax.add(new Decimal(0.1).mul(step)), step); return min > max ? reverse(values) : values; }
[ "function", "getNiceTickValuesFn", "(", "[", "min", ",", "max", "]", ",", "tickCount", "=", "6", ",", "allowDecimals", "=", "true", ")", "{", "const", "count", "=", "Math", ".", "max", "(", "tickCount", ",", "2", ")", ";", "const", "[", "cormin", ",", "cormax", "]", "=", "getValidInterval", "(", "[", "min", ",", "max", "]", ")", ";", "if", "(", "cormin", "===", "-", "Infinity", "||", "cormax", "===", "Infinity", ")", "{", "const", "values", "=", "cormax", "===", "Infinity", "?", "[", "cormin", ",", "...", "range", "(", "0", ",", "tickCount", "-", "1", ")", ".", "map", "(", "(", ")", "=>", "Infinity", ")", "]", ":", "[", "...", "range", "(", "0", ",", "tickCount", "-", "1", ")", ".", "map", "(", "(", ")", "=>", "-", "Infinity", ")", ",", "cormax", "]", ";", "return", "min", ">", "max", "?", "reverse", "(", "values", ")", ":", "values", ";", "}", "if", "(", "cormin", "===", "cormax", ")", "{", "return", "getTickOfSingleValue", "(", "cormin", ",", "tickCount", ",", "allowDecimals", ")", ";", "}", "const", "{", "step", ",", "tickMin", ",", "tickMax", "}", "=", "calculateStep", "(", "cormin", ",", "cormax", ",", "count", ",", "allowDecimals", ")", ";", "const", "values", "=", "Arithmetic", ".", "rangeStep", "(", "tickMin", ",", "tickMax", ".", "add", "(", "new", "Decimal", "(", "0.1", ")", ".", "mul", "(", "step", ")", ")", ",", "step", ")", ";", "return", "min", ">", "max", "?", "reverse", "(", "values", ")", ":", "values", ";", "}" ]
Calculate the ticks of an interval, the count of ticks will be guraranteed @param {Number} min, max min: The minimum value, max: The maximum value @param {Integer} tickCount The count of ticks @param {Boolean} allowDecimals Allow the ticks to be decimals or not @return {Array} ticks
[ "Calculate", "the", "ticks", "of", "an", "interval", "the", "count", "of", "ticks", "will", "be", "guraranteed" ]
8fdf6d32d24cdabf6da75f1cd9d0a3e33336dc2a
https://github.com/recharts/recharts-scale/blob/8fdf6d32d24cdabf6da75f1cd9d0a3e33336dc2a/src/getNiceTickValues.js#L167-L190
train
recharts/recharts-scale
src/getNiceTickValues.js
getTickValuesFn
function getTickValuesFn([min, max], tickCount = 6, allowDecimals = true) { // More than two ticks should be return const count = Math.max(tickCount, 2); const [cormin, cormax] = getValidInterval([min, max]); if (cormin === -Infinity || cormax === Infinity) { return [min, max]; } if (cormin === cormax) { return getTickOfSingleValue(cormin, tickCount, allowDecimals); } const step = getFormatStep(new Decimal(cormax).sub(cormin).div(count - 1), allowDecimals, 0); const fn = compose( map(n => new Decimal(cormin).add(new Decimal(n).mul(step)).toNumber()), range, ); const values = fn(0, count).filter(entry => (entry >= cormin && entry <= cormax)); return min > max ? reverse(values) : values; }
javascript
function getTickValuesFn([min, max], tickCount = 6, allowDecimals = true) { // More than two ticks should be return const count = Math.max(tickCount, 2); const [cormin, cormax] = getValidInterval([min, max]); if (cormin === -Infinity || cormax === Infinity) { return [min, max]; } if (cormin === cormax) { return getTickOfSingleValue(cormin, tickCount, allowDecimals); } const step = getFormatStep(new Decimal(cormax).sub(cormin).div(count - 1), allowDecimals, 0); const fn = compose( map(n => new Decimal(cormin).add(new Decimal(n).mul(step)).toNumber()), range, ); const values = fn(0, count).filter(entry => (entry >= cormin && entry <= cormax)); return min > max ? reverse(values) : values; }
[ "function", "getTickValuesFn", "(", "[", "min", ",", "max", "]", ",", "tickCount", "=", "6", ",", "allowDecimals", "=", "true", ")", "{", "const", "count", "=", "Math", ".", "max", "(", "tickCount", ",", "2", ")", ";", "const", "[", "cormin", ",", "cormax", "]", "=", "getValidInterval", "(", "[", "min", ",", "max", "]", ")", ";", "if", "(", "cormin", "===", "-", "Infinity", "||", "cormax", "===", "Infinity", ")", "{", "return", "[", "min", ",", "max", "]", ";", "}", "if", "(", "cormin", "===", "cormax", ")", "{", "return", "getTickOfSingleValue", "(", "cormin", ",", "tickCount", ",", "allowDecimals", ")", ";", "}", "const", "step", "=", "getFormatStep", "(", "new", "Decimal", "(", "cormax", ")", ".", "sub", "(", "cormin", ")", ".", "div", "(", "count", "-", "1", ")", ",", "allowDecimals", ",", "0", ")", ";", "const", "fn", "=", "compose", "(", "map", "(", "n", "=>", "new", "Decimal", "(", "cormin", ")", ".", "add", "(", "new", "Decimal", "(", "n", ")", ".", "mul", "(", "step", ")", ")", ".", "toNumber", "(", ")", ")", ",", "range", ",", ")", ";", "const", "values", "=", "fn", "(", "0", ",", "count", ")", ".", "filter", "(", "entry", "=>", "(", "entry", ">=", "cormin", "&&", "entry", "<=", "cormax", ")", ")", ";", "return", "min", ">", "max", "?", "reverse", "(", "values", ")", ":", "values", ";", "}" ]
Calculate the ticks of an interval, the count of ticks won't be guraranteed @param {Number} min, max min: The minimum value, max: The maximum value @param {Integer} tickCount The count of ticks @param {Boolean} allowDecimals Allow the ticks to be decimals or not @return {Array} ticks
[ "Calculate", "the", "ticks", "of", "an", "interval", "the", "count", "of", "ticks", "won", "t", "be", "guraranteed" ]
8fdf6d32d24cdabf6da75f1cd9d0a3e33336dc2a
https://github.com/recharts/recharts-scale/blob/8fdf6d32d24cdabf6da75f1cd9d0a3e33336dc2a/src/getNiceTickValues.js#L200-L223
train
recharts/recharts-scale
src/getNiceTickValues.js
getTickValuesFixedDomainFn
function getTickValuesFixedDomainFn([min, max], tickCount, allowDecimals = true) { // More than two ticks should be return const [cormin, cormax] = getValidInterval([min, max]); if (cormin === -Infinity || cormax === Infinity) { return [min, max]; } if (cormin === cormax) { return [cormin]; } const count = Math.max(tickCount, 2); const step = getFormatStep(new Decimal(cormax).sub(cormin).div(count - 1), allowDecimals, 0); const values = [ ...Arithmetic.rangeStep( new Decimal(cormin), new Decimal(cormax).sub(new Decimal(0.99).mul(step)), step, ), cormax, ]; return min > max ? reverse(values) : values; }
javascript
function getTickValuesFixedDomainFn([min, max], tickCount, allowDecimals = true) { // More than two ticks should be return const [cormin, cormax] = getValidInterval([min, max]); if (cormin === -Infinity || cormax === Infinity) { return [min, max]; } if (cormin === cormax) { return [cormin]; } const count = Math.max(tickCount, 2); const step = getFormatStep(new Decimal(cormax).sub(cormin).div(count - 1), allowDecimals, 0); const values = [ ...Arithmetic.rangeStep( new Decimal(cormin), new Decimal(cormax).sub(new Decimal(0.99).mul(step)), step, ), cormax, ]; return min > max ? reverse(values) : values; }
[ "function", "getTickValuesFixedDomainFn", "(", "[", "min", ",", "max", "]", ",", "tickCount", ",", "allowDecimals", "=", "true", ")", "{", "const", "[", "cormin", ",", "cormax", "]", "=", "getValidInterval", "(", "[", "min", ",", "max", "]", ")", ";", "if", "(", "cormin", "===", "-", "Infinity", "||", "cormax", "===", "Infinity", ")", "{", "return", "[", "min", ",", "max", "]", ";", "}", "if", "(", "cormin", "===", "cormax", ")", "{", "return", "[", "cormin", "]", ";", "}", "const", "count", "=", "Math", ".", "max", "(", "tickCount", ",", "2", ")", ";", "const", "step", "=", "getFormatStep", "(", "new", "Decimal", "(", "cormax", ")", ".", "sub", "(", "cormin", ")", ".", "div", "(", "count", "-", "1", ")", ",", "allowDecimals", ",", "0", ")", ";", "const", "values", "=", "[", "...", "Arithmetic", ".", "rangeStep", "(", "new", "Decimal", "(", "cormin", ")", ",", "new", "Decimal", "(", "cormax", ")", ".", "sub", "(", "new", "Decimal", "(", "0.99", ")", ".", "mul", "(", "step", ")", ")", ",", "step", ",", ")", ",", "cormax", ",", "]", ";", "return", "min", ">", "max", "?", "reverse", "(", "values", ")", ":", "values", ";", "}" ]
Calculate the ticks of an interval, the count of ticks won't be guraranteed, but the domain will be guaranteed @param {Number} min, max min: The minimum value, max: The maximum value @param {Integer} tickCount The count of ticks @param {Boolean} allowDecimals Allow the ticks to be decimals or not @return {Array} ticks
[ "Calculate", "the", "ticks", "of", "an", "interval", "the", "count", "of", "ticks", "won", "t", "be", "guraranteed", "but", "the", "domain", "will", "be", "guaranteed" ]
8fdf6d32d24cdabf6da75f1cd9d0a3e33336dc2a
https://github.com/recharts/recharts-scale/blob/8fdf6d32d24cdabf6da75f1cd9d0a3e33336dc2a/src/getNiceTickValues.js#L234-L256
train
rexxars/commonmark-react-renderer
src/commonmark-react-renderer.js
List
function List(props) { var tag = props.type.toLowerCase() === 'bullet' ? 'ul' : 'ol'; var attrs = getCoreProps(props); if (props.start !== null && props.start !== 1) { attrs.start = props.start.toString(); } return createElement(tag, attrs, props.children); }
javascript
function List(props) { var tag = props.type.toLowerCase() === 'bullet' ? 'ul' : 'ol'; var attrs = getCoreProps(props); if (props.start !== null && props.start !== 1) { attrs.start = props.start.toString(); } return createElement(tag, attrs, props.children); }
[ "function", "List", "(", "props", ")", "{", "var", "tag", "=", "props", ".", "type", ".", "toLowerCase", "(", ")", "===", "'bullet'", "?", "'ul'", ":", "'ol'", ";", "var", "attrs", "=", "getCoreProps", "(", "props", ")", ";", "if", "(", "props", ".", "start", "!==", "null", "&&", "props", ".", "start", "!==", "1", ")", "{", "attrs", ".", "start", "=", "props", ".", "start", ".", "toString", "(", ")", ";", "}", "return", "createElement", "(", "tag", ",", "attrs", ",", "props", ".", "children", ")", ";", "}" ]
eslint-disable-line camelcase
[ "eslint", "-", "disable", "-", "line", "camelcase" ]
6774beb39b462a377dda7ef7bba45991b4212e67
https://github.com/rexxars/commonmark-react-renderer/blob/6774beb39b462a377dda7ef7bba45991b4212e67/src/commonmark-react-renderer.js#L32-L41
train
rexxars/commonmark-react-renderer
src/commonmark-react-renderer.js
getNodeProps
function getNodeProps(node, key, opts, renderer) { var props = { key: key }, undef; // `sourcePos` is true if the user wants source information (line/column info from markdown source) if (opts.sourcePos && node.sourcepos) { props['data-sourcepos'] = flattenPosition(node.sourcepos); } var type = normalizeTypeName(node.type); switch (type) { case 'html_inline': case 'html_block': props.isBlock = type === 'html_block'; props.escapeHtml = opts.escapeHtml; props.skipHtml = opts.skipHtml; break; case 'code_block': var codeInfo = node.info ? node.info.split(/ +/) : []; if (codeInfo.length > 0 && codeInfo[0].length > 0) { props.language = codeInfo[0]; props.codeinfo = codeInfo; } break; case 'code': props.children = node.literal; props.inline = true; break; case 'heading': props.level = node.level; break; case 'softbreak': props.softBreak = opts.softBreak; break; case 'link': props.href = opts.transformLinkUri ? opts.transformLinkUri(node.destination) : node.destination; props.title = node.title || undef; if (opts.linkTarget) { props.target = opts.linkTarget; } break; case 'image': props.src = opts.transformImageUri ? opts.transformImageUri(node.destination) : node.destination; props.title = node.title || undef; // Commonmark treats image description as children. We just want the text props.alt = node.react.children.join(''); node.react.children = undef; break; case 'list': props.start = node.listStart; props.type = node.listType; props.tight = node.listTight; break; default: } if (typeof renderer !== 'string') { props.literal = node.literal; } var children = props.children || (node.react && node.react.children); if (Array.isArray(children)) { props.children = children.reduce(reduceChildren, []) || null; } return props; }
javascript
function getNodeProps(node, key, opts, renderer) { var props = { key: key }, undef; // `sourcePos` is true if the user wants source information (line/column info from markdown source) if (opts.sourcePos && node.sourcepos) { props['data-sourcepos'] = flattenPosition(node.sourcepos); } var type = normalizeTypeName(node.type); switch (type) { case 'html_inline': case 'html_block': props.isBlock = type === 'html_block'; props.escapeHtml = opts.escapeHtml; props.skipHtml = opts.skipHtml; break; case 'code_block': var codeInfo = node.info ? node.info.split(/ +/) : []; if (codeInfo.length > 0 && codeInfo[0].length > 0) { props.language = codeInfo[0]; props.codeinfo = codeInfo; } break; case 'code': props.children = node.literal; props.inline = true; break; case 'heading': props.level = node.level; break; case 'softbreak': props.softBreak = opts.softBreak; break; case 'link': props.href = opts.transformLinkUri ? opts.transformLinkUri(node.destination) : node.destination; props.title = node.title || undef; if (opts.linkTarget) { props.target = opts.linkTarget; } break; case 'image': props.src = opts.transformImageUri ? opts.transformImageUri(node.destination) : node.destination; props.title = node.title || undef; // Commonmark treats image description as children. We just want the text props.alt = node.react.children.join(''); node.react.children = undef; break; case 'list': props.start = node.listStart; props.type = node.listType; props.tight = node.listTight; break; default: } if (typeof renderer !== 'string') { props.literal = node.literal; } var children = props.children || (node.react && node.react.children); if (Array.isArray(children)) { props.children = children.reduce(reduceChildren, []) || null; } return props; }
[ "function", "getNodeProps", "(", "node", ",", "key", ",", "opts", ",", "renderer", ")", "{", "var", "props", "=", "{", "key", ":", "key", "}", ",", "undef", ";", "if", "(", "opts", ".", "sourcePos", "&&", "node", ".", "sourcepos", ")", "{", "props", "[", "'data-sourcepos'", "]", "=", "flattenPosition", "(", "node", ".", "sourcepos", ")", ";", "}", "var", "type", "=", "normalizeTypeName", "(", "node", ".", "type", ")", ";", "switch", "(", "type", ")", "{", "case", "'html_inline'", ":", "case", "'html_block'", ":", "props", ".", "isBlock", "=", "type", "===", "'html_block'", ";", "props", ".", "escapeHtml", "=", "opts", ".", "escapeHtml", ";", "props", ".", "skipHtml", "=", "opts", ".", "skipHtml", ";", "break", ";", "case", "'code_block'", ":", "var", "codeInfo", "=", "node", ".", "info", "?", "node", ".", "info", ".", "split", "(", "/", " +", "/", ")", ":", "[", "]", ";", "if", "(", "codeInfo", ".", "length", ">", "0", "&&", "codeInfo", "[", "0", "]", ".", "length", ">", "0", ")", "{", "props", ".", "language", "=", "codeInfo", "[", "0", "]", ";", "props", ".", "codeinfo", "=", "codeInfo", ";", "}", "break", ";", "case", "'code'", ":", "props", ".", "children", "=", "node", ".", "literal", ";", "props", ".", "inline", "=", "true", ";", "break", ";", "case", "'heading'", ":", "props", ".", "level", "=", "node", ".", "level", ";", "break", ";", "case", "'softbreak'", ":", "props", ".", "softBreak", "=", "opts", ".", "softBreak", ";", "break", ";", "case", "'link'", ":", "props", ".", "href", "=", "opts", ".", "transformLinkUri", "?", "opts", ".", "transformLinkUri", "(", "node", ".", "destination", ")", ":", "node", ".", "destination", ";", "props", ".", "title", "=", "node", ".", "title", "||", "undef", ";", "if", "(", "opts", ".", "linkTarget", ")", "{", "props", ".", "target", "=", "opts", ".", "linkTarget", ";", "}", "break", ";", "case", "'image'", ":", "props", ".", "src", "=", "opts", ".", "transformImageUri", "?", "opts", ".", "transformImageUri", "(", "node", ".", "destination", ")", ":", "node", ".", "destination", ";", "props", ".", "title", "=", "node", ".", "title", "||", "undef", ";", "props", ".", "alt", "=", "node", ".", "react", ".", "children", ".", "join", "(", "''", ")", ";", "node", ".", "react", ".", "children", "=", "undef", ";", "break", ";", "case", "'list'", ":", "props", ".", "start", "=", "node", ".", "listStart", ";", "props", ".", "type", "=", "node", ".", "listType", ";", "props", ".", "tight", "=", "node", ".", "listTight", ";", "break", ";", "default", ":", "}", "if", "(", "typeof", "renderer", "!==", "'string'", ")", "{", "props", ".", "literal", "=", "node", ".", "literal", ";", "}", "var", "children", "=", "props", ".", "children", "||", "(", "node", ".", "react", "&&", "node", ".", "react", ".", "children", ")", ";", "if", "(", "Array", ".", "isArray", "(", "children", ")", ")", "{", "props", ".", "children", "=", "children", ".", "reduce", "(", "reduceChildren", ",", "[", "]", ")", "||", "null", ";", "}", "return", "props", ";", "}" ]
For some nodes, we want to include more props than for others
[ "For", "some", "nodes", "we", "want", "to", "include", "more", "props", "than", "for", "others" ]
6774beb39b462a377dda7ef7bba45991b4212e67
https://github.com/rexxars/commonmark-react-renderer/blob/6774beb39b462a377dda7ef7bba45991b4212e67/src/commonmark-react-renderer.js#L136-L203
train
mweibel/lcov-result-merger
index.js
BRDA
function BRDA (lineNumber, blockNumber, branchNumber, hits) { this.lineNumber = lineNumber this.blockNumber = blockNumber this.branchNumber = branchNumber this.hits = hits }
javascript
function BRDA (lineNumber, blockNumber, branchNumber, hits) { this.lineNumber = lineNumber this.blockNumber = blockNumber this.branchNumber = branchNumber this.hits = hits }
[ "function", "BRDA", "(", "lineNumber", ",", "blockNumber", ",", "branchNumber", ",", "hits", ")", "{", "this", ".", "lineNumber", "=", "lineNumber", "this", ".", "blockNumber", "=", "blockNumber", "this", ".", "branchNumber", "=", "branchNumber", "this", ".", "hits", "=", "hits", "}" ]
Represents a BRDA record @param {number} lineNumber @param {number} blockNumber @param {number} branchNumber @param {number} hits @constructor
[ "Represents", "a", "BRDA", "record" ]
41576894b3d52326ccf0f0e4c2c9e871e2c37028
https://github.com/mweibel/lcov-result-merger/blob/41576894b3d52326ccf0f0e4c2c9e871e2c37028/index.js#L44-L49
train
mweibel/lcov-result-merger
index.js
findDA
function findDA (source, lineNumber) { for (var i = 0; i < source.length; i++) { var da = source[i] if (da.lineNumber === lineNumber) { return da } } return null }
javascript
function findDA (source, lineNumber) { for (var i = 0; i < source.length; i++) { var da = source[i] if (da.lineNumber === lineNumber) { return da } } return null }
[ "function", "findDA", "(", "source", ",", "lineNumber", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "source", ".", "length", ";", "i", "++", ")", "{", "var", "da", "=", "source", "[", "i", "]", "if", "(", "da", ".", "lineNumber", "===", "lineNumber", ")", "{", "return", "da", "}", "}", "return", "null", "}" ]
Find an existing DA record @param {DA[]} source @param {number} lineNumber @returns {DA|null}
[ "Find", "an", "existing", "DA", "record" ]
41576894b3d52326ccf0f0e4c2c9e871e2c37028
https://github.com/mweibel/lcov-result-merger/blob/41576894b3d52326ccf0f0e4c2c9e871e2c37028/index.js#L105-L113
train
mweibel/lcov-result-merger
index.js
findBRDA
function findBRDA (source, blockNumber, branchNumber, lineNumber) { for (var i = 0; i < source.length; i++) { var brda = source[i] if (brda.blockNumber === blockNumber && brda.branchNumber === branchNumber && brda.lineNumber === lineNumber) { return brda } } return null }
javascript
function findBRDA (source, blockNumber, branchNumber, lineNumber) { for (var i = 0; i < source.length; i++) { var brda = source[i] if (brda.blockNumber === blockNumber && brda.branchNumber === branchNumber && brda.lineNumber === lineNumber) { return brda } } return null }
[ "function", "findBRDA", "(", "source", ",", "blockNumber", ",", "branchNumber", ",", "lineNumber", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "source", ".", "length", ";", "i", "++", ")", "{", "var", "brda", "=", "source", "[", "i", "]", "if", "(", "brda", ".", "blockNumber", "===", "blockNumber", "&&", "brda", ".", "branchNumber", "===", "branchNumber", "&&", "brda", ".", "lineNumber", "===", "lineNumber", ")", "{", "return", "brda", "}", "}", "return", "null", "}" ]
Find an existing BRDA record @param {BRDA[]} source @param {number} blockNumber @param {number} branchNumber @param {number} lineNumber @returns {BRDA|null}
[ "Find", "an", "existing", "BRDA", "record" ]
41576894b3d52326ccf0f0e4c2c9e871e2c37028
https://github.com/mweibel/lcov-result-merger/blob/41576894b3d52326ccf0f0e4c2c9e871e2c37028/index.js#L125-L135
train
mweibel/lcov-result-merger
index.js
findCoverageFile
function findCoverageFile (source, filename) { for (var i = 0; i < source.length; i++) { var file = source[i] if (file.filename === filename) { return file } } return null }
javascript
function findCoverageFile (source, filename) { for (var i = 0; i < source.length; i++) { var file = source[i] if (file.filename === filename) { return file } } return null }
[ "function", "findCoverageFile", "(", "source", ",", "filename", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "source", ".", "length", ";", "i", "++", ")", "{", "var", "file", "=", "source", "[", "i", "]", "if", "(", "file", ".", "filename", "===", "filename", ")", "{", "return", "file", "}", "}", "return", "null", "}" ]
Find an existing coverage file @param {CoverageFile[]} source @param {string} filename @returns {CoverageFile|null}
[ "Find", "an", "existing", "coverage", "file" ]
41576894b3d52326ccf0f0e4c2c9e871e2c37028
https://github.com/mweibel/lcov-result-merger/blob/41576894b3d52326ccf0f0e4c2c9e871e2c37028/index.js#L145-L153
train
mweibel/lcov-result-merger
index.js
parseSF
function parseSF (lcov, prefixSplit) { // If the filepath contains a ':', we want to preserve it. prefixSplit.shift() var currentFileName = prefixSplit.join(':') var currentCoverageFile = findCoverageFile(lcov, currentFileName) if (currentCoverageFile) { return currentCoverageFile } currentCoverageFile = new CoverageFile(currentFileName) lcov.push(currentCoverageFile) return currentCoverageFile }
javascript
function parseSF (lcov, prefixSplit) { // If the filepath contains a ':', we want to preserve it. prefixSplit.shift() var currentFileName = prefixSplit.join(':') var currentCoverageFile = findCoverageFile(lcov, currentFileName) if (currentCoverageFile) { return currentCoverageFile } currentCoverageFile = new CoverageFile(currentFileName) lcov.push(currentCoverageFile) return currentCoverageFile }
[ "function", "parseSF", "(", "lcov", ",", "prefixSplit", ")", "{", "prefixSplit", ".", "shift", "(", ")", "var", "currentFileName", "=", "prefixSplit", ".", "join", "(", "':'", ")", "var", "currentCoverageFile", "=", "findCoverageFile", "(", "lcov", ",", "currentFileName", ")", "if", "(", "currentCoverageFile", ")", "{", "return", "currentCoverageFile", "}", "currentCoverageFile", "=", "new", "CoverageFile", "(", "currentFileName", ")", "lcov", ".", "push", "(", "currentCoverageFile", ")", "return", "currentCoverageFile", "}" ]
Parses a SF section @param {CoverageFile[]} lcov @param {string[]} prefixSplit @returns {CoverageFile|null}
[ "Parses", "a", "SF", "section" ]
41576894b3d52326ccf0f0e4c2c9e871e2c37028
https://github.com/mweibel/lcov-result-merger/blob/41576894b3d52326ccf0f0e4c2c9e871e2c37028/index.js#L209-L221
train
mweibel/lcov-result-merger
index.js
parseDA
function parseDA (currentCoverageFile, prefixSplit) { var numberSplit = splitNumbers(prefixSplit) var lineNumber = parseInt(numberSplit[0], 10) var hits = parseInt(numberSplit[1], 10) var existingDA = findDA(currentCoverageFile.DARecords, lineNumber) if (existingDA) { existingDA.hits += hits return } currentCoverageFile.DARecords.push(new DA(lineNumber, hits)) }
javascript
function parseDA (currentCoverageFile, prefixSplit) { var numberSplit = splitNumbers(prefixSplit) var lineNumber = parseInt(numberSplit[0], 10) var hits = parseInt(numberSplit[1], 10) var existingDA = findDA(currentCoverageFile.DARecords, lineNumber) if (existingDA) { existingDA.hits += hits return } currentCoverageFile.DARecords.push(new DA(lineNumber, hits)) }
[ "function", "parseDA", "(", "currentCoverageFile", ",", "prefixSplit", ")", "{", "var", "numberSplit", "=", "splitNumbers", "(", "prefixSplit", ")", "var", "lineNumber", "=", "parseInt", "(", "numberSplit", "[", "0", "]", ",", "10", ")", "var", "hits", "=", "parseInt", "(", "numberSplit", "[", "1", "]", ",", "10", ")", "var", "existingDA", "=", "findDA", "(", "currentCoverageFile", ".", "DARecords", ",", "lineNumber", ")", "if", "(", "existingDA", ")", "{", "existingDA", ".", "hits", "+=", "hits", "return", "}", "currentCoverageFile", ".", "DARecords", ".", "push", "(", "new", "DA", "(", "lineNumber", ",", "hits", ")", ")", "}" ]
Parses a DA section @param {CoverageFile} currentCoverageFile @param {string[]} prefixSplit
[ "Parses", "a", "DA", "section" ]
41576894b3d52326ccf0f0e4c2c9e871e2c37028
https://github.com/mweibel/lcov-result-merger/blob/41576894b3d52326ccf0f0e4c2c9e871e2c37028/index.js#L229-L241
train
mweibel/lcov-result-merger
index.js
parseBRDA
function parseBRDA (currentCoverageFile, prefixSplit) { var numberSplit = splitNumbers(prefixSplit) var lineNumber = parseInt(numberSplit[0], 10) var blockNumber = parseInt(numberSplit[1], 10) var branchNumber = parseInt(numberSplit[2], 10) var existingBRDA = findBRDA(currentCoverageFile.BRDARecords, blockNumber, branchNumber, lineNumber) // Special case, hits might be a '-'. This means that the code block // where the branch was contained was never executed at all (as opposed // to the code being executed, but the branch not being taken). Keep // it as a string and let mergedBRDAHits work it out. var hits = numberSplit[3] if (existingBRDA) { existingBRDA.hits = mergedBRDAHits(existingBRDA.hits, hits) return } currentCoverageFile.BRDARecords.push(new BRDA(lineNumber, blockNumber, branchNumber, hits)) }
javascript
function parseBRDA (currentCoverageFile, prefixSplit) { var numberSplit = splitNumbers(prefixSplit) var lineNumber = parseInt(numberSplit[0], 10) var blockNumber = parseInt(numberSplit[1], 10) var branchNumber = parseInt(numberSplit[2], 10) var existingBRDA = findBRDA(currentCoverageFile.BRDARecords, blockNumber, branchNumber, lineNumber) // Special case, hits might be a '-'. This means that the code block // where the branch was contained was never executed at all (as opposed // to the code being executed, but the branch not being taken). Keep // it as a string and let mergedBRDAHits work it out. var hits = numberSplit[3] if (existingBRDA) { existingBRDA.hits = mergedBRDAHits(existingBRDA.hits, hits) return } currentCoverageFile.BRDARecords.push(new BRDA(lineNumber, blockNumber, branchNumber, hits)) }
[ "function", "parseBRDA", "(", "currentCoverageFile", ",", "prefixSplit", ")", "{", "var", "numberSplit", "=", "splitNumbers", "(", "prefixSplit", ")", "var", "lineNumber", "=", "parseInt", "(", "numberSplit", "[", "0", "]", ",", "10", ")", "var", "blockNumber", "=", "parseInt", "(", "numberSplit", "[", "1", "]", ",", "10", ")", "var", "branchNumber", "=", "parseInt", "(", "numberSplit", "[", "2", "]", ",", "10", ")", "var", "existingBRDA", "=", "findBRDA", "(", "currentCoverageFile", ".", "BRDARecords", ",", "blockNumber", ",", "branchNumber", ",", "lineNumber", ")", "var", "hits", "=", "numberSplit", "[", "3", "]", "if", "(", "existingBRDA", ")", "{", "existingBRDA", ".", "hits", "=", "mergedBRDAHits", "(", "existingBRDA", ".", "hits", ",", "hits", ")", "return", "}", "currentCoverageFile", ".", "BRDARecords", ".", "push", "(", "new", "BRDA", "(", "lineNumber", ",", "blockNumber", ",", "branchNumber", ",", "hits", ")", ")", "}" ]
Parses a BRDA section @param {CoverageFile} currentCoverageFile @param {string[]} prefixSplit
[ "Parses", "a", "BRDA", "section" ]
41576894b3d52326ccf0f0e4c2c9e871e2c37028
https://github.com/mweibel/lcov-result-merger/blob/41576894b3d52326ccf0f0e4c2c9e871e2c37028/index.js#L249-L270
train
mweibel/lcov-result-merger
index.js
processFile
function processFile (data, lcov) { var lines = data.split(/\r?\n/) var currentCoverageFile = null for (var i = 0, l = lines.length; i < l; i++) { var line = lines[i] if (line === 'end_of_record' || line === '') { currentCoverageFile = null continue } var prefixSplit = line.split(':') var prefix = prefixSplit[0] switch (prefix) { case 'SF': currentCoverageFile = parseSF(lcov, prefixSplit) break case 'DA': parseDA(currentCoverageFile, prefixSplit) break case 'BRDA': parseBRDA(currentCoverageFile, prefixSplit) break default: // do nothing with not implemented prefixes } } return lcov }
javascript
function processFile (data, lcov) { var lines = data.split(/\r?\n/) var currentCoverageFile = null for (var i = 0, l = lines.length; i < l; i++) { var line = lines[i] if (line === 'end_of_record' || line === '') { currentCoverageFile = null continue } var prefixSplit = line.split(':') var prefix = prefixSplit[0] switch (prefix) { case 'SF': currentCoverageFile = parseSF(lcov, prefixSplit) break case 'DA': parseDA(currentCoverageFile, prefixSplit) break case 'BRDA': parseBRDA(currentCoverageFile, prefixSplit) break default: // do nothing with not implemented prefixes } } return lcov }
[ "function", "processFile", "(", "data", ",", "lcov", ")", "{", "var", "lines", "=", "data", ".", "split", "(", "/", "\\r?\\n", "/", ")", "var", "currentCoverageFile", "=", "null", "for", "(", "var", "i", "=", "0", ",", "l", "=", "lines", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "var", "line", "=", "lines", "[", "i", "]", "if", "(", "line", "===", "'end_of_record'", "||", "line", "===", "''", ")", "{", "currentCoverageFile", "=", "null", "continue", "}", "var", "prefixSplit", "=", "line", ".", "split", "(", "':'", ")", "var", "prefix", "=", "prefixSplit", "[", "0", "]", "switch", "(", "prefix", ")", "{", "case", "'SF'", ":", "currentCoverageFile", "=", "parseSF", "(", "lcov", ",", "prefixSplit", ")", "break", "case", "'DA'", ":", "parseDA", "(", "currentCoverageFile", ",", "prefixSplit", ")", "break", "case", "'BRDA'", ":", "parseBRDA", "(", "currentCoverageFile", ",", "prefixSplit", ")", "break", "default", ":", "}", "}", "return", "lcov", "}" ]
Process a lcov input file into the representing Objects @param {string} data @param {CoverageFile[]} lcov @returns {CoverageFile[]}
[ "Process", "a", "lcov", "input", "file", "into", "the", "representing", "Objects" ]
41576894b3d52326ccf0f0e4c2c9e871e2c37028
https://github.com/mweibel/lcov-result-merger/blob/41576894b3d52326ccf0f0e4c2c9e871e2c37028/index.js#L280-L309
train
jasmine-contrib/grunt-jasmine-runner
tasks/jasmine/reporters/JUnitReporter.js
JUnitXmlReporter
function JUnitXmlReporter(savePath, consolidate, useDotNotation) { this.savePath = savePath || ''; this.consolidate = typeof consolidate === 'undefined' ? true : consolidate; this.useDotNotation = typeof useDotNotation === 'undefined' ? true : useDotNotation; }
javascript
function JUnitXmlReporter(savePath, consolidate, useDotNotation) { this.savePath = savePath || ''; this.consolidate = typeof consolidate === 'undefined' ? true : consolidate; this.useDotNotation = typeof useDotNotation === 'undefined' ? true : useDotNotation; }
[ "function", "JUnitXmlReporter", "(", "savePath", ",", "consolidate", ",", "useDotNotation", ")", "{", "this", ".", "savePath", "=", "savePath", "||", "''", ";", "this", ".", "consolidate", "=", "typeof", "consolidate", "===", "'undefined'", "?", "true", ":", "consolidate", ";", "this", ".", "useDotNotation", "=", "typeof", "useDotNotation", "===", "'undefined'", "?", "true", ":", "useDotNotation", ";", "}" ]
Generates JUnit XML for the given spec run. Allows the test results to be used in java based CI systems like CruiseControl and Hudson. @param {string} savePath where to save the files @param {boolean} consolidate whether to save nested describes within the same file as their parent; default: true @param {boolean} useDotNotation whether to separate suite names with dots rather than spaces (ie "Class.init" not "Class init"); default: true
[ "Generates", "JUnit", "XML", "for", "the", "given", "spec", "run", ".", "Allows", "the", "test", "results", "to", "be", "used", "in", "java", "based", "CI", "systems", "like", "CruiseControl", "and", "Hudson", "." ]
62c7ba51deeab8879680ba1ba68f0ed88ec69200
https://github.com/jasmine-contrib/grunt-jasmine-runner/blob/62c7ba51deeab8879680ba1ba68f0ed88ec69200/tasks/jasmine/reporters/JUnitReporter.js#L46-L50
train
jasmine-contrib/grunt-jasmine-runner
tasks/lib/phantomjs.js
function(version) { var current = [version.major, version.minor, version.patch].join('.'); var required = '>= 1.6.0'; if (!semver.satisfies(current, required)) { exports.halt(); grunt.log.writeln(); grunt.log.errorlns( 'In order for this task to work properly, PhantomJS version ' + required + ' must be installed, but version ' + current + ' was detected.' ); grunt.warn('The correct version of PhantomJS needs to be installed.', 127); } }
javascript
function(version) { var current = [version.major, version.minor, version.patch].join('.'); var required = '>= 1.6.0'; if (!semver.satisfies(current, required)) { exports.halt(); grunt.log.writeln(); grunt.log.errorlns( 'In order for this task to work properly, PhantomJS version ' + required + ' must be installed, but version ' + current + ' was detected.' ); grunt.warn('The correct version of PhantomJS needs to be installed.', 127); } }
[ "function", "(", "version", ")", "{", "var", "current", "=", "[", "version", ".", "major", ",", "version", ".", "minor", ",", "version", ".", "patch", "]", ".", "join", "(", "'.'", ")", ";", "var", "required", "=", "'>= 1.6.0'", ";", "if", "(", "!", "semver", ".", "satisfies", "(", "current", ",", "required", ")", ")", "{", "exports", ".", "halt", "(", ")", ";", "grunt", ".", "log", ".", "writeln", "(", ")", ";", "grunt", ".", "log", ".", "errorlns", "(", "'In order for this task to work properly, PhantomJS version '", "+", "required", "+", "' must be installed, but version '", "+", "current", "+", "' was detected.'", ")", ";", "grunt", ".", "warn", "(", "'The correct version of PhantomJS needs to be installed.'", ",", "127", ")", ";", "}", "}" ]
Abort if PhantomJS version isn't adequate.
[ "Abort", "if", "PhantomJS", "version", "isn", "t", "adequate", "." ]
62c7ba51deeab8879680ba1ba68f0ed88ec69200
https://github.com/jasmine-contrib/grunt-jasmine-runner/blob/62c7ba51deeab8879680ba1ba68f0ed88ec69200/tasks/lib/phantomjs.js#L47-L60
train
pascalopitz/nodestalker
lib/beanstalk_client.js
function() { if(!_self.waitingForResponse && _self.queue.length) { _self.waitingForResponse = true; var cmd = _self.queue.shift(); if(_self.conn) { _self.conn.removeAllListeners('data'); _self.conn.addListener('data', function(data) { Debug.log('response:'); Debug.log(data); cmd.responseHandler.call(cmd, data); }); } Debug.log('request:'); Debug.log(cmd.command()); process.nextTick(function() { _self.conn.write(cmd.command()); }); } }
javascript
function() { if(!_self.waitingForResponse && _self.queue.length) { _self.waitingForResponse = true; var cmd = _self.queue.shift(); if(_self.conn) { _self.conn.removeAllListeners('data'); _self.conn.addListener('data', function(data) { Debug.log('response:'); Debug.log(data); cmd.responseHandler.call(cmd, data); }); } Debug.log('request:'); Debug.log(cmd.command()); process.nextTick(function() { _self.conn.write(cmd.command()); }); } }
[ "function", "(", ")", "{", "if", "(", "!", "_self", ".", "waitingForResponse", "&&", "_self", ".", "queue", ".", "length", ")", "{", "_self", ".", "waitingForResponse", "=", "true", ";", "var", "cmd", "=", "_self", ".", "queue", ".", "shift", "(", ")", ";", "if", "(", "_self", ".", "conn", ")", "{", "_self", ".", "conn", ".", "removeAllListeners", "(", "'data'", ")", ";", "_self", ".", "conn", ".", "addListener", "(", "'data'", ",", "function", "(", "data", ")", "{", "Debug", ".", "log", "(", "'response:'", ")", ";", "Debug", ".", "log", "(", "data", ")", ";", "cmd", ".", "responseHandler", ".", "call", "(", "cmd", ",", "data", ")", ";", "}", ")", ";", "}", "Debug", ".", "log", "(", "'request:'", ")", ";", "Debug", ".", "log", "(", "cmd", ".", "command", "(", ")", ")", ";", "process", ".", "nextTick", "(", "function", "(", ")", "{", "_self", ".", "conn", ".", "write", "(", "cmd", ".", "command", "(", ")", ")", ";", "}", ")", ";", "}", "}" ]
pushes commands to the server
[ "pushes", "commands", "to", "the", "server" ]
4ace7d5d9f2bb913023d2c70df5adf945743a628
https://github.com/pascalopitz/nodestalker/blob/4ace7d5d9f2bb913023d2c70df5adf945743a628/lib/beanstalk_client.js#L276-L295
train
ethjs/ethjs-provider-signer
src/index.js
SignerProvider
function SignerProvider(path, options) { if (!(this instanceof SignerProvider)) { throw new Error('[ethjs-provider-signer] the SignerProvider instance requires the "new" flag in order to function normally (e.g. `const eth = new Eth(new SignerProvider(...));`).'); } if (typeof options !== 'object') { throw new Error(`[ethjs-provider-signer] the SignerProvider requires an options object be provided with the 'privateKey' property specified, you provided type ${typeof options}.`); } if (typeof options.signTransaction !== 'function') { throw new Error(`[ethjs-provider-signer] the SignerProvider requires an options object be provided with the 'signTransaction' property specified, you provided type ${typeof options.privateKey} (e.g. 'const eth = new Eth(new SignerProvider("http://ropsten.infura.io", { privateKey: (account, cb) => cb(null, 'some private key') }));').`); } const self = this; self.options = Object.assign({ provider: HTTPProvider, }, options); self.timeout = options.timeout || 0; self.provider = new self.options.provider(path, self.timeout); // eslint-disable-line self.rpc = new EthRPC(self.provider); }
javascript
function SignerProvider(path, options) { if (!(this instanceof SignerProvider)) { throw new Error('[ethjs-provider-signer] the SignerProvider instance requires the "new" flag in order to function normally (e.g. `const eth = new Eth(new SignerProvider(...));`).'); } if (typeof options !== 'object') { throw new Error(`[ethjs-provider-signer] the SignerProvider requires an options object be provided with the 'privateKey' property specified, you provided type ${typeof options}.`); } if (typeof options.signTransaction !== 'function') { throw new Error(`[ethjs-provider-signer] the SignerProvider requires an options object be provided with the 'signTransaction' property specified, you provided type ${typeof options.privateKey} (e.g. 'const eth = new Eth(new SignerProvider("http://ropsten.infura.io", { privateKey: (account, cb) => cb(null, 'some private key') }));').`); } const self = this; self.options = Object.assign({ provider: HTTPProvider, }, options); self.timeout = options.timeout || 0; self.provider = new self.options.provider(path, self.timeout); // eslint-disable-line self.rpc = new EthRPC(self.provider); }
[ "function", "SignerProvider", "(", "path", ",", "options", ")", "{", "if", "(", "!", "(", "this", "instanceof", "SignerProvider", ")", ")", "{", "throw", "new", "Error", "(", "'[ethjs-provider-signer] the SignerProvider instance requires the \"new\" flag in order to function normally (e.g. `const eth = new Eth(new SignerProvider(...));`).'", ")", ";", "}", "if", "(", "typeof", "options", "!==", "'object'", ")", "{", "throw", "new", "Error", "(", "`", "${", "typeof", "options", "}", "`", ")", ";", "}", "if", "(", "typeof", "options", ".", "signTransaction", "!==", "'function'", ")", "{", "throw", "new", "Error", "(", "`", "${", "typeof", "options", ".", "privateKey", "}", "`", ")", ";", "}", "const", "self", "=", "this", ";", "self", ".", "options", "=", "Object", ".", "assign", "(", "{", "provider", ":", "HTTPProvider", ",", "}", ",", "options", ")", ";", "self", ".", "timeout", "=", "options", ".", "timeout", "||", "0", ";", "self", ".", "provider", "=", "new", "self", ".", "options", ".", "provider", "(", "path", ",", "self", ".", "timeout", ")", ";", "self", ".", "rpc", "=", "new", "EthRPC", "(", "self", ".", "provider", ")", ";", "}" ]
Signer provider constructor @method SignerProvider @param {String} path the input data payload @param {Object} options the send async callback @returns {Object} provider instance
[ "Signer", "provider", "constructor" ]
0bdb4f41e11f445c793f3a24d26b8a76dc67b1c8
https://github.com/ethjs/ethjs-provider-signer/blob/0bdb4f41e11f445c793f3a24d26b8a76dc67b1c8/src/index.js#L14-L26
train
whitfin/it.each
lib/util.js
generateArgs
function generateArgs(test, title, fields, index){ var formatting = fields.concat(), args = (formatting.unshift(title), formatting); for (var i = 1; i <= args.length - 1; i++) { if (args[i] === 'x') { args[i] = index; } else if (args[i] === 'element') { args[i] = test; } else { args[i] = dots.get(test, args[i]); } } return args; }
javascript
function generateArgs(test, title, fields, index){ var formatting = fields.concat(), args = (formatting.unshift(title), formatting); for (var i = 1; i <= args.length - 1; i++) { if (args[i] === 'x') { args[i] = index; } else if (args[i] === 'element') { args[i] = test; } else { args[i] = dots.get(test, args[i]); } } return args; }
[ "function", "generateArgs", "(", "test", ",", "title", ",", "fields", ",", "index", ")", "{", "var", "formatting", "=", "fields", ".", "concat", "(", ")", ",", "args", "=", "(", "formatting", ".", "unshift", "(", "title", ")", ",", "formatting", ")", ";", "for", "(", "var", "i", "=", "1", ";", "i", "<=", "args", ".", "length", "-", "1", ";", "i", "++", ")", "{", "if", "(", "args", "[", "i", "]", "===", "'x'", ")", "{", "args", "[", "i", "]", "=", "index", ";", "}", "else", "if", "(", "args", "[", "i", "]", "===", "'element'", ")", "{", "args", "[", "i", "]", "=", "test", ";", "}", "else", "{", "args", "[", "i", "]", "=", "dots", ".", "get", "(", "test", ",", "args", "[", "i", "]", ")", ";", "}", "}", "return", "args", ";", "}" ]
Generic replacement of the test name to a dynamic name with a set of fields. Replaces any format sequences with the given values, and replaces 'x' with the current iteration. @param test the test we're running @param title the test title to replace @param fields the fields to replace with @param index the index of the iteration
[ "Generic", "replacement", "of", "the", "test", "name", "to", "a", "dynamic", "name", "with", "a", "set", "of", "fields", ".", "Replaces", "any", "format", "sequences", "with", "the", "given", "values", "and", "replaces", "x", "with", "the", "current", "iteration", "." ]
ae7f31afa7556fa237e9c67494398ab8fd6488cc
https://github.com/whitfin/it.each/blob/ae7f31afa7556fa237e9c67494398ab8fd6488cc/lib/util.js#L13-L26
train
node-eval/node-eval
index.js
wrap
function wrap(body, extKeys) { const wrapper = [ '(function (exports, require, module, __filename, __dirname', ') { ', '\n});' ]; extKeys = extKeys ? `, ${extKeys}` : ''; return wrapper[0] + extKeys + wrapper[1] + body + wrapper[2]; }
javascript
function wrap(body, extKeys) { const wrapper = [ '(function (exports, require, module, __filename, __dirname', ') { ', '\n});' ]; extKeys = extKeys ? `, ${extKeys}` : ''; return wrapper[0] + extKeys + wrapper[1] + body + wrapper[2]; }
[ "function", "wrap", "(", "body", ",", "extKeys", ")", "{", "const", "wrapper", "=", "[", "'(function (exports, require, module, __filename, __dirname'", ",", "') { '", ",", "'\\n});'", "]", ";", "\\n", "extKeys", "=", "extKeys", "?", "`", "${", "extKeys", "}", "`", ":", "''", ";", "}" ]
Wrap code with function expression Use nodejs style default wrapper @param {String} body @param {String[]} [extKeys] keys to extend function args @returns {String}
[ "Wrap", "code", "with", "function", "expression", "Use", "nodejs", "style", "default", "wrapper" ]
a40a069933879f7cb085b52870a3fee90bd6dc8d
https://github.com/node-eval/node-eval/blob/a40a069933879f7cb085b52870a3fee90bd6dc8d/index.js#L96-L106
train
node-eval/node-eval
index.js
_getCalleeFilename
function _getCalleeFilename(calls) { calls = (calls|0) + 3; // 3 is a number of inner calls const e = {}; Error.captureStackTrace(e); return parseStackLine(e.stack.split(/\n/)[calls]).filename; }
javascript
function _getCalleeFilename(calls) { calls = (calls|0) + 3; // 3 is a number of inner calls const e = {}; Error.captureStackTrace(e); return parseStackLine(e.stack.split(/\n/)[calls]).filename; }
[ "function", "_getCalleeFilename", "(", "calls", ")", "{", "calls", "=", "(", "calls", "|", "0", ")", "+", "3", ";", "const", "e", "=", "{", "}", ";", "Error", ".", "captureStackTrace", "(", "e", ")", ";", "return", "parseStackLine", "(", "e", ".", "stack", ".", "split", "(", "/", "\\n", "/", ")", "[", "calls", "]", ")", ".", "filename", ";", "}" ]
Get callee filename @param {Number} [calls] - number of additional inner calls @returns {String} - filename of a file that call
[ "Get", "callee", "filename" ]
a40a069933879f7cb085b52870a3fee90bd6dc8d
https://github.com/node-eval/node-eval/blob/a40a069933879f7cb085b52870a3fee90bd6dc8d/index.js#L142-L147
train
osdat/jsdataframe
spec/dataframe-spec.js
function(subset, key) { return [ key.nRow(), key.nCol(), key.at(0, 'D'), key.at(0, 'C'), ]; }
javascript
function(subset, key) { return [ key.nRow(), key.nCol(), key.at(0, 'D'), key.at(0, 'C'), ]; }
[ "function", "(", "subset", ",", "key", ")", "{", "return", "[", "key", ".", "nRow", "(", ")", ",", "key", ".", "nCol", "(", ")", ",", "key", ".", "at", "(", "0", ",", "'D'", ")", ",", "key", ".", "at", "(", "0", ",", "'C'", ")", ",", "]", ";", "}" ]
Check groupKey dimensions and content
[ "Check", "groupKey", "dimensions", "and", "content" ]
d9f2028b33f9565c92329ccbca8c0fc1e865d97e
https://github.com/osdat/jsdataframe/blob/d9f2028b33f9565c92329ccbca8c0fc1e865d97e/spec/dataframe-spec.js#L1744-L1751
train
osdat/jsdataframe
spec/dataframe-spec.js
function(joinDf, indicatorValues) { var boolInd = joinDf.c('_join').isIn(indicatorValues); return joinDf.s(boolInd); }
javascript
function(joinDf, indicatorValues) { var boolInd = joinDf.c('_join').isIn(indicatorValues); return joinDf.s(boolInd); }
[ "function", "(", "joinDf", ",", "indicatorValues", ")", "{", "var", "boolInd", "=", "joinDf", ".", "c", "(", "'_join'", ")", ".", "isIn", "(", "indicatorValues", ")", ";", "return", "joinDf", ".", "s", "(", "boolInd", ")", ";", "}" ]
Helper for subsetting joinDf by only selecting rows with "_join" column containing values in "indicatorValues"
[ "Helper", "for", "subsetting", "joinDf", "by", "only", "selecting", "rows", "with", "_join", "column", "containing", "values", "in", "indicatorValues" ]
d9f2028b33f9565c92329ccbca8c0fc1e865d97e
https://github.com/osdat/jsdataframe/blob/d9f2028b33f9565c92329ccbca8c0fc1e865d97e/spec/dataframe-spec.js#L2477-L2480
train
osdat/jsdataframe
jsdataframe.js
dfFromMatrixHelper
function dfFromMatrixHelper(matrix, startRow, colNames) { var nCol = colNames.size(); var nRow = matrix.length - startRow; var columns = allocArray(nCol); var j; for (j = 0; j < nCol; j++) { columns[j] = allocArray(nRow); } for (var i = 0; i < nRow; i++) { var rowArray = matrix[i + startRow]; if (rowArray.length !== nCol) { throw new Error('all row arrays must be of the same size'); } for (j = 0; j < nCol; j++) { columns[j][i] = rowArray[j]; } } return newDataFrame(columns, colNames); }
javascript
function dfFromMatrixHelper(matrix, startRow, colNames) { var nCol = colNames.size(); var nRow = matrix.length - startRow; var columns = allocArray(nCol); var j; for (j = 0; j < nCol; j++) { columns[j] = allocArray(nRow); } for (var i = 0; i < nRow; i++) { var rowArray = matrix[i + startRow]; if (rowArray.length !== nCol) { throw new Error('all row arrays must be of the same size'); } for (j = 0; j < nCol; j++) { columns[j][i] = rowArray[j]; } } return newDataFrame(columns, colNames); }
[ "function", "dfFromMatrixHelper", "(", "matrix", ",", "startRow", ",", "colNames", ")", "{", "var", "nCol", "=", "colNames", ".", "size", "(", ")", ";", "var", "nRow", "=", "matrix", ".", "length", "-", "startRow", ";", "var", "columns", "=", "allocArray", "(", "nCol", ")", ";", "var", "j", ";", "for", "(", "j", "=", "0", ";", "j", "<", "nCol", ";", "j", "++", ")", "{", "columns", "[", "j", "]", "=", "allocArray", "(", "nRow", ")", ";", "}", "for", "(", "var", "i", "=", "0", ";", "i", "<", "nRow", ";", "i", "++", ")", "{", "var", "rowArray", "=", "matrix", "[", "i", "+", "startRow", "]", ";", "if", "(", "rowArray", ".", "length", "!==", "nCol", ")", "{", "throw", "new", "Error", "(", "'all row arrays must be of the same size'", ")", ";", "}", "for", "(", "j", "=", "0", ";", "j", "<", "nCol", ";", "j", "++", ")", "{", "columns", "[", "j", "]", "[", "i", "]", "=", "rowArray", "[", "j", "]", ";", "}", "}", "return", "newDataFrame", "(", "columns", ",", "colNames", ")", ";", "}" ]
Forms a data frame using 'matrix' starting with 'startRow' and setting column names to the 'colNames' string vector
[ "Forms", "a", "data", "frame", "using", "matrix", "starting", "with", "startRow", "and", "setting", "column", "names", "to", "the", "colNames", "string", "vector" ]
d9f2028b33f9565c92329ccbca8c0fc1e865d97e
https://github.com/osdat/jsdataframe/blob/d9f2028b33f9565c92329ccbca8c0fc1e865d97e/jsdataframe.js#L498-L516
train
osdat/jsdataframe
jsdataframe.js
rightAlign
function rightAlign(strVec) { var maxWidth = strVec.nChar().max(); var padding = jd.rep(' ', maxWidth).strJoin(''); return strVec.map(function(str) { return (padding + str).slice(-padding.length); }); }
javascript
function rightAlign(strVec) { var maxWidth = strVec.nChar().max(); var padding = jd.rep(' ', maxWidth).strJoin(''); return strVec.map(function(str) { return (padding + str).slice(-padding.length); }); }
[ "function", "rightAlign", "(", "strVec", ")", "{", "var", "maxWidth", "=", "strVec", ".", "nChar", "(", ")", ".", "max", "(", ")", ";", "var", "padding", "=", "jd", ".", "rep", "(", "' '", ",", "maxWidth", ")", ".", "strJoin", "(", "''", ")", ";", "return", "strVec", ".", "map", "(", "function", "(", "str", ")", "{", "return", "(", "padding", "+", "str", ")", ".", "slice", "(", "-", "padding", ".", "length", ")", ";", "}", ")", ";", "}" ]
Helper for right-aligning every element in a string vector, padding with spaces so all elements are the same width
[ "Helper", "for", "right", "-", "aligning", "every", "element", "in", "a", "string", "vector", "padding", "with", "spaces", "so", "all", "elements", "are", "the", "same", "width" ]
d9f2028b33f9565c92329ccbca8c0fc1e865d97e
https://github.com/osdat/jsdataframe/blob/d9f2028b33f9565c92329ccbca8c0fc1e865d97e/jsdataframe.js#L952-L958
train
osdat/jsdataframe
jsdataframe.js
makeRowIds
function makeRowIds(numRows, maxLines) { var printVec = jd.seq(numRows)._toTruncatedPrintVector(maxLines); return printVec.map(function(str) { return str === _SKIP_MARKER ? str : str + _ROW_ID_SUFFIX; }); }
javascript
function makeRowIds(numRows, maxLines) { var printVec = jd.seq(numRows)._toTruncatedPrintVector(maxLines); return printVec.map(function(str) { return str === _SKIP_MARKER ? str : str + _ROW_ID_SUFFIX; }); }
[ "function", "makeRowIds", "(", "numRows", ",", "maxLines", ")", "{", "var", "printVec", "=", "jd", ".", "seq", "(", "numRows", ")", ".", "_toTruncatedPrintVector", "(", "maxLines", ")", ";", "return", "printVec", ".", "map", "(", "function", "(", "str", ")", "{", "return", "str", "===", "_SKIP_MARKER", "?", "str", ":", "str", "+", "_ROW_ID_SUFFIX", ";", "}", ")", ";", "}" ]
Helper to create column of row ids for printing
[ "Helper", "to", "create", "column", "of", "row", "ids", "for", "printing" ]
d9f2028b33f9565c92329ccbca8c0fc1e865d97e
https://github.com/osdat/jsdataframe/blob/d9f2028b33f9565c92329ccbca8c0fc1e865d97e/jsdataframe.js#L961-L966
train
osdat/jsdataframe
jsdataframe.js
toPrintString
function toPrintString(value) { if (isUndefined(value)) { return 'undefined'; } else if (value === null) { return 'null'; } else if (Number.isNaN(value)) { return 'NaN'; } else { var str = coerceToStr(value); var lines = str.split('\n', 2); if (lines.length > 1) { str = lines[0] + '...'; } if (str.length > _MAX_STR_WIDTH) { str = str.slice(0, _MAX_STR_WIDTH - 3) + '...'; } return str; } }
javascript
function toPrintString(value) { if (isUndefined(value)) { return 'undefined'; } else if (value === null) { return 'null'; } else if (Number.isNaN(value)) { return 'NaN'; } else { var str = coerceToStr(value); var lines = str.split('\n', 2); if (lines.length > 1) { str = lines[0] + '...'; } if (str.length > _MAX_STR_WIDTH) { str = str.slice(0, _MAX_STR_WIDTH - 3) + '...'; } return str; } }
[ "function", "toPrintString", "(", "value", ")", "{", "if", "(", "isUndefined", "(", "value", ")", ")", "{", "return", "'undefined'", ";", "}", "else", "if", "(", "value", "===", "null", ")", "{", "return", "'null'", ";", "}", "else", "if", "(", "Number", ".", "isNaN", "(", "value", ")", ")", "{", "return", "'NaN'", ";", "}", "else", "{", "var", "str", "=", "coerceToStr", "(", "value", ")", ";", "var", "lines", "=", "str", ".", "split", "(", "'\\n'", ",", "\\n", ")", ";", "2", "if", "(", "lines", ".", "length", ">", "1", ")", "{", "str", "=", "lines", "[", "0", "]", "+", "'...'", ";", "}", "if", "(", "str", ".", "length", ">", "_MAX_STR_WIDTH", ")", "{", "str", "=", "str", ".", "slice", "(", "0", ",", "_MAX_STR_WIDTH", "-", "3", ")", "+", "'...'", ";", "}", "}", "}" ]
Helper for converting a value to a printable string
[ "Helper", "for", "converting", "a", "value", "to", "a", "printable", "string" ]
d9f2028b33f9565c92329ccbca8c0fc1e865d97e
https://github.com/osdat/jsdataframe/blob/d9f2028b33f9565c92329ccbca8c0fc1e865d97e/jsdataframe.js#L969-L987
train
osdat/jsdataframe
jsdataframe.js
validatePrintMax
function validatePrintMax(candidate, lowerBound, label) { if (typeof candidate !== 'number' || Number.isNaN(candidate)) { throw new Error('"' + label + '" must be a number'); } else if (candidate < lowerBound) { throw new Error('"' + label + '" too small'); } }
javascript
function validatePrintMax(candidate, lowerBound, label) { if (typeof candidate !== 'number' || Number.isNaN(candidate)) { throw new Error('"' + label + '" must be a number'); } else if (candidate < lowerBound) { throw new Error('"' + label + '" too small'); } }
[ "function", "validatePrintMax", "(", "candidate", ",", "lowerBound", ",", "label", ")", "{", "if", "(", "typeof", "candidate", "!==", "'number'", "||", "Number", ".", "isNaN", "(", "candidate", ")", ")", "{", "throw", "new", "Error", "(", "'\"'", "+", "label", "+", "'\" must be a number'", ")", ";", "}", "else", "if", "(", "candidate", "<", "lowerBound", ")", "{", "throw", "new", "Error", "(", "'\"'", "+", "label", "+", "'\" too small'", ")", ";", "}", "}" ]
Helper to validate a candidate print maximum
[ "Helper", "to", "validate", "a", "candidate", "print", "maximum" ]
d9f2028b33f9565c92329ccbca8c0fc1e865d97e
https://github.com/osdat/jsdataframe/blob/d9f2028b33f9565c92329ccbca8c0fc1e865d97e/jsdataframe.js#L991-L997
train
osdat/jsdataframe
jsdataframe.js
fractionDigits
function fractionDigits(number) { var splitArr = number.toString().split('.'); return (splitArr.length > 1) ? splitArr[1].length : 0; }
javascript
function fractionDigits(number) { var splitArr = number.toString().split('.'); return (splitArr.length > 1) ? splitArr[1].length : 0; }
[ "function", "fractionDigits", "(", "number", ")", "{", "var", "splitArr", "=", "number", ".", "toString", "(", ")", ".", "split", "(", "'.'", ")", ";", "return", "(", "splitArr", ".", "length", ">", "1", ")", "?", "splitArr", "[", "1", "]", ".", "length", ":", "0", ";", "}" ]
Helper for retrieving the number of digits after the decimal point for the given number. This function doesn't work for numbers represented in scientific notation, but such numbers will trigger different printing logic anyway.
[ "Helper", "for", "retrieving", "the", "number", "of", "digits", "after", "the", "decimal", "point", "for", "the", "given", "number", ".", "This", "function", "doesn", "t", "work", "for", "numbers", "represented", "in", "scientific", "notation", "but", "such", "numbers", "will", "trigger", "different", "printing", "logic", "anyway", "." ]
d9f2028b33f9565c92329ccbca8c0fc1e865d97e
https://github.com/osdat/jsdataframe/blob/d9f2028b33f9565c92329ccbca8c0fc1e865d97e/jsdataframe.js#L1003-L1008
train
osdat/jsdataframe
jsdataframe.js
packVector
function packVector(vector, includeMetadata) { includeMetadata = isUndefined(includeMetadata) ? true : includeMetadata; var dtype = vector.dtype; if (vector.dtype === 'date') { vector = vector.toDtype('number'); } var values = (vector.dtype !== 'number') ? vector.values.slice() : vector.values.map(function(x) { return Number.isNaN(x) ? null : x; }); var result = {dtype: dtype, values: values}; if (includeMetadata) { result.version = jd.version; result.type = vectorProto.type; } return result; }
javascript
function packVector(vector, includeMetadata) { includeMetadata = isUndefined(includeMetadata) ? true : includeMetadata; var dtype = vector.dtype; if (vector.dtype === 'date') { vector = vector.toDtype('number'); } var values = (vector.dtype !== 'number') ? vector.values.slice() : vector.values.map(function(x) { return Number.isNaN(x) ? null : x; }); var result = {dtype: dtype, values: values}; if (includeMetadata) { result.version = jd.version; result.type = vectorProto.type; } return result; }
[ "function", "packVector", "(", "vector", ",", "includeMetadata", ")", "{", "includeMetadata", "=", "isUndefined", "(", "includeMetadata", ")", "?", "true", ":", "includeMetadata", ";", "var", "dtype", "=", "vector", ".", "dtype", ";", "if", "(", "vector", ".", "dtype", "===", "'date'", ")", "{", "vector", "=", "vector", ".", "toDtype", "(", "'number'", ")", ";", "}", "var", "values", "=", "(", "vector", ".", "dtype", "!==", "'number'", ")", "?", "vector", ".", "values", ".", "slice", "(", ")", ":", "vector", ".", "values", ".", "map", "(", "function", "(", "x", ")", "{", "return", "Number", ".", "isNaN", "(", "x", ")", "?", "null", ":", "x", ";", "}", ")", ";", "var", "result", "=", "{", "dtype", ":", "dtype", ",", "values", ":", "values", "}", ";", "if", "(", "includeMetadata", ")", "{", "result", ".", "version", "=", "jd", ".", "version", ";", "result", ".", "type", "=", "vectorProto", ".", "type", ";", "}", "return", "result", ";", "}" ]
Helper for packing the given vector, including metadata by default
[ "Helper", "for", "packing", "the", "given", "vector", "including", "metadata", "by", "default" ]
d9f2028b33f9565c92329ccbca8c0fc1e865d97e
https://github.com/osdat/jsdataframe/blob/d9f2028b33f9565c92329ccbca8c0fc1e865d97e/jsdataframe.js#L1070-L1088
train
osdat/jsdataframe
jsdataframe.js
numClose
function numClose(x, y) { return (Number.isNaN(x) && Number.isNaN(y)) || Math.abs(x - y) <= 1e-7; }
javascript
function numClose(x, y) { return (Number.isNaN(x) && Number.isNaN(y)) || Math.abs(x - y) <= 1e-7; }
[ "function", "numClose", "(", "x", ",", "y", ")", "{", "return", "(", "Number", ".", "isNaN", "(", "x", ")", "&&", "Number", ".", "isNaN", "(", "y", ")", ")", "||", "Math", ".", "abs", "(", "x", "-", "y", ")", "<=", "1e-7", ";", "}" ]
Returns true if x and y are within 1e-7 tolerance or are both NaN
[ "Returns", "true", "if", "x", "and", "y", "are", "within", "1e", "-", "7", "tolerance", "or", "are", "both", "NaN" ]
d9f2028b33f9565c92329ccbca8c0fc1e865d97e
https://github.com/osdat/jsdataframe/blob/d9f2028b33f9565c92329ccbca8c0fc1e865d97e/jsdataframe.js#L1407-L1410
train
osdat/jsdataframe
jsdataframe.js
appendJoinRow
function appendJoinRow(arrayCols, keyDf, leftNonKeyDf, rightNonKeyDf, leftInd, rightInd, indicatorValue, rightIndForKey) { var keyInd = rightIndForKey ? rightInd : leftInd; var i, nCol; var colInd = 0; nCol = keyDf.nCol(); for (i = 0; i < nCol; i++) { arrayCols[colInd].push(keyDf._cols[i].values[keyInd]); colInd++; } nCol = leftNonKeyDf.nCol(); for (i = 0; i < nCol; i++) { var leftVal = (leftInd === null) ? null : leftNonKeyDf._cols[i].values[leftInd]; arrayCols[colInd].push(leftVal); colInd++; } nCol = rightNonKeyDf.nCol(); for (i = 0; i < nCol; i++) { var rightVal = (rightInd === null) ? null : rightNonKeyDf._cols[i].values[rightInd]; arrayCols[colInd].push(rightVal); colInd++; } if (colInd < arrayCols.length) { // Add the join indicator value if there's a final column for it arrayCols[colInd].push(indicatorValue); } }
javascript
function appendJoinRow(arrayCols, keyDf, leftNonKeyDf, rightNonKeyDf, leftInd, rightInd, indicatorValue, rightIndForKey) { var keyInd = rightIndForKey ? rightInd : leftInd; var i, nCol; var colInd = 0; nCol = keyDf.nCol(); for (i = 0; i < nCol; i++) { arrayCols[colInd].push(keyDf._cols[i].values[keyInd]); colInd++; } nCol = leftNonKeyDf.nCol(); for (i = 0; i < nCol; i++) { var leftVal = (leftInd === null) ? null : leftNonKeyDf._cols[i].values[leftInd]; arrayCols[colInd].push(leftVal); colInd++; } nCol = rightNonKeyDf.nCol(); for (i = 0; i < nCol; i++) { var rightVal = (rightInd === null) ? null : rightNonKeyDf._cols[i].values[rightInd]; arrayCols[colInd].push(rightVal); colInd++; } if (colInd < arrayCols.length) { // Add the join indicator value if there's a final column for it arrayCols[colInd].push(indicatorValue); } }
[ "function", "appendJoinRow", "(", "arrayCols", ",", "keyDf", ",", "leftNonKeyDf", ",", "rightNonKeyDf", ",", "leftInd", ",", "rightInd", ",", "indicatorValue", ",", "rightIndForKey", ")", "{", "var", "keyInd", "=", "rightIndForKey", "?", "rightInd", ":", "leftInd", ";", "var", "i", ",", "nCol", ";", "var", "colInd", "=", "0", ";", "nCol", "=", "keyDf", ".", "nCol", "(", ")", ";", "for", "(", "i", "=", "0", ";", "i", "<", "nCol", ";", "i", "++", ")", "{", "arrayCols", "[", "colInd", "]", ".", "push", "(", "keyDf", ".", "_cols", "[", "i", "]", ".", "values", "[", "keyInd", "]", ")", ";", "colInd", "++", ";", "}", "nCol", "=", "leftNonKeyDf", ".", "nCol", "(", ")", ";", "for", "(", "i", "=", "0", ";", "i", "<", "nCol", ";", "i", "++", ")", "{", "var", "leftVal", "=", "(", "leftInd", "===", "null", ")", "?", "null", ":", "leftNonKeyDf", ".", "_cols", "[", "i", "]", ".", "values", "[", "leftInd", "]", ";", "arrayCols", "[", "colInd", "]", ".", "push", "(", "leftVal", ")", ";", "colInd", "++", ";", "}", "nCol", "=", "rightNonKeyDf", ".", "nCol", "(", ")", ";", "for", "(", "i", "=", "0", ";", "i", "<", "nCol", ";", "i", "++", ")", "{", "var", "rightVal", "=", "(", "rightInd", "===", "null", ")", "?", "null", ":", "rightNonKeyDf", ".", "_cols", "[", "i", "]", ".", "values", "[", "rightInd", "]", ";", "arrayCols", "[", "colInd", "]", ".", "push", "(", "rightVal", ")", ";", "colInd", "++", ";", "}", "if", "(", "colInd", "<", "arrayCols", ".", "length", ")", "{", "arrayCols", "[", "colInd", "]", ".", "push", "(", "indicatorValue", ")", ";", "}", "}" ]
Helper for appending values to "arrayCols" from "leftInd" and "rightInd"
[ "Helper", "for", "appending", "values", "to", "arrayCols", "from", "leftInd", "and", "rightInd" ]
d9f2028b33f9565c92329ccbca8c0fc1e865d97e
https://github.com/osdat/jsdataframe/blob/d9f2028b33f9565c92329ccbca8c0fc1e865d97e/jsdataframe.js#L3122-L3151
train
osdat/jsdataframe
jsdataframe.js
keyIndexing
function keyIndexing(selector, maxLen, index) { var opts = resolverOpts(RESOLVE_MODE.KEY, maxLen, index); return resolveSelector(selector, opts); }
javascript
function keyIndexing(selector, maxLen, index) { var opts = resolverOpts(RESOLVE_MODE.KEY, maxLen, index); return resolveSelector(selector, opts); }
[ "function", "keyIndexing", "(", "selector", ",", "maxLen", ",", "index", ")", "{", "var", "opts", "=", "resolverOpts", "(", "RESOLVE_MODE", ".", "KEY", ",", "maxLen", ",", "index", ")", ";", "return", "resolveSelector", "(", "selector", ",", "opts", ")", ";", "}" ]
Perform key lookup indexing 'index' should be an AbstractIndex implementation
[ "Perform", "key", "lookup", "indexing", "index", "should", "be", "an", "AbstractIndex", "implementation" ]
d9f2028b33f9565c92329ccbca8c0fc1e865d97e
https://github.com/osdat/jsdataframe/blob/d9f2028b33f9565c92329ccbca8c0fc1e865d97e/jsdataframe.js#L3367-L3370
train
osdat/jsdataframe
jsdataframe.js
attemptBoolIndexing
function attemptBoolIndexing(selector, maxLen) { if (selector.type === exclusionProto.type) { var intIdxVector = attemptBoolIndexing(selector._selector, maxLen); return isUndefined(intIdxVector) ? undefined : excludeIntIndices(intIdxVector, maxLen); } if (Array.isArray(selector)) { selector = inferVectorDtype(selector.slice(), 'object'); } if (selector.type === vectorProto.type && selector.dtype === 'boolean') { if (selector.size() !== maxLen) { throw new Error('inappropriate boolean indexer length (' + selector.size() + '); expected length to be ' + maxLen); } return selector.which(); } }
javascript
function attemptBoolIndexing(selector, maxLen) { if (selector.type === exclusionProto.type) { var intIdxVector = attemptBoolIndexing(selector._selector, maxLen); return isUndefined(intIdxVector) ? undefined : excludeIntIndices(intIdxVector, maxLen); } if (Array.isArray(selector)) { selector = inferVectorDtype(selector.slice(), 'object'); } if (selector.type === vectorProto.type && selector.dtype === 'boolean') { if (selector.size() !== maxLen) { throw new Error('inappropriate boolean indexer length (' + selector.size() + '); expected length to be ' + maxLen); } return selector.which(); } }
[ "function", "attemptBoolIndexing", "(", "selector", ",", "maxLen", ")", "{", "if", "(", "selector", ".", "type", "===", "exclusionProto", ".", "type", ")", "{", "var", "intIdxVector", "=", "attemptBoolIndexing", "(", "selector", ".", "_selector", ",", "maxLen", ")", ";", "return", "isUndefined", "(", "intIdxVector", ")", "?", "undefined", ":", "excludeIntIndices", "(", "intIdxVector", ",", "maxLen", ")", ";", "}", "if", "(", "Array", ".", "isArray", "(", "selector", ")", ")", "{", "selector", "=", "inferVectorDtype", "(", "selector", ".", "slice", "(", ")", ",", "'object'", ")", ";", "}", "if", "(", "selector", ".", "type", "===", "vectorProto", ".", "type", "&&", "selector", ".", "dtype", "===", "'boolean'", ")", "{", "if", "(", "selector", ".", "size", "(", ")", "!==", "maxLen", ")", "{", "throw", "new", "Error", "(", "'inappropriate boolean indexer length ('", "+", "selector", ".", "size", "(", ")", "+", "'); expected length to be '", "+", "maxLen", ")", ";", "}", "return", "selector", ".", "which", "(", ")", ";", "}", "}" ]
Performs boolean indexing if 'selector' is a boolean vector or array of the same length as maxLen or an exclusion wrapping such a vector or array. Returns undefined if 'selector' is inappropriate for boolean indexing; returns a vector of integer indices if boolean indexing resolves appropriately.
[ "Performs", "boolean", "indexing", "if", "selector", "is", "a", "boolean", "vector", "or", "array", "of", "the", "same", "length", "as", "maxLen", "or", "an", "exclusion", "wrapping", "such", "a", "vector", "or", "array", ".", "Returns", "undefined", "if", "selector", "is", "inappropriate", "for", "boolean", "indexing", ";", "returns", "a", "vector", "of", "integer", "indices", "if", "boolean", "indexing", "resolves", "appropriately", "." ]
d9f2028b33f9565c92329ccbca8c0fc1e865d97e
https://github.com/osdat/jsdataframe/blob/d9f2028b33f9565c92329ccbca8c0fc1e865d97e/jsdataframe.js#L3379-L3396
train
osdat/jsdataframe
jsdataframe.js
excludeIntIndices
function excludeIntIndices(intIdxVector, maxLen) { return jd.seq(maxLen).isIn(intIdxVector).not().which(); }
javascript
function excludeIntIndices(intIdxVector, maxLen) { return jd.seq(maxLen).isIn(intIdxVector).not().which(); }
[ "function", "excludeIntIndices", "(", "intIdxVector", ",", "maxLen", ")", "{", "return", "jd", ".", "seq", "(", "maxLen", ")", ".", "isIn", "(", "intIdxVector", ")", ".", "not", "(", ")", ".", "which", "(", ")", ";", "}" ]
Returns the integer indices resulting from excluding the intIdxVector based on the given maxLen
[ "Returns", "the", "integer", "indices", "resulting", "from", "excluding", "the", "intIdxVector", "based", "on", "the", "given", "maxLen" ]
d9f2028b33f9565c92329ccbca8c0fc1e865d97e
https://github.com/osdat/jsdataframe/blob/d9f2028b33f9565c92329ccbca8c0fc1e865d97e/jsdataframe.js#L3401-L3403
train
osdat/jsdataframe
jsdataframe.js
resolveSelector
function resolveSelector(selector, opts) { var resultArr = []; resolveSelectorHelper(selector, opts, resultArr); return newVector(resultArr, 'number'); }
javascript
function resolveSelector(selector, opts) { var resultArr = []; resolveSelectorHelper(selector, opts, resultArr); return newVector(resultArr, 'number'); }
[ "function", "resolveSelector", "(", "selector", ",", "opts", ")", "{", "var", "resultArr", "=", "[", "]", ";", "resolveSelectorHelper", "(", "selector", ",", "opts", ",", "resultArr", ")", ";", "return", "newVector", "(", "resultArr", ",", "'number'", ")", ";", "}" ]
Resolve a selector to a vector of integer indices using the 'opts' object
[ "Resolve", "a", "selector", "to", "a", "vector", "of", "integer", "indices", "using", "the", "opts", "object" ]
d9f2028b33f9565c92329ccbca8c0fc1e865d97e
https://github.com/osdat/jsdataframe/blob/d9f2028b33f9565c92329ccbca8c0fc1e865d97e/jsdataframe.js#L3424-L3428
train
osdat/jsdataframe
jsdataframe.js
resolveSelectorHelper
function resolveSelectorHelper(selector, opts, resultArr) { if (selector !== null && typeof selector === 'object') { if (typeof selector._resolveSelectorHelper === 'function') { selector._resolveSelectorHelper(opts, resultArr); return; } if (Array.isArray(selector)) { for (var i = 0; i < selector.length; i++) { resolveSelectorHelper(selector[i], opts, resultArr); } return; } } // Handle scalar case var intInds; switch (opts.resolveMode) { case RESOLVE_MODE.INT: resultArr.push(resolveIntIdx(selector, opts.maxLen)); break; case RESOLVE_MODE.COL: if (isNumber(selector)) { resultArr.push(resolveIntIdx(selector, opts.maxLen)); } else if (isString(selector) || selector === null) { intInds = opts.index.lookupKey([selector]); processLookupResults(intInds, selector, opts, resultArr); } else { throw new Error('expected integer or string selector but got: ' + selector); } break; case RESOLVE_MODE.KEY: if (opts.index.arity === 1) { var expectedDtype = opts.index.initVectors[0].dtype; validateScalarIsDtype(selector, expectedDtype); intInds = opts.index.lookupKey([selector]); processLookupResults(intInds, selector, opts, resultArr); } else { // TODO throw new Error('unimplemented case (TODO)'); } break; default: throw new Error('Unrecognized RESOLVE_MODE: ' + opts.resolveMode); } }
javascript
function resolveSelectorHelper(selector, opts, resultArr) { if (selector !== null && typeof selector === 'object') { if (typeof selector._resolveSelectorHelper === 'function') { selector._resolveSelectorHelper(opts, resultArr); return; } if (Array.isArray(selector)) { for (var i = 0; i < selector.length; i++) { resolveSelectorHelper(selector[i], opts, resultArr); } return; } } // Handle scalar case var intInds; switch (opts.resolveMode) { case RESOLVE_MODE.INT: resultArr.push(resolveIntIdx(selector, opts.maxLen)); break; case RESOLVE_MODE.COL: if (isNumber(selector)) { resultArr.push(resolveIntIdx(selector, opts.maxLen)); } else if (isString(selector) || selector === null) { intInds = opts.index.lookupKey([selector]); processLookupResults(intInds, selector, opts, resultArr); } else { throw new Error('expected integer or string selector but got: ' + selector); } break; case RESOLVE_MODE.KEY: if (opts.index.arity === 1) { var expectedDtype = opts.index.initVectors[0].dtype; validateScalarIsDtype(selector, expectedDtype); intInds = opts.index.lookupKey([selector]); processLookupResults(intInds, selector, opts, resultArr); } else { // TODO throw new Error('unimplemented case (TODO)'); } break; default: throw new Error('Unrecognized RESOLVE_MODE: ' + opts.resolveMode); } }
[ "function", "resolveSelectorHelper", "(", "selector", ",", "opts", ",", "resultArr", ")", "{", "if", "(", "selector", "!==", "null", "&&", "typeof", "selector", "===", "'object'", ")", "{", "if", "(", "typeof", "selector", ".", "_resolveSelectorHelper", "===", "'function'", ")", "{", "selector", ".", "_resolveSelectorHelper", "(", "opts", ",", "resultArr", ")", ";", "return", ";", "}", "if", "(", "Array", ".", "isArray", "(", "selector", ")", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "selector", ".", "length", ";", "i", "++", ")", "{", "resolveSelectorHelper", "(", "selector", "[", "i", "]", ",", "opts", ",", "resultArr", ")", ";", "}", "return", ";", "}", "}", "var", "intInds", ";", "switch", "(", "opts", ".", "resolveMode", ")", "{", "case", "RESOLVE_MODE", ".", "INT", ":", "resultArr", ".", "push", "(", "resolveIntIdx", "(", "selector", ",", "opts", ".", "maxLen", ")", ")", ";", "break", ";", "case", "RESOLVE_MODE", ".", "COL", ":", "if", "(", "isNumber", "(", "selector", ")", ")", "{", "resultArr", ".", "push", "(", "resolveIntIdx", "(", "selector", ",", "opts", ".", "maxLen", ")", ")", ";", "}", "else", "if", "(", "isString", "(", "selector", ")", "||", "selector", "===", "null", ")", "{", "intInds", "=", "opts", ".", "index", ".", "lookupKey", "(", "[", "selector", "]", ")", ";", "processLookupResults", "(", "intInds", ",", "selector", ",", "opts", ",", "resultArr", ")", ";", "}", "else", "{", "throw", "new", "Error", "(", "'expected integer or string selector but got: '", "+", "selector", ")", ";", "}", "break", ";", "case", "RESOLVE_MODE", ".", "KEY", ":", "if", "(", "opts", ".", "index", ".", "arity", "===", "1", ")", "{", "var", "expectedDtype", "=", "opts", ".", "index", ".", "initVectors", "[", "0", "]", ".", "dtype", ";", "validateScalarIsDtype", "(", "selector", ",", "expectedDtype", ")", ";", "intInds", "=", "opts", ".", "index", ".", "lookupKey", "(", "[", "selector", "]", ")", ";", "processLookupResults", "(", "intInds", ",", "selector", ",", "opts", ",", "resultArr", ")", ";", "}", "else", "{", "throw", "new", "Error", "(", "'unimplemented case (TODO)'", ")", ";", "}", "break", ";", "default", ":", "throw", "new", "Error", "(", "'Unrecognized RESOLVE_MODE: '", "+", "opts", ".", "resolveMode", ")", ";", "}", "}" ]
Recursive helper that updates running results in 'resultArr'
[ "Recursive", "helper", "that", "updates", "running", "results", "in", "resultArr" ]
d9f2028b33f9565c92329ccbca8c0fc1e865d97e
https://github.com/osdat/jsdataframe/blob/d9f2028b33f9565c92329ccbca8c0fc1e865d97e/jsdataframe.js#L3430-L3475
train
osdat/jsdataframe
jsdataframe.js
resolveRangeBound
function resolveRangeBound(bound, opts, isStop, includeStop) { var result; if (isUndefined(bound)) { return isStop ? opts.maxLen : 0; } var useIntIndexing = ( opts.resolveMode === RESOLVE_MODE.INT || (opts.resolveMode === RESOLVE_MODE.COL && typeof bound === 'number') ); if (includeStop === null) { includeStop = useIntIndexing ? false : true; } if (useIntIndexing) { result = resolveIntIdx(bound, opts.maxLen, false); return (isStop && includeStop) ? result + 1 : result; } else { if (opts.index.arity === 1) { result = opts.index.lookupKey([bound]); if (result === null) { throw new Error('could not find entry for range bound: ' + bound); } else if (typeof result === 'number') { return (isStop && includeStop) ? result + 1 : result; } else { return (isStop && includeStop) ? result[result.length - 1] + 1 : result[0]; } } else { // TODO throw new Error('unimplemented case (TODO)'); } } }
javascript
function resolveRangeBound(bound, opts, isStop, includeStop) { var result; if (isUndefined(bound)) { return isStop ? opts.maxLen : 0; } var useIntIndexing = ( opts.resolveMode === RESOLVE_MODE.INT || (opts.resolveMode === RESOLVE_MODE.COL && typeof bound === 'number') ); if (includeStop === null) { includeStop = useIntIndexing ? false : true; } if (useIntIndexing) { result = resolveIntIdx(bound, opts.maxLen, false); return (isStop && includeStop) ? result + 1 : result; } else { if (opts.index.arity === 1) { result = opts.index.lookupKey([bound]); if (result === null) { throw new Error('could not find entry for range bound: ' + bound); } else if (typeof result === 'number') { return (isStop && includeStop) ? result + 1 : result; } else { return (isStop && includeStop) ? result[result.length - 1] + 1 : result[0]; } } else { // TODO throw new Error('unimplemented case (TODO)'); } } }
[ "function", "resolveRangeBound", "(", "bound", ",", "opts", ",", "isStop", ",", "includeStop", ")", "{", "var", "result", ";", "if", "(", "isUndefined", "(", "bound", ")", ")", "{", "return", "isStop", "?", "opts", ".", "maxLen", ":", "0", ";", "}", "var", "useIntIndexing", "=", "(", "opts", ".", "resolveMode", "===", "RESOLVE_MODE", ".", "INT", "||", "(", "opts", ".", "resolveMode", "===", "RESOLVE_MODE", ".", "COL", "&&", "typeof", "bound", "===", "'number'", ")", ")", ";", "if", "(", "includeStop", "===", "null", ")", "{", "includeStop", "=", "useIntIndexing", "?", "false", ":", "true", ";", "}", "if", "(", "useIntIndexing", ")", "{", "result", "=", "resolveIntIdx", "(", "bound", ",", "opts", ".", "maxLen", ",", "false", ")", ";", "return", "(", "isStop", "&&", "includeStop", ")", "?", "result", "+", "1", ":", "result", ";", "}", "else", "{", "if", "(", "opts", ".", "index", ".", "arity", "===", "1", ")", "{", "result", "=", "opts", ".", "index", ".", "lookupKey", "(", "[", "bound", "]", ")", ";", "if", "(", "result", "===", "null", ")", "{", "throw", "new", "Error", "(", "'could not find entry for range bound: '", "+", "bound", ")", ";", "}", "else", "if", "(", "typeof", "result", "===", "'number'", ")", "{", "return", "(", "isStop", "&&", "includeStop", ")", "?", "result", "+", "1", ":", "result", ";", "}", "else", "{", "return", "(", "isStop", "&&", "includeStop", ")", "?", "result", "[", "result", ".", "length", "-", "1", "]", "+", "1", ":", "result", "[", "0", "]", ";", "}", "}", "else", "{", "throw", "new", "Error", "(", "'unimplemented case (TODO)'", ")", ";", "}", "}", "}" ]
Returns the resolved integer index for the bound
[ "Returns", "the", "resolved", "integer", "index", "for", "the", "bound" ]
d9f2028b33f9565c92329ccbca8c0fc1e865d97e
https://github.com/osdat/jsdataframe/blob/d9f2028b33f9565c92329ccbca8c0fc1e865d97e/jsdataframe.js#L3553-L3585
train
osdat/jsdataframe
jsdataframe.js
resolveIntIdx
function resolveIntIdx(inputInt, maxLen, checkBounds) { if (isUndefined(checkBounds)) { checkBounds = true; } if (!Number.isInteger(inputInt)) { throw new Error('expected integer selector for integer indexing ' + 'but got non-integer: ' + inputInt); } var result = inputInt < 0 ? maxLen + inputInt : inputInt; if (checkBounds && (result < 0 || result >= maxLen)) { throw new Error('integer index out of bounds'); } return result; }
javascript
function resolveIntIdx(inputInt, maxLen, checkBounds) { if (isUndefined(checkBounds)) { checkBounds = true; } if (!Number.isInteger(inputInt)) { throw new Error('expected integer selector for integer indexing ' + 'but got non-integer: ' + inputInt); } var result = inputInt < 0 ? maxLen + inputInt : inputInt; if (checkBounds && (result < 0 || result >= maxLen)) { throw new Error('integer index out of bounds'); } return result; }
[ "function", "resolveIntIdx", "(", "inputInt", ",", "maxLen", ",", "checkBounds", ")", "{", "if", "(", "isUndefined", "(", "checkBounds", ")", ")", "{", "checkBounds", "=", "true", ";", "}", "if", "(", "!", "Number", ".", "isInteger", "(", "inputInt", ")", ")", "{", "throw", "new", "Error", "(", "'expected integer selector for integer indexing '", "+", "'but got non-integer: '", "+", "inputInt", ")", ";", "}", "var", "result", "=", "inputInt", "<", "0", "?", "maxLen", "+", "inputInt", ":", "inputInt", ";", "if", "(", "checkBounds", "&&", "(", "result", "<", "0", "||", "result", ">=", "maxLen", ")", ")", "{", "throw", "new", "Error", "(", "'integer index out of bounds'", ")", ";", "}", "return", "result", ";", "}" ]
Uses 'maxLen' to compute the integer index for 'inputInt' or throws an error if invalid. 'checkBounds' is true by default but if false, the resulting integer index won't be checked.
[ "Uses", "maxLen", "to", "compute", "the", "integer", "index", "for", "inputInt", "or", "throws", "an", "error", "if", "invalid", ".", "checkBounds", "is", "true", "by", "default", "but", "if", "false", "the", "resulting", "integer", "index", "won", "t", "be", "checked", "." ]
d9f2028b33f9565c92329ccbca8c0fc1e865d97e
https://github.com/osdat/jsdataframe/blob/d9f2028b33f9565c92329ccbca8c0fc1e865d97e/jsdataframe.js#L3615-L3628
train
osdat/jsdataframe
jsdataframe.js
processLookupResults
function processLookupResults(intInds, key, opts, resultArr) { if (intInds === null) { if (opts.resolveMode === RESOLVE_MODE.COL) { throw new Error('could not find column named "' + key + '"'); } else { throw new Error('could find entry for key: ' + key); } } else if (typeof intInds === 'number') { resultArr.push(intInds); } else { for (var j = 0; j < intInds.length; j++) { resultArr.push(intInds[j]); } } }
javascript
function processLookupResults(intInds, key, opts, resultArr) { if (intInds === null) { if (opts.resolveMode === RESOLVE_MODE.COL) { throw new Error('could not find column named "' + key + '"'); } else { throw new Error('could find entry for key: ' + key); } } else if (typeof intInds === 'number') { resultArr.push(intInds); } else { for (var j = 0; j < intInds.length; j++) { resultArr.push(intInds[j]); } } }
[ "function", "processLookupResults", "(", "intInds", ",", "key", ",", "opts", ",", "resultArr", ")", "{", "if", "(", "intInds", "===", "null", ")", "{", "if", "(", "opts", ".", "resolveMode", "===", "RESOLVE_MODE", ".", "COL", ")", "{", "throw", "new", "Error", "(", "'could not find column named \"'", "+", "key", "+", "'\"'", ")", ";", "}", "else", "{", "throw", "new", "Error", "(", "'could find entry for key: '", "+", "key", ")", ";", "}", "}", "else", "if", "(", "typeof", "intInds", "===", "'number'", ")", "{", "resultArr", ".", "push", "(", "intInds", ")", ";", "}", "else", "{", "for", "(", "var", "j", "=", "0", ";", "j", "<", "intInds", ".", "length", ";", "j", "++", ")", "{", "resultArr", ".", "push", "(", "intInds", "[", "j", "]", ")", ";", "}", "}", "}" ]
Processes 'intInds', the result returned from lookup via an AbstractIndex. Results are placed in 'resultArr' if present, or an error is thrown.
[ "Processes", "intInds", "the", "result", "returned", "from", "lookup", "via", "an", "AbstractIndex", ".", "Results", "are", "placed", "in", "resultArr", "if", "present", "or", "an", "error", "is", "thrown", "." ]
d9f2028b33f9565c92329ccbca8c0fc1e865d97e
https://github.com/osdat/jsdataframe/blob/d9f2028b33f9565c92329ccbca8c0fc1e865d97e/jsdataframe.js#L3633-L3647
train
osdat/jsdataframe
jsdataframe.js
singleColNameLookup
function singleColNameLookup(selector, colNames) { if (isUndefined(selector)) { throw new Error('selector must not be undefined'); } selector = ensureScalar(selector); if (isNumber(selector)) { return resolveIntIdx(selector, colNames.values.length); } else if (isString(selector) || selector === null) { var intInds = colNames._getIndex().lookupKey([selector]); if (intInds === null) { throw new Error('invalid column name: ' + selector); } else if (typeof intInds !== 'number') { // must be an array, so use the first element intInds = intInds[0]; } return intInds; } else { throw new Error('column selector must be an integer or string'); } }
javascript
function singleColNameLookup(selector, colNames) { if (isUndefined(selector)) { throw new Error('selector must not be undefined'); } selector = ensureScalar(selector); if (isNumber(selector)) { return resolveIntIdx(selector, colNames.values.length); } else if (isString(selector) || selector === null) { var intInds = colNames._getIndex().lookupKey([selector]); if (intInds === null) { throw new Error('invalid column name: ' + selector); } else if (typeof intInds !== 'number') { // must be an array, so use the first element intInds = intInds[0]; } return intInds; } else { throw new Error('column selector must be an integer or string'); } }
[ "function", "singleColNameLookup", "(", "selector", ",", "colNames", ")", "{", "if", "(", "isUndefined", "(", "selector", ")", ")", "{", "throw", "new", "Error", "(", "'selector must not be undefined'", ")", ";", "}", "selector", "=", "ensureScalar", "(", "selector", ")", ";", "if", "(", "isNumber", "(", "selector", ")", ")", "{", "return", "resolveIntIdx", "(", "selector", ",", "colNames", ".", "values", ".", "length", ")", ";", "}", "else", "if", "(", "isString", "(", "selector", ")", "||", "selector", "===", "null", ")", "{", "var", "intInds", "=", "colNames", ".", "_getIndex", "(", ")", ".", "lookupKey", "(", "[", "selector", "]", ")", ";", "if", "(", "intInds", "===", "null", ")", "{", "throw", "new", "Error", "(", "'invalid column name: '", "+", "selector", ")", ";", "}", "else", "if", "(", "typeof", "intInds", "!==", "'number'", ")", "{", "intInds", "=", "intInds", "[", "0", "]", ";", "}", "return", "intInds", ";", "}", "else", "{", "throw", "new", "Error", "(", "'column selector must be an integer or string'", ")", ";", "}", "}" ]
Returns the integer index of the first occurrence of a single column name or throws an error if 'selector' is invalid or no occurrence is found. 'selector' can be a single integer or string expressed as a scalar, array, or vector. 'colNames' must be a string vector
[ "Returns", "the", "integer", "index", "of", "the", "first", "occurrence", "of", "a", "single", "column", "name", "or", "throws", "an", "error", "if", "selector", "is", "invalid", "or", "no", "occurrence", "is", "found", ".", "selector", "can", "be", "a", "single", "integer", "or", "string", "expressed", "as", "a", "scalar", "array", "or", "vector", ".", "colNames", "must", "be", "a", "string", "vector" ]
d9f2028b33f9565c92329ccbca8c0fc1e865d97e
https://github.com/osdat/jsdataframe/blob/d9f2028b33f9565c92329ccbca8c0fc1e865d97e/jsdataframe.js#L3654-L3673
train
osdat/jsdataframe
jsdataframe.js
cleanKey
function cleanKey(key, dtype) { return ( key === null ? ESCAPED_KEYS.null : isUndefined(key) ? ESCAPED_KEYS.undefined : dtype === 'date' ? key.valueOf() : key ); }
javascript
function cleanKey(key, dtype) { return ( key === null ? ESCAPED_KEYS.null : isUndefined(key) ? ESCAPED_KEYS.undefined : dtype === 'date' ? key.valueOf() : key ); }
[ "function", "cleanKey", "(", "key", ",", "dtype", ")", "{", "return", "(", "key", "===", "null", "?", "ESCAPED_KEYS", ".", "null", ":", "isUndefined", "(", "key", ")", "?", "ESCAPED_KEYS", ".", "undefined", ":", "dtype", "===", "'date'", "?", "key", ".", "valueOf", "(", ")", ":", "key", ")", ";", "}" ]
Returns a clean version of the given 'key', transforming if the dtype doesn't hash well directly and escaping if necessary to avoid collisions for missing values
[ "Returns", "a", "clean", "version", "of", "the", "given", "key", "transforming", "if", "the", "dtype", "doesn", "t", "hash", "well", "directly", "and", "escaping", "if", "necessary", "to", "avoid", "collisions", "for", "missing", "values" ]
d9f2028b33f9565c92329ccbca8c0fc1e865d97e
https://github.com/osdat/jsdataframe/blob/d9f2028b33f9565c92329ccbca8c0fc1e865d97e/jsdataframe.js#L3845-L3852
train
osdat/jsdataframe
jsdataframe.js
newVector
function newVector(array, dtype) { validateDtype(dtype); var proto = PROTO_MAP[dtype]; var vector = Object.create(proto); vector._init(array); return vector; }
javascript
function newVector(array, dtype) { validateDtype(dtype); var proto = PROTO_MAP[dtype]; var vector = Object.create(proto); vector._init(array); return vector; }
[ "function", "newVector", "(", "array", ",", "dtype", ")", "{", "validateDtype", "(", "dtype", ")", ";", "var", "proto", "=", "PROTO_MAP", "[", "dtype", "]", ";", "var", "vector", "=", "Object", ".", "create", "(", "proto", ")", ";", "vector", ".", "_init", "(", "array", ")", ";", "return", "vector", ";", "}" ]
Constructs a vector of the given dtype backed by the given array without checking or modifying any of the array elements
[ "Constructs", "a", "vector", "of", "the", "given", "dtype", "backed", "by", "the", "given", "array", "without", "checking", "or", "modifying", "any", "of", "the", "array", "elements" ]
d9f2028b33f9565c92329ccbca8c0fc1e865d97e
https://github.com/osdat/jsdataframe/blob/d9f2028b33f9565c92329ccbca8c0fc1e865d97e/jsdataframe.js#L3977-L3983
train
osdat/jsdataframe
jsdataframe.js
mapNonNa
function mapNonNa(array, naValue, func) { var len = array.length; var result = allocArray(len); for (var i = 0; i < len; i++) { var value = array[i]; result[i] = isMissing(value) ? naValue : func(value); } return result; }
javascript
function mapNonNa(array, naValue, func) { var len = array.length; var result = allocArray(len); for (var i = 0; i < len; i++) { var value = array[i]; result[i] = isMissing(value) ? naValue : func(value); } return result; }
[ "function", "mapNonNa", "(", "array", ",", "naValue", ",", "func", ")", "{", "var", "len", "=", "array", ".", "length", ";", "var", "result", "=", "allocArray", "(", "len", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "len", ";", "i", "++", ")", "{", "var", "value", "=", "array", "[", "i", "]", ";", "result", "[", "i", "]", "=", "isMissing", "(", "value", ")", "?", "naValue", ":", "func", "(", "value", ")", ";", "}", "return", "result", ";", "}" ]
Maps the 'func' on all non-missing elements of array while immediately yielding 'naValue' instead of applying 'func' for any missing elements. The returned result will be a new array of the same length as 'array'.
[ "Maps", "the", "func", "on", "all", "non", "-", "missing", "elements", "of", "array", "while", "immediately", "yielding", "naValue", "instead", "of", "applying", "func", "for", "any", "missing", "elements", ".", "The", "returned", "result", "will", "be", "a", "new", "array", "of", "the", "same", "length", "as", "array", "." ]
d9f2028b33f9565c92329ccbca8c0fc1e865d97e
https://github.com/osdat/jsdataframe/blob/d9f2028b33f9565c92329ccbca8c0fc1e865d97e/jsdataframe.js#L3989-L3997
train
osdat/jsdataframe
jsdataframe.js
reduceNonNa
function reduceNonNa(array, initValue, func) { var result = initValue; for (var i = 0; i < array.length; i++) { var value = array[i]; if (!isMissing(value)) { result = func(result, value); } } return result; }
javascript
function reduceNonNa(array, initValue, func) { var result = initValue; for (var i = 0; i < array.length; i++) { var value = array[i]; if (!isMissing(value)) { result = func(result, value); } } return result; }
[ "function", "reduceNonNa", "(", "array", ",", "initValue", ",", "func", ")", "{", "var", "result", "=", "initValue", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "array", ".", "length", ";", "i", "++", ")", "{", "var", "value", "=", "array", "[", "i", "]", ";", "if", "(", "!", "isMissing", "(", "value", ")", ")", "{", "result", "=", "func", "(", "result", ",", "value", ")", ";", "}", "}", "return", "result", ";", "}" ]
Performs a left-to-right reduce on 'array' using 'func' starting with 'initValue' while skipping over any missing values. If there are no non-missing values then the result is simply 'initValue'.
[ "Performs", "a", "left", "-", "to", "-", "right", "reduce", "on", "array", "using", "func", "starting", "with", "initValue", "while", "skipping", "over", "any", "missing", "values", ".", "If", "there", "are", "no", "non", "-", "missing", "values", "then", "the", "result", "is", "simply", "initValue", "." ]
d9f2028b33f9565c92329ccbca8c0fc1e865d97e
https://github.com/osdat/jsdataframe/blob/d9f2028b33f9565c92329ccbca8c0fc1e865d97e/jsdataframe.js#L4004-L4013
train
osdat/jsdataframe
jsdataframe.js
reduceUnless
function reduceUnless(array, initValue, condFunc, func) { var result = initValue; for (var i = 0; i < array.length; i++) { var value = array[i]; if (condFunc(value)) { return value; } result = func(result, value); } return result; }
javascript
function reduceUnless(array, initValue, condFunc, func) { var result = initValue; for (var i = 0; i < array.length; i++) { var value = array[i]; if (condFunc(value)) { return value; } result = func(result, value); } return result; }
[ "function", "reduceUnless", "(", "array", ",", "initValue", ",", "condFunc", ",", "func", ")", "{", "var", "result", "=", "initValue", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "array", ".", "length", ";", "i", "++", ")", "{", "var", "value", "=", "array", "[", "i", "]", ";", "if", "(", "condFunc", "(", "value", ")", ")", "{", "return", "value", ";", "}", "result", "=", "func", "(", "result", ",", "value", ")", ";", "}", "return", "result", ";", "}" ]
Performs a left-to-right reduce on 'array' using 'func' starting with 'initValue' unless there's an element for which 'condFunc' returns truthy, in which case this element is immediately returned, halting the rest of the reduction. For an empty array 'initValue' is immediaately returned.
[ "Performs", "a", "left", "-", "to", "-", "right", "reduce", "on", "array", "using", "func", "starting", "with", "initValue", "unless", "there", "s", "an", "element", "for", "which", "condFunc", "returns", "truthy", "in", "which", "case", "this", "element", "is", "immediately", "returned", "halting", "the", "rest", "of", "the", "reduction", ".", "For", "an", "empty", "array", "initValue", "is", "immediaately", "returned", "." ]
d9f2028b33f9565c92329ccbca8c0fc1e865d97e
https://github.com/osdat/jsdataframe/blob/d9f2028b33f9565c92329ccbca8c0fc1e865d97e/jsdataframe.js#L4021-L4031
train
osdat/jsdataframe
jsdataframe.js
combineArrays
function combineArrays(array1, array2, naValue, func) { var skipMissing = true; if (isUndefined(func)) { func = naValue; skipMissing = false; } var arr1Len = array1.length; var arr2Len = array2.length; var outputLen = validateArrayLengths(arr1Len, arr2Len); var isSingleton1 = (arr1Len === 1); var isSingleton2 = (arr2Len === 1); var result = allocArray(outputLen); for (var i = 0; i < outputLen; i++) { var val1 = isSingleton1 ? array1[0] : array1[i]; var val2 = isSingleton2 ? array2[0] : array2[i]; if (skipMissing && (isMissing(val1) || isMissing(val2))) { result[i] = naValue; } else { result[i] = func(val1, val2); } } return result; }
javascript
function combineArrays(array1, array2, naValue, func) { var skipMissing = true; if (isUndefined(func)) { func = naValue; skipMissing = false; } var arr1Len = array1.length; var arr2Len = array2.length; var outputLen = validateArrayLengths(arr1Len, arr2Len); var isSingleton1 = (arr1Len === 1); var isSingleton2 = (arr2Len === 1); var result = allocArray(outputLen); for (var i = 0; i < outputLen; i++) { var val1 = isSingleton1 ? array1[0] : array1[i]; var val2 = isSingleton2 ? array2[0] : array2[i]; if (skipMissing && (isMissing(val1) || isMissing(val2))) { result[i] = naValue; } else { result[i] = func(val1, val2); } } return result; }
[ "function", "combineArrays", "(", "array1", ",", "array2", ",", "naValue", ",", "func", ")", "{", "var", "skipMissing", "=", "true", ";", "if", "(", "isUndefined", "(", "func", ")", ")", "{", "func", "=", "naValue", ";", "skipMissing", "=", "false", ";", "}", "var", "arr1Len", "=", "array1", ".", "length", ";", "var", "arr2Len", "=", "array2", ".", "length", ";", "var", "outputLen", "=", "validateArrayLengths", "(", "arr1Len", ",", "arr2Len", ")", ";", "var", "isSingleton1", "=", "(", "arr1Len", "===", "1", ")", ";", "var", "isSingleton2", "=", "(", "arr2Len", "===", "1", ")", ";", "var", "result", "=", "allocArray", "(", "outputLen", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "outputLen", ";", "i", "++", ")", "{", "var", "val1", "=", "isSingleton1", "?", "array1", "[", "0", "]", ":", "array1", "[", "i", "]", ";", "var", "val2", "=", "isSingleton2", "?", "array2", "[", "0", "]", ":", "array2", "[", "i", "]", ";", "if", "(", "skipMissing", "&&", "(", "isMissing", "(", "val1", ")", "||", "isMissing", "(", "val2", ")", ")", ")", "{", "result", "[", "i", "]", "=", "naValue", ";", "}", "else", "{", "result", "[", "i", "]", "=", "func", "(", "val1", ",", "val2", ")", ";", "}", "}", "return", "result", ";", "}" ]
Applies the given 'func' to each pair of elements from the 2 given arrays and yields a new array with the results. The lengths of the input arrays must either be identical or one of the arrays must have length 1, in which case that single value will be repeated for the length of the other array. The 'naValue' argument is optional. If present, any pair of elements with either value missing will immediately result in 'naValue' without evaluating 'func'. If 'naValue' isn't specified, 'func' will be applied to all pairs of elements.
[ "Applies", "the", "given", "func", "to", "each", "pair", "of", "elements", "from", "the", "2", "given", "arrays", "and", "yields", "a", "new", "array", "with", "the", "results", ".", "The", "lengths", "of", "the", "input", "arrays", "must", "either", "be", "identical", "or", "one", "of", "the", "arrays", "must", "have", "length", "1", "in", "which", "case", "that", "single", "value", "will", "be", "repeated", "for", "the", "length", "of", "the", "other", "array", ".", "The", "naValue", "argument", "is", "optional", ".", "If", "present", "any", "pair", "of", "elements", "with", "either", "value", "missing", "will", "immediately", "result", "in", "naValue", "without", "evaluating", "func", ".", "If", "naValue", "isn", "t", "specified", "func", "will", "be", "applied", "to", "all", "pairs", "of", "elements", "." ]
d9f2028b33f9565c92329ccbca8c0fc1e865d97e
https://github.com/osdat/jsdataframe/blob/d9f2028b33f9565c92329ccbca8c0fc1e865d97e/jsdataframe.js#L4043-L4067
train
osdat/jsdataframe
jsdataframe.js
cumulativeReduce
function cumulativeReduce(array, naValue, func) { var skipMissing = false; if (isUndefined(func)) { func = naValue; skipMissing = true; } var outputLen = array.length; var result = allocArray(outputLen); var accumulatedVal = null; var foundNonMissing = false; for (var i = 0; i < outputLen; i++) { var currVal = array[i]; if (isMissing(currVal)) { result[i] = currVal; if (!skipMissing) { // Fill the rest of the array with naValue and break; for (var j = i + 1; j < outputLen; j++) { result[j] = naValue; } break; } } else { accumulatedVal = foundNonMissing ? func(accumulatedVal, currVal) : currVal; foundNonMissing = true; result[i] = accumulatedVal; } } return result; }
javascript
function cumulativeReduce(array, naValue, func) { var skipMissing = false; if (isUndefined(func)) { func = naValue; skipMissing = true; } var outputLen = array.length; var result = allocArray(outputLen); var accumulatedVal = null; var foundNonMissing = false; for (var i = 0; i < outputLen; i++) { var currVal = array[i]; if (isMissing(currVal)) { result[i] = currVal; if (!skipMissing) { // Fill the rest of the array with naValue and break; for (var j = i + 1; j < outputLen; j++) { result[j] = naValue; } break; } } else { accumulatedVal = foundNonMissing ? func(accumulatedVal, currVal) : currVal; foundNonMissing = true; result[i] = accumulatedVal; } } return result; }
[ "function", "cumulativeReduce", "(", "array", ",", "naValue", ",", "func", ")", "{", "var", "skipMissing", "=", "false", ";", "if", "(", "isUndefined", "(", "func", ")", ")", "{", "func", "=", "naValue", ";", "skipMissing", "=", "true", ";", "}", "var", "outputLen", "=", "array", ".", "length", ";", "var", "result", "=", "allocArray", "(", "outputLen", ")", ";", "var", "accumulatedVal", "=", "null", ";", "var", "foundNonMissing", "=", "false", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "outputLen", ";", "i", "++", ")", "{", "var", "currVal", "=", "array", "[", "i", "]", ";", "if", "(", "isMissing", "(", "currVal", ")", ")", "{", "result", "[", "i", "]", "=", "currVal", ";", "if", "(", "!", "skipMissing", ")", "{", "for", "(", "var", "j", "=", "i", "+", "1", ";", "j", "<", "outputLen", ";", "j", "++", ")", "{", "result", "[", "j", "]", "=", "naValue", ";", "}", "break", ";", "}", "}", "else", "{", "accumulatedVal", "=", "foundNonMissing", "?", "func", "(", "accumulatedVal", ",", "currVal", ")", ":", "currVal", ";", "foundNonMissing", "=", "true", ";", "result", "[", "i", "]", "=", "accumulatedVal", ";", "}", "}", "return", "result", ";", "}" ]
Applies the given 'func' to reduce each element in 'array', returning the cumulative results in a new array. The 'naValue' argument is optional. Any missing value will result in a corresponding missing element in the output, but if 'naValue' isn't specified, the 'func' reduction will still be carried out on subsequent non-missing elements. On the other hand, if 'naValue' is supplied it will be used as the output value for all elements following the first missing value encountered.
[ "Applies", "the", "given", "func", "to", "reduce", "each", "element", "in", "array", "returning", "the", "cumulative", "results", "in", "a", "new", "array", ".", "The", "naValue", "argument", "is", "optional", ".", "Any", "missing", "value", "will", "result", "in", "a", "corresponding", "missing", "element", "in", "the", "output", "but", "if", "naValue", "isn", "t", "specified", "the", "func", "reduction", "will", "still", "be", "carried", "out", "on", "subsequent", "non", "-", "missing", "elements", ".", "On", "the", "other", "hand", "if", "naValue", "is", "supplied", "it", "will", "be", "used", "as", "the", "output", "value", "for", "all", "elements", "following", "the", "first", "missing", "value", "encountered", "." ]
d9f2028b33f9565c92329ccbca8c0fc1e865d97e
https://github.com/osdat/jsdataframe/blob/d9f2028b33f9565c92329ccbca8c0fc1e865d97e/jsdataframe.js#L4122-L4154
train
osdat/jsdataframe
jsdataframe.js
subsetArray
function subsetArray(array, intIdx) { var result = allocArray(intIdx.length); for (var i = 0; i < intIdx.length; i++) { result[i] = array[intIdx[i]]; } return result; }
javascript
function subsetArray(array, intIdx) { var result = allocArray(intIdx.length); for (var i = 0; i < intIdx.length; i++) { result[i] = array[intIdx[i]]; } return result; }
[ "function", "subsetArray", "(", "array", ",", "intIdx", ")", "{", "var", "result", "=", "allocArray", "(", "intIdx", ".", "length", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "intIdx", ".", "length", ";", "i", "++", ")", "{", "result", "[", "i", "]", "=", "array", "[", "intIdx", "[", "i", "]", "]", ";", "}", "return", "result", ";", "}" ]
Uses the integer indexes in 'intIdx' to subset 'array', returning the results. All indices in 'intIdx' are assumed to be in bounds.
[ "Uses", "the", "integer", "indexes", "in", "intIdx", "to", "subset", "array", "returning", "the", "results", ".", "All", "indices", "in", "intIdx", "are", "assumed", "to", "be", "in", "bounds", "." ]
d9f2028b33f9565c92329ccbca8c0fc1e865d97e
https://github.com/osdat/jsdataframe/blob/d9f2028b33f9565c92329ccbca8c0fc1e865d97e/jsdataframe.js#L4159-L4165
train
osdat/jsdataframe
jsdataframe.js
enforceVectorDtype
function enforceVectorDtype(array, dtype) { validateDtype(dtype); var coerceFunc = COERCE_FUNC[dtype]; // Coerce all elements to dtype for (var i = 0; i < array.length; i++) { array[i] = coerceFunc(array[i]); } // Construct vector return newVector(array, dtype); }
javascript
function enforceVectorDtype(array, dtype) { validateDtype(dtype); var coerceFunc = COERCE_FUNC[dtype]; // Coerce all elements to dtype for (var i = 0; i < array.length; i++) { array[i] = coerceFunc(array[i]); } // Construct vector return newVector(array, dtype); }
[ "function", "enforceVectorDtype", "(", "array", ",", "dtype", ")", "{", "validateDtype", "(", "dtype", ")", ";", "var", "coerceFunc", "=", "COERCE_FUNC", "[", "dtype", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "array", ".", "length", ";", "i", "++", ")", "{", "array", "[", "i", "]", "=", "coerceFunc", "(", "array", "[", "i", "]", ")", ";", "}", "return", "newVector", "(", "array", ",", "dtype", ")", ";", "}" ]
Creates a new vector backed by the given array after coercing each element to the given dtype.
[ "Creates", "a", "new", "vector", "backed", "by", "the", "given", "array", "after", "coercing", "each", "element", "to", "the", "given", "dtype", "." ]
d9f2028b33f9565c92329ccbca8c0fc1e865d97e
https://github.com/osdat/jsdataframe/blob/d9f2028b33f9565c92329ccbca8c0fc1e865d97e/jsdataframe.js#L4268-L4279
train
osdat/jsdataframe
jsdataframe.js
argSort
function argSort(vectors, ascending) { if (vectors.length !== ascending.length) { throw new Error('length of "ascending" must match the number of ' + 'sort columns'); } if (vectors.length === 0) { return null; } var nRow = vectors[0].size(); var result = allocArray(nRow); for (var i = 0; i < nRow; i++) { result[i] = i; } // Create composite compare function var compareFuncs = ascending.map(function(asc) { return asc ? compare : compareReverse; }); var compositeCompare = function(a, b) { var result = 0; for (var i = 0; i < compareFuncs.length; i++) { var aValue = vectors[i].values[a]; var bValue = vectors[i].values[b]; result = compareFuncs[i](aValue, bValue); if (result !== 0) { return result; } } // Order based on row index as last resort to ensure stable sorting return compare(a, b); }; result.sort(compositeCompare); return result; }
javascript
function argSort(vectors, ascending) { if (vectors.length !== ascending.length) { throw new Error('length of "ascending" must match the number of ' + 'sort columns'); } if (vectors.length === 0) { return null; } var nRow = vectors[0].size(); var result = allocArray(nRow); for (var i = 0; i < nRow; i++) { result[i] = i; } // Create composite compare function var compareFuncs = ascending.map(function(asc) { return asc ? compare : compareReverse; }); var compositeCompare = function(a, b) { var result = 0; for (var i = 0; i < compareFuncs.length; i++) { var aValue = vectors[i].values[a]; var bValue = vectors[i].values[b]; result = compareFuncs[i](aValue, bValue); if (result !== 0) { return result; } } // Order based on row index as last resort to ensure stable sorting return compare(a, b); }; result.sort(compositeCompare); return result; }
[ "function", "argSort", "(", "vectors", ",", "ascending", ")", "{", "if", "(", "vectors", ".", "length", "!==", "ascending", ".", "length", ")", "{", "throw", "new", "Error", "(", "'length of \"ascending\" must match the number of '", "+", "'sort columns'", ")", ";", "}", "if", "(", "vectors", ".", "length", "===", "0", ")", "{", "return", "null", ";", "}", "var", "nRow", "=", "vectors", "[", "0", "]", ".", "size", "(", ")", ";", "var", "result", "=", "allocArray", "(", "nRow", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "nRow", ";", "i", "++", ")", "{", "result", "[", "i", "]", "=", "i", ";", "}", "var", "compareFuncs", "=", "ascending", ".", "map", "(", "function", "(", "asc", ")", "{", "return", "asc", "?", "compare", ":", "compareReverse", ";", "}", ")", ";", "var", "compositeCompare", "=", "function", "(", "a", ",", "b", ")", "{", "var", "result", "=", "0", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "compareFuncs", ".", "length", ";", "i", "++", ")", "{", "var", "aValue", "=", "vectors", "[", "i", "]", ".", "values", "[", "a", "]", ";", "var", "bValue", "=", "vectors", "[", "i", "]", ".", "values", "[", "b", "]", ";", "result", "=", "compareFuncs", "[", "i", "]", "(", "aValue", ",", "bValue", ")", ";", "if", "(", "result", "!==", "0", ")", "{", "return", "result", ";", "}", "}", "return", "compare", "(", "a", ",", "b", ")", ";", "}", ";", "result", ".", "sort", "(", "compositeCompare", ")", ";", "return", "result", ";", "}" ]
Returns an array of integer indices that would sort the given array of vectors, starting with the first vector, then the second, etc. "ascending" must be an array of booleans with the same length as "vectors". Returns null if "vectors" is empty.
[ "Returns", "an", "array", "of", "integer", "indices", "that", "would", "sort", "the", "given", "array", "of", "vectors", "starting", "with", "the", "first", "vector", "then", "the", "second", "etc", ".", "ascending", "must", "be", "an", "array", "of", "booleans", "with", "the", "same", "length", "as", "vectors", ".", "Returns", "null", "if", "vectors", "is", "empty", "." ]
d9f2028b33f9565c92329ccbca8c0fc1e865d97e
https://github.com/osdat/jsdataframe/blob/d9f2028b33f9565c92329ccbca8c0fc1e865d97e/jsdataframe.js#L4443-L4477
train
osdat/jsdataframe
jsdataframe.js
validateArrayLengths
function validateArrayLengths(len1, len2) { var outputLen = len1; if (len1 !== len2) { if (len1 === 1) { outputLen = len2; } else if (len2 !== 1) { throw new Error('incompatible array lengths: ' + len1 + ' and ' + len2); } } return outputLen; }
javascript
function validateArrayLengths(len1, len2) { var outputLen = len1; if (len1 !== len2) { if (len1 === 1) { outputLen = len2; } else if (len2 !== 1) { throw new Error('incompatible array lengths: ' + len1 + ' and ' + len2); } } return outputLen; }
[ "function", "validateArrayLengths", "(", "len1", ",", "len2", ")", "{", "var", "outputLen", "=", "len1", ";", "if", "(", "len1", "!==", "len2", ")", "{", "if", "(", "len1", "===", "1", ")", "{", "outputLen", "=", "len2", ";", "}", "else", "if", "(", "len2", "!==", "1", ")", "{", "throw", "new", "Error", "(", "'incompatible array lengths: '", "+", "len1", "+", "' and '", "+", "len2", ")", ";", "}", "}", "return", "outputLen", ";", "}" ]
Returns the compatible output vector length for element-wise operation on vectors of length 'len1' and 'len2' or throws an error if incompatible
[ "Returns", "the", "compatible", "output", "vector", "length", "for", "element", "-", "wise", "operation", "on", "vectors", "of", "length", "len1", "and", "len2", "or", "throws", "an", "error", "if", "incompatible" ]
d9f2028b33f9565c92329ccbca8c0fc1e865d97e
https://github.com/osdat/jsdataframe/blob/d9f2028b33f9565c92329ccbca8c0fc1e865d97e/jsdataframe.js#L4559-L4570
train
osdat/jsdataframe
jsdataframe.js
ensureScalar
function ensureScalar(value) { if (isUndefined(value) || value === null) { return value; } var length = 1; var description = 'a scalar'; if (value.type === vectorProto.type) { length = value.size(); value = value.values[0]; description = 'a vector'; } else if (Array.isArray(value)) { length = value.length; value = value[0]; description = 'an array'; } if (length !== 1) { throw new Error('expected a single scalar value but got ' + description + ' of length ' + length); } return value; }
javascript
function ensureScalar(value) { if (isUndefined(value) || value === null) { return value; } var length = 1; var description = 'a scalar'; if (value.type === vectorProto.type) { length = value.size(); value = value.values[0]; description = 'a vector'; } else if (Array.isArray(value)) { length = value.length; value = value[0]; description = 'an array'; } if (length !== 1) { throw new Error('expected a single scalar value but got ' + description + ' of length ' + length); } return value; }
[ "function", "ensureScalar", "(", "value", ")", "{", "if", "(", "isUndefined", "(", "value", ")", "||", "value", "===", "null", ")", "{", "return", "value", ";", "}", "var", "length", "=", "1", ";", "var", "description", "=", "'a scalar'", ";", "if", "(", "value", ".", "type", "===", "vectorProto", ".", "type", ")", "{", "length", "=", "value", ".", "size", "(", ")", ";", "value", "=", "value", ".", "values", "[", "0", "]", ";", "description", "=", "'a vector'", ";", "}", "else", "if", "(", "Array", ".", "isArray", "(", "value", ")", ")", "{", "length", "=", "value", ".", "length", ";", "value", "=", "value", "[", "0", "]", ";", "description", "=", "'an array'", ";", "}", "if", "(", "length", "!==", "1", ")", "{", "throw", "new", "Error", "(", "'expected a single scalar value but got '", "+", "description", "+", "' of length '", "+", "length", ")", ";", "}", "return", "value", ";", "}" ]
If value is a vector or array, this function will return the single scalar value contained or throw an error if the length is not 1. If value isn't a vector or array, it is simply returned.
[ "If", "value", "is", "a", "vector", "or", "array", "this", "function", "will", "return", "the", "single", "scalar", "value", "contained", "or", "throw", "an", "error", "if", "the", "length", "is", "not", "1", ".", "If", "value", "isn", "t", "a", "vector", "or", "array", "it", "is", "simply", "returned", "." ]
d9f2028b33f9565c92329ccbca8c0fc1e865d97e
https://github.com/osdat/jsdataframe/blob/d9f2028b33f9565c92329ccbca8c0fc1e865d97e/jsdataframe.js#L4575-L4595
train
osdat/jsdataframe
jsdataframe.js
ensureVector
function ensureVector(values, defaultDtype) { if (isMissing(values) || values.type !== vectorProto.type) { values = Array.isArray(values) ? inferVectorDtype(values.slice(), defaultDtype) : inferVectorDtype([values], defaultDtype); } return values; }
javascript
function ensureVector(values, defaultDtype) { if (isMissing(values) || values.type !== vectorProto.type) { values = Array.isArray(values) ? inferVectorDtype(values.slice(), defaultDtype) : inferVectorDtype([values], defaultDtype); } return values; }
[ "function", "ensureVector", "(", "values", ",", "defaultDtype", ")", "{", "if", "(", "isMissing", "(", "values", ")", "||", "values", ".", "type", "!==", "vectorProto", ".", "type", ")", "{", "values", "=", "Array", ".", "isArray", "(", "values", ")", "?", "inferVectorDtype", "(", "values", ".", "slice", "(", ")", ",", "defaultDtype", ")", ":", "inferVectorDtype", "(", "[", "values", "]", ",", "defaultDtype", ")", ";", "}", "return", "values", ";", "}" ]
Returns a vector representing the given values, which can be either a vector, array, or scalar. If already a vector, this vector is simply returned. If an array, it's converted to a vector with inferred dtype. If a scalar, it's wrapped in an array and converted to a vector also. The defaultDtype is used only if all values are missing. It defaults to 'object' if undefined.
[ "Returns", "a", "vector", "representing", "the", "given", "values", "which", "can", "be", "either", "a", "vector", "array", "or", "scalar", ".", "If", "already", "a", "vector", "this", "vector", "is", "simply", "returned", ".", "If", "an", "array", "it", "s", "converted", "to", "a", "vector", "with", "inferred", "dtype", ".", "If", "a", "scalar", "it", "s", "wrapped", "in", "an", "array", "and", "converted", "to", "a", "vector", "also", ".", "The", "defaultDtype", "is", "used", "only", "if", "all", "values", "are", "missing", ".", "It", "defaults", "to", "object", "if", "undefined", "." ]
d9f2028b33f9565c92329ccbca8c0fc1e865d97e
https://github.com/osdat/jsdataframe/blob/d9f2028b33f9565c92329ccbca8c0fc1e865d97e/jsdataframe.js#L4604-L4611
train
osdat/jsdataframe
jsdataframe.js
ensureStringVector
function ensureStringVector(values) { values = ensureVector(values, 'string'); return (values.dtype !== 'string') ? values.toDtype('string') : values; }
javascript
function ensureStringVector(values) { values = ensureVector(values, 'string'); return (values.dtype !== 'string') ? values.toDtype('string') : values; }
[ "function", "ensureStringVector", "(", "values", ")", "{", "values", "=", "ensureVector", "(", "values", ",", "'string'", ")", ";", "return", "(", "values", ".", "dtype", "!==", "'string'", ")", "?", "values", ".", "toDtype", "(", "'string'", ")", ":", "values", ";", "}" ]
Like 'ensureVector', but converts the result to 'string' dtype if necessary
[ "Like", "ensureVector", "but", "converts", "the", "result", "to", "string", "dtype", "if", "necessary" ]
d9f2028b33f9565c92329ccbca8c0fc1e865d97e
https://github.com/osdat/jsdataframe/blob/d9f2028b33f9565c92329ccbca8c0fc1e865d97e/jsdataframe.js#L4615-L4620
train
bharatraj88/angular2-timepicker
dist/vendor.js
extractMessages
function extractMessages(nodes, interpolationConfig, implicitTags, implicitAttrs) { var visitor = new _Visitor(implicitTags, implicitAttrs); return visitor.extract(nodes, interpolationConfig); }
javascript
function extractMessages(nodes, interpolationConfig, implicitTags, implicitAttrs) { var visitor = new _Visitor(implicitTags, implicitAttrs); return visitor.extract(nodes, interpolationConfig); }
[ "function", "extractMessages", "(", "nodes", ",", "interpolationConfig", ",", "implicitTags", ",", "implicitAttrs", ")", "{", "var", "visitor", "=", "new", "_Visitor", "(", "implicitTags", ",", "implicitAttrs", ")", ";", "return", "visitor", ".", "extract", "(", "nodes", ",", "interpolationConfig", ")", ";", "}" ]
Extract translatable messages from an html AST
[ "Extract", "translatable", "messages", "from", "an", "html", "AST" ]
748330a2a5e7f89a02cd99477b480237aacdb295
https://github.com/bharatraj88/angular2-timepicker/blob/748330a2a5e7f89a02cd99477b480237aacdb295/dist/vendor.js#L6249-L6252
train
bharatraj88/angular2-timepicker
dist/vendor.js
extractPlaceholderToIds
function extractPlaceholderToIds(messageBundle) { var messageMap = messageBundle.getMessageMap(); var placeholderToIds = {}; Object.keys(messageMap).forEach(function (msgId) { placeholderToIds[msgId] = messageMap[msgId].placeholderToMsgIds; }); return placeholderToIds; }
javascript
function extractPlaceholderToIds(messageBundle) { var messageMap = messageBundle.getMessageMap(); var placeholderToIds = {}; Object.keys(messageMap).forEach(function (msgId) { placeholderToIds[msgId] = messageMap[msgId].placeholderToMsgIds; }); return placeholderToIds; }
[ "function", "extractPlaceholderToIds", "(", "messageBundle", ")", "{", "var", "messageMap", "=", "messageBundle", ".", "getMessageMap", "(", ")", ";", "var", "placeholderToIds", "=", "{", "}", ";", "Object", ".", "keys", "(", "messageMap", ")", ".", "forEach", "(", "function", "(", "msgId", ")", "{", "placeholderToIds", "[", "msgId", "]", "=", "messageMap", "[", "msgId", "]", ".", "placeholderToMsgIds", ";", "}", ")", ";", "return", "placeholderToIds", ";", "}" ]
Generate a map of placeholder to message ids indexed by message ids
[ "Generate", "a", "map", "of", "placeholder", "to", "message", "ids", "indexed", "by", "message", "ids" ]
748330a2a5e7f89a02cd99477b480237aacdb295
https://github.com/bharatraj88/angular2-timepicker/blob/748330a2a5e7f89a02cd99477b480237aacdb295/dist/vendor.js#L6728-L6735
train
bharatraj88/angular2-timepicker
dist/vendor.js
extractStyleUrls
function extractStyleUrls(resolver, baseUrl, cssText) { var foundUrls = []; var modifiedCssText = cssText.replace(_cssImportRe, function () { var m = []; for (var _i = 0; _i < arguments.length; _i++) { m[_i - 0] = arguments[_i]; } var url = m[1] || m[2]; if (!isStyleUrlResolvable(url)) { // Do not attempt to resolve non-package absolute URLs with URI scheme return m[0]; } foundUrls.push(resolver.resolve(baseUrl, url)); return ''; }); return new StyleWithImports(modifiedCssText, foundUrls); }
javascript
function extractStyleUrls(resolver, baseUrl, cssText) { var foundUrls = []; var modifiedCssText = cssText.replace(_cssImportRe, function () { var m = []; for (var _i = 0; _i < arguments.length; _i++) { m[_i - 0] = arguments[_i]; } var url = m[1] || m[2]; if (!isStyleUrlResolvable(url)) { // Do not attempt to resolve non-package absolute URLs with URI scheme return m[0]; } foundUrls.push(resolver.resolve(baseUrl, url)); return ''; }); return new StyleWithImports(modifiedCssText, foundUrls); }
[ "function", "extractStyleUrls", "(", "resolver", ",", "baseUrl", ",", "cssText", ")", "{", "var", "foundUrls", "=", "[", "]", ";", "var", "modifiedCssText", "=", "cssText", ".", "replace", "(", "_cssImportRe", ",", "function", "(", ")", "{", "var", "m", "=", "[", "]", ";", "for", "(", "var", "_i", "=", "0", ";", "_i", "<", "arguments", ".", "length", ";", "_i", "++", ")", "{", "m", "[", "_i", "-", "0", "]", "=", "arguments", "[", "_i", "]", ";", "}", "var", "url", "=", "m", "[", "1", "]", "||", "m", "[", "2", "]", ";", "if", "(", "!", "isStyleUrlResolvable", "(", "url", ")", ")", "{", "return", "m", "[", "0", "]", ";", "}", "foundUrls", ".", "push", "(", "resolver", ".", "resolve", "(", "baseUrl", ",", "url", ")", ")", ";", "return", "''", ";", "}", ")", ";", "return", "new", "StyleWithImports", "(", "modifiedCssText", ",", "foundUrls", ")", ";", "}" ]
Rewrites stylesheets by resolving and removing the @import urls that are either relative or don't have a `package:` scheme
[ "Rewrites", "stylesheets", "by", "resolving", "and", "removing", "the" ]
748330a2a5e7f89a02cd99477b480237aacdb295
https://github.com/bharatraj88/angular2-timepicker/blob/748330a2a5e7f89a02cd99477b480237aacdb295/dist/vendor.js#L8328-L8344
train
bharatraj88/angular2-timepicker
dist/vendor.js
createPlatform
function createPlatform(injector) { if (_platform && !_platform.destroyed) { throw new Error('There can be only one platform. Destroy the previous one to create a new one.'); } _platform = injector.get(PlatformRef); var inits = injector.get(PLATFORM_INITIALIZER, null); if (inits) inits.forEach(function (init) { return init(); }); return _platform; }
javascript
function createPlatform(injector) { if (_platform && !_platform.destroyed) { throw new Error('There can be only one platform. Destroy the previous one to create a new one.'); } _platform = injector.get(PlatformRef); var inits = injector.get(PLATFORM_INITIALIZER, null); if (inits) inits.forEach(function (init) { return init(); }); return _platform; }
[ "function", "createPlatform", "(", "injector", ")", "{", "if", "(", "_platform", "&&", "!", "_platform", ".", "destroyed", ")", "{", "throw", "new", "Error", "(", "'There can be only one platform. Destroy the previous one to create a new one.'", ")", ";", "}", "_platform", "=", "injector", ".", "get", "(", "PlatformRef", ")", ";", "var", "inits", "=", "injector", ".", "get", "(", "PLATFORM_INITIALIZER", ",", "null", ")", ";", "if", "(", "inits", ")", "inits", ".", "forEach", "(", "function", "(", "init", ")", "{", "return", "init", "(", ")", ";", "}", ")", ";", "return", "_platform", ";", "}" ]
Creates a platform. Platforms have to be eagerly created via this function. @experimental APIs related to application bootstrap are currently under review.
[ "Creates", "a", "platform", ".", "Platforms", "have", "to", "be", "eagerly", "created", "via", "this", "function", "." ]
748330a2a5e7f89a02cd99477b480237aacdb295
https://github.com/bharatraj88/angular2-timepicker/blob/748330a2a5e7f89a02cd99477b480237aacdb295/dist/vendor.js#L24310-L24319
train
bharatraj88/angular2-timepicker
dist/vendor.js
concat
function concat() { var observables = []; for (var _i = 0; _i < arguments.length; _i++) { observables[_i - 0] = arguments[_i]; } return concatStatic.apply(void 0, [this].concat(observables)); }
javascript
function concat() { var observables = []; for (var _i = 0; _i < arguments.length; _i++) { observables[_i - 0] = arguments[_i]; } return concatStatic.apply(void 0, [this].concat(observables)); }
[ "function", "concat", "(", ")", "{", "var", "observables", "=", "[", "]", ";", "for", "(", "var", "_i", "=", "0", ";", "_i", "<", "arguments", ".", "length", ";", "_i", "++", ")", "{", "observables", "[", "_i", "-", "0", "]", "=", "arguments", "[", "_i", "]", ";", "}", "return", "concatStatic", ".", "apply", "(", "void", "0", ",", "[", "this", "]", ".", "concat", "(", "observables", ")", ")", ";", "}" ]
Creates an output Observable which sequentially emits all values from every given input Observable after the current Observable. <span class="informal">Concatenates multiple Observables together by sequentially emitting their values, one Observable after the other.</span> <img src="./img/concat.png" width="100%"> Joins this Observable with multiple other Observables by subscribing to them one at a time, starting with the source, and merging their results into the output Observable. Will wait for each Observable to complete before moving on to the next. @example <caption>Concatenate a timer counting from 0 to 3 with a synchronous sequence from 1 to 10</caption> var timer = Rx.Observable.interval(1000).take(4); var sequence = Rx.Observable.range(1, 10); var result = timer.concat(sequence); result.subscribe(x => console.log(x)); @example <caption>Concatenate 3 Observables</caption> var timer1 = Rx.Observable.interval(1000).take(10); var timer2 = Rx.Observable.interval(2000).take(6); var timer3 = Rx.Observable.interval(500).take(10); var result = timer1.concat(timer2, timer3); result.subscribe(x => console.log(x)); @see {@link concatAll} @see {@link concatMap} @see {@link concatMapTo} @param {Observable} other An input Observable to concatenate after the source Observable. More than one input Observables may be given as argument. @param {Scheduler} [scheduler=null] An optional Scheduler to schedule each Observable subscription on. @return {Observable} All values of each passed Observable merged into a single Observable, in order, in serial fashion. @method concat @owner Observable
[ "Creates", "an", "output", "Observable", "which", "sequentially", "emits", "all", "values", "from", "every", "given", "input", "Observable", "after", "the", "current", "Observable", "." ]
748330a2a5e7f89a02cd99477b480237aacdb295
https://github.com/bharatraj88/angular2-timepicker/blob/748330a2a5e7f89a02cd99477b480237aacdb295/dist/vendor.js#L38141-L38147
train
bharatraj88/angular2-timepicker
dist/vendor.js
merge
function merge() { var observables = []; for (var _i = 0; _i < arguments.length; _i++) { observables[_i - 0] = arguments[_i]; } observables.unshift(this); return mergeStatic.apply(this, observables); }
javascript
function merge() { var observables = []; for (var _i = 0; _i < arguments.length; _i++) { observables[_i - 0] = arguments[_i]; } observables.unshift(this); return mergeStatic.apply(this, observables); }
[ "function", "merge", "(", ")", "{", "var", "observables", "=", "[", "]", ";", "for", "(", "var", "_i", "=", "0", ";", "_i", "<", "arguments", ".", "length", ";", "_i", "++", ")", "{", "observables", "[", "_i", "-", "0", "]", "=", "arguments", "[", "_i", "]", ";", "}", "observables", ".", "unshift", "(", "this", ")", ";", "return", "mergeStatic", ".", "apply", "(", "this", ",", "observables", ")", ";", "}" ]
Creates an output Observable which concurrently emits all values from every given input Observable. <span class="informal">Flattens multiple Observables together by blending their values into one Observable.</span> <img src="./img/merge.png" width="100%"> `merge` subscribes to each given input Observable (either the source or an Observable given as argument), and simply forwards (without doing any transformation) all the values from all the input Observables to the output Observable. The output Observable only completes once all input Observables have completed. Any error delivered by an input Observable will be immediately emitted on the output Observable. @example <caption>Merge together two Observables: 1s interval and clicks</caption> var clicks = Rx.Observable.fromEvent(document, 'click'); var timer = Rx.Observable.interval(1000); var clicksOrTimer = clicks.merge(timer); clicksOrTimer.subscribe(x => console.log(x)); @example <caption>Merge together 3 Observables, but only 2 run concurrently</caption> var timer1 = Rx.Observable.interval(1000).take(10); var timer2 = Rx.Observable.interval(2000).take(6); var timer3 = Rx.Observable.interval(500).take(10); var concurrent = 2; // the argument var merged = timer1.merge(timer2, timer3, concurrent); merged.subscribe(x => console.log(x)); @see {@link mergeAll} @see {@link mergeMap} @see {@link mergeMapTo} @see {@link mergeScan} @param {Observable} other An input Observable to merge with the source Observable. More than one input Observables may be given as argument. @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of input Observables being subscribed to concurrently. @param {Scheduler} [scheduler=null] The Scheduler to use for managing concurrency of input Observables. @return {Observable} an Observable that emits items that are the result of every input Observable. @method merge @owner Observable
[ "Creates", "an", "output", "Observable", "which", "concurrently", "emits", "all", "values", "from", "every", "given", "input", "Observable", "." ]
748330a2a5e7f89a02cd99477b480237aacdb295
https://github.com/bharatraj88/angular2-timepicker/blob/748330a2a5e7f89a02cd99477b480237aacdb295/dist/vendor.js#L40234-L40241
train
bharatraj88/angular2-timepicker
dist/vendor.js
race
function race() { var observables = []; for (var _i = 0; _i < arguments.length; _i++) { observables[_i - 0] = arguments[_i]; } // if the only argument is an array, it was most likely called with // `pair([obs1, obs2, ...])` if (observables.length === 1 && isArray_1.isArray(observables[0])) { observables = observables[0]; } observables.unshift(this); return raceStatic.apply(this, observables); }
javascript
function race() { var observables = []; for (var _i = 0; _i < arguments.length; _i++) { observables[_i - 0] = arguments[_i]; } // if the only argument is an array, it was most likely called with // `pair([obs1, obs2, ...])` if (observables.length === 1 && isArray_1.isArray(observables[0])) { observables = observables[0]; } observables.unshift(this); return raceStatic.apply(this, observables); }
[ "function", "race", "(", ")", "{", "var", "observables", "=", "[", "]", ";", "for", "(", "var", "_i", "=", "0", ";", "_i", "<", "arguments", ".", "length", ";", "_i", "++", ")", "{", "observables", "[", "_i", "-", "0", "]", "=", "arguments", "[", "_i", "]", ";", "}", "if", "(", "observables", ".", "length", "===", "1", "&&", "isArray_1", ".", "isArray", "(", "observables", "[", "0", "]", ")", ")", "{", "observables", "=", "observables", "[", "0", "]", ";", "}", "observables", ".", "unshift", "(", "this", ")", ";", "return", "raceStatic", ".", "apply", "(", "this", ",", "observables", ")", ";", "}" ]
Returns an Observable that mirrors the first source Observable to emit an item from the combination of this Observable and supplied Observables @param {...Observables} ...observables sources used to race for which Observable emits first. @return {Observable} an Observable that mirrors the output of the first Observable to emit an item. @method race @owner Observable
[ "Returns", "an", "Observable", "that", "mirrors", "the", "first", "source", "Observable", "to", "emit", "an", "item", "from", "the", "combination", "of", "this", "Observable", "and", "supplied", "Observables" ]
748330a2a5e7f89a02cd99477b480237aacdb295
https://github.com/bharatraj88/angular2-timepicker/blob/748330a2a5e7f89a02cd99477b480237aacdb295/dist/vendor.js#L40347-L40359
train
bharatraj88/angular2-timepicker
dist/vendor.js
mergeMapTo
function mergeMapTo(innerObservable, resultSelector, concurrent) { if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; } if (typeof resultSelector === 'number') { concurrent = resultSelector; resultSelector = null; } return this.lift(new MergeMapToOperator(innerObservable, resultSelector, concurrent)); }
javascript
function mergeMapTo(innerObservable, resultSelector, concurrent) { if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; } if (typeof resultSelector === 'number') { concurrent = resultSelector; resultSelector = null; } return this.lift(new MergeMapToOperator(innerObservable, resultSelector, concurrent)); }
[ "function", "mergeMapTo", "(", "innerObservable", ",", "resultSelector", ",", "concurrent", ")", "{", "if", "(", "concurrent", "===", "void", "0", ")", "{", "concurrent", "=", "Number", ".", "POSITIVE_INFINITY", ";", "}", "if", "(", "typeof", "resultSelector", "===", "'number'", ")", "{", "concurrent", "=", "resultSelector", ";", "resultSelector", "=", "null", ";", "}", "return", "this", ".", "lift", "(", "new", "MergeMapToOperator", "(", "innerObservable", ",", "resultSelector", ",", "concurrent", ")", ")", ";", "}" ]
Projects each source value to the same Observable which is merged multiple times in the output Observable. <span class="informal">It's like {@link mergeMap}, but maps each value always to the same inner Observable.</span> <img src="./img/mergeMapTo.png" width="100%"> Maps each source value to the given Observable `innerObservable` regardless of the source value, and then merges those resulting Observables into one single Observable, which is the output Observable. @example <caption>For each click event, start an interval Observable ticking every 1 second</caption> var clicks = Rx.Observable.fromEvent(document, 'click'); var result = clicks.mergeMapTo(Rx.Observable.interval(1000)); result.subscribe(x => console.log(x)); @see {@link concatMapTo} @see {@link merge} @see {@link mergeAll} @see {@link mergeMap} @see {@link mergeScan} @see {@link switchMapTo} @param {Observable} innerObservable An Observable to replace each value from the source Observable. @param {function(outerValue: T, innerValue: I, outerIndex: number, innerIndex: number): any} [resultSelector] A function to produce the value on the output Observable based on the values and the indices of the source (outer) emission and the inner Observable emission. The arguments passed to this function are: - `outerValue`: the value that came from the source - `innerValue`: the value that came from the projected Observable - `outerIndex`: the "index" of the value that came from the source - `innerIndex`: the "index" of the value from the projected Observable @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of input Observables being subscribed to concurrently. @return {Observable} An Observable that emits items from the given `innerObservable` (and optionally transformed through `resultSelector`) every time a value is emitted on the source Observable. @method mergeMapTo @owner Observable
[ "Projects", "each", "source", "value", "to", "the", "same", "Observable", "which", "is", "merged", "multiple", "times", "in", "the", "output", "Observable", "." ]
748330a2a5e7f89a02cd99477b480237aacdb295
https://github.com/bharatraj88/angular2-timepicker/blob/748330a2a5e7f89a02cd99477b480237aacdb295/dist/vendor.js#L43823-L43830
train
bharatraj88/angular2-timepicker
dist/vendor.js
delay
function delay(delay, scheduler) { if (scheduler === void 0) { scheduler = async_1.async; } var absoluteDelay = isDate_1.isDate(delay); var delayFor = absoluteDelay ? (+delay - scheduler.now()) : Math.abs(delay); return this.lift(new DelayOperator(delayFor, scheduler)); }
javascript
function delay(delay, scheduler) { if (scheduler === void 0) { scheduler = async_1.async; } var absoluteDelay = isDate_1.isDate(delay); var delayFor = absoluteDelay ? (+delay - scheduler.now()) : Math.abs(delay); return this.lift(new DelayOperator(delayFor, scheduler)); }
[ "function", "delay", "(", "delay", ",", "scheduler", ")", "{", "if", "(", "scheduler", "===", "void", "0", ")", "{", "scheduler", "=", "async_1", ".", "async", ";", "}", "var", "absoluteDelay", "=", "isDate_1", ".", "isDate", "(", "delay", ")", ";", "var", "delayFor", "=", "absoluteDelay", "?", "(", "+", "delay", "-", "scheduler", ".", "now", "(", ")", ")", ":", "Math", ".", "abs", "(", "delay", ")", ";", "return", "this", ".", "lift", "(", "new", "DelayOperator", "(", "delayFor", ",", "scheduler", ")", ")", ";", "}" ]
Delays the emission of items from the source Observable by a given timeout or until a given Date. <span class="informal">Time shifts each item by some specified amount of milliseconds.</span> <img src="./img/delay.png" width="100%"> If the delay argument is a Number, this operator time shifts the source Observable by that amount of time expressed in milliseconds. The relative time intervals between the values are preserved. If the delay argument is a Date, this operator time shifts the start of the Observable execution until the given date occurs. @example <caption>Delay each click by one second</caption> var clicks = Rx.Observable.fromEvent(document, 'click'); var delayedClicks = clicks.delay(1000); // each click emitted after 1 second delayedClicks.subscribe(x => console.log(x)); @example <caption>Delay all clicks until a future date happens</caption> var clicks = Rx.Observable.fromEvent(document, 'click'); var date = new Date('March 15, 2050 12:00:00'); // in the future var delayedClicks = clicks.delay(date); // click emitted only after that date delayedClicks.subscribe(x => console.log(x)); @see {@link debounceTime} @see {@link delayWhen} @param {number|Date} delay The delay duration in milliseconds (a `number`) or a `Date` until which the emission of the source items is delayed. @param {Scheduler} [scheduler=async] The Scheduler to use for managing the timers that handle the time-shift for each item. @return {Observable} An Observable that delays the emissions of the source Observable by the specified timeout or Date. @method delay @owner Observable
[ "Delays", "the", "emission", "of", "items", "from", "the", "source", "Observable", "by", "a", "given", "timeout", "or", "until", "a", "given", "Date", "." ]
748330a2a5e7f89a02cd99477b480237aacdb295
https://github.com/bharatraj88/angular2-timepicker/blob/748330a2a5e7f89a02cd99477b480237aacdb295/dist/vendor.js#L44562-L44567
train
bharatraj88/angular2-timepicker
dist/vendor.js
distinctKey
function distinctKey(key, compare, flushes) { return distinct_1.distinct.call(this, function (x, y) { if (compare) { return compare(x[key], y[key]); } return x[key] === y[key]; }, flushes); }
javascript
function distinctKey(key, compare, flushes) { return distinct_1.distinct.call(this, function (x, y) { if (compare) { return compare(x[key], y[key]); } return x[key] === y[key]; }, flushes); }
[ "function", "distinctKey", "(", "key", ",", "compare", ",", "flushes", ")", "{", "return", "distinct_1", ".", "distinct", ".", "call", "(", "this", ",", "function", "(", "x", ",", "y", ")", "{", "if", "(", "compare", ")", "{", "return", "compare", "(", "x", "[", "key", "]", ",", "y", "[", "key", "]", ")", ";", "}", "return", "x", "[", "key", "]", "===", "y", "[", "key", "]", ";", "}", ",", "flushes", ")", ";", "}" ]
Returns an Observable that emits all items emitted by the source Observable that are distinct by comparison from previous items, using a property accessed by using the key provided to check if the two items are distinct. If a comparator function is provided, then it will be called for each item to test for whether or not that value should be emitted. If a comparator function is not provided, an equality check is used by default. As the internal HashSet of this operator grows larger and larger, care should be taken in the domain of inputs this operator may see. An optional parameter is also provided such that an Observable can be provided to queue the internal HashSet to flush the values it holds. @param {string} key string key for object property lookup on each item. @param {function} [compare] optional comparison function called to test if an item is distinct from previous items in the source. @param {Observable} [flushes] optional Observable for flushing the internal HashSet of the operator. @return {Observable} an Observable that emits items from the source Observable with distinct values. @method distinctKey @owner Observable
[ "Returns", "an", "Observable", "that", "emits", "all", "items", "emitted", "by", "the", "source", "Observable", "that", "are", "distinct", "by", "comparison", "from", "previous", "items", "using", "a", "property", "accessed", "by", "using", "the", "key", "provided", "to", "check", "if", "the", "two", "items", "are", "distinct", ".", "If", "a", "comparator", "function", "is", "provided", "then", "it", "will", "be", "called", "for", "each", "item", "to", "test", "for", "whether", "or", "not", "that", "value", "should", "be", "emitted", ".", "If", "a", "comparator", "function", "is", "not", "provided", "an", "equality", "check", "is", "used", "by", "default", ".", "As", "the", "internal", "HashSet", "of", "this", "operator", "grows", "larger", "and", "larger", "care", "should", "be", "taken", "in", "the", "domain", "of", "inputs", "this", "operator", "may", "see", ".", "An", "optional", "parameter", "is", "also", "provided", "such", "that", "an", "Observable", "can", "be", "provided", "to", "queue", "the", "internal", "HashSet", "to", "flush", "the", "values", "it", "holds", "." ]
748330a2a5e7f89a02cd99477b480237aacdb295
https://github.com/bharatraj88/angular2-timepicker/blob/748330a2a5e7f89a02cd99477b480237aacdb295/dist/vendor.js#L44982-L44989
train
bharatraj88/angular2-timepicker
dist/vendor.js
distinctUntilKeyChanged
function distinctUntilKeyChanged(key, compare) { return distinctUntilChanged_1.distinctUntilChanged.call(this, function (x, y) { if (compare) { return compare(x[key], y[key]); } return x[key] === y[key]; }); }
javascript
function distinctUntilKeyChanged(key, compare) { return distinctUntilChanged_1.distinctUntilChanged.call(this, function (x, y) { if (compare) { return compare(x[key], y[key]); } return x[key] === y[key]; }); }
[ "function", "distinctUntilKeyChanged", "(", "key", ",", "compare", ")", "{", "return", "distinctUntilChanged_1", ".", "distinctUntilChanged", ".", "call", "(", "this", ",", "function", "(", "x", ",", "y", ")", "{", "if", "(", "compare", ")", "{", "return", "compare", "(", "x", "[", "key", "]", ",", "y", "[", "key", "]", ")", ";", "}", "return", "x", "[", "key", "]", "===", "y", "[", "key", "]", ";", "}", ")", ";", "}" ]
Returns an Observable that emits all items emitted by the source Observable that are distinct by comparison from the previous item, using a property accessed by using the key provided to check if the two items are distinct. If a comparator function is provided, then it will be called for each item to test for whether or not that value should be emitted. If a comparator function is not provided, an equality check is used by default. @param {string} key string key for object property lookup on each item. @param {function} [compare] optional comparison function called to test if an item is distinct from the previous item in the source. @return {Observable} an Observable that emits items from the source Observable with distinct values based on the key specified. @method distinctUntilKeyChanged @owner Observable
[ "Returns", "an", "Observable", "that", "emits", "all", "items", "emitted", "by", "the", "source", "Observable", "that", "are", "distinct", "by", "comparison", "from", "the", "previous", "item", "using", "a", "property", "accessed", "by", "using", "the", "key", "provided", "to", "check", "if", "the", "two", "items", "are", "distinct", ".", "If", "a", "comparator", "function", "is", "provided", "then", "it", "will", "be", "called", "for", "each", "item", "to", "test", "for", "whether", "or", "not", "that", "value", "should", "be", "emitted", ".", "If", "a", "comparator", "function", "is", "not", "provided", "an", "equality", "check", "is", "used", "by", "default", "." ]
748330a2a5e7f89a02cd99477b480237aacdb295
https://github.com/bharatraj88/angular2-timepicker/blob/748330a2a5e7f89a02cd99477b480237aacdb295/dist/vendor.js#L45112-L45119
train
bharatraj88/angular2-timepicker
dist/vendor.js
find
function find(predicate, thisArg) { if (typeof predicate !== 'function') { throw new TypeError('predicate is not a function'); } return this.lift(new FindValueOperator(predicate, this, false, thisArg)); }
javascript
function find(predicate, thisArg) { if (typeof predicate !== 'function') { throw new TypeError('predicate is not a function'); } return this.lift(new FindValueOperator(predicate, this, false, thisArg)); }
[ "function", "find", "(", "predicate", ",", "thisArg", ")", "{", "if", "(", "typeof", "predicate", "!==", "'function'", ")", "{", "throw", "new", "TypeError", "(", "'predicate is not a function'", ")", ";", "}", "return", "this", ".", "lift", "(", "new", "FindValueOperator", "(", "predicate", ",", "this", ",", "false", ",", "thisArg", ")", ")", ";", "}" ]
Emits only the first value emitted by the source Observable that meets some condition. <span class="informal">Finds the first value that passes some test and emits that.</span> <img src="./img/find.png" width="100%"> `find` searches for the first item in the source Observable that matches the specified condition embodied by the `predicate`, and returns the first occurrence in the source. Unlike {@link first}, the `predicate` is required in `find`, and does not emit an error if a valid value is not found. @example <caption>Find and emit the first click that happens on a DIV element</caption> var clicks = Rx.Observable.fromEvent(document, 'click'); var result = clicks.find(ev => ev.target.tagName === 'DIV'); result.subscribe(x => console.log(x)); @see {@link filter} @see {@link first} @see {@link findIndex} @see {@link take} @param {function(value: T, index: number, source: Observable<T>): boolean} predicate A function called with each item to test for condition matching. @param {any} [thisArg] An optional argument to determine the value of `this` in the `predicate` function. @return {Observable<T>} An Observable of the first item that matches the condition. @method find @owner Observable
[ "Emits", "only", "the", "first", "value", "emitted", "by", "the", "source", "Observable", "that", "meets", "some", "condition", "." ]
748330a2a5e7f89a02cd99477b480237aacdb295
https://github.com/bharatraj88/angular2-timepicker/blob/748330a2a5e7f89a02cd99477b480237aacdb295/dist/vendor.js#L46037-L46042
train
bharatraj88/angular2-timepicker
dist/vendor.js
multicast
function multicast(subjectOrSubjectFactory, selector) { var subjectFactory; if (typeof subjectOrSubjectFactory === 'function') { subjectFactory = subjectOrSubjectFactory; } else { subjectFactory = function subjectFactory() { return subjectOrSubjectFactory; }; } return !selector ? new ConnectableObservable_1.ConnectableObservable(this, subjectFactory) : new MulticastObservable_1.MulticastObservable(this, subjectFactory, selector); }
javascript
function multicast(subjectOrSubjectFactory, selector) { var subjectFactory; if (typeof subjectOrSubjectFactory === 'function') { subjectFactory = subjectOrSubjectFactory; } else { subjectFactory = function subjectFactory() { return subjectOrSubjectFactory; }; } return !selector ? new ConnectableObservable_1.ConnectableObservable(this, subjectFactory) : new MulticastObservable_1.MulticastObservable(this, subjectFactory, selector); }
[ "function", "multicast", "(", "subjectOrSubjectFactory", ",", "selector", ")", "{", "var", "subjectFactory", ";", "if", "(", "typeof", "subjectOrSubjectFactory", "===", "'function'", ")", "{", "subjectFactory", "=", "subjectOrSubjectFactory", ";", "}", "else", "{", "subjectFactory", "=", "function", "subjectFactory", "(", ")", "{", "return", "subjectOrSubjectFactory", ";", "}", ";", "}", "return", "!", "selector", "?", "new", "ConnectableObservable_1", ".", "ConnectableObservable", "(", "this", ",", "subjectFactory", ")", ":", "new", "MulticastObservable_1", ".", "MulticastObservable", "(", "this", ",", "subjectFactory", ",", "selector", ")", ";", "}" ]
Returns an Observable that emits the results of invoking a specified selector on items emitted by a ConnectableObservable that shares a single subscription to the underlying stream. <img src="./img/multicast.png" width="100%"> @param {Function|Subject} Factory function to create an intermediate subject through which the source sequence's elements will be multicast to the selector function or Subject to push source elements into. @param {Function} Optional selector function that can use the multicasted source stream as many times as needed, without causing multiple subscriptions to the source stream. Subscribers to the given source will receive all notifications of the source from the time of the subscription forward. @return {Observable} an Observable that emits the results of invoking the selector on the items emitted by a `ConnectableObservable` that shares a single subscription to the underlying stream. @method multicast @owner Observable
[ "Returns", "an", "Observable", "that", "emits", "the", "results", "of", "invoking", "a", "specified", "selector", "on", "items", "emitted", "by", "a", "ConnectableObservable", "that", "shares", "a", "single", "subscription", "to", "the", "underlying", "stream", "." ]
748330a2a5e7f89a02cd99477b480237aacdb295
https://github.com/bharatraj88/angular2-timepicker/blob/748330a2a5e7f89a02cd99477b480237aacdb295/dist/vendor.js#L47887-L47900
train
bharatraj88/angular2-timepicker
dist/vendor.js
publish
function publish(selector) { return selector ? multicast_1.multicast.call(this, function () { return new Subject_1.Subject(); }, selector) : multicast_1.multicast.call(this, new Subject_1.Subject()); }
javascript
function publish(selector) { return selector ? multicast_1.multicast.call(this, function () { return new Subject_1.Subject(); }, selector) : multicast_1.multicast.call(this, new Subject_1.Subject()); }
[ "function", "publish", "(", "selector", ")", "{", "return", "selector", "?", "multicast_1", ".", "multicast", ".", "call", "(", "this", ",", "function", "(", ")", "{", "return", "new", "Subject_1", ".", "Subject", "(", ")", ";", "}", ",", "selector", ")", ":", "multicast_1", ".", "multicast", ".", "call", "(", "this", ",", "new", "Subject_1", ".", "Subject", "(", ")", ")", ";", "}" ]
Returns a ConnectableObservable, which is a variety of Observable that waits until its connect method is called before it begins emitting items to those Observers that have subscribed to it. <img src="./img/publish.png" width="100%"> @param {Function} Optional selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all notifications of the source from the time of the subscription on. @return a ConnectableObservable that upon connection causes the source Observable to emit items to its Observers. @method publish @owner Observable
[ "Returns", "a", "ConnectableObservable", "which", "is", "a", "variety", "of", "Observable", "that", "waits", "until", "its", "connect", "method", "is", "called", "before", "it", "begins", "emitting", "items", "to", "those", "Observers", "that", "have", "subscribed", "to", "it", "." ]
748330a2a5e7f89a02cd99477b480237aacdb295
https://github.com/bharatraj88/angular2-timepicker/blob/748330a2a5e7f89a02cd99477b480237aacdb295/dist/vendor.js#L48393-L48396
train
bharatraj88/angular2-timepicker
dist/app.js
done
function done( status, nativeStatusText, responses, headers ) { var isSuccess, success, error, response, modified, statusText = nativeStatusText; // Called once if ( state === 2 ) { return; } // State is "done" now state = 2; // Clear timeout if it exists if ( timeoutTimer ) { window.clearTimeout( timeoutTimer ); } // Dereference transport for early garbage collection // (no matter how long the jqXHR object will be used) transport = undefined; // Cache response headers responseHeadersString = headers || ""; // Set readyState jqXHR.readyState = status > 0 ? 4 : 0; // Determine if successful isSuccess = status >= 200 && status < 300 || status === 304; // Get response data if ( responses ) { response = ajaxHandleResponses( s, jqXHR, responses ); } // Convert no matter what (that way responseXXX fields are always set) response = ajaxConvert( s, response, jqXHR, isSuccess ); // If successful, handle type chaining if ( isSuccess ) { // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { modified = jqXHR.getResponseHeader( "Last-Modified" ); if ( modified ) { jQuery.lastModified[ cacheURL ] = modified; } modified = jqXHR.getResponseHeader( "etag" ); if ( modified ) { jQuery.etag[ cacheURL ] = modified; } } // if no content if ( status === 204 || s.type === "HEAD" ) { statusText = "nocontent"; // if not modified } else if ( status === 304 ) { statusText = "notmodified"; // If we have data, let's convert it } else { statusText = response.state; success = response.data; error = response.error; isSuccess = !error; } } else { // Extract error from statusText and normalize for non-aborts error = statusText; if ( status || !statusText ) { statusText = "error"; if ( status < 0 ) { status = 0; } } } // Set data for the fake xhr object jqXHR.status = status; jqXHR.statusText = ( nativeStatusText || statusText ) + ""; // Success/Error if ( isSuccess ) { deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); } else { deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); } // Status-dependent callbacks jqXHR.statusCode( statusCode ); statusCode = undefined; if ( fireGlobals ) { globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError", [ jqXHR, s, isSuccess ? success : error ] ); } // Complete completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); if ( fireGlobals ) { globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); // Handle the global AJAX counter if ( !( --jQuery.active ) ) { jQuery.event.trigger( "ajaxStop" ); } } }
javascript
function done( status, nativeStatusText, responses, headers ) { var isSuccess, success, error, response, modified, statusText = nativeStatusText; // Called once if ( state === 2 ) { return; } // State is "done" now state = 2; // Clear timeout if it exists if ( timeoutTimer ) { window.clearTimeout( timeoutTimer ); } // Dereference transport for early garbage collection // (no matter how long the jqXHR object will be used) transport = undefined; // Cache response headers responseHeadersString = headers || ""; // Set readyState jqXHR.readyState = status > 0 ? 4 : 0; // Determine if successful isSuccess = status >= 200 && status < 300 || status === 304; // Get response data if ( responses ) { response = ajaxHandleResponses( s, jqXHR, responses ); } // Convert no matter what (that way responseXXX fields are always set) response = ajaxConvert( s, response, jqXHR, isSuccess ); // If successful, handle type chaining if ( isSuccess ) { // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { modified = jqXHR.getResponseHeader( "Last-Modified" ); if ( modified ) { jQuery.lastModified[ cacheURL ] = modified; } modified = jqXHR.getResponseHeader( "etag" ); if ( modified ) { jQuery.etag[ cacheURL ] = modified; } } // if no content if ( status === 204 || s.type === "HEAD" ) { statusText = "nocontent"; // if not modified } else if ( status === 304 ) { statusText = "notmodified"; // If we have data, let's convert it } else { statusText = response.state; success = response.data; error = response.error; isSuccess = !error; } } else { // Extract error from statusText and normalize for non-aborts error = statusText; if ( status || !statusText ) { statusText = "error"; if ( status < 0 ) { status = 0; } } } // Set data for the fake xhr object jqXHR.status = status; jqXHR.statusText = ( nativeStatusText || statusText ) + ""; // Success/Error if ( isSuccess ) { deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); } else { deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); } // Status-dependent callbacks jqXHR.statusCode( statusCode ); statusCode = undefined; if ( fireGlobals ) { globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError", [ jqXHR, s, isSuccess ? success : error ] ); } // Complete completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); if ( fireGlobals ) { globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); // Handle the global AJAX counter if ( !( --jQuery.active ) ) { jQuery.event.trigger( "ajaxStop" ); } } }
[ "function", "done", "(", "status", ",", "nativeStatusText", ",", "responses", ",", "headers", ")", "{", "var", "isSuccess", ",", "success", ",", "error", ",", "response", ",", "modified", ",", "statusText", "=", "nativeStatusText", ";", "if", "(", "state", "===", "2", ")", "{", "return", ";", "}", "state", "=", "2", ";", "if", "(", "timeoutTimer", ")", "{", "window", ".", "clearTimeout", "(", "timeoutTimer", ")", ";", "}", "transport", "=", "undefined", ";", "responseHeadersString", "=", "headers", "||", "\"\"", ";", "jqXHR", ".", "readyState", "=", "status", ">", "0", "?", "4", ":", "0", ";", "isSuccess", "=", "status", ">=", "200", "&&", "status", "<", "300", "||", "status", "===", "304", ";", "if", "(", "responses", ")", "{", "response", "=", "ajaxHandleResponses", "(", "s", ",", "jqXHR", ",", "responses", ")", ";", "}", "response", "=", "ajaxConvert", "(", "s", ",", "response", ",", "jqXHR", ",", "isSuccess", ")", ";", "if", "(", "isSuccess", ")", "{", "if", "(", "s", ".", "ifModified", ")", "{", "modified", "=", "jqXHR", ".", "getResponseHeader", "(", "\"Last-Modified\"", ")", ";", "if", "(", "modified", ")", "{", "jQuery", ".", "lastModified", "[", "cacheURL", "]", "=", "modified", ";", "}", "modified", "=", "jqXHR", ".", "getResponseHeader", "(", "\"etag\"", ")", ";", "if", "(", "modified", ")", "{", "jQuery", ".", "etag", "[", "cacheURL", "]", "=", "modified", ";", "}", "}", "if", "(", "status", "===", "204", "||", "s", ".", "type", "===", "\"HEAD\"", ")", "{", "statusText", "=", "\"nocontent\"", ";", "}", "else", "if", "(", "status", "===", "304", ")", "{", "statusText", "=", "\"notmodified\"", ";", "}", "else", "{", "statusText", "=", "response", ".", "state", ";", "success", "=", "response", ".", "data", ";", "error", "=", "response", ".", "error", ";", "isSuccess", "=", "!", "error", ";", "}", "}", "else", "{", "error", "=", "statusText", ";", "if", "(", "status", "||", "!", "statusText", ")", "{", "statusText", "=", "\"error\"", ";", "if", "(", "status", "<", "0", ")", "{", "status", "=", "0", ";", "}", "}", "}", "jqXHR", ".", "status", "=", "status", ";", "jqXHR", ".", "statusText", "=", "(", "nativeStatusText", "||", "statusText", ")", "+", "\"\"", ";", "if", "(", "isSuccess", ")", "{", "deferred", ".", "resolveWith", "(", "callbackContext", ",", "[", "success", ",", "statusText", ",", "jqXHR", "]", ")", ";", "}", "else", "{", "deferred", ".", "rejectWith", "(", "callbackContext", ",", "[", "jqXHR", ",", "statusText", ",", "error", "]", ")", ";", "}", "jqXHR", ".", "statusCode", "(", "statusCode", ")", ";", "statusCode", "=", "undefined", ";", "if", "(", "fireGlobals", ")", "{", "globalEventContext", ".", "trigger", "(", "isSuccess", "?", "\"ajaxSuccess\"", ":", "\"ajaxError\"", ",", "[", "jqXHR", ",", "s", ",", "isSuccess", "?", "success", ":", "error", "]", ")", ";", "}", "completeDeferred", ".", "fireWith", "(", "callbackContext", ",", "[", "jqXHR", ",", "statusText", "]", ")", ";", "if", "(", "fireGlobals", ")", "{", "globalEventContext", ".", "trigger", "(", "\"ajaxComplete\"", ",", "[", "jqXHR", ",", "s", "]", ")", ";", "if", "(", "!", "(", "--", "jQuery", ".", "active", ")", ")", "{", "jQuery", ".", "event", ".", "trigger", "(", "\"ajaxStop\"", ")", ";", "}", "}", "}" ]
Callback for when everything is done
[ "Callback", "for", "when", "everything", "is", "done" ]
748330a2a5e7f89a02cd99477b480237aacdb295
https://github.com/bharatraj88/angular2-timepicker/blob/748330a2a5e7f89a02cd99477b480237aacdb295/dist/app.js#L13436-L13547
train
milindalvares/ember-cli-accounting
addon/utils.js
defaults
function defaults(object, defs) { var key; object = assign({}, object); defs = defs || {}; // Iterate over object non-prototype properties: for (key in defs) { if (defs.hasOwnProperty(key)) { // Replace values with defaults only if undefined (allow empty/zero values): if (object[key] == null) { object[key] = defs[key]; } } } return object; }
javascript
function defaults(object, defs) { var key; object = assign({}, object); defs = defs || {}; // Iterate over object non-prototype properties: for (key in defs) { if (defs.hasOwnProperty(key)) { // Replace values with defaults only if undefined (allow empty/zero values): if (object[key] == null) { object[key] = defs[key]; } } } return object; }
[ "function", "defaults", "(", "object", ",", "defs", ")", "{", "var", "key", ";", "object", "=", "assign", "(", "{", "}", ",", "object", ")", ";", "defs", "=", "defs", "||", "{", "}", ";", "for", "(", "key", "in", "defs", ")", "{", "if", "(", "defs", ".", "hasOwnProperty", "(", "key", ")", ")", "{", "if", "(", "object", "[", "key", "]", "==", "null", ")", "{", "object", "[", "key", "]", "=", "defs", "[", "key", "]", ";", "}", "}", "}", "return", "object", ";", "}" ]
Extends an object with a defaults object, similar to underscore's _.defaults Used for abstracting parameter handling from API methods
[ "Extends", "an", "object", "with", "a", "defaults", "object", "similar", "to", "underscore", "s", "_", ".", "defaults" ]
ae19823ed9373a31d328f2f74520fcd450add4f0
https://github.com/milindalvares/ember-cli-accounting/blob/ae19823ed9373a31d328f2f74520fcd450add4f0/addon/utils.js#L11-L25
train
waynebloss/react-mvvm
cjs/ViewModel.js
function (VMType, ViewType) { var vm = new VMType(); var vmFunctionProps = getFunctionalPropertiesMap(vm); var VConnect = /** @class */ (function (_super) { __extends(VConnect, _super); function VConnect() { return _super !== null && _super.apply(this, arguments) || this; } VConnect.prototype.render = function () { var props = this.props; return (react_1.default.createElement(ViewType, __assign({ vm: vm }, vmFunctionProps, props))); }; return VConnect; }(react_1.default.PureComponent)); return VConnect; }
javascript
function (VMType, ViewType) { var vm = new VMType(); var vmFunctionProps = getFunctionalPropertiesMap(vm); var VConnect = /** @class */ (function (_super) { __extends(VConnect, _super); function VConnect() { return _super !== null && _super.apply(this, arguments) || this; } VConnect.prototype.render = function () { var props = this.props; return (react_1.default.createElement(ViewType, __assign({ vm: vm }, vmFunctionProps, props))); }; return VConnect; }(react_1.default.PureComponent)); return VConnect; }
[ "function", "(", "VMType", ",", "ViewType", ")", "{", "var", "vm", "=", "new", "VMType", "(", ")", ";", "var", "vmFunctionProps", "=", "getFunctionalPropertiesMap", "(", "vm", ")", ";", "var", "VConnect", "=", "(", "function", "(", "_super", ")", "{", "__extends", "(", "VConnect", ",", "_super", ")", ";", "function", "VConnect", "(", ")", "{", "return", "_super", "!==", "null", "&&", "_super", ".", "apply", "(", "this", ",", "arguments", ")", "||", "this", ";", "}", "VConnect", ".", "prototype", ".", "render", "=", "function", "(", ")", "{", "var", "props", "=", "this", ".", "props", ";", "return", "(", "react_1", ".", "default", ".", "createElement", "(", "ViewType", ",", "__assign", "(", "{", "vm", ":", "vm", "}", ",", "vmFunctionProps", ",", "props", ")", ")", ")", ";", "}", ";", "return", "VConnect", ";", "}", "(", "react_1", ".", "default", ".", "PureComponent", ")", ")", ";", "return", "VConnect", ";", "}" ]
Connects a view model to a view. @param VMType The view model constructor. @param ViewType The view constructor.
[ "Connects", "a", "view", "model", "to", "a", "view", "." ]
cabf60ca31c39da27b71a31b767252c86cbeaf75
https://github.com/waynebloss/react-mvvm/blob/cabf60ca31c39da27b71a31b767252c86cbeaf75/cjs/ViewModel.js#L45-L60
train
austinhallock/html5-virtual-game-controller
src/gamecontroller.js
function() { var _this = this; this.canvas = document.createElement('canvas'); // Scale to same size as original canvas this.resize(true); document.body.appendChild(this.canvas); this.ctx = this.canvas.getContext( '2d'); window.addEventListener( 'resize', function() { setTimeout(function(){ GameController.resize.call(_this); }, 10); }); // Set the touch events for this new canvas this.setTouchEvents(); // Load in the initial UI elements this.loadSide('left'); this.loadSide('right'); // Starts up the rendering / drawing this.render(); // pause until a touch event if( !this.touches || !this.touches.length ) this.paused = true; }
javascript
function() { var _this = this; this.canvas = document.createElement('canvas'); // Scale to same size as original canvas this.resize(true); document.body.appendChild(this.canvas); this.ctx = this.canvas.getContext( '2d'); window.addEventListener( 'resize', function() { setTimeout(function(){ GameController.resize.call(_this); }, 10); }); // Set the touch events for this new canvas this.setTouchEvents(); // Load in the initial UI elements this.loadSide('left'); this.loadSide('right'); // Starts up the rendering / drawing this.render(); // pause until a touch event if( !this.touches || !this.touches.length ) this.paused = true; }
[ "function", "(", ")", "{", "var", "_this", "=", "this", ";", "this", ".", "canvas", "=", "document", ".", "createElement", "(", "'canvas'", ")", ";", "this", ".", "resize", "(", "true", ")", ";", "document", ".", "body", ".", "appendChild", "(", "this", ".", "canvas", ")", ";", "this", ".", "ctx", "=", "this", ".", "canvas", ".", "getContext", "(", "'2d'", ")", ";", "window", ".", "addEventListener", "(", "'resize'", ",", "function", "(", ")", "{", "setTimeout", "(", "function", "(", ")", "{", "GameController", ".", "resize", ".", "call", "(", "_this", ")", ";", "}", ",", "10", ")", ";", "}", ")", ";", "this", ".", "setTouchEvents", "(", ")", ";", "this", ".", "loadSide", "(", "'left'", ")", ";", "this", ".", "loadSide", "(", "'right'", ")", ";", "this", ".", "render", "(", ")", ";", "if", "(", "!", "this", ".", "touches", "||", "!", "this", ".", "touches", ".", "length", ")", "this", ".", "paused", "=", "true", ";", "}" ]
Creates the canvas that sits on top of the game's canvas and holds game controls
[ "Creates", "the", "canvas", "that", "sits", "on", "top", "of", "the", "game", "s", "canvas", "and", "holds", "game", "controls" ]
a850fdf4dc0284110102afe7a884db6e14246822
https://github.com/austinhallock/html5-virtual-game-controller/blob/a850fdf4dc0284110102afe7a884db6e14246822/src/gamecontroller.js#L299-L322
train
austinhallock/html5-virtual-game-controller
src/gamecontroller.js
function( value, axis ){ if( !value ) return 0; if( typeof value === 'number' ) return value; // a percentage return parseInt(value, 10) / 100 * (axis === 'x' ? this.canvas.width : this.canvas.height); }
javascript
function( value, axis ){ if( !value ) return 0; if( typeof value === 'number' ) return value; // a percentage return parseInt(value, 10) / 100 * (axis === 'x' ? this.canvas.width : this.canvas.height); }
[ "function", "(", "value", ",", "axis", ")", "{", "if", "(", "!", "value", ")", "return", "0", ";", "if", "(", "typeof", "value", "===", "'number'", ")", "return", "value", ";", "return", "parseInt", "(", "value", ",", "10", ")", "/", "100", "*", "(", "axis", "===", "'x'", "?", "this", ".", "canvas", ".", "width", ":", "this", ".", "canvas", ".", "height", ")", ";", "}" ]
Returns the scaled pixels. Given the value passed @param {int/string} value - either an integer for # of pixels, or 'x%' for relative @param {char} axis - x, y
[ "Returns", "the", "scaled", "pixels", ".", "Given", "the", "value", "passed" ]
a850fdf4dc0284110102afe7a884db6e14246822
https://github.com/austinhallock/html5-virtual-game-controller/blob/a850fdf4dc0284110102afe7a884db6e14246822/src/gamecontroller.js#L368-L374
train
austinhallock/html5-virtual-game-controller
src/gamecontroller.js
function( eventName, keyCode ) { // No keyboard, can't simulate... if( typeof window.onkeydown === 'undefined' ) return false; var oEvent = document.createEvent('KeyboardEvent'); // Chromium Hack if( navigator.userAgent.toLowerCase().indexOf( 'chrome' ) !== -1 ) { Object.defineProperty( oEvent, 'keyCode', { get: function() { return this.keyCodeVal; } }); Object.defineProperty( oEvent, 'which', { get: function() { return this.keyCodeVal; } }); } var initKeyEvent = oEvent.initKeyboardEvent || oEvent.initKeyEvent; initKeyEvent.call(oEvent, 'key' + eventName, true, true, document.defaultView, false, false, false, false, keyCode, keyCode ); oEvent.keyCodeVal = keyCode; }
javascript
function( eventName, keyCode ) { // No keyboard, can't simulate... if( typeof window.onkeydown === 'undefined' ) return false; var oEvent = document.createEvent('KeyboardEvent'); // Chromium Hack if( navigator.userAgent.toLowerCase().indexOf( 'chrome' ) !== -1 ) { Object.defineProperty( oEvent, 'keyCode', { get: function() { return this.keyCodeVal; } }); Object.defineProperty( oEvent, 'which', { get: function() { return this.keyCodeVal; } }); } var initKeyEvent = oEvent.initKeyboardEvent || oEvent.initKeyEvent; initKeyEvent.call(oEvent, 'key' + eventName, true, true, document.defaultView, false, false, false, false, keyCode, keyCode ); oEvent.keyCodeVal = keyCode; }
[ "function", "(", "eventName", ",", "keyCode", ")", "{", "if", "(", "typeof", "window", ".", "onkeydown", "===", "'undefined'", ")", "return", "false", ";", "var", "oEvent", "=", "document", ".", "createEvent", "(", "'KeyboardEvent'", ")", ";", "if", "(", "navigator", ".", "userAgent", ".", "toLowerCase", "(", ")", ".", "indexOf", "(", "'chrome'", ")", "!==", "-", "1", ")", "{", "Object", ".", "defineProperty", "(", "oEvent", ",", "'keyCode'", ",", "{", "get", ":", "function", "(", ")", "{", "return", "this", ".", "keyCodeVal", ";", "}", "}", ")", ";", "Object", ".", "defineProperty", "(", "oEvent", ",", "'which'", ",", "{", "get", ":", "function", "(", ")", "{", "return", "this", ".", "keyCodeVal", ";", "}", "}", ")", ";", "}", "var", "initKeyEvent", "=", "oEvent", ".", "initKeyboardEvent", "||", "oEvent", ".", "initKeyEvent", ";", "initKeyEvent", ".", "call", "(", "oEvent", ",", "'key'", "+", "eventName", ",", "true", ",", "true", ",", "document", ".", "defaultView", ",", "false", ",", "false", ",", "false", ",", "false", ",", "keyCode", ",", "keyCode", ")", ";", "oEvent", ".", "keyCodeVal", "=", "keyCode", ";", "}" ]
Simulates a key press @param {string} eventName - 'down', 'up' @param {char} character
[ "Simulates", "a", "key", "press" ]
a850fdf4dc0284110102afe7a884db6e14246822
https://github.com/austinhallock/html5-virtual-game-controller/blob/a850fdf4dc0284110102afe7a884db6e14246822/src/gamecontroller.js#L381-L411
train
austinhallock/html5-virtual-game-controller
src/gamecontroller.js
function( options ) { var direction = new TouchableDirection( options); direction.id = this.touchableAreas.push( direction); this.touchableAreasCount++; this.boundingSet(options); }
javascript
function( options ) { var direction = new TouchableDirection( options); direction.id = this.touchableAreas.push( direction); this.touchableAreasCount++; this.boundingSet(options); }
[ "function", "(", "options", ")", "{", "var", "direction", "=", "new", "TouchableDirection", "(", "options", ")", ";", "direction", ".", "id", "=", "this", ".", "touchableAreas", ".", "push", "(", "direction", ")", ";", "this", ".", "touchableAreasCount", "++", ";", "this", ".", "boundingSet", "(", "options", ")", ";", "}" ]
Adds the area to a list of touchable areas, draws @param {object} options with properties: x, y, width, height, touchStart, touchEnd, touchMove
[ "Adds", "the", "area", "to", "a", "list", "of", "touchable", "areas", "draws" ]
a850fdf4dc0284110102afe7a884db6e14246822
https://github.com/austinhallock/html5-virtual-game-controller/blob/a850fdf4dc0284110102afe7a884db6e14246822/src/gamecontroller.js#L471-L476
train
austinhallock/html5-virtual-game-controller
src/gamecontroller.js
function() { for( var i = 0, j = this.touchableAreasCount; i < j; i++ ) { var area = this.touchableAreas[ i ]; if( typeof area === 'undefined' ) continue; area.draw(); // Go through all touches to see if any hit this area var touched = false; for( var k = 0, l = this.touches.length; k < l; k++ ) { var touch = this.touches[ k ]; if( typeof touch === 'undefined' ) continue; var x = this.normalizeTouchPositionX(touch.clientX), y = this.normalizeTouchPositionY(touch.clientY); // Check that it's in the bounding box/circle if( area.check(x, y) && !touched) touched = this.touches[k]; } if( touched ) { if( !area.active ) area.touchStartWrapper(touched); area.touchMoveWrapper(touched); } else if( area.active ) area.touchEndWrapper(touched); } }
javascript
function() { for( var i = 0, j = this.touchableAreasCount; i < j; i++ ) { var area = this.touchableAreas[ i ]; if( typeof area === 'undefined' ) continue; area.draw(); // Go through all touches to see if any hit this area var touched = false; for( var k = 0, l = this.touches.length; k < l; k++ ) { var touch = this.touches[ k ]; if( typeof touch === 'undefined' ) continue; var x = this.normalizeTouchPositionX(touch.clientX), y = this.normalizeTouchPositionY(touch.clientY); // Check that it's in the bounding box/circle if( area.check(x, y) && !touched) touched = this.touches[k]; } if( touched ) { if( !area.active ) area.touchStartWrapper(touched); area.touchMoveWrapper(touched); } else if( area.active ) area.touchEndWrapper(touched); } }
[ "function", "(", ")", "{", "for", "(", "var", "i", "=", "0", ",", "j", "=", "this", ".", "touchableAreasCount", ";", "i", "<", "j", ";", "i", "++", ")", "{", "var", "area", "=", "this", ".", "touchableAreas", "[", "i", "]", ";", "if", "(", "typeof", "area", "===", "'undefined'", ")", "continue", ";", "area", ".", "draw", "(", ")", ";", "var", "touched", "=", "false", ";", "for", "(", "var", "k", "=", "0", ",", "l", "=", "this", ".", "touches", ".", "length", ";", "k", "<", "l", ";", "k", "++", ")", "{", "var", "touch", "=", "this", ".", "touches", "[", "k", "]", ";", "if", "(", "typeof", "touch", "===", "'undefined'", ")", "continue", ";", "var", "x", "=", "this", ".", "normalizeTouchPositionX", "(", "touch", ".", "clientX", ")", ",", "y", "=", "this", ".", "normalizeTouchPositionY", "(", "touch", ".", "clientY", ")", ";", "if", "(", "area", ".", "check", "(", "x", ",", "y", ")", "&&", "!", "touched", ")", "touched", "=", "this", ".", "touches", "[", "k", "]", ";", "}", "if", "(", "touched", ")", "{", "if", "(", "!", "area", ".", "active", ")", "area", ".", "touchStartWrapper", "(", "touched", ")", ";", "area", ".", "touchMoveWrapper", "(", "touched", ")", ";", "}", "else", "if", "(", "area", ".", "active", ")", "area", ".", "touchEndWrapper", "(", "touched", ")", ";", "}", "}" ]
Processes the info for each touchableArea
[ "Processes", "the", "info", "for", "each", "touchableArea" ]
a850fdf4dc0284110102afe7a884db6e14246822
https://github.com/austinhallock/html5-virtual-game-controller/blob/a850fdf4dc0284110102afe7a884db6e14246822/src/gamecontroller.js#L642-L663
train
austinhallock/html5-virtual-game-controller
src/gamecontroller.js
TouchableButton
function TouchableButton( options ) { for( var i in options ) { if( i === 'x' ) this[i] = GameController.getPixels( options[i], 'x'); else if( i === 'y' || i === 'radius' ){ this[i] = GameController.getPixels(options[i], 'y'); } else this[i] = options[i]; } this.draw(); }
javascript
function TouchableButton( options ) { for( var i in options ) { if( i === 'x' ) this[i] = GameController.getPixels( options[i], 'x'); else if( i === 'y' || i === 'radius' ){ this[i] = GameController.getPixels(options[i], 'y'); } else this[i] = options[i]; } this.draw(); }
[ "function", "TouchableButton", "(", "options", ")", "{", "for", "(", "var", "i", "in", "options", ")", "{", "if", "(", "i", "===", "'x'", ")", "this", "[", "i", "]", "=", "GameController", ".", "getPixels", "(", "options", "[", "i", "]", ",", "'x'", ")", ";", "else", "if", "(", "i", "===", "'y'", "||", "i", "===", "'radius'", ")", "{", "this", "[", "i", "]", "=", "GameController", ".", "getPixels", "(", "options", "[", "i", "]", ",", "'y'", ")", ";", "}", "else", "this", "[", "i", "]", "=", "options", "[", "i", "]", ";", "}", "this", ".", "draw", "(", ")", ";", "}" ]
x, y, radius, backgroundColor )
[ "x", "y", "radius", "backgroundColor", ")" ]
a850fdf4dc0284110102afe7a884db6e14246822
https://github.com/austinhallock/html5-virtual-game-controller/blob/a850fdf4dc0284110102afe7a884db6e14246822/src/gamecontroller.js#L906-L914
train
ninjablocks/node-zigbee
lib/zcl/ZCLClient.js
ZCLClient
function ZCLClient(config) { ZNPClient.call(this, config); // handle zcl messages this.on('incoming-message', this._handleIncomingMessage.bind(this)); // handle attribute reports this.on('zcl-command:ReportAttributes', this._handleReportAttributes.bind(this)); // XXX: This really should be pulled out and handled by the user, or at least put into a IASZone mixin this.on('zcl-command:IAS Zone.Zone Enroll Request', this._handleZoneEnrollRequest.bind(this)); }
javascript
function ZCLClient(config) { ZNPClient.call(this, config); // handle zcl messages this.on('incoming-message', this._handleIncomingMessage.bind(this)); // handle attribute reports this.on('zcl-command:ReportAttributes', this._handleReportAttributes.bind(this)); // XXX: This really should be pulled out and handled by the user, or at least put into a IASZone mixin this.on('zcl-command:IAS Zone.Zone Enroll Request', this._handleZoneEnrollRequest.bind(this)); }
[ "function", "ZCLClient", "(", "config", ")", "{", "ZNPClient", ".", "call", "(", "this", ",", "config", ")", ";", "this", ".", "on", "(", "'incoming-message'", ",", "this", ".", "_handleIncomingMessage", ".", "bind", "(", "this", ")", ")", ";", "this", ".", "on", "(", "'zcl-command:ReportAttributes'", ",", "this", ".", "_handleReportAttributes", ".", "bind", "(", "this", ")", ")", ";", "this", ".", "on", "(", "'zcl-command:IAS Zone.Zone Enroll Request'", ",", "this", ".", "_handleZoneEnrollRequest", ".", "bind", "(", "this", ")", ")", ";", "}" ]
Extends ZNPClient to provice the ZCL layer, without understanding any of the underlying hardware.
[ "Extends", "ZNPClient", "to", "provice", "the", "ZCL", "layer", "without", "understanding", "any", "of", "the", "underlying", "hardware", "." ]
fccfb47b6c8a2ae9192bcbed622522d7b2d296e7
https://github.com/ninjablocks/node-zigbee/blob/fccfb47b6c8a2ae9192bcbed622522d7b2d296e7/lib/zcl/ZCLClient.js#L17-L28
train
ninjablocks/node-zigbee
lib/znp/ZNPClient.js
ZNPClient
function ZNPClient(config) { this._devices = {}; this.config = config; if (!config || !config.panId) { throw new Error('You must set "panId" on ZNPClient config'); } this.comms = new ZNPSerial(); // Device state notifications this.comms.on('command:ZDO_STATE_CHANGE_IND', this._handleStateChange.bind(this)); // Device announcements this.comms.on('command:ZDO_END_DEVICE_ANNCE_IND', this._handleDeviceAnnounce.bind(this)); // Device endpoint responses this.comms.on('command:ZDO_MATCH_DESC_RSP', this._handleDeviceMatchDescriptionResponse.bind(this)); this.comms.on('command:ZDO_ACTIVE_EP_RSP', this._handleDeviceMatchDescriptionResponse.bind(this)); // Endpoint description responses this.comms.on('command:ZDO_SIMPLE_DESC_RSP', this._handleEndpointSimpleDescriptorResponse.bind(this)); // Application framework (ZCL) messages this.comms.on('command:AF_INCOMING_MSG', this._handleAFIncomingMessage.bind(this)); }
javascript
function ZNPClient(config) { this._devices = {}; this.config = config; if (!config || !config.panId) { throw new Error('You must set "panId" on ZNPClient config'); } this.comms = new ZNPSerial(); // Device state notifications this.comms.on('command:ZDO_STATE_CHANGE_IND', this._handleStateChange.bind(this)); // Device announcements this.comms.on('command:ZDO_END_DEVICE_ANNCE_IND', this._handleDeviceAnnounce.bind(this)); // Device endpoint responses this.comms.on('command:ZDO_MATCH_DESC_RSP', this._handleDeviceMatchDescriptionResponse.bind(this)); this.comms.on('command:ZDO_ACTIVE_EP_RSP', this._handleDeviceMatchDescriptionResponse.bind(this)); // Endpoint description responses this.comms.on('command:ZDO_SIMPLE_DESC_RSP', this._handleEndpointSimpleDescriptorResponse.bind(this)); // Application framework (ZCL) messages this.comms.on('command:AF_INCOMING_MSG', this._handleAFIncomingMessage.bind(this)); }
[ "function", "ZNPClient", "(", "config", ")", "{", "this", ".", "_devices", "=", "{", "}", ";", "this", ".", "config", "=", "config", ";", "if", "(", "!", "config", "||", "!", "config", ".", "panId", ")", "{", "throw", "new", "Error", "(", "'You must set \"panId\" on ZNPClient config'", ")", ";", "}", "this", ".", "comms", "=", "new", "ZNPSerial", "(", ")", ";", "this", ".", "comms", ".", "on", "(", "'command:ZDO_STATE_CHANGE_IND'", ",", "this", ".", "_handleStateChange", ".", "bind", "(", "this", ")", ")", ";", "this", ".", "comms", ".", "on", "(", "'command:ZDO_END_DEVICE_ANNCE_IND'", ",", "this", ".", "_handleDeviceAnnounce", ".", "bind", "(", "this", ")", ")", ";", "this", ".", "comms", ".", "on", "(", "'command:ZDO_MATCH_DESC_RSP'", ",", "this", ".", "_handleDeviceMatchDescriptionResponse", ".", "bind", "(", "this", ")", ")", ";", "this", ".", "comms", ".", "on", "(", "'command:ZDO_ACTIVE_EP_RSP'", ",", "this", ".", "_handleDeviceMatchDescriptionResponse", ".", "bind", "(", "this", ")", ")", ";", "this", ".", "comms", ".", "on", "(", "'command:ZDO_SIMPLE_DESC_RSP'", ",", "this", ".", "_handleEndpointSimpleDescriptorResponse", ".", "bind", "(", "this", ")", ")", ";", "this", ".", "comms", ".", "on", "(", "'command:AF_INCOMING_MSG'", ",", "this", ".", "_handleAFIncomingMessage", ".", "bind", "(", "this", ")", ")", ";", "}" ]
A ZigBee client, handling higher level functions relating to the ZigBee network. interface responsible for communicating with the ZigBee SOC.
[ "A", "ZigBee", "client", "handling", "higher", "level", "functions", "relating", "to", "the", "ZigBee", "network", ".", "interface", "responsible", "for", "communicating", "with", "the", "ZigBee", "SOC", "." ]
fccfb47b6c8a2ae9192bcbed622522d7b2d296e7
https://github.com/ninjablocks/node-zigbee/blob/fccfb47b6c8a2ae9192bcbed622522d7b2d296e7/lib/znp/ZNPClient.js#L22-L48
train
ninjablocks/node-zigbee
lib/znp/ZNPSerial.js
calculateFCS
function calculateFCS(buffer) { var fcs = 0; for (var i = 0; i < buffer.length; i++) { fcs ^= buffer[i]; } return fcs; }
javascript
function calculateFCS(buffer) { var fcs = 0; for (var i = 0; i < buffer.length; i++) { fcs ^= buffer[i]; } return fcs; }
[ "function", "calculateFCS", "(", "buffer", ")", "{", "var", "fcs", "=", "0", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "buffer", ".", "length", ";", "i", "++", ")", "{", "fcs", "^=", "buffer", "[", "i", "]", ";", "}", "return", "fcs", ";", "}" ]
Calculates the FCS for a given buffer. @param {Buffer} buffer @return {Integer} FCS
[ "Calculates", "the", "FCS", "for", "a", "given", "buffer", "." ]
fccfb47b6c8a2ae9192bcbed622522d7b2d296e7
https://github.com/ninjablocks/node-zigbee/blob/fccfb47b6c8a2ae9192bcbed622522d7b2d296e7/lib/znp/ZNPSerial.js#L271-L279
train
ninjablocks/node-zigbee
lib/profile/Cluster.js
ZCLCluster
function ZCLCluster(endpoint, clusterId) { this.endpoint = endpoint; this.device = this.endpoint.device; this.client = this.device.client; this.comms = this.client.comms; // XXX: Horrible hack, fix me. this.client.on('command.' + this.device.shortAddress + '.' + endpoint.endpointId + '.' + clusterId, function(command) { debug(this, 'command received', command); this.emit('command', command); }.bind(this)); this.clusterId = clusterId; this.description = profileStore.getCluster(clusterId) || { name: 'UNKNOWN DEVICE' }; this.name = this.description.name; this.attributes = {}; if (this.description.attribute) { this.description.attribute.forEach(function(attr) { var attrId = attr.id; this.attributes[attr.name] = this.attributes[attrId] = { name: attr.name, id: attr.id, read: function() { return this.readAttributes(attrId).then(function(responses) { var response = responses[attrId]; //debug('Responses', responses); if (response.status.key !== 'SUCCESS') { throw new Error('Failed to get attribute. Status', status); } return response.value; }); }.bind(this) /*, write: function(value) { return this.writeAttributes(attrId).then(function(responses) { var response = responses[0]; if (response.status.key !== 'SUCCESS') { throw new Error('Failed to get attribute. Status', status); } return response.value; }); }.bind(this)*/ }; }.bind(this)); } this.commands = {}; if (this.description.command) { this.description.command.forEach(function(command) { var commandId = command.id; this.commands[command.name] = this.commands[commandId] = function(payload) { debug(this, 'Sending command', command, command.id, commandId); return this.sendClusterSpecificCommand(commandId, payload); }.bind(this); }.bind(this)); } }
javascript
function ZCLCluster(endpoint, clusterId) { this.endpoint = endpoint; this.device = this.endpoint.device; this.client = this.device.client; this.comms = this.client.comms; // XXX: Horrible hack, fix me. this.client.on('command.' + this.device.shortAddress + '.' + endpoint.endpointId + '.' + clusterId, function(command) { debug(this, 'command received', command); this.emit('command', command); }.bind(this)); this.clusterId = clusterId; this.description = profileStore.getCluster(clusterId) || { name: 'UNKNOWN DEVICE' }; this.name = this.description.name; this.attributes = {}; if (this.description.attribute) { this.description.attribute.forEach(function(attr) { var attrId = attr.id; this.attributes[attr.name] = this.attributes[attrId] = { name: attr.name, id: attr.id, read: function() { return this.readAttributes(attrId).then(function(responses) { var response = responses[attrId]; //debug('Responses', responses); if (response.status.key !== 'SUCCESS') { throw new Error('Failed to get attribute. Status', status); } return response.value; }); }.bind(this) /*, write: function(value) { return this.writeAttributes(attrId).then(function(responses) { var response = responses[0]; if (response.status.key !== 'SUCCESS') { throw new Error('Failed to get attribute. Status', status); } return response.value; }); }.bind(this)*/ }; }.bind(this)); } this.commands = {}; if (this.description.command) { this.description.command.forEach(function(command) { var commandId = command.id; this.commands[command.name] = this.commands[commandId] = function(payload) { debug(this, 'Sending command', command, command.id, commandId); return this.sendClusterSpecificCommand(commandId, payload); }.bind(this); }.bind(this)); } }
[ "function", "ZCLCluster", "(", "endpoint", ",", "clusterId", ")", "{", "this", ".", "endpoint", "=", "endpoint", ";", "this", ".", "device", "=", "this", ".", "endpoint", ".", "device", ";", "this", ".", "client", "=", "this", ".", "device", ".", "client", ";", "this", ".", "comms", "=", "this", ".", "client", ".", "comms", ";", "this", ".", "client", ".", "on", "(", "'command.'", "+", "this", ".", "device", ".", "shortAddress", "+", "'.'", "+", "endpoint", ".", "endpointId", "+", "'.'", "+", "clusterId", ",", "function", "(", "command", ")", "{", "debug", "(", "this", ",", "'command received'", ",", "command", ")", ";", "this", ".", "emit", "(", "'command'", ",", "command", ")", ";", "}", ".", "bind", "(", "this", ")", ")", ";", "this", ".", "clusterId", "=", "clusterId", ";", "this", ".", "description", "=", "profileStore", ".", "getCluster", "(", "clusterId", ")", "||", "{", "name", ":", "'UNKNOWN DEVICE'", "}", ";", "this", ".", "name", "=", "this", ".", "description", ".", "name", ";", "this", ".", "attributes", "=", "{", "}", ";", "if", "(", "this", ".", "description", ".", "attribute", ")", "{", "this", ".", "description", ".", "attribute", ".", "forEach", "(", "function", "(", "attr", ")", "{", "var", "attrId", "=", "attr", ".", "id", ";", "this", ".", "attributes", "[", "attr", ".", "name", "]", "=", "this", ".", "attributes", "[", "attrId", "]", "=", "{", "name", ":", "attr", ".", "name", ",", "id", ":", "attr", ".", "id", ",", "read", ":", "function", "(", ")", "{", "return", "this", ".", "readAttributes", "(", "attrId", ")", ".", "then", "(", "function", "(", "responses", ")", "{", "var", "response", "=", "responses", "[", "attrId", "]", ";", "if", "(", "response", ".", "status", ".", "key", "!==", "'SUCCESS'", ")", "{", "throw", "new", "Error", "(", "'Failed to get attribute. Status'", ",", "status", ")", ";", "}", "return", "response", ".", "value", ";", "}", ")", ";", "}", ".", "bind", "(", "this", ")", "}", ";", "}", ".", "bind", "(", "this", ")", ")", ";", "}", "this", ".", "commands", "=", "{", "}", ";", "if", "(", "this", ".", "description", ".", "command", ")", "{", "this", ".", "description", ".", "command", ".", "forEach", "(", "function", "(", "command", ")", "{", "var", "commandId", "=", "command", ".", "id", ";", "this", ".", "commands", "[", "command", ".", "name", "]", "=", "this", ".", "commands", "[", "commandId", "]", "=", "function", "(", "payload", ")", "{", "debug", "(", "this", ",", "'Sending command'", ",", "command", ",", "command", ".", "id", ",", "commandId", ")", ";", "return", "this", ".", "sendClusterSpecificCommand", "(", "commandId", ",", "payload", ")", ";", "}", ".", "bind", "(", "this", ")", ";", "}", ".", "bind", "(", "this", ")", ")", ";", "}", "}" ]
Represents a ZCL cluster on a specific endpoint on a device. @param {Endpoint} endpoint @param {Number} clusterId
[ "Represents", "a", "ZCL", "cluster", "on", "a", "specific", "endpoint", "on", "a", "device", "." ]
fccfb47b6c8a2ae9192bcbed622522d7b2d296e7
https://github.com/ninjablocks/node-zigbee/blob/fccfb47b6c8a2ae9192bcbed622522d7b2d296e7/lib/profile/Cluster.js#L24-L91
train
building5/sails-db-migrate
lib/sailsDbMigrate.js
buildURL
function buildURL(connection) { var scheme; var url; switch (connection.adapter) { case 'sails-mysql': scheme = 'mysql'; break; case 'sails-postgresql': scheme = 'postgres'; break; case 'sails-mongo': scheme = 'mongodb' break; default: throw new Error('migrations not supported for ' + connection.adapter); } // return the connection url if one is configured if (connection.url) { return connection.url; } url = scheme + '://'; if (connection.user) { url += connection.user; if (connection.password) { url += ':' + encodeURIComponent(connection.password) } url += '@'; } url += connection.host || 'localhost'; if (connection.port) { url += ':' + connection.port; } if (connection.database) { url += '/' + encodeURIComponent(connection.database); } var params = []; if (connection.multipleStatements) { params.push('multipleStatements=true'); } if (params.length > 0) { url += '?' + params.join('&'); } return url; }
javascript
function buildURL(connection) { var scheme; var url; switch (connection.adapter) { case 'sails-mysql': scheme = 'mysql'; break; case 'sails-postgresql': scheme = 'postgres'; break; case 'sails-mongo': scheme = 'mongodb' break; default: throw new Error('migrations not supported for ' + connection.adapter); } // return the connection url if one is configured if (connection.url) { return connection.url; } url = scheme + '://'; if (connection.user) { url += connection.user; if (connection.password) { url += ':' + encodeURIComponent(connection.password) } url += '@'; } url += connection.host || 'localhost'; if (connection.port) { url += ':' + connection.port; } if (connection.database) { url += '/' + encodeURIComponent(connection.database); } var params = []; if (connection.multipleStatements) { params.push('multipleStatements=true'); } if (params.length > 0) { url += '?' + params.join('&'); } return url; }
[ "function", "buildURL", "(", "connection", ")", "{", "var", "scheme", ";", "var", "url", ";", "switch", "(", "connection", ".", "adapter", ")", "{", "case", "'sails-mysql'", ":", "scheme", "=", "'mysql'", ";", "break", ";", "case", "'sails-postgresql'", ":", "scheme", "=", "'postgres'", ";", "break", ";", "case", "'sails-mongo'", ":", "scheme", "=", "'mongodb'", "break", ";", "default", ":", "throw", "new", "Error", "(", "'migrations not supported for '", "+", "connection", ".", "adapter", ")", ";", "}", "if", "(", "connection", ".", "url", ")", "{", "return", "connection", ".", "url", ";", "}", "url", "=", "scheme", "+", "'://'", ";", "if", "(", "connection", ".", "user", ")", "{", "url", "+=", "connection", ".", "user", ";", "if", "(", "connection", ".", "password", ")", "{", "url", "+=", "':'", "+", "encodeURIComponent", "(", "connection", ".", "password", ")", "}", "url", "+=", "'@'", ";", "}", "url", "+=", "connection", ".", "host", "||", "'localhost'", ";", "if", "(", "connection", ".", "port", ")", "{", "url", "+=", "':'", "+", "connection", ".", "port", ";", "}", "if", "(", "connection", ".", "database", ")", "{", "url", "+=", "'/'", "+", "encodeURIComponent", "(", "connection", ".", "database", ")", ";", "}", "var", "params", "=", "[", "]", ";", "if", "(", "connection", ".", "multipleStatements", ")", "{", "params", ".", "push", "(", "'multipleStatements=true'", ")", ";", "}", "if", "(", "params", ".", "length", ">", "0", ")", "{", "url", "+=", "'?'", "+", "params", ".", "join", "(", "'&'", ")", ";", "}", "return", "url", ";", "}" ]
Build a URL from the Sails connection config. @param {object} connection Sails connection config. @returns {string} URL for connecting to the specified database. @throws Error if adapter is not supported.
[ "Build", "a", "URL", "from", "the", "Sails", "connection", "config", "." ]
41ffc849446f433298fe23dbccee771c1a55137f
https://github.com/building5/sails-db-migrate/blob/41ffc849446f433298fe23dbccee771c1a55137f/lib/sailsDbMigrate.js#L14-L63
train
building5/sails-db-migrate
lib/sailsDbMigrate.js
parseSailsConfig
function parseSailsConfig(sailsConfig) { var res = {}; var connection; if (!sailsConfig.migrations) { throw new Error('Migrations not configured. Please setup ./config/migrations.js'); } var connectionName = sailsConfig.migrations.connection; if (!connectionName) { throw new Error('connection missing from ./config/migrations.js'); } connection = sailsConfig.connections[connectionName]; if (!connection) { throw new Error('could not find connection ' + connectionName + ' in ./config/connections.js'); } // build the db url, which contains the password res.url = buildURL(connection); // check for ssl option in connection config if (connection.ssl) { res.adapter = connection.adapter; res.ssl = true; } // now build a clean one for logging, without the password if (connection.password != null) { connection.password = '****'; } res.cleanURL = buildURL(connection); return res; }
javascript
function parseSailsConfig(sailsConfig) { var res = {}; var connection; if (!sailsConfig.migrations) { throw new Error('Migrations not configured. Please setup ./config/migrations.js'); } var connectionName = sailsConfig.migrations.connection; if (!connectionName) { throw new Error('connection missing from ./config/migrations.js'); } connection = sailsConfig.connections[connectionName]; if (!connection) { throw new Error('could not find connection ' + connectionName + ' in ./config/connections.js'); } // build the db url, which contains the password res.url = buildURL(connection); // check for ssl option in connection config if (connection.ssl) { res.adapter = connection.adapter; res.ssl = true; } // now build a clean one for logging, without the password if (connection.password != null) { connection.password = '****'; } res.cleanURL = buildURL(connection); return res; }
[ "function", "parseSailsConfig", "(", "sailsConfig", ")", "{", "var", "res", "=", "{", "}", ";", "var", "connection", ";", "if", "(", "!", "sailsConfig", ".", "migrations", ")", "{", "throw", "new", "Error", "(", "'Migrations not configured. Please setup ./config/migrations.js'", ")", ";", "}", "var", "connectionName", "=", "sailsConfig", ".", "migrations", ".", "connection", ";", "if", "(", "!", "connectionName", ")", "{", "throw", "new", "Error", "(", "'connection missing from ./config/migrations.js'", ")", ";", "}", "connection", "=", "sailsConfig", ".", "connections", "[", "connectionName", "]", ";", "if", "(", "!", "connection", ")", "{", "throw", "new", "Error", "(", "'could not find connection '", "+", "connectionName", "+", "' in ./config/connections.js'", ")", ";", "}", "res", ".", "url", "=", "buildURL", "(", "connection", ")", ";", "if", "(", "connection", ".", "ssl", ")", "{", "res", ".", "adapter", "=", "connection", ".", "adapter", ";", "res", ".", "ssl", "=", "true", ";", "}", "if", "(", "connection", ".", "password", "!=", "null", ")", "{", "connection", ".", "password", "=", "'****'", ";", "}", "res", ".", "cleanURL", "=", "buildURL", "(", "connection", ")", ";", "return", "res", ";", "}" ]
Parse out the database URL from the sails config. @param sailsConfig Sails config object. @returns {object} .url and .cleanURL for the database connection. @throws Error if adapter is not supported.
[ "Parse", "out", "the", "database", "URL", "from", "the", "sails", "config", "." ]
41ffc849446f433298fe23dbccee771c1a55137f
https://github.com/building5/sails-db-migrate/blob/41ffc849446f433298fe23dbccee771c1a55137f/lib/sailsDbMigrate.js#L72-L105
train
building5/sails-db-migrate
lib/gruntTasks.js
buildDbMigrateArgs
function buildDbMigrateArgs(grunt, config, command) { var args = []; var name = grunt.option('name'); args.push(command); if (command === 'create') { if (!name) { throw new Error('--name required to create migration'); } args.push(name); } if (grunt.option('count') !== undefined) { args.push('--count'); args.push(grunt.option('count')); } if (grunt.option('dry-run')) { args.push('--dry-run'); } if (grunt.option('db-verbose')) { args.push('--verbose'); } if (grunt.option('sql-file')) { args.push('--sql-file'); } if (grunt.option('coffee-file')) { args.push('--coffee-file'); } else if (config.coffeeFile) { args.push('--coffee-file'); } if (grunt.option('migrations-dir')) { args.push('--migrations-dir'); args.push(grunt.option('migrations-dir')); } else if (config.migrationsDir) { args.push('--migrations-dir'); args.push(config.migrationsDir); } if (grunt.option('table')) { args.push('--table'); args.push(grunt.option('table')); } else if (config.table) { args.push('--table'); args.push(config.table); } return args; }
javascript
function buildDbMigrateArgs(grunt, config, command) { var args = []; var name = grunt.option('name'); args.push(command); if (command === 'create') { if (!name) { throw new Error('--name required to create migration'); } args.push(name); } if (grunt.option('count') !== undefined) { args.push('--count'); args.push(grunt.option('count')); } if (grunt.option('dry-run')) { args.push('--dry-run'); } if (grunt.option('db-verbose')) { args.push('--verbose'); } if (grunt.option('sql-file')) { args.push('--sql-file'); } if (grunt.option('coffee-file')) { args.push('--coffee-file'); } else if (config.coffeeFile) { args.push('--coffee-file'); } if (grunt.option('migrations-dir')) { args.push('--migrations-dir'); args.push(grunt.option('migrations-dir')); } else if (config.migrationsDir) { args.push('--migrations-dir'); args.push(config.migrationsDir); } if (grunt.option('table')) { args.push('--table'); args.push(grunt.option('table')); } else if (config.table) { args.push('--table'); args.push(config.table); } return args; }
[ "function", "buildDbMigrateArgs", "(", "grunt", ",", "config", ",", "command", ")", "{", "var", "args", "=", "[", "]", ";", "var", "name", "=", "grunt", ".", "option", "(", "'name'", ")", ";", "args", ".", "push", "(", "command", ")", ";", "if", "(", "command", "===", "'create'", ")", "{", "if", "(", "!", "name", ")", "{", "throw", "new", "Error", "(", "'--name required to create migration'", ")", ";", "}", "args", ".", "push", "(", "name", ")", ";", "}", "if", "(", "grunt", ".", "option", "(", "'count'", ")", "!==", "undefined", ")", "{", "args", ".", "push", "(", "'--count'", ")", ";", "args", ".", "push", "(", "grunt", ".", "option", "(", "'count'", ")", ")", ";", "}", "if", "(", "grunt", ".", "option", "(", "'dry-run'", ")", ")", "{", "args", ".", "push", "(", "'--dry-run'", ")", ";", "}", "if", "(", "grunt", ".", "option", "(", "'db-verbose'", ")", ")", "{", "args", ".", "push", "(", "'--verbose'", ")", ";", "}", "if", "(", "grunt", ".", "option", "(", "'sql-file'", ")", ")", "{", "args", ".", "push", "(", "'--sql-file'", ")", ";", "}", "if", "(", "grunt", ".", "option", "(", "'coffee-file'", ")", ")", "{", "args", ".", "push", "(", "'--coffee-file'", ")", ";", "}", "else", "if", "(", "config", ".", "coffeeFile", ")", "{", "args", ".", "push", "(", "'--coffee-file'", ")", ";", "}", "if", "(", "grunt", ".", "option", "(", "'migrations-dir'", ")", ")", "{", "args", ".", "push", "(", "'--migrations-dir'", ")", ";", "args", ".", "push", "(", "grunt", ".", "option", "(", "'migrations-dir'", ")", ")", ";", "}", "else", "if", "(", "config", ".", "migrationsDir", ")", "{", "args", ".", "push", "(", "'--migrations-dir'", ")", ";", "args", ".", "push", "(", "config", ".", "migrationsDir", ")", ";", "}", "if", "(", "grunt", ".", "option", "(", "'table'", ")", ")", "{", "args", ".", "push", "(", "'--table'", ")", ";", "args", ".", "push", "(", "grunt", ".", "option", "(", "'table'", ")", ")", ";", "}", "else", "if", "(", "config", ".", "table", ")", "{", "args", ".", "push", "(", "'--table'", ")", ";", "args", ".", "push", "(", "config", ".", "table", ")", ";", "}", "return", "args", ";", "}" ]
Builds the command line arguments to pass to db-migrate. @param grunt Grunt object. @param command The db-migrate command to run. @returns Arguments array for the db-migrate command.
[ "Builds", "the", "command", "line", "arguments", "to", "pass", "to", "db", "-", "migrate", "." ]
41ffc849446f433298fe23dbccee771c1a55137f
https://github.com/building5/sails-db-migrate/blob/41ffc849446f433298fe23dbccee771c1a55137f/lib/gruntTasks.js#L13-L66
train
building5/sails-db-migrate
lib/gruntTasks.js
usage
function usage(grunt) { grunt.log.writeln('usage: grunt db:migrate[:up|:down|:create] [options]'); grunt.log.writeln(' See ./migrations/README.md for more details'); grunt.log.writeln(); grunt.log.writeln('db:migrate:create Options:'); grunt.log.writeln(' --name=NAME Name of the migration to create'); grunt.log.writeln(); grunt.log.writeln('db:migrate[:up|:down] Options:'); grunt.log.writeln(' --count=N Max number of migrations to run.'); grunt.log.writeln(' --dry-run Prints the SQL but doesn\'t run it.'); grunt.log.writeln(' --db-verbose Verbose mode.'); grunt.log.writeln(' --sql-file Create sql files for up and down.'); grunt.log.writeln(' --coffee-file Create a coffeescript migration file.'); grunt.log.writeln(' --migrations-dir The directory to use for migration files.'); grunt.log.writeln(' Defaults to "migrations".'); grunt.log.writeln(' --table Specify the table to track migrations in.'); grunt.log.writeln(' Defaults to "migrations".'); }
javascript
function usage(grunt) { grunt.log.writeln('usage: grunt db:migrate[:up|:down|:create] [options]'); grunt.log.writeln(' See ./migrations/README.md for more details'); grunt.log.writeln(); grunt.log.writeln('db:migrate:create Options:'); grunt.log.writeln(' --name=NAME Name of the migration to create'); grunt.log.writeln(); grunt.log.writeln('db:migrate[:up|:down] Options:'); grunt.log.writeln(' --count=N Max number of migrations to run.'); grunt.log.writeln(' --dry-run Prints the SQL but doesn\'t run it.'); grunt.log.writeln(' --db-verbose Verbose mode.'); grunt.log.writeln(' --sql-file Create sql files for up and down.'); grunt.log.writeln(' --coffee-file Create a coffeescript migration file.'); grunt.log.writeln(' --migrations-dir The directory to use for migration files.'); grunt.log.writeln(' Defaults to "migrations".'); grunt.log.writeln(' --table Specify the table to track migrations in.'); grunt.log.writeln(' Defaults to "migrations".'); }
[ "function", "usage", "(", "grunt", ")", "{", "grunt", ".", "log", ".", "writeln", "(", "'usage: grunt db:migrate[:up|:down|:create] [options]'", ")", ";", "grunt", ".", "log", ".", "writeln", "(", "' See ./migrations/README.md for more details'", ")", ";", "grunt", ".", "log", ".", "writeln", "(", ")", ";", "grunt", ".", "log", ".", "writeln", "(", "'db:migrate:create Options:'", ")", ";", "grunt", ".", "log", ".", "writeln", "(", "' --name=NAME Name of the migration to create'", ")", ";", "grunt", ".", "log", ".", "writeln", "(", ")", ";", "grunt", ".", "log", ".", "writeln", "(", "'db:migrate[:up|:down] Options:'", ")", ";", "grunt", ".", "log", ".", "writeln", "(", "' --count=N Max number of migrations to run.'", ")", ";", "grunt", ".", "log", ".", "writeln", "(", "' --dry-run Prints the SQL but doesn\\'t run it.'", ")", ";", "\\'", "grunt", ".", "log", ".", "writeln", "(", "' --db-verbose Verbose mode.'", ")", ";", "grunt", ".", "log", ".", "writeln", "(", "' --sql-file Create sql files for up and down.'", ")", ";", "grunt", ".", "log", ".", "writeln", "(", "' --coffee-file Create a coffeescript migration file.'", ")", ";", "grunt", ".", "log", ".", "writeln", "(", "' --migrations-dir The directory to use for migration files.'", ")", ";", "grunt", ".", "log", ".", "writeln", "(", "' Defaults to \"migrations\".'", ")", ";", "grunt", ".", "log", ".", "writeln", "(", "' --table Specify the table to track migrations in.'", ")", ";", "}" ]
Display command usage information. @param grunt Grunt object.
[ "Display", "command", "usage", "information", "." ]
41ffc849446f433298fe23dbccee771c1a55137f
https://github.com/building5/sails-db-migrate/blob/41ffc849446f433298fe23dbccee771c1a55137f/lib/gruntTasks.js#L73-L90
train
anvaka/ngraph.asyncforce
lib/layoutWorker.js
handleMessageFromMainThread
function handleMessageFromMainThread(message) { var kind = message.data.kind; var payload = message.data.payload; if (kind === messageKind.init) { graph = fromjson(payload.graph); var options = JSON.parse(payload.options); init(graph, options); } else if (kind === messageKind.step) { step(); } else if (kind === messageKind.pinNode) { pinNode(payload.nodeId, payload.isPinned); } else if (kind === messageKind.setNodePosition) { setNodePosition(payload.nodeId, payload.x, payload.y, payload.z); } // TODO: listen for graph changes from main thread and update layout here. }
javascript
function handleMessageFromMainThread(message) { var kind = message.data.kind; var payload = message.data.payload; if (kind === messageKind.init) { graph = fromjson(payload.graph); var options = JSON.parse(payload.options); init(graph, options); } else if (kind === messageKind.step) { step(); } else if (kind === messageKind.pinNode) { pinNode(payload.nodeId, payload.isPinned); } else if (kind === messageKind.setNodePosition) { setNodePosition(payload.nodeId, payload.x, payload.y, payload.z); } // TODO: listen for graph changes from main thread and update layout here. }
[ "function", "handleMessageFromMainThread", "(", "message", ")", "{", "var", "kind", "=", "message", ".", "data", ".", "kind", ";", "var", "payload", "=", "message", ".", "data", ".", "payload", ";", "if", "(", "kind", "===", "messageKind", ".", "init", ")", "{", "graph", "=", "fromjson", "(", "payload", ".", "graph", ")", ";", "var", "options", "=", "JSON", ".", "parse", "(", "payload", ".", "options", ")", ";", "init", "(", "graph", ",", "options", ")", ";", "}", "else", "if", "(", "kind", "===", "messageKind", ".", "step", ")", "{", "step", "(", ")", ";", "}", "else", "if", "(", "kind", "===", "messageKind", ".", "pinNode", ")", "{", "pinNode", "(", "payload", ".", "nodeId", ",", "payload", ".", "isPinned", ")", ";", "}", "else", "if", "(", "kind", "===", "messageKind", ".", "setNodePosition", ")", "{", "setNodePosition", "(", "payload", ".", "nodeId", ",", "payload", ".", "x", ",", "payload", ".", "y", ",", "payload", ".", "z", ")", ";", "}", "}" ]
public API is over. Below are private methods only.
[ "public", "API", "is", "over", ".", "Below", "are", "private", "methods", "only", "." ]
98cc8f87074f61d36215b672f0b31855b4deca4a
https://github.com/anvaka/ngraph.asyncforce/blob/98cc8f87074f61d36215b672f0b31855b4deca4a/lib/layoutWorker.js#L26-L43
train
rintoj/statex
dist/core/decorators.js
bindData
function bindData(target, key, selector) { return state_1.State.select(selector).subscribe(function (args) { if (typeof target.setState === 'function') { var state = {}; state[key] = args; target.setState(state); } if (typeof target[key] === 'function') return target[key].call(target, args); target[key] = args; }); }
javascript
function bindData(target, key, selector) { return state_1.State.select(selector).subscribe(function (args) { if (typeof target.setState === 'function') { var state = {}; state[key] = args; target.setState(state); } if (typeof target[key] === 'function') return target[key].call(target, args); target[key] = args; }); }
[ "function", "bindData", "(", "target", ",", "key", ",", "selector", ")", "{", "return", "state_1", ".", "State", ".", "select", "(", "selector", ")", ".", "subscribe", "(", "function", "(", "args", ")", "{", "if", "(", "typeof", "target", ".", "setState", "===", "'function'", ")", "{", "var", "state", "=", "{", "}", ";", "state", "[", "key", "]", "=", "args", ";", "target", ".", "setState", "(", "state", ")", ";", "}", "if", "(", "typeof", "target", "[", "key", "]", "===", "'function'", ")", "return", "target", "[", "key", "]", ".", "call", "(", "target", ",", "args", ")", ";", "target", "[", "key", "]", "=", "args", ";", "}", ")", ";", "}" ]
Bind data for give key and target using a selector function @param {any} target @param {any} key @param {any} selectorFunc
[ "Bind", "data", "for", "give", "key", "and", "target", "using", "a", "selector", "function" ]
19d2a321587c67ee6ff406251ea3d6b3eeaa3418
https://github.com/rintoj/statex/blob/19d2a321587c67ee6ff406251ea3d6b3eeaa3418/dist/core/decorators.js#L13-L24
train
rintoj/statex
dist/core/decorators.js
action
function action(targetAction) { return function (target, propertyKey, descriptor) { if (targetAction == undefined) { var metadata = Reflect.getMetadata('design:paramtypes', target, propertyKey); if (metadata == undefined || metadata.length < 2) throw new Error('@action() must be applied to a function with two arguments. ' + 'eg: reducer(state: State, action: SubclassOfAction): State { }'); targetAction = metadata[1]; } var statexActions = {}; if (Reflect.hasMetadata(constance_1.STATEX_ACTION_KEY, target)) { statexActions = Reflect.getMetadata(constance_1.STATEX_ACTION_KEY, target); } statexActions[propertyKey] = targetAction; Reflect.defineMetadata(constance_1.STATEX_ACTION_KEY, statexActions, target); return { value: function (state, payload) { return descriptor.value.call(this, state, payload); } }; }; }
javascript
function action(targetAction) { return function (target, propertyKey, descriptor) { if (targetAction == undefined) { var metadata = Reflect.getMetadata('design:paramtypes', target, propertyKey); if (metadata == undefined || metadata.length < 2) throw new Error('@action() must be applied to a function with two arguments. ' + 'eg: reducer(state: State, action: SubclassOfAction): State { }'); targetAction = metadata[1]; } var statexActions = {}; if (Reflect.hasMetadata(constance_1.STATEX_ACTION_KEY, target)) { statexActions = Reflect.getMetadata(constance_1.STATEX_ACTION_KEY, target); } statexActions[propertyKey] = targetAction; Reflect.defineMetadata(constance_1.STATEX_ACTION_KEY, statexActions, target); return { value: function (state, payload) { return descriptor.value.call(this, state, payload); } }; }; }
[ "function", "action", "(", "targetAction", ")", "{", "return", "function", "(", "target", ",", "propertyKey", ",", "descriptor", ")", "{", "if", "(", "targetAction", "==", "undefined", ")", "{", "var", "metadata", "=", "Reflect", ".", "getMetadata", "(", "'design:paramtypes'", ",", "target", ",", "propertyKey", ")", ";", "if", "(", "metadata", "==", "undefined", "||", "metadata", ".", "length", "<", "2", ")", "throw", "new", "Error", "(", "'@action() must be applied to a function with two arguments. '", "+", "'eg: reducer(state: State, action: SubclassOfAction): State { }'", ")", ";", "targetAction", "=", "metadata", "[", "1", "]", ";", "}", "var", "statexActions", "=", "{", "}", ";", "if", "(", "Reflect", ".", "hasMetadata", "(", "constance_1", ".", "STATEX_ACTION_KEY", ",", "target", ")", ")", "{", "statexActions", "=", "Reflect", ".", "getMetadata", "(", "constance_1", ".", "STATEX_ACTION_KEY", ",", "target", ")", ";", "}", "statexActions", "[", "propertyKey", "]", "=", "targetAction", ";", "Reflect", ".", "defineMetadata", "(", "constance_1", ".", "STATEX_ACTION_KEY", ",", "statexActions", ",", "target", ")", ";", "return", "{", "value", ":", "function", "(", "state", ",", "payload", ")", "{", "return", "descriptor", ".", "value", ".", "call", "(", "this", ",", "state", ",", "payload", ")", ";", "}", "}", ";", "}", ";", "}" ]
Binds action to a function @example class TodoStore { @action addTodo(state: State, action: AddTodoAction): State { // return modified state } } @export @param {*} target @param {string} propertyKey @param {PropertyDescriptor} descriptor @returns
[ "Binds", "action", "to", "a", "function" ]
19d2a321587c67ee6ff406251ea3d6b3eeaa3418
https://github.com/rintoj/statex/blob/19d2a321587c67ee6ff406251ea3d6b3eeaa3418/dist/core/decorators.js#L44-L65
train
rintoj/statex
dist/core/decorators.js
subscribe
function subscribe(propsClass) { var _this = this; var dataBindings = Reflect.getMetadata(constance_1.STATEX_DATA_BINDINGS_KEY, propsClass || this); if (dataBindings != undefined) { var selectors_1 = dataBindings.selectors || {}; dataBindings.subscriptions = (dataBindings.subscriptions || []).concat(Object.keys(selectors_1).map(function (key) { return ({ target: _this, subscription: bindData(_this, key, selectors_1[key]) }); })); Reflect.defineMetadata(constance_1.STATEX_DATA_BINDINGS_KEY, dataBindings, this); } }
javascript
function subscribe(propsClass) { var _this = this; var dataBindings = Reflect.getMetadata(constance_1.STATEX_DATA_BINDINGS_KEY, propsClass || this); if (dataBindings != undefined) { var selectors_1 = dataBindings.selectors || {}; dataBindings.subscriptions = (dataBindings.subscriptions || []).concat(Object.keys(selectors_1).map(function (key) { return ({ target: _this, subscription: bindData(_this, key, selectors_1[key]) }); })); Reflect.defineMetadata(constance_1.STATEX_DATA_BINDINGS_KEY, dataBindings, this); } }
[ "function", "subscribe", "(", "propsClass", ")", "{", "var", "_this", "=", "this", ";", "var", "dataBindings", "=", "Reflect", ".", "getMetadata", "(", "constance_1", ".", "STATEX_DATA_BINDINGS_KEY", ",", "propsClass", "||", "this", ")", ";", "if", "(", "dataBindings", "!=", "undefined", ")", "{", "var", "selectors_1", "=", "dataBindings", ".", "selectors", "||", "{", "}", ";", "dataBindings", ".", "subscriptions", "=", "(", "dataBindings", ".", "subscriptions", "||", "[", "]", ")", ".", "concat", "(", "Object", ".", "keys", "(", "selectors_1", ")", ".", "map", "(", "function", "(", "key", ")", "{", "return", "(", "{", "target", ":", "_this", ",", "subscription", ":", "bindData", "(", "_this", ",", "key", ",", "selectors_1", "[", "key", "]", ")", "}", ")", ";", "}", ")", ")", ";", "Reflect", ".", "defineMetadata", "(", "constance_1", ".", "STATEX_DATA_BINDINGS_KEY", ",", "dataBindings", ",", "this", ")", ";", "}", "}" ]
Subscribe to the state events and map it to properties @export
[ "Subscribe", "to", "the", "state", "events", "and", "map", "it", "to", "properties" ]
19d2a321587c67ee6ff406251ea3d6b3eeaa3418
https://github.com/rintoj/statex/blob/19d2a321587c67ee6ff406251ea3d6b3eeaa3418/dist/core/decorators.js#L99-L110
train
rintoj/statex
dist/core/decorators.js
unsubscribe
function unsubscribe() { var _this = this; var dataBindings = Reflect.getMetadata(constance_1.STATEX_DATA_BINDINGS_KEY, this); if (dataBindings != undefined) { var subscriptions = dataBindings.subscriptions || []; subscriptions.forEach(function (item) { return item.target === _this && item.subscription != undefined && item.subscription.unsubscribe(); }); dataBindings.subscriptions = subscriptions.filter(function (item) { return item.target !== _this; }); Reflect.defineMetadata(constance_1.STATEX_DATA_BINDINGS_KEY, dataBindings, this); } }
javascript
function unsubscribe() { var _this = this; var dataBindings = Reflect.getMetadata(constance_1.STATEX_DATA_BINDINGS_KEY, this); if (dataBindings != undefined) { var subscriptions = dataBindings.subscriptions || []; subscriptions.forEach(function (item) { return item.target === _this && item.subscription != undefined && item.subscription.unsubscribe(); }); dataBindings.subscriptions = subscriptions.filter(function (item) { return item.target !== _this; }); Reflect.defineMetadata(constance_1.STATEX_DATA_BINDINGS_KEY, dataBindings, this); } }
[ "function", "unsubscribe", "(", ")", "{", "var", "_this", "=", "this", ";", "var", "dataBindings", "=", "Reflect", ".", "getMetadata", "(", "constance_1", ".", "STATEX_DATA_BINDINGS_KEY", ",", "this", ")", ";", "if", "(", "dataBindings", "!=", "undefined", ")", "{", "var", "subscriptions", "=", "dataBindings", ".", "subscriptions", "||", "[", "]", ";", "subscriptions", ".", "forEach", "(", "function", "(", "item", ")", "{", "return", "item", ".", "target", "===", "_this", "&&", "item", ".", "subscription", "!=", "undefined", "&&", "item", ".", "subscription", ".", "unsubscribe", "(", ")", ";", "}", ")", ";", "dataBindings", ".", "subscriptions", "=", "subscriptions", ".", "filter", "(", "function", "(", "item", ")", "{", "return", "item", ".", "target", "!==", "_this", ";", "}", ")", ";", "Reflect", ".", "defineMetadata", "(", "constance_1", ".", "STATEX_DATA_BINDINGS_KEY", ",", "dataBindings", ",", "this", ")", ";", "}", "}" ]
Unsubscribe from the state changes @export
[ "Unsubscribe", "from", "the", "state", "changes" ]
19d2a321587c67ee6ff406251ea3d6b3eeaa3418
https://github.com/rintoj/statex/blob/19d2a321587c67ee6ff406251ea3d6b3eeaa3418/dist/core/decorators.js#L117-L126
train
leifoolsen/mdl-ext
demo/scripts/dialog-polyfill.js
function() { if (!this.openAsModal_) { return; } this.openAsModal_ = false; this.dialog_.style.zIndex = ''; // This won't match the native <dialog> exactly because if the user set top on a centered // polyfill dialog, that top gets thrown away when the dialog is closed. Not sure it's // possible to polyfill this perfectly. if (this.replacedStyleTop_) { this.dialog_.style.top = ''; this.replacedStyleTop_ = false; } // Clear the backdrop and remove from the manager. this.backdrop_.parentNode && this.backdrop_.parentNode.removeChild(this.backdrop_); dialogPolyfill.dm.removeDialog(this); }
javascript
function() { if (!this.openAsModal_) { return; } this.openAsModal_ = false; this.dialog_.style.zIndex = ''; // This won't match the native <dialog> exactly because if the user set top on a centered // polyfill dialog, that top gets thrown away when the dialog is closed. Not sure it's // possible to polyfill this perfectly. if (this.replacedStyleTop_) { this.dialog_.style.top = ''; this.replacedStyleTop_ = false; } // Clear the backdrop and remove from the manager. this.backdrop_.parentNode && this.backdrop_.parentNode.removeChild(this.backdrop_); dialogPolyfill.dm.removeDialog(this); }
[ "function", "(", ")", "{", "if", "(", "!", "this", ".", "openAsModal_", ")", "{", "return", ";", "}", "this", ".", "openAsModal_", "=", "false", ";", "this", ".", "dialog_", ".", "style", ".", "zIndex", "=", "''", ";", "if", "(", "this", ".", "replacedStyleTop_", ")", "{", "this", ".", "dialog_", ".", "style", ".", "top", "=", "''", ";", "this", ".", "replacedStyleTop_", "=", "false", ";", "}", "this", ".", "backdrop_", ".", "parentNode", "&&", "this", ".", "backdrop_", ".", "parentNode", ".", "removeChild", "(", "this", ".", "backdrop_", ")", ";", "dialogPolyfill", ".", "dm", ".", "removeDialog", "(", "this", ")", ";", "}" ]
Remove this dialog from the modal top layer, leaving it as a non-modal.
[ "Remove", "this", "dialog", "from", "the", "modal", "top", "layer", "leaving", "it", "as", "a", "non", "-", "modal", "." ]
a22a7be564ff81a41e94eb14bda6cd36401dc962
https://github.com/leifoolsen/mdl-ext/blob/a22a7be564ff81a41e94eb14bda6cd36401dc962/demo/scripts/dialog-polyfill.js#L161-L177
train
leifoolsen/mdl-ext
demo/scripts/dialog-polyfill.js
function() { // Find element with `autofocus` attribute, or fall back to the first form/tabindex control. var target = this.dialog_.querySelector('[autofocus]:not([disabled])'); if (!target && this.dialog_.tabIndex >= 0) { target = this.dialog_; } if (!target) { // Note that this is 'any focusable area'. This list is probably not exhaustive, but the // alternative involves stepping through and trying to focus everything. var opts = ['button', 'input', 'keygen', 'select', 'textarea']; var query = opts.map(function(el) { return el + ':not([disabled])'; }); // TODO(samthor): tabindex values that are not numeric are not focusable. query.push('[tabindex]:not([disabled]):not([tabindex=""])'); // tabindex != "", not disabled target = this.dialog_.querySelector(query.join(', ')); } safeBlur(document.activeElement); target && target.focus(); }
javascript
function() { // Find element with `autofocus` attribute, or fall back to the first form/tabindex control. var target = this.dialog_.querySelector('[autofocus]:not([disabled])'); if (!target && this.dialog_.tabIndex >= 0) { target = this.dialog_; } if (!target) { // Note that this is 'any focusable area'. This list is probably not exhaustive, but the // alternative involves stepping through and trying to focus everything. var opts = ['button', 'input', 'keygen', 'select', 'textarea']; var query = opts.map(function(el) { return el + ':not([disabled])'; }); // TODO(samthor): tabindex values that are not numeric are not focusable. query.push('[tabindex]:not([disabled]):not([tabindex=""])'); // tabindex != "", not disabled target = this.dialog_.querySelector(query.join(', ')); } safeBlur(document.activeElement); target && target.focus(); }
[ "function", "(", ")", "{", "var", "target", "=", "this", ".", "dialog_", ".", "querySelector", "(", "'[autofocus]:not([disabled])'", ")", ";", "if", "(", "!", "target", "&&", "this", ".", "dialog_", ".", "tabIndex", ">=", "0", ")", "{", "target", "=", "this", ".", "dialog_", ";", "}", "if", "(", "!", "target", ")", "{", "var", "opts", "=", "[", "'button'", ",", "'input'", ",", "'keygen'", ",", "'select'", ",", "'textarea'", "]", ";", "var", "query", "=", "opts", ".", "map", "(", "function", "(", "el", ")", "{", "return", "el", "+", "':not([disabled])'", ";", "}", ")", ";", "query", ".", "push", "(", "'[tabindex]:not([disabled]):not([tabindex=\"\"])'", ")", ";", "target", "=", "this", ".", "dialog_", ".", "querySelector", "(", "query", ".", "join", "(", "', '", ")", ")", ";", "}", "safeBlur", "(", "document", ".", "activeElement", ")", ";", "target", "&&", "target", ".", "focus", "(", ")", ";", "}" ]
Focuses on the first focusable element within the dialog. This will always blur the current focus, even if nothing within the dialog is found.
[ "Focuses", "on", "the", "first", "focusable", "element", "within", "the", "dialog", ".", "This", "will", "always", "blur", "the", "current", "focus", "even", "if", "nothing", "within", "the", "dialog", "is", "found", "." ]
a22a7be564ff81a41e94eb14bda6cd36401dc962
https://github.com/leifoolsen/mdl-ext/blob/a22a7be564ff81a41e94eb14bda6cd36401dc962/demo/scripts/dialog-polyfill.js#L223-L242
train
leifoolsen/mdl-ext
demo/scripts/dialog-polyfill.js
function(opt_returnValue) { if (!this.dialog_.hasAttribute('open')) { throw new Error('Failed to execute \'close\' on dialog: The element does not have an \'open\' attribute, and therefore cannot be closed.'); } this.setOpen(false); // Leave returnValue untouched in case it was set directly on the element if (opt_returnValue !== undefined) { this.dialog_.returnValue = opt_returnValue; } // Triggering "close" event for any attached listeners on the <dialog>. var closeEvent = new supportCustomEvent('close', { bubbles: false, cancelable: false }); this.dialog_.dispatchEvent(closeEvent); }
javascript
function(opt_returnValue) { if (!this.dialog_.hasAttribute('open')) { throw new Error('Failed to execute \'close\' on dialog: The element does not have an \'open\' attribute, and therefore cannot be closed.'); } this.setOpen(false); // Leave returnValue untouched in case it was set directly on the element if (opt_returnValue !== undefined) { this.dialog_.returnValue = opt_returnValue; } // Triggering "close" event for any attached listeners on the <dialog>. var closeEvent = new supportCustomEvent('close', { bubbles: false, cancelable: false }); this.dialog_.dispatchEvent(closeEvent); }
[ "function", "(", "opt_returnValue", ")", "{", "if", "(", "!", "this", ".", "dialog_", ".", "hasAttribute", "(", "'open'", ")", ")", "{", "throw", "new", "Error", "(", "'Failed to execute \\'close\\' on dialog: The element does not have an \\'open\\' attribute, and therefore cannot be closed.'", ")", ";", "}", "\\'", "\\'", "\\'", "\\'", "}" ]
Closes this HTMLDialogElement. This is optional vs clearing the open attribute, however this fires a 'close' event. @param {string=} opt_returnValue to use as the returnValue
[ "Closes", "this", "HTMLDialogElement", ".", "This", "is", "optional", "vs", "clearing", "the", "open", "attribute", "however", "this", "fires", "a", "close", "event", "." ]
a22a7be564ff81a41e94eb14bda6cd36401dc962
https://github.com/leifoolsen/mdl-ext/blob/a22a7be564ff81a41e94eb14bda6cd36401dc962/demo/scripts/dialog-polyfill.js#L312-L329
train
rintoj/statex
dist/core/store.js
store
function store() { return function (storeClass) { // save a reference to the original constructor var original = storeClass; // a utility function to generate instances of a class function construct(constructor, args) { var dynamicClass = function () { return new (constructor.bind.apply(constructor, [void 0].concat(args)))(); }; dynamicClass.prototype = constructor.prototype; return new dynamicClass(); } // the new constructor behavior var overriddenConstructor = function Store() { var _this = this; var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } if (!Reflect.hasMetadata(constance_1.STATEX_ACTION_KEY, this)) return; var statexActions = Reflect.getMetadata(constance_1.STATEX_ACTION_KEY, this); Object.keys(statexActions).forEach(function (name) { return new statexActions[name]().subscribe(_this[name], _this); }); return construct(original, args); }; // copy prototype so instanceof operator still works overriddenConstructor.prototype = original.prototype; // create singleton instance var instance = new overriddenConstructor(); // return new constructor (will override original) return instance && overriddenConstructor; }; }
javascript
function store() { return function (storeClass) { // save a reference to the original constructor var original = storeClass; // a utility function to generate instances of a class function construct(constructor, args) { var dynamicClass = function () { return new (constructor.bind.apply(constructor, [void 0].concat(args)))(); }; dynamicClass.prototype = constructor.prototype; return new dynamicClass(); } // the new constructor behavior var overriddenConstructor = function Store() { var _this = this; var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } if (!Reflect.hasMetadata(constance_1.STATEX_ACTION_KEY, this)) return; var statexActions = Reflect.getMetadata(constance_1.STATEX_ACTION_KEY, this); Object.keys(statexActions).forEach(function (name) { return new statexActions[name]().subscribe(_this[name], _this); }); return construct(original, args); }; // copy prototype so instanceof operator still works overriddenConstructor.prototype = original.prototype; // create singleton instance var instance = new overriddenConstructor(); // return new constructor (will override original) return instance && overriddenConstructor; }; }
[ "function", "store", "(", ")", "{", "return", "function", "(", "storeClass", ")", "{", "var", "original", "=", "storeClass", ";", "function", "construct", "(", "constructor", ",", "args", ")", "{", "var", "dynamicClass", "=", "function", "(", ")", "{", "return", "new", "(", "constructor", ".", "bind", ".", "apply", "(", "constructor", ",", "[", "void", "0", "]", ".", "concat", "(", "args", ")", ")", ")", "(", ")", ";", "}", ";", "dynamicClass", ".", "prototype", "=", "constructor", ".", "prototype", ";", "return", "new", "dynamicClass", "(", ")", ";", "}", "var", "overriddenConstructor", "=", "function", "Store", "(", ")", "{", "var", "_this", "=", "this", ";", "var", "args", "=", "[", "]", ";", "for", "(", "var", "_i", "=", "0", ";", "_i", "<", "arguments", ".", "length", ";", "_i", "++", ")", "{", "args", "[", "_i", "]", "=", "arguments", "[", "_i", "]", ";", "}", "if", "(", "!", "Reflect", ".", "hasMetadata", "(", "constance_1", ".", "STATEX_ACTION_KEY", ",", "this", ")", ")", "return", ";", "var", "statexActions", "=", "Reflect", ".", "getMetadata", "(", "constance_1", ".", "STATEX_ACTION_KEY", ",", "this", ")", ";", "Object", ".", "keys", "(", "statexActions", ")", ".", "forEach", "(", "function", "(", "name", ")", "{", "return", "new", "statexActions", "[", "name", "]", "(", ")", ".", "subscribe", "(", "_this", "[", "name", "]", ",", "_this", ")", ";", "}", ")", ";", "return", "construct", "(", "original", ",", "args", ")", ";", "}", ";", "overriddenConstructor", ".", "prototype", "=", "original", ".", "prototype", ";", "var", "instance", "=", "new", "overriddenConstructor", "(", ")", ";", "return", "instance", "&&", "overriddenConstructor", ";", "}", ";", "}" ]
This decorator configure instance of a store @export @param {*} storeClass @returns
[ "This", "decorator", "configure", "instance", "of", "a", "store" ]
19d2a321587c67ee6ff406251ea3d6b3eeaa3418
https://github.com/rintoj/statex/blob/19d2a321587c67ee6ff406251ea3d6b3eeaa3418/dist/core/store.js#L11-L43
train
rintoj/statex
dist/core/store.js
Store
function Store() { var _this = this; var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } if (!Reflect.hasMetadata(constance_1.STATEX_ACTION_KEY, this)) return; var statexActions = Reflect.getMetadata(constance_1.STATEX_ACTION_KEY, this); Object.keys(statexActions).forEach(function (name) { return new statexActions[name]().subscribe(_this[name], _this); }); return construct(original, args); }
javascript
function Store() { var _this = this; var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } if (!Reflect.hasMetadata(constance_1.STATEX_ACTION_KEY, this)) return; var statexActions = Reflect.getMetadata(constance_1.STATEX_ACTION_KEY, this); Object.keys(statexActions).forEach(function (name) { return new statexActions[name]().subscribe(_this[name], _this); }); return construct(original, args); }
[ "function", "Store", "(", ")", "{", "var", "_this", "=", "this", ";", "var", "args", "=", "[", "]", ";", "for", "(", "var", "_i", "=", "0", ";", "_i", "<", "arguments", ".", "length", ";", "_i", "++", ")", "{", "args", "[", "_i", "]", "=", "arguments", "[", "_i", "]", ";", "}", "if", "(", "!", "Reflect", ".", "hasMetadata", "(", "constance_1", ".", "STATEX_ACTION_KEY", ",", "this", ")", ")", "return", ";", "var", "statexActions", "=", "Reflect", ".", "getMetadata", "(", "constance_1", ".", "STATEX_ACTION_KEY", ",", "this", ")", ";", "Object", ".", "keys", "(", "statexActions", ")", ".", "forEach", "(", "function", "(", "name", ")", "{", "return", "new", "statexActions", "[", "name", "]", "(", ")", ".", "subscribe", "(", "_this", "[", "name", "]", ",", "_this", ")", ";", "}", ")", ";", "return", "construct", "(", "original", ",", "args", ")", ";", "}" ]
the new constructor behavior
[ "the", "new", "constructor", "behavior" ]
19d2a321587c67ee6ff406251ea3d6b3eeaa3418
https://github.com/rintoj/statex/blob/19d2a321587c67ee6ff406251ea3d6b3eeaa3418/dist/core/store.js#L24-L35
train
rintoj/statex
dist/core/state.js
select
function select(state, selector) { if (state == undefined) return; if (selector == undefined) return state; try { return selector(state); } catch (error) { return undefined; } }
javascript
function select(state, selector) { if (state == undefined) return; if (selector == undefined) return state; try { return selector(state); } catch (error) { return undefined; } }
[ "function", "select", "(", "state", ",", "selector", ")", "{", "if", "(", "state", "==", "undefined", ")", "return", ";", "if", "(", "selector", "==", "undefined", ")", "return", "state", ";", "try", "{", "return", "selector", "(", "state", ")", ";", "}", "catch", "(", "error", ")", "{", "return", "undefined", ";", "}", "}" ]
Run selector function on the given state and return it's result. Return undefined if an error occurred @param {*} state @param {StateSelector} selector @returns The value return by the selector, undefined if an error occurred.
[ "Run", "selector", "function", "on", "the", "given", "state", "and", "return", "it", "s", "result", ".", "Return", "undefined", "if", "an", "error", "occurred" ]
19d2a321587c67ee6ff406251ea3d6b3eeaa3418
https://github.com/rintoj/statex/blob/19d2a321587c67ee6ff406251ea3d6b3eeaa3418/dist/core/state.js#L93-L104
train
bholloway/nginject-loader
index.js
loader
function loader(content, sourceMap) { /* jshint validthis:true */ // loader result is cacheable this.cacheable(); // path of the file being processed var filename = path.relative(this.options.context || process.cwd(), this.resourcePath).replace(/\\/g, '/'), options = loaderUtils.parseQuery(this.query), useMap = loader.sourceMap || options.sourceMap; // make sure the AST has the data from the original source map var pending = migrate.processSync(content, { filename : filename, sourceMap: useMap && (sourceMap || true), quoteChar: options.singleQuote ? '\'' : '"' }); // emit deprecation warning if ((pending.isChanged) && (options.deprecate)) { var text = ' ' + PACKAGE_NAME + ': @ngInject doctag is deprecated, use "ngInject" string directive instead'; this.emitWarning(text); } // emit errors if (pending.errors.length) { var text = pending.errors.map(indent).join('\n'); this.emitError(text); } // complete if (useMap) { this.callback(null, pending.content, pending.sourceMap); } else { return pending.content; } }
javascript
function loader(content, sourceMap) { /* jshint validthis:true */ // loader result is cacheable this.cacheable(); // path of the file being processed var filename = path.relative(this.options.context || process.cwd(), this.resourcePath).replace(/\\/g, '/'), options = loaderUtils.parseQuery(this.query), useMap = loader.sourceMap || options.sourceMap; // make sure the AST has the data from the original source map var pending = migrate.processSync(content, { filename : filename, sourceMap: useMap && (sourceMap || true), quoteChar: options.singleQuote ? '\'' : '"' }); // emit deprecation warning if ((pending.isChanged) && (options.deprecate)) { var text = ' ' + PACKAGE_NAME + ': @ngInject doctag is deprecated, use "ngInject" string directive instead'; this.emitWarning(text); } // emit errors if (pending.errors.length) { var text = pending.errors.map(indent).join('\n'); this.emitError(text); } // complete if (useMap) { this.callback(null, pending.content, pending.sourceMap); } else { return pending.content; } }
[ "function", "loader", "(", "content", ",", "sourceMap", ")", "{", "this", ".", "cacheable", "(", ")", ";", "var", "filename", "=", "path", ".", "relative", "(", "this", ".", "options", ".", "context", "||", "process", ".", "cwd", "(", ")", ",", "this", ".", "resourcePath", ")", ".", "replace", "(", "/", "\\\\", "/", "g", ",", "'/'", ")", ",", "options", "=", "loaderUtils", ".", "parseQuery", "(", "this", ".", "query", ")", ",", "useMap", "=", "loader", ".", "sourceMap", "||", "options", ".", "sourceMap", ";", "var", "pending", "=", "migrate", ".", "processSync", "(", "content", ",", "{", "filename", ":", "filename", ",", "sourceMap", ":", "useMap", "&&", "(", "sourceMap", "||", "true", ")", ",", "quoteChar", ":", "options", ".", "singleQuote", "?", "'\\''", ":", "\\'", "}", ")", ";", "'\"'", "if", "(", "(", "pending", ".", "isChanged", ")", "&&", "(", "options", ".", "deprecate", ")", ")", "{", "var", "text", "=", "' '", "+", "PACKAGE_NAME", "+", "': @ngInject doctag is deprecated, use \"ngInject\" string directive instead'", ";", "this", ".", "emitWarning", "(", "text", ")", ";", "}", "if", "(", "pending", ".", "errors", ".", "length", ")", "{", "var", "text", "=", "pending", ".", "errors", ".", "map", "(", "indent", ")", ".", "join", "(", "'\\n'", ")", ";", "\\n", "}", "}" ]
Webpack loader where explicit @ngInject comment creates pre-minification $inject property. @param {string} content JS content @param {object} sourceMap The source-map @returns {string|String}
[ "Webpack", "loader", "where", "explicit" ]
2ca938d453fb487c05fcca87f3b9c4ad8ae1ec7d
https://github.com/bholloway/nginject-loader/blob/2ca938d453fb487c05fcca87f3b9c4ad8ae1ec7d/index.js#L16-L52
train
aurbano/smart-area
dist/smart-area.js
highlightText
function highlightText(){ var text = $scope.areaData, html = htmlEncode(text); if(typeof($scope.areaConfig.autocomplete) === 'undefined' || $scope.areaConfig.autocomplete.length === 0){ return; } $scope.areaConfig.autocomplete.forEach(function(autoList){ for(var i=0; i<autoList.words.length; i++){ if(typeof(autoList.words[i]) === "string"){ html = html.replace(new RegExp("([^\\w]|\\b)("+autoList.words[i]+")([^\\w]|\\b)", 'g'), '$1<span class="'+autoList.cssClass+'">$2</span>$3'); }else{ html = html.replace(autoList.words[i], function(match){ return '<span class="'+autoList.cssClass+'">'+match+'</span>'; }); } } }); // Add to the fakeArea $scope.fakeArea = $sce.trustAsHtml(html); }
javascript
function highlightText(){ var text = $scope.areaData, html = htmlEncode(text); if(typeof($scope.areaConfig.autocomplete) === 'undefined' || $scope.areaConfig.autocomplete.length === 0){ return; } $scope.areaConfig.autocomplete.forEach(function(autoList){ for(var i=0; i<autoList.words.length; i++){ if(typeof(autoList.words[i]) === "string"){ html = html.replace(new RegExp("([^\\w]|\\b)("+autoList.words[i]+")([^\\w]|\\b)", 'g'), '$1<span class="'+autoList.cssClass+'">$2</span>$3'); }else{ html = html.replace(autoList.words[i], function(match){ return '<span class="'+autoList.cssClass+'">'+match+'</span>'; }); } } }); // Add to the fakeArea $scope.fakeArea = $sce.trustAsHtml(html); }
[ "function", "highlightText", "(", ")", "{", "var", "text", "=", "$scope", ".", "areaData", ",", "html", "=", "htmlEncode", "(", "text", ")", ";", "if", "(", "typeof", "(", "$scope", ".", "areaConfig", ".", "autocomplete", ")", "===", "'undefined'", "||", "$scope", ".", "areaConfig", ".", "autocomplete", ".", "length", "===", "0", ")", "{", "return", ";", "}", "$scope", ".", "areaConfig", ".", "autocomplete", ".", "forEach", "(", "function", "(", "autoList", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "autoList", ".", "words", ".", "length", ";", "i", "++", ")", "{", "if", "(", "typeof", "(", "autoList", ".", "words", "[", "i", "]", ")", "===", "\"string\"", ")", "{", "html", "=", "html", ".", "replace", "(", "new", "RegExp", "(", "\"([^\\\\w]|\\\\b)(\"", "+", "\\\\", "+", "\\\\", ",", "autoList", ".", "words", "[", "i", "]", ")", ",", "\")([^\\\\w]|\\\\b)\"", ")", ";", "}", "else", "\\\\", "}", "}", ")", ";", "\\\\", "}" ]
Perform the "syntax" highlighting of autocomplete words that have a cssClass specified.
[ "Perform", "the", "syntax", "highlighting", "of", "autocomplete", "words", "that", "have", "a", "cssClass", "specified", "." ]
372b17f9c4c5541591f181ddde4d0e4475c85f3f
https://github.com/aurbano/smart-area/blob/372b17f9c4c5541591f181ddde4d0e4475c85f3f/dist/smart-area.js#L301-L322
train