id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
20,000
octoblu/meshblu
docs/vendor/mixitup/mixitup.js
function(isResetting, operation) { var self = this, startOrder = isResetting ? operation.newOrder : operation.startOrder, newOrder = isResetting ? operation.startOrder : operation.newOrder, nextSibling = startOrder.length ? startOrder[startOrder.length - 1].dom.el.nextElementSibling : null, frag = window.document.createDocumentFragment(), whitespace = null, target = null, el = null, i = -1; self.callActions('beforePrintSort', arguments); // Empty the container for (i = 0; target = startOrder[i]; i++) { el = target.dom.el; if (el.style.position === 'absolute') continue; h.removeWhitespace(el.previousSibling); el.parentElement.removeChild(el); } whitespace = nextSibling ? nextSibling.previousSibling : self.dom.parent.lastChild; if (whitespace && whitespace.nodeName === '#text') { h.removeWhitespace(whitespace); } for (i = 0; target = newOrder[i]; i++) { // Add targets into a document fragment el = target.dom.el; if (h.isElement(frag.lastChild)) { frag.appendChild(window.document.createTextNode(' ')); } frag.appendChild(el); } // Insert the document fragment into the container // before any other non-target elements if (self.dom.parent.firstChild && self.dom.parent.firstChild !== nextSibling) { frag.insertBefore(window.document.createTextNode(' '), frag.childNodes[0]); } if (nextSibling) { frag.appendChild(window.document.createTextNode(' ')); self.dom.parent.insertBefore(frag, nextSibling); } else { self.dom.parent.appendChild(frag); } self.callActions('afterPrintSort', arguments); }
javascript
function(isResetting, operation) { var self = this, startOrder = isResetting ? operation.newOrder : operation.startOrder, newOrder = isResetting ? operation.startOrder : operation.newOrder, nextSibling = startOrder.length ? startOrder[startOrder.length - 1].dom.el.nextElementSibling : null, frag = window.document.createDocumentFragment(), whitespace = null, target = null, el = null, i = -1; self.callActions('beforePrintSort', arguments); // Empty the container for (i = 0; target = startOrder[i]; i++) { el = target.dom.el; if (el.style.position === 'absolute') continue; h.removeWhitespace(el.previousSibling); el.parentElement.removeChild(el); } whitespace = nextSibling ? nextSibling.previousSibling : self.dom.parent.lastChild; if (whitespace && whitespace.nodeName === '#text') { h.removeWhitespace(whitespace); } for (i = 0; target = newOrder[i]; i++) { // Add targets into a document fragment el = target.dom.el; if (h.isElement(frag.lastChild)) { frag.appendChild(window.document.createTextNode(' ')); } frag.appendChild(el); } // Insert the document fragment into the container // before any other non-target elements if (self.dom.parent.firstChild && self.dom.parent.firstChild !== nextSibling) { frag.insertBefore(window.document.createTextNode(' '), frag.childNodes[0]); } if (nextSibling) { frag.appendChild(window.document.createTextNode(' ')); self.dom.parent.insertBefore(frag, nextSibling); } else { self.dom.parent.appendChild(frag); } self.callActions('afterPrintSort', arguments); }
[ "function", "(", "isResetting", ",", "operation", ")", "{", "var", "self", "=", "this", ",", "startOrder", "=", "isResetting", "?", "operation", ".", "newOrder", ":", "operation", ".", "startOrder", ",", "newOrder", "=", "isResetting", "?", "operation", ".", "startOrder", ":", "operation", ".", "newOrder", ",", "nextSibling", "=", "startOrder", ".", "length", "?", "startOrder", "[", "startOrder", ".", "length", "-", "1", "]", ".", "dom", ".", "el", ".", "nextElementSibling", ":", "null", ",", "frag", "=", "window", ".", "document", ".", "createDocumentFragment", "(", ")", ",", "whitespace", "=", "null", ",", "target", "=", "null", ",", "el", "=", "null", ",", "i", "=", "-", "1", ";", "self", ".", "callActions", "(", "'beforePrintSort'", ",", "arguments", ")", ";", "// Empty the container", "for", "(", "i", "=", "0", ";", "target", "=", "startOrder", "[", "i", "]", ";", "i", "++", ")", "{", "el", "=", "target", ".", "dom", ".", "el", ";", "if", "(", "el", ".", "style", ".", "position", "===", "'absolute'", ")", "continue", ";", "h", ".", "removeWhitespace", "(", "el", ".", "previousSibling", ")", ";", "el", ".", "parentElement", ".", "removeChild", "(", "el", ")", ";", "}", "whitespace", "=", "nextSibling", "?", "nextSibling", ".", "previousSibling", ":", "self", ".", "dom", ".", "parent", ".", "lastChild", ";", "if", "(", "whitespace", "&&", "whitespace", ".", "nodeName", "===", "'#text'", ")", "{", "h", ".", "removeWhitespace", "(", "whitespace", ")", ";", "}", "for", "(", "i", "=", "0", ";", "target", "=", "newOrder", "[", "i", "]", ";", "i", "++", ")", "{", "// Add targets into a document fragment", "el", "=", "target", ".", "dom", ".", "el", ";", "if", "(", "h", ".", "isElement", "(", "frag", ".", "lastChild", ")", ")", "{", "frag", ".", "appendChild", "(", "window", ".", "document", ".", "createTextNode", "(", "' '", ")", ")", ";", "}", "frag", ".", "appendChild", "(", "el", ")", ";", "}", "// Insert the document fragment into the container", "// before any other non-target elements", "if", "(", "self", ".", "dom", ".", "parent", ".", "firstChild", "&&", "self", ".", "dom", ".", "parent", ".", "firstChild", "!==", "nextSibling", ")", "{", "frag", ".", "insertBefore", "(", "window", ".", "document", ".", "createTextNode", "(", "' '", ")", ",", "frag", ".", "childNodes", "[", "0", "]", ")", ";", "}", "if", "(", "nextSibling", ")", "{", "frag", ".", "appendChild", "(", "window", ".", "document", ".", "createTextNode", "(", "' '", ")", ")", ";", "self", ".", "dom", ".", "parent", ".", "insertBefore", "(", "frag", ",", "nextSibling", ")", ";", "}", "else", "{", "self", ".", "dom", ".", "parent", ".", "appendChild", "(", "frag", ")", ";", "}", "self", ".", "callActions", "(", "'afterPrintSort'", ",", "arguments", ")", ";", "}" ]
Inserts elements into the DOM in the appropriate order using a document fragment for minimal DOM thrashing @private @instance @since 2.0.0 @param {boolean} isResetting @param {Operation} operation @return {void}
[ "Inserts", "elements", "into", "the", "DOM", "in", "the", "appropriate", "order", "using", "a", "document", "fragment", "for", "minimal", "DOM", "thrashing" ]
4e7a5a0460b4eb097dfe9ff2db15853eccc779d7
https://github.com/octoblu/meshblu/blob/4e7a5a0460b4eb097dfe9ff2db15853eccc779d7/docs/vendor/mixitup/mixitup.js#L5842-L5901
20,001
octoblu/meshblu
docs/vendor/mixitup/mixitup.js
function() { var self = this, transformName = '', effectsIn = self.config.animation.effectsIn || self.config.animation.effects, effectsOut = self.config.animation.effectsOut || self.config.animation.effects; self.callActions('beforeParseEffects', arguments); self.effectsIn = new mixitup.StyleData(); self.effectsOut = new mixitup.StyleData(); self.transformIn = []; self.transformOut = []; self.effectsIn.opacity = self.effectsOut.opacity = 1; self.parseEffect('fade', effectsIn, self.effectsIn, self.transformIn); self.parseEffect('fade', effectsOut, self.effectsOut, self.transformOut, true); for (transformName in mixitup.transformDefaults) { if (!(mixitup.transformDefaults[transformName] instanceof mixitup.TransformData)) { continue; } self.parseEffect(transformName, effectsIn, self.effectsIn, self.transformIn); self.parseEffect(transformName, effectsOut, self.effectsOut, self.transformOut, true); } self.parseEffect('stagger', effectsIn, self.effectsIn, self.transformIn); self.parseEffect('stagger', effectsOut, self.effectsOut, self.transformOut, true); self.callActions('afterParseEffects', arguments); }
javascript
function() { var self = this, transformName = '', effectsIn = self.config.animation.effectsIn || self.config.animation.effects, effectsOut = self.config.animation.effectsOut || self.config.animation.effects; self.callActions('beforeParseEffects', arguments); self.effectsIn = new mixitup.StyleData(); self.effectsOut = new mixitup.StyleData(); self.transformIn = []; self.transformOut = []; self.effectsIn.opacity = self.effectsOut.opacity = 1; self.parseEffect('fade', effectsIn, self.effectsIn, self.transformIn); self.parseEffect('fade', effectsOut, self.effectsOut, self.transformOut, true); for (transformName in mixitup.transformDefaults) { if (!(mixitup.transformDefaults[transformName] instanceof mixitup.TransformData)) { continue; } self.parseEffect(transformName, effectsIn, self.effectsIn, self.transformIn); self.parseEffect(transformName, effectsOut, self.effectsOut, self.transformOut, true); } self.parseEffect('stagger', effectsIn, self.effectsIn, self.transformIn); self.parseEffect('stagger', effectsOut, self.effectsOut, self.transformOut, true); self.callActions('afterParseEffects', arguments); }
[ "function", "(", ")", "{", "var", "self", "=", "this", ",", "transformName", "=", "''", ",", "effectsIn", "=", "self", ".", "config", ".", "animation", ".", "effectsIn", "||", "self", ".", "config", ".", "animation", ".", "effects", ",", "effectsOut", "=", "self", ".", "config", ".", "animation", ".", "effectsOut", "||", "self", ".", "config", ".", "animation", ".", "effects", ";", "self", ".", "callActions", "(", "'beforeParseEffects'", ",", "arguments", ")", ";", "self", ".", "effectsIn", "=", "new", "mixitup", ".", "StyleData", "(", ")", ";", "self", ".", "effectsOut", "=", "new", "mixitup", ".", "StyleData", "(", ")", ";", "self", ".", "transformIn", "=", "[", "]", ";", "self", ".", "transformOut", "=", "[", "]", ";", "self", ".", "effectsIn", ".", "opacity", "=", "self", ".", "effectsOut", ".", "opacity", "=", "1", ";", "self", ".", "parseEffect", "(", "'fade'", ",", "effectsIn", ",", "self", ".", "effectsIn", ",", "self", ".", "transformIn", ")", ";", "self", ".", "parseEffect", "(", "'fade'", ",", "effectsOut", ",", "self", ".", "effectsOut", ",", "self", ".", "transformOut", ",", "true", ")", ";", "for", "(", "transformName", "in", "mixitup", ".", "transformDefaults", ")", "{", "if", "(", "!", "(", "mixitup", ".", "transformDefaults", "[", "transformName", "]", "instanceof", "mixitup", ".", "TransformData", ")", ")", "{", "continue", ";", "}", "self", ".", "parseEffect", "(", "transformName", ",", "effectsIn", ",", "self", ".", "effectsIn", ",", "self", ".", "transformIn", ")", ";", "self", ".", "parseEffect", "(", "transformName", ",", "effectsOut", ",", "self", ".", "effectsOut", ",", "self", ".", "transformOut", ",", "true", ")", ";", "}", "self", ".", "parseEffect", "(", "'stagger'", ",", "effectsIn", ",", "self", ".", "effectsIn", ",", "self", ".", "transformIn", ")", ";", "self", ".", "parseEffect", "(", "'stagger'", ",", "effectsOut", ",", "self", ".", "effectsOut", ",", "self", ".", "transformOut", ",", "true", ")", ";", "self", ".", "callActions", "(", "'afterParseEffects'", ",", "arguments", ")", ";", "}" ]
Parses all effects out of the user-defined `animation.effects` string into their respective properties and units. @private @instance @since 2.0.0 @return {void}
[ "Parses", "all", "effects", "out", "of", "the", "user", "-", "defined", "animation", ".", "effects", "string", "into", "their", "respective", "properties", "and", "units", "." ]
4e7a5a0460b4eb097dfe9ff2db15853eccc779d7
https://github.com/octoblu/meshblu/blob/4e7a5a0460b4eb097dfe9ff2db15853eccc779d7/docs/vendor/mixitup/mixitup.js#L5972-L6003
20,002
octoblu/meshblu
docs/vendor/mixitup/mixitup.js
function(statusChange, hasEffect, posIn, posOut) { var self = this, result = false; if (!h.isVisible(self.dom.container)) { // If the container is not visible, the transitionEnd // event will not occur and MixItUp will hang result = false; } else if ( (statusChange !== 'none' && hasEffect) || posIn.x !== posOut.x || posIn.y !== posOut.y ) { // If opacity and/or translate will change result = true; } else if (self.config.animation.animateResizeTargets) { // Check if width, height or margins will change result = ( posIn.width !== posOut.width || posIn.height !== posOut.height || posIn.marginRight !== posOut.marginRight || posIn.marginTop !== posOut.marginTop ); } else { result = false; } return self.callFilters('resultWillTransition', result, arguments); }
javascript
function(statusChange, hasEffect, posIn, posOut) { var self = this, result = false; if (!h.isVisible(self.dom.container)) { // If the container is not visible, the transitionEnd // event will not occur and MixItUp will hang result = false; } else if ( (statusChange !== 'none' && hasEffect) || posIn.x !== posOut.x || posIn.y !== posOut.y ) { // If opacity and/or translate will change result = true; } else if (self.config.animation.animateResizeTargets) { // Check if width, height or margins will change result = ( posIn.width !== posOut.width || posIn.height !== posOut.height || posIn.marginRight !== posOut.marginRight || posIn.marginTop !== posOut.marginTop ); } else { result = false; } return self.callFilters('resultWillTransition', result, arguments); }
[ "function", "(", "statusChange", ",", "hasEffect", ",", "posIn", ",", "posOut", ")", "{", "var", "self", "=", "this", ",", "result", "=", "false", ";", "if", "(", "!", "h", ".", "isVisible", "(", "self", ".", "dom", ".", "container", ")", ")", "{", "// If the container is not visible, the transitionEnd", "// event will not occur and MixItUp will hang", "result", "=", "false", ";", "}", "else", "if", "(", "(", "statusChange", "!==", "'none'", "&&", "hasEffect", ")", "||", "posIn", ".", "x", "!==", "posOut", ".", "x", "||", "posIn", ".", "y", "!==", "posOut", ".", "y", ")", "{", "// If opacity and/or translate will change", "result", "=", "true", ";", "}", "else", "if", "(", "self", ".", "config", ".", "animation", ".", "animateResizeTargets", ")", "{", "// Check if width, height or margins will change", "result", "=", "(", "posIn", ".", "width", "!==", "posOut", ".", "width", "||", "posIn", ".", "height", "!==", "posOut", ".", "height", "||", "posIn", ".", "marginRight", "!==", "posOut", ".", "marginRight", "||", "posIn", ".", "marginTop", "!==", "posOut", ".", "marginTop", ")", ";", "}", "else", "{", "result", "=", "false", ";", "}", "return", "self", ".", "callFilters", "(", "'resultWillTransition'", ",", "result", ",", "arguments", ")", ";", "}" ]
Determines if a target element will transition in some fasion and therefore requires binding of transitionEnd @private @instance @since 3.0.0 @param {string} statusChange @param {boolean} hasEffect @param {StyleData} posIn @param {StyleData} posOut @return {boolean}
[ "Determines", "if", "a", "target", "element", "will", "transition", "in", "some", "fasion", "and", "therefore", "requires", "binding", "of", "transitionEnd" ]
4e7a5a0460b4eb097dfe9ff2db15853eccc779d7
https://github.com/octoblu/meshblu/blob/4e7a5a0460b4eb097dfe9ff2db15853eccc779d7/docs/vendor/mixitup/mixitup.js#L6815-L6846
20,003
octoblu/meshblu
docs/vendor/mixitup/mixitup.js
function() { var self = this, instruction = self.parseFilterArgs(arguments); return self.multimix({ filter: instruction.command }, instruction.animate, instruction.callback); }
javascript
function() { var self = this, instruction = self.parseFilterArgs(arguments); return self.multimix({ filter: instruction.command }, instruction.animate, instruction.callback); }
[ "function", "(", ")", "{", "var", "self", "=", "this", ",", "instruction", "=", "self", ".", "parseFilterArgs", "(", "arguments", ")", ";", "return", "self", ".", "multimix", "(", "{", "filter", ":", "instruction", ".", "command", "}", ",", "instruction", ".", "animate", ",", "instruction", ".", "callback", ")", ";", "}" ]
Filters all targets in the container by a provided selector string, or the values `'all'` or `'none'`. Only targets matching the selector will be shown. @example .filter(selector [, animate] [, callback]) @example <caption>Example 1: Filtering targets by a class selector</caption> mixer.filter('.category-a') .then(function(state) { console.log(state.totalShow === containerEl.querySelectorAll('.category-a').length); // true }); @example <caption>Example 2: Filtering targets by an attribute selector</caption> mixer.filter('[data-category~="a"]') .then(function(state) { console.log(state.totalShow === containerEl.querySelectorAll('[data-category~="a"]').length); // true }); @example <caption>Example 3: Filtering targets by a compound selector</caption> // Show only those targets with the classes 'category-a' AND 'category-b' mixer.filter('.category-a.category-c') .then(function(state) { console.log(state.totalShow === containerEl.querySelectorAll('.category-a.category-c').length); // true }); @example <caption>Example 4: Filtering via an element collection</caption> var collection = Array.from(container.querySelectorAll('.mix')); console.log(collection.length); // 34 // Filter the collection manually using Array.prototype.filter var filtered = collection.filter(function(target) { return parseInt(target.getAttribute('data-price')) > 10; }); console.log(filtered.length); // 22 // Pass the filtered collection to MixItUp mixer.filter(filtered) .then(function(state) { console.log(state.activeFilter.collection.length === 22); // true }); @public @instance @since 2.0.0 @param {(string|HTMLElement|Array.<HTMLElement>)} selector Any valid CSS selector (i.e. `'.category-a'`), or the values `'all'` or `'none'`. The filter method also accepts a reference to single target element or a collection of target elements to show. @param {boolean} [animate=true] An optional boolean dictating whether the operation should animate, or occur syncronously with no animation. `true` by default. @param {function} [callback=null] An optional callback function to be invoked after the operation has completed. @return {Promise.<mixitup.State>} A promise resolving with the current state object.
[ "Filters", "all", "targets", "in", "the", "container", "by", "a", "provided", "selector", "string", "or", "the", "values", "all", "or", "none", ".", "Only", "targets", "matching", "the", "selector", "will", "be", "shown", "." ]
4e7a5a0460b4eb097dfe9ff2db15853eccc779d7
https://github.com/octoblu/meshblu/blob/4e7a5a0460b4eb097dfe9ff2db15853eccc779d7/docs/vendor/mixitup/mixitup.js#L7920-L7927
20,004
octoblu/meshblu
docs/vendor/mixitup/mixitup.js
function() { var self = this, instruction = self.parseFilterArgs(arguments), selector = instruction.command.selector, toggleSelector = ''; self.isToggling = true; if (self.toggleArray.indexOf(selector) < 0) { self.toggleArray.push(selector); } toggleSelector = self.getToggleSelector(); return self.multimix({ filter: toggleSelector }, instruction.animate, instruction.callback); }
javascript
function() { var self = this, instruction = self.parseFilterArgs(arguments), selector = instruction.command.selector, toggleSelector = ''; self.isToggling = true; if (self.toggleArray.indexOf(selector) < 0) { self.toggleArray.push(selector); } toggleSelector = self.getToggleSelector(); return self.multimix({ filter: toggleSelector }, instruction.animate, instruction.callback); }
[ "function", "(", ")", "{", "var", "self", "=", "this", ",", "instruction", "=", "self", ".", "parseFilterArgs", "(", "arguments", ")", ",", "selector", "=", "instruction", ".", "command", ".", "selector", ",", "toggleSelector", "=", "''", ";", "self", ".", "isToggling", "=", "true", ";", "if", "(", "self", ".", "toggleArray", ".", "indexOf", "(", "selector", ")", "<", "0", ")", "{", "self", ".", "toggleArray", ".", "push", "(", "selector", ")", ";", "}", "toggleSelector", "=", "self", ".", "getToggleSelector", "(", ")", ";", "return", "self", ".", "multimix", "(", "{", "filter", ":", "toggleSelector", "}", ",", "instruction", ".", "animate", ",", "instruction", ".", "callback", ")", ";", "}" ]
Adds an additional selector to the currently active filter selector, concatenating as per the logic defined in `controls.toggleLogic`. @example .toggleOn(selector [, animate] [, callback]) @example <caption>Example: Toggling on a filter selector</caption> console.log(mixer.getState().activeFilter.selector); // '.category-a' mixer.toggleOn('.category-b') .then(function(state) { console.log(state.activeFilter.selector); // '.category-a, .category-b' }); @public @instance @since 3.0.0 @param {string} selector Any valid CSS selector (i.e. `'.category-a'`) @param {boolean} [animate=true] An optional boolean dictating whether the operation should animate, or occur syncronously with no animation. `true` by default. @param {function} [callback=null] An optional callback function to be invoked after the operation has completed. @return {Promise.<mixitup.State>} A promise resolving with the current state object.
[ "Adds", "an", "additional", "selector", "to", "the", "currently", "active", "filter", "selector", "concatenating", "as", "per", "the", "logic", "defined", "in", "controls", ".", "toggleLogic", "." ]
4e7a5a0460b4eb097dfe9ff2db15853eccc779d7
https://github.com/octoblu/meshblu/blob/4e7a5a0460b4eb097dfe9ff2db15853eccc779d7/docs/vendor/mixitup/mixitup.js#L7959-L7976
20,005
octoblu/meshblu
docs/vendor/mixitup/mixitup.js
function() { var self = this, instruction = self.parseSortArgs(arguments); return self.multimix({ sort: instruction.command }, instruction.animate, instruction.callback); }
javascript
function() { var self = this, instruction = self.parseSortArgs(arguments); return self.multimix({ sort: instruction.command }, instruction.animate, instruction.callback); }
[ "function", "(", ")", "{", "var", "self", "=", "this", ",", "instruction", "=", "self", ".", "parseSortArgs", "(", "arguments", ")", ";", "return", "self", ".", "multimix", "(", "{", "sort", ":", "instruction", ".", "command", "}", ",", "instruction", ".", "animate", ",", "instruction", ".", "callback", ")", ";", "}" ]
Sorts all targets in the container according to a provided sort string. @example .sort(sortString [, animate] [, callback]) @example <caption>Example 1: Sorting by the default DOM order</caption> // Reverse the default order of the targets mixer.sort('default:desc') .then(function(state) { console.log(state.activeSort.attribute === 'default'); // true console.log(state.activeSort.order === 'desc'); // true }); @example <caption>Example 2: Sorting by a custom data-attribute</caption> // Sort the targets by the value of a `data-published-date` attribute mixer.sort('published-date:asc') .then(function(state) { console.log(state.activeSort.attribute === 'published-date'); // true console.log(state.activeSort.order === 'asc'); // true }); @example <caption>Example 3: Sorting by multiple attributes</caption> // Sort the targets by the value of a `data-published-date` attribute, then by `data-title` mixer.sort('published-date:desc data-title:asc') .then(function(state) { console.log(state.activeSort.attribute === 'published-date'); // true console.log(state.activeSort.order === 'desc'); // true console.log(state.activeSort.next.attribute === 'title'); // true console.log(state.activeSort.next.order === 'asc'); // true }); @example <caption>Example 4: Sorting by random</caption> mixer.sort('random') .then(function(state) { console.log(state.activeSort.order === 'random') // true }); @example <caption>Example 5: Sorting via an element collection</caption> var collection = Array.from(container.querySelectorAll('.mix')); // Swap the position of two elements in the collection: var temp = collection[1]; collection[1] = collection[0]; collection[0] = temp; // Pass the sorted collection to MixItUp mixer.sort(collection) .then(function(state) { console.log(state.targets[0] === collection[0]); // true }); @public @instance @since 2.0.0 @param {(string|Array.<HTMLElement>)} sortString A valid sort string (e.g. `'default'`, `'published-date:asc'`, or `'random'`). The sort method also accepts an array of all target elements in a user-defined order. @param {boolean} [animate=true] An optional boolean dictating whether the operation should animate, or occur syncronously with no animation. `true` by default. @param {function} [callback=null] An optional callback function to be invoked after the operation has completed. @return {Promise.<mixitup.State>} A promise resolving with the current state object.
[ "Sorts", "all", "targets", "in", "the", "container", "according", "to", "a", "provided", "sort", "string", "." ]
4e7a5a0460b4eb097dfe9ff2db15853eccc779d7
https://github.com/octoblu/meshblu/blob/4e7a5a0460b4eb097dfe9ff2db15853eccc779d7/docs/vendor/mixitup/mixitup.js#L8102-L8109
20,006
octoblu/meshblu
docs/vendor/mixitup/mixitup.js
function() { var self = this, instruction = self.parseChangeLayoutArgs(arguments); return self.multimix({ changeLayout: instruction.command }, instruction.animate, instruction.callback); }
javascript
function() { var self = this, instruction = self.parseChangeLayoutArgs(arguments); return self.multimix({ changeLayout: instruction.command }, instruction.animate, instruction.callback); }
[ "function", "(", ")", "{", "var", "self", "=", "this", ",", "instruction", "=", "self", ".", "parseChangeLayoutArgs", "(", "arguments", ")", ";", "return", "self", ".", "multimix", "(", "{", "changeLayout", ":", "instruction", ".", "command", "}", ",", "instruction", ".", "animate", ",", "instruction", ".", "callback", ")", ";", "}" ]
Changes the layout of the container by adding, removing or updating a layout-specific class name. If `animation.animateResizetargets` is enabled, MixItUp will attempt to gracefully animate the width, height, and position of targets between layout states. @example .changeLayout(containerClassName [, animate] [, callback]) @example <caption>Example 1: Adding a new class name to the container</caption> mixer.changeLayout('container-list') .then(function(state) { console.log(state.activeContainerClass === 'container-list'); // true }); @example <caption>Example 2: Removing a previously added class name from the container</caption> mixer.changeLayout('') .then(function(state) { console.log(state.activeContainerClass === ''); // true }); @public @instance @since 2.0.0 @param {string} containerClassName A layout-specific class name to add to the container. @param {boolean} [animate=true] An optional boolean dictating whether the operation should animate, or occur syncronously with no animation. `true` by default. @param {function} [callback=null] An optional callback function to be invoked after the operation has completed. @return {Promise.<mixitup.State>} A promise resolving with the current state object.
[ "Changes", "the", "layout", "of", "the", "container", "by", "adding", "removing", "or", "updating", "a", "layout", "-", "specific", "class", "name", ".", "If", "animation", ".", "animateResizetargets", "is", "enabled", "MixItUp", "will", "attempt", "to", "gracefully", "animate", "the", "width", "height", "and", "position", "of", "targets", "between", "layout", "states", "." ]
4e7a5a0460b4eb097dfe9ff2db15853eccc779d7
https://github.com/octoblu/meshblu/blob/4e7a5a0460b4eb097dfe9ff2db15853eccc779d7/docs/vendor/mixitup/mixitup.js#L8148-L8155
20,007
octoblu/meshblu
docs/vendor/mixitup/mixitup.js
function() { var self = this, instruction = self.parseDatasetArgs(arguments), operation = null, queueItem = null, animate = false; self.callActions('beforeDataset', arguments); if (!self.isBusy) { if (instruction.callback) self.userCallback = instruction.callback; animate = (instruction.animate ^ self.config.animation.enable) ? instruction.animate : self.config.animation.enable; operation = self.getDataOperation(instruction.command.dataset); return self.goMix(animate, operation); } else { queueItem = new mixitup.QueueItem(); queueItem.args = arguments; queueItem.instruction = instruction; return self.queueMix(queueItem); } }
javascript
function() { var self = this, instruction = self.parseDatasetArgs(arguments), operation = null, queueItem = null, animate = false; self.callActions('beforeDataset', arguments); if (!self.isBusy) { if (instruction.callback) self.userCallback = instruction.callback; animate = (instruction.animate ^ self.config.animation.enable) ? instruction.animate : self.config.animation.enable; operation = self.getDataOperation(instruction.command.dataset); return self.goMix(animate, operation); } else { queueItem = new mixitup.QueueItem(); queueItem.args = arguments; queueItem.instruction = instruction; return self.queueMix(queueItem); } }
[ "function", "(", ")", "{", "var", "self", "=", "this", ",", "instruction", "=", "self", ".", "parseDatasetArgs", "(", "arguments", ")", ",", "operation", "=", "null", ",", "queueItem", "=", "null", ",", "animate", "=", "false", ";", "self", ".", "callActions", "(", "'beforeDataset'", ",", "arguments", ")", ";", "if", "(", "!", "self", ".", "isBusy", ")", "{", "if", "(", "instruction", ".", "callback", ")", "self", ".", "userCallback", "=", "instruction", ".", "callback", ";", "animate", "=", "(", "instruction", ".", "animate", "^", "self", ".", "config", ".", "animation", ".", "enable", ")", "?", "instruction", ".", "animate", ":", "self", ".", "config", ".", "animation", ".", "enable", ";", "operation", "=", "self", ".", "getDataOperation", "(", "instruction", ".", "command", ".", "dataset", ")", ";", "return", "self", ".", "goMix", "(", "animate", ",", "operation", ")", ";", "}", "else", "{", "queueItem", "=", "new", "mixitup", ".", "QueueItem", "(", ")", ";", "queueItem", ".", "args", "=", "arguments", ";", "queueItem", ".", "instruction", "=", "instruction", ";", "return", "self", ".", "queueMix", "(", "queueItem", ")", ";", "}", "}" ]
Updates the contents and order of the container to reflect the provided dataset, if the dataset API is in use. The dataset API is designed for use in API-driven JavaScript applications, and can be used instead of DOM-based methods such as `.filter()`, `.sort()`, `.insert()`, etc. When used, insertion, removal, sorting and pagination can be achieved purely via changes to your data model, without the uglyness of having to interact with or query the DOM directly. @example .dataset(dataset [, animate] [, callback]) @example <caption>Example 1: Rendering a dataset</caption> var myDataset = [ {id: 1, ...}, {id: 2, ...}, {id: 3, ...} ]; mixer.dataset(myDataset) .then(function(state) { console.log(state.totalShow === 3); // true }); @example <caption>Example 2: Sorting a dataset</caption> // Create a new dataset in reverse order var newDataset = myDataset.slice().reverse(); mixer.dataset(newDataset) .then(function(state) { console.log(state.activeDataset[0] === myDataset[2]); // true }); @example <caption>Example 3: Removing an item from the dataset</caption> console.log(myDataset.length); // 3 // Create a new dataset with the last item removed. var newDataset = myDataset.slice().pop(); mixer.dataset(newDataset) .then(function(state) { console.log(state.totalShow === 2); // true }); @public @instance @since 3.0.0 @param {Array.<object>} dataset An array of objects, each one representing the underlying data model of a target to be rendered. @param {boolean} [animate=true] An optional boolean dictating whether the operation should animate, or occur syncronously with no animation. `true` by default. @param {function} [callback=null] An optional callback function to be invoked after the operation has completed. @return {Promise.<mixitup.State>} A promise resolving with the current state object.
[ "Updates", "the", "contents", "and", "order", "of", "the", "container", "to", "reflect", "the", "provided", "dataset", "if", "the", "dataset", "API", "is", "in", "use", "." ]
4e7a5a0460b4eb097dfe9ff2db15853eccc779d7
https://github.com/octoblu/meshblu/blob/4e7a5a0460b4eb097dfe9ff2db15853eccc779d7/docs/vendor/mixitup/mixitup.js#L8221-L8246
20,008
octoblu/meshblu
docs/vendor/mixitup/mixitup.js
function() { var self = this, operation = null, animate = false, queueItem = null, instruction = self.parseMultimixArgs(arguments); self.callActions('beforeMultimix', arguments); if (!self.isBusy) { operation = self.getOperation(instruction.command); if (self.config.controls.enable) { // Update controls for API calls if (instruction.command.filter && !self.isToggling) { // As we are not toggling, reset the toggle array // so new filter overrides existing toggles self.toggleArray.length = 0; self.buildToggleArray(operation.command); } if (self.queue.length < 1) { self.updateControls(operation.command); } } if (instruction.callback) self.userCallback = instruction.callback; // Always allow the instruction to override the instance setting animate = (instruction.animate ^ self.config.animation.enable) ? instruction.animate : self.config.animation.enable; self.callFilters('operationMultimix', operation, arguments); return self.goMix(animate, operation); } else { queueItem = new mixitup.QueueItem(); queueItem.args = arguments; queueItem.instruction = instruction; queueItem.triggerElement = self.lastClicked; queueItem.isToggling = self.isToggling; return self.queueMix(queueItem); } }
javascript
function() { var self = this, operation = null, animate = false, queueItem = null, instruction = self.parseMultimixArgs(arguments); self.callActions('beforeMultimix', arguments); if (!self.isBusy) { operation = self.getOperation(instruction.command); if (self.config.controls.enable) { // Update controls for API calls if (instruction.command.filter && !self.isToggling) { // As we are not toggling, reset the toggle array // so new filter overrides existing toggles self.toggleArray.length = 0; self.buildToggleArray(operation.command); } if (self.queue.length < 1) { self.updateControls(operation.command); } } if (instruction.callback) self.userCallback = instruction.callback; // Always allow the instruction to override the instance setting animate = (instruction.animate ^ self.config.animation.enable) ? instruction.animate : self.config.animation.enable; self.callFilters('operationMultimix', operation, arguments); return self.goMix(animate, operation); } else { queueItem = new mixitup.QueueItem(); queueItem.args = arguments; queueItem.instruction = instruction; queueItem.triggerElement = self.lastClicked; queueItem.isToggling = self.isToggling; return self.queueMix(queueItem); } }
[ "function", "(", ")", "{", "var", "self", "=", "this", ",", "operation", "=", "null", ",", "animate", "=", "false", ",", "queueItem", "=", "null", ",", "instruction", "=", "self", ".", "parseMultimixArgs", "(", "arguments", ")", ";", "self", ".", "callActions", "(", "'beforeMultimix'", ",", "arguments", ")", ";", "if", "(", "!", "self", ".", "isBusy", ")", "{", "operation", "=", "self", ".", "getOperation", "(", "instruction", ".", "command", ")", ";", "if", "(", "self", ".", "config", ".", "controls", ".", "enable", ")", "{", "// Update controls for API calls", "if", "(", "instruction", ".", "command", ".", "filter", "&&", "!", "self", ".", "isToggling", ")", "{", "// As we are not toggling, reset the toggle array", "// so new filter overrides existing toggles", "self", ".", "toggleArray", ".", "length", "=", "0", ";", "self", ".", "buildToggleArray", "(", "operation", ".", "command", ")", ";", "}", "if", "(", "self", ".", "queue", ".", "length", "<", "1", ")", "{", "self", ".", "updateControls", "(", "operation", ".", "command", ")", ";", "}", "}", "if", "(", "instruction", ".", "callback", ")", "self", ".", "userCallback", "=", "instruction", ".", "callback", ";", "// Always allow the instruction to override the instance setting", "animate", "=", "(", "instruction", ".", "animate", "^", "self", ".", "config", ".", "animation", ".", "enable", ")", "?", "instruction", ".", "animate", ":", "self", ".", "config", ".", "animation", ".", "enable", ";", "self", ".", "callFilters", "(", "'operationMultimix'", ",", "operation", ",", "arguments", ")", ";", "return", "self", ".", "goMix", "(", "animate", ",", "operation", ")", ";", "}", "else", "{", "queueItem", "=", "new", "mixitup", ".", "QueueItem", "(", ")", ";", "queueItem", ".", "args", "=", "arguments", ";", "queueItem", ".", "instruction", "=", "instruction", ";", "queueItem", ".", "triggerElement", "=", "self", ".", "lastClicked", ";", "queueItem", ".", "isToggling", "=", "self", ".", "isToggling", ";", "return", "self", ".", "queueMix", "(", "queueItem", ")", ";", "}", "}" ]
Performs simultaneous `filter`, `sort`, `insert`, `remove` and `changeLayout` operations as requested. @example .multimix(multimixCommand [, animate] [, callback]) @example <caption>Example 1: Performing simultaneous filtering and sorting</caption> mixer.multimix({ filter: '.category-b', sort: 'published-date:desc' }) .then(function(state) { console.log(state.activeFilter.selector === '.category-b'); // true console.log(state.activeSort.attribute === 'published-date'); // true }); @example <caption>Example 2: Performing simultaneous sorting, insertion, and removal</caption> console.log(mixer.getState().totalShow); // 6 // NB: When inserting via `multimix()`, an object should be provided as the value // for the `insert` portion of the command, allowing for a collection of elements // and an insertion index to be specified. mixer.multimix({ sort: 'published-date:desc', // Sort the container, including any new elements insert: { collection: [newElementReferenceA, newElementReferenceB], // Add 2 new elements at index 5 index: 5 }, remove: existingElementReference // Remove 1 existing element }) .then(function(state) { console.log(state.activeSort.attribute === 'published-date'); // true console.log(state.totalShow === 7); // true }); @public @instance @since 2.0.0 @param {object} multimixCommand An object containing one or more things to do @param {boolean} [animate=true] An optional boolean dictating whether the operation should animate, or occur syncronously with no animation. `true` by default. @param {function} [callback=null] An optional callback function to be invoked after the operation has completed. @return {Promise.<mixitup.State>} A promise resolving with the current state object.
[ "Performs", "simultaneous", "filter", "sort", "insert", "remove", "and", "changeLayout", "operations", "as", "requested", "." ]
4e7a5a0460b4eb097dfe9ff2db15853eccc779d7
https://github.com/octoblu/meshblu/blob/4e7a5a0460b4eb097dfe9ff2db15853eccc779d7/docs/vendor/mixitup/mixitup.js#L8301-L8350
20,009
octoblu/meshblu
docs/vendor/mixitup/mixitup.js
function(operation, multiplier) { var target = null, posData = null, toHideIndex = -1, i = -1; multiplier = Math.min(multiplier, 1); multiplier = Math.max(multiplier, 0); for (i = 0; target = operation.show[i]; i++) { posData = operation.showPosData[i]; target.applyTween(posData, multiplier); } for (i = 0; target = operation.hide[i]; i++) { if (target.isShown) { target.hide(); } if ((toHideIndex = operation.toHide.indexOf(target)) > -1) { posData = operation.toHidePosData[toHideIndex]; if (!target.isShown) { target.show(); } target.applyTween(posData, multiplier); } } }
javascript
function(operation, multiplier) { var target = null, posData = null, toHideIndex = -1, i = -1; multiplier = Math.min(multiplier, 1); multiplier = Math.max(multiplier, 0); for (i = 0; target = operation.show[i]; i++) { posData = operation.showPosData[i]; target.applyTween(posData, multiplier); } for (i = 0; target = operation.hide[i]; i++) { if (target.isShown) { target.hide(); } if ((toHideIndex = operation.toHide.indexOf(target)) > -1) { posData = operation.toHidePosData[toHideIndex]; if (!target.isShown) { target.show(); } target.applyTween(posData, multiplier); } } }
[ "function", "(", "operation", ",", "multiplier", ")", "{", "var", "target", "=", "null", ",", "posData", "=", "null", ",", "toHideIndex", "=", "-", "1", ",", "i", "=", "-", "1", ";", "multiplier", "=", "Math", ".", "min", "(", "multiplier", ",", "1", ")", ";", "multiplier", "=", "Math", ".", "max", "(", "multiplier", ",", "0", ")", ";", "for", "(", "i", "=", "0", ";", "target", "=", "operation", ".", "show", "[", "i", "]", ";", "i", "++", ")", "{", "posData", "=", "operation", ".", "showPosData", "[", "i", "]", ";", "target", ".", "applyTween", "(", "posData", ",", "multiplier", ")", ";", "}", "for", "(", "i", "=", "0", ";", "target", "=", "operation", ".", "hide", "[", "i", "]", ";", "i", "++", ")", "{", "if", "(", "target", ".", "isShown", ")", "{", "target", ".", "hide", "(", ")", ";", "}", "if", "(", "(", "toHideIndex", "=", "operation", ".", "toHide", ".", "indexOf", "(", "target", ")", ")", ">", "-", "1", ")", "{", "posData", "=", "operation", ".", "toHidePosData", "[", "toHideIndex", "]", ";", "if", "(", "!", "target", ".", "isShown", ")", "{", "target", ".", "show", "(", ")", ";", "}", "target", ".", "applyTween", "(", "posData", ",", "multiplier", ")", ";", "}", "}", "}" ]
Renders a previously created operation at a specific point in its path, as determined by a multiplier between 0 and 1. @example .tween(operation, multiplier) @private @instance @since 3.0.0 @param {mixitup.Operation} operation An operation object created via the `getOperation` method @param {Float} multiplier Any number between 0 and 1 representing the percentage complete of the operation @return {void}
[ "Renders", "a", "previously", "created", "operation", "at", "a", "specific", "point", "in", "its", "path", "as", "determined", "by", "a", "multiplier", "between", "0", "and", "1", "." ]
4e7a5a0460b4eb097dfe9ff2db15853eccc779d7
https://github.com/octoblu/meshblu/blob/4e7a5a0460b4eb097dfe9ff2db15853eccc779d7/docs/vendor/mixitup/mixitup.js#L8478-L8508
20,010
octoblu/meshblu
docs/vendor/mixitup/mixitup.js
function() { var self = this, args = self.parseInsertArgs(arguments); return self.multimix({ insert: args.command }, args.animate, args.callback); }
javascript
function() { var self = this, args = self.parseInsertArgs(arguments); return self.multimix({ insert: args.command }, args.animate, args.callback); }
[ "function", "(", ")", "{", "var", "self", "=", "this", ",", "args", "=", "self", ".", "parseInsertArgs", "(", "arguments", ")", ";", "return", "self", ".", "multimix", "(", "{", "insert", ":", "args", ".", "command", "}", ",", "args", ".", "animate", ",", "args", ".", "callback", ")", ";", "}" ]
Inserts one or more new target elements into the container at a specified index. To be indexed as targets, new elements must match the `selectors.target` selector (`'.mix'` by default). @example .insert(newElements [, index] [, animate], [, callback]) @example <caption>Example 1: Inserting a single element via reference</caption> console.log(mixer.getState().totalShow); // 0 // Create a new element var newElement = document.createElement('div'); newElement.classList.add('mix'); mixer.insert(newElement) .then(function(state) { console.log(state.totalShow === 1); // true }); @example <caption>Example 2: Inserting a single element via HTML string</caption> console.log(mixer.getState().totalShow); // 1 // Create a new element via reference var newElementHtml = '&lt;div class="mix"&gt;&lt;/div&gt;'; // Create and insert the new element at index 1 mixer.insert(newElementHtml, 1) .then(function(state) { console.log(state.totalShow === 2); // true console.log(state.show[1].outerHTML === newElementHtml); // true }); @example <caption>Example 3: Inserting multiple elements via reference</caption> console.log(mixer.getState().totalShow); // 2 // Create an array of new elements to insert. var newElement1 = document.createElement('div'); var newElement2 = document.createElement('div'); newElement1.classList.add('mix'); newElement2.classList.add('mix'); var newElementsCollection = [newElement1, newElement2]; // Insert the new elements starting at index 1 mixer.insert(newElementsCollection, 1) .then(function(state) { console.log(state.totalShow === 4); // true console.log(state.show[1] === newElement1); // true console.log(state.show[2] === newElement2); // true }); @example <caption>Example 4: Inserting a jQuery collection object containing one or more elements</caption> console.log(mixer.getState().totalShow); // 4 var $newElement = $('&lt;div class="mix"&gt;&lt;/div&gt;'); // Insert the new elements starting at index 3 mixer.insert(newElementsCollection, 3) .then(function(state) { console.log(state.totalShow === 5); // true console.log(state.show[3] === $newElement[0]); // true }); @public @instance @since 2.0.0 @param {(HTMLElement|Array.<HTMLElement>|string)} newElements A reference to a single element to insert, an array-like collection of elements, or an HTML string representing a single element. @param {number} index=0 The index at which to insert the new element(s). `0` by default. @param {boolean} [animate=true] An optional boolean dictating whether the operation should animate, or occur syncronously with no animation. `true` by default. @param {function} [callback=null] An optional callback function to be invoked after the operation has completed. @return {Promise.<mixitup.State>} A promise resolving with the current state object.
[ "Inserts", "one", "or", "more", "new", "target", "elements", "into", "the", "container", "at", "a", "specified", "index", "." ]
4e7a5a0460b4eb097dfe9ff2db15853eccc779d7
https://github.com/octoblu/meshblu/blob/4e7a5a0460b4eb097dfe9ff2db15853eccc779d7/docs/vendor/mixitup/mixitup.js#L8603-L8610
20,011
octoblu/meshblu
docs/vendor/mixitup/mixitup.js
function() { var self = this, args = self.parseRemoveArgs(arguments); return self.multimix({ remove: args.command }, args.animate, args.callback); }
javascript
function() { var self = this, args = self.parseRemoveArgs(arguments); return self.multimix({ remove: args.command }, args.animate, args.callback); }
[ "function", "(", ")", "{", "var", "self", "=", "this", ",", "args", "=", "self", ".", "parseRemoveArgs", "(", "arguments", ")", ";", "return", "self", ".", "multimix", "(", "{", "remove", ":", "args", ".", "command", "}", ",", "args", ".", "animate", ",", "args", ".", "callback", ")", ";", "}" ]
Removes one or more existing target elements from the container. @example .remove(elements [, animate] [, callback]) @example <caption>Example 1: Removing an element by reference</caption> var elementToRemove = containerEl.firstElementChild; mixer.remove(elementToRemove) .then(function(state) { console.log(state.targets.indexOf(elementToRemove) === -1); // true }); @example <caption>Example 2: Removing a collection of elements by reference</caption> var elementsToRemove = containerEl.querySelectorAll('.category-a'); console.log(elementsToRemove.length) // 3 mixer.remove(elementsToRemove) .then(function() { console.log(containerEl.querySelectorAll('.category-a').length); // 0 }); @example <caption>Example 3: Removing one or more elements by selector</caption> mixer.remove('.category-a') .then(function() { console.log(containerEl.querySelectorAll('.category-a').length); // 0 }); @example <caption>Example 4: Removing an element by index</caption> console.log(mixer.getState.totalShow); // 4 // Remove the element at index 3 mixer.remove(3) .then(function(state) { console.log(state.totalShow); // 3 console.log(state.show[3]); // undefined }); @public @instance @since 3.0.0 @param {(HTMLElement|Array.<HTMLElement>|string|number)} elements A reference to a single element to remove, an array-like collection of elements, a selector string, or the index of an element to remove. @param {boolean} [animate=true] An optional boolean dictating whether the operation should animate, or occur syncronously with no animation. `true` by default. @param {function} [callback=null] An optional callback function to be invoked after the operation has completed. @return {Promise.<mixitup.State>} A promise resolving with the current state object.
[ "Removes", "one", "or", "more", "existing", "target", "elements", "from", "the", "container", "." ]
4e7a5a0460b4eb097dfe9ff2db15853eccc779d7
https://github.com/octoblu/meshblu/blob/4e7a5a0460b4eb097dfe9ff2db15853eccc779d7/docs/vendor/mixitup/mixitup.js#L8852-L8859
20,012
octoblu/meshblu
docs/vendor/mixitup/mixitup.js
function(stringKey) { var self = this, value = null; if (!stringKey) { value = self.config; } else { value = h.getProperty(self.config, stringKey); } return self.callFilters('valueGetConfig', value, arguments); }
javascript
function(stringKey) { var self = this, value = null; if (!stringKey) { value = self.config; } else { value = h.getProperty(self.config, stringKey); } return self.callFilters('valueGetConfig', value, arguments); }
[ "function", "(", "stringKey", ")", "{", "var", "self", "=", "this", ",", "value", "=", "null", ";", "if", "(", "!", "stringKey", ")", "{", "value", "=", "self", ".", "config", ";", "}", "else", "{", "value", "=", "h", ".", "getProperty", "(", "self", ".", "config", ",", "stringKey", ")", ";", "}", "return", "self", ".", "callFilters", "(", "'valueGetConfig'", ",", "value", ",", "arguments", ")", ";", "}" ]
Retrieves the the value of any property or sub-object within the current mixitup configuration, or the whole configuration object. @example .getConfig([stringKey]) @example <caption>Example 1: retrieve the entire configuration object</caption> var config = mixer.getConfig(); // Config { ... } @example <caption>Example 2: retrieve a named sub-object of configuration object</caption> var animation = mixer.getConfig('animation'); // ConfigAnimation { ... } @example <caption>Example 3: retrieve a value of configuration object via a dot-notation string key</caption> var effects = mixer.getConfig('animation.effects'); // 'fade scale' @public @instance @since 2.0.0 @param {string} [stringKey] A "dot-notation" string key @return {*}
[ "Retrieves", "the", "the", "value", "of", "any", "property", "or", "sub", "-", "object", "within", "the", "current", "mixitup", "configuration", "or", "the", "whole", "configuration", "object", "." ]
4e7a5a0460b4eb097dfe9ff2db15853eccc779d7
https://github.com/octoblu/meshblu/blob/4e7a5a0460b4eb097dfe9ff2db15853eccc779d7/docs/vendor/mixitup/mixitup.js#L8888-L8899
20,013
octoblu/meshblu
docs/vendor/mixitup/mixitup.js
function(config) { var self = this; self.callActions('beforeConfigure', arguments); h.extend(self.config, config, true, true); self.callActions('afterConfigure', arguments); }
javascript
function(config) { var self = this; self.callActions('beforeConfigure', arguments); h.extend(self.config, config, true, true); self.callActions('afterConfigure', arguments); }
[ "function", "(", "config", ")", "{", "var", "self", "=", "this", ";", "self", ".", "callActions", "(", "'beforeConfigure'", ",", "arguments", ")", ";", "h", ".", "extend", "(", "self", ".", "config", ",", "config", ",", "true", ",", "true", ")", ";", "self", ".", "callActions", "(", "'afterConfigure'", ",", "arguments", ")", ";", "}" ]
Updates the configuration of the mixer, after it has been instantiated. See the Configuration Object documentation for a full list of avilable configuration options. @example .configure(config) @example <caption>Example 1: Updating animation options</caption> mixer.configure({ animation: { effects: 'fade translateX(-100%)', duration: 300 } }); @example <caption>Example 2: Removing a callback after it has been set</caption> var mixer; function handleMixEndOnce() { // Do something .. // Then nullify the callback mixer.configure({ callbacks: { onMixEnd: null } }); }; // Instantiate a mixer with a callback defined mixer = mixitup(containerEl, { callbacks: { onMixEnd: handleMixEndOnce } }); @public @instance @since 3.0.0 @param {object} config An object containing one of more configuration options. @return {void}
[ "Updates", "the", "configuration", "of", "the", "mixer", "after", "it", "has", "been", "instantiated", "." ]
4e7a5a0460b4eb097dfe9ff2db15853eccc779d7
https://github.com/octoblu/meshblu/blob/4e7a5a0460b4eb097dfe9ff2db15853eccc779d7/docs/vendor/mixitup/mixitup.js#L8952-L8960
20,014
octoblu/meshblu
docs/vendor/mixitup/mixitup.js
function() { var self = this, state = null; state = new mixitup.State(); h.extend(state, self.state); h.freeze(state); return self.callFilters('stateGetState', state, arguments); }
javascript
function() { var self = this, state = null; state = new mixitup.State(); h.extend(state, self.state); h.freeze(state); return self.callFilters('stateGetState', state, arguments); }
[ "function", "(", ")", "{", "var", "self", "=", "this", ",", "state", "=", "null", ";", "state", "=", "new", "mixitup", ".", "State", "(", ")", ";", "h", ".", "extend", "(", "state", ",", "self", ".", "state", ")", ";", "h", ".", "freeze", "(", "state", ")", ";", "return", "self", ".", "callFilters", "(", "'stateGetState'", ",", "state", ",", "arguments", ")", ";", "}" ]
Returns an object containing information about the current state of the mixer. See the State Object documentation for more information. NB: State objects are immutable and should therefore be regenerated after any operation. @example .getState(); @example <caption>Example: Retrieving a state object</caption> var state = mixer.getState(); console.log(state.totalShow + 'targets are currently shown'); @public @instance @since 2.0.0 @return {mixitup.State} An object reflecting the current state of the mixer.
[ "Returns", "an", "object", "containing", "information", "about", "the", "current", "state", "of", "the", "mixer", ".", "See", "the", "State", "Object", "documentation", "for", "more", "information", "." ]
4e7a5a0460b4eb097dfe9ff2db15853eccc779d7
https://github.com/octoblu/meshblu/blob/4e7a5a0460b4eb097dfe9ff2db15853eccc779d7/docs/vendor/mixitup/mixitup.js#L8985-L8996
20,015
octoblu/meshblu
docs/vendor/mixitup/mixitup.js
function(cleanUp) { var self = this, control = null, target = null, i = 0; self.callActions('beforeDestroy', arguments); for (i = 0; control = self.controls[i]; i++) { control.removeBinding(self); } for (i = 0; target = self.targets[i]; i++) { if (cleanUp) { target.show(); } target.unbindEvents(); } if (self.dom.container.id.match(/^MixItUp/)) { self.dom.container.removeAttribute('id'); } delete mixitup.instances[self.id]; self.callActions('afterDestroy', arguments); }
javascript
function(cleanUp) { var self = this, control = null, target = null, i = 0; self.callActions('beforeDestroy', arguments); for (i = 0; control = self.controls[i]; i++) { control.removeBinding(self); } for (i = 0; target = self.targets[i]; i++) { if (cleanUp) { target.show(); } target.unbindEvents(); } if (self.dom.container.id.match(/^MixItUp/)) { self.dom.container.removeAttribute('id'); } delete mixitup.instances[self.id]; self.callActions('afterDestroy', arguments); }
[ "function", "(", "cleanUp", ")", "{", "var", "self", "=", "this", ",", "control", "=", "null", ",", "target", "=", "null", ",", "i", "=", "0", ";", "self", ".", "callActions", "(", "'beforeDestroy'", ",", "arguments", ")", ";", "for", "(", "i", "=", "0", ";", "control", "=", "self", ".", "controls", "[", "i", "]", ";", "i", "++", ")", "{", "control", ".", "removeBinding", "(", "self", ")", ";", "}", "for", "(", "i", "=", "0", ";", "target", "=", "self", ".", "targets", "[", "i", "]", ";", "i", "++", ")", "{", "if", "(", "cleanUp", ")", "{", "target", ".", "show", "(", ")", ";", "}", "target", ".", "unbindEvents", "(", ")", ";", "}", "if", "(", "self", ".", "dom", ".", "container", ".", "id", ".", "match", "(", "/", "^MixItUp", "/", ")", ")", "{", "self", ".", "dom", ".", "container", ".", "removeAttribute", "(", "'id'", ")", ";", "}", "delete", "mixitup", ".", "instances", "[", "self", ".", "id", "]", ";", "self", ".", "callActions", "(", "'afterDestroy'", ",", "arguments", ")", ";", "}" ]
Removes mixitup functionality from the container, unbinds all control event handlers, and deletes the mixer instance from MixItUp's internal cache. This should be performed whenever a mixer's container is removed from the DOM, such as during a page change in a single page application, or React's `componentWillUnmount()`. @example .destroy([cleanUp]) @example <caption>Example: Destroying the mixer before removing its container element</caption> mixer.destroy(); containerEl.parentElement.removeChild(containerEl); @public @instance @since 2.0.0 @param {boolean} [cleanUp=false] An optional boolean dictating whether or not to clean up any inline `display: none;` styling applied to hidden targets. @return {void}
[ "Removes", "mixitup", "functionality", "from", "the", "container", "unbinds", "all", "control", "event", "handlers", "and", "deletes", "the", "mixer", "instance", "from", "MixItUp", "s", "internal", "cache", "." ]
4e7a5a0460b4eb097dfe9ff2db15853eccc779d7
https://github.com/octoblu/meshblu/blob/4e7a5a0460b4eb097dfe9ff2db15853eccc779d7/docs/vendor/mixitup/mixitup.js#L9069-L9096
20,016
octoblu/meshblu
docs/vendor/mixitup/mixitup.js
function(el, mixer, data) { var self = this, id = ''; self.callActions('beforeInit', arguments); self.mixer = mixer; if (!el) { // If no element is provided, render it el = self.render(data); } self.cacheDom(el); self.bindEvents(); if (self.dom.el.style.display !== 'none') { self.isShown = true; } if (data && mixer.config.data.uidKey) { if (typeof (id = data[mixer.config.data.uidKey]) === 'undefined' || id.toString().length < 1) { throw new TypeError(mixitup.messages.errorDatasetInvalidUidKey({ uidKey: mixer.config.data.uidKey })); } self.id = id; self.data = data; mixer.cache[id] = self; } self.callActions('afterInit', arguments); }
javascript
function(el, mixer, data) { var self = this, id = ''; self.callActions('beforeInit', arguments); self.mixer = mixer; if (!el) { // If no element is provided, render it el = self.render(data); } self.cacheDom(el); self.bindEvents(); if (self.dom.el.style.display !== 'none') { self.isShown = true; } if (data && mixer.config.data.uidKey) { if (typeof (id = data[mixer.config.data.uidKey]) === 'undefined' || id.toString().length < 1) { throw new TypeError(mixitup.messages.errorDatasetInvalidUidKey({ uidKey: mixer.config.data.uidKey })); } self.id = id; self.data = data; mixer.cache[id] = self; } self.callActions('afterInit', arguments); }
[ "function", "(", "el", ",", "mixer", ",", "data", ")", "{", "var", "self", "=", "this", ",", "id", "=", "''", ";", "self", ".", "callActions", "(", "'beforeInit'", ",", "arguments", ")", ";", "self", ".", "mixer", "=", "mixer", ";", "if", "(", "!", "el", ")", "{", "// If no element is provided, render it", "el", "=", "self", ".", "render", "(", "data", ")", ";", "}", "self", ".", "cacheDom", "(", "el", ")", ";", "self", ".", "bindEvents", "(", ")", ";", "if", "(", "self", ".", "dom", ".", "el", ".", "style", ".", "display", "!==", "'none'", ")", "{", "self", ".", "isShown", "=", "true", ";", "}", "if", "(", "data", "&&", "mixer", ".", "config", ".", "data", ".", "uidKey", ")", "{", "if", "(", "typeof", "(", "id", "=", "data", "[", "mixer", ".", "config", ".", "data", ".", "uidKey", "]", ")", "===", "'undefined'", "||", "id", ".", "toString", "(", ")", ".", "length", "<", "1", ")", "{", "throw", "new", "TypeError", "(", "mixitup", ".", "messages", ".", "errorDatasetInvalidUidKey", "(", "{", "uidKey", ":", "mixer", ".", "config", ".", "data", ".", "uidKey", "}", ")", ")", ";", "}", "self", ".", "id", "=", "id", ";", "self", ".", "data", "=", "data", ";", "mixer", ".", "cache", "[", "id", "]", "=", "self", ";", "}", "self", ".", "callActions", "(", "'afterInit'", ",", "arguments", ")", ";", "}" ]
Initialises a newly instantiated Target. @private @instance @since 3.0.0 @param {(Element|null)} el @param {object} mixer @param {object} [data] @return {void}
[ "Initialises", "a", "newly", "instantiated", "Target", "." ]
4e7a5a0460b4eb097dfe9ff2db15853eccc779d7
https://github.com/octoblu/meshblu/blob/4e7a5a0460b4eb097dfe9ff2db15853eccc779d7/docs/vendor/mixitup/mixitup.js#L9205-L9241
20,017
octoblu/meshblu
docs/vendor/mixitup/mixitup.js
function(data) { var self = this, render = null, el = null, temp = null, output = ''; self.callActions('beforeRender', arguments); render = self.callFilters('renderRender', self.mixer.config.render.target, arguments); if (typeof render !== 'function') { throw new TypeError(mixitup.messages.errorDatasetRendererNotSet()); } output = render(data); if (output && typeof output === 'object' && h.isElement(output)) { el = output; } else if (typeof output === 'string') { temp = document.createElement('div'); temp.innerHTML = output; el = temp.firstElementChild; } return self.callFilters('elRender', el, arguments); }
javascript
function(data) { var self = this, render = null, el = null, temp = null, output = ''; self.callActions('beforeRender', arguments); render = self.callFilters('renderRender', self.mixer.config.render.target, arguments); if (typeof render !== 'function') { throw new TypeError(mixitup.messages.errorDatasetRendererNotSet()); } output = render(data); if (output && typeof output === 'object' && h.isElement(output)) { el = output; } else if (typeof output === 'string') { temp = document.createElement('div'); temp.innerHTML = output; el = temp.firstElementChild; } return self.callFilters('elRender', el, arguments); }
[ "function", "(", "data", ")", "{", "var", "self", "=", "this", ",", "render", "=", "null", ",", "el", "=", "null", ",", "temp", "=", "null", ",", "output", "=", "''", ";", "self", ".", "callActions", "(", "'beforeRender'", ",", "arguments", ")", ";", "render", "=", "self", ".", "callFilters", "(", "'renderRender'", ",", "self", ".", "mixer", ".", "config", ".", "render", ".", "target", ",", "arguments", ")", ";", "if", "(", "typeof", "render", "!==", "'function'", ")", "{", "throw", "new", "TypeError", "(", "mixitup", ".", "messages", ".", "errorDatasetRendererNotSet", "(", ")", ")", ";", "}", "output", "=", "render", "(", "data", ")", ";", "if", "(", "output", "&&", "typeof", "output", "===", "'object'", "&&", "h", ".", "isElement", "(", "output", ")", ")", "{", "el", "=", "output", ";", "}", "else", "if", "(", "typeof", "output", "===", "'string'", ")", "{", "temp", "=", "document", ".", "createElement", "(", "'div'", ")", ";", "temp", ".", "innerHTML", "=", "output", ";", "el", "=", "temp", ".", "firstElementChild", ";", "}", "return", "self", ".", "callFilters", "(", "'elRender'", ",", "el", ",", "arguments", ")", ";", "}" ]
Renders the target element using a user-defined renderer function. @private @instance @since 3.1.4 @param {object} data @return {void}
[ "Renders", "the", "target", "element", "using", "a", "user", "-", "defined", "renderer", "function", "." ]
4e7a5a0460b4eb097dfe9ff2db15853eccc779d7
https://github.com/octoblu/meshblu/blob/4e7a5a0460b4eb097dfe9ff2db15853eccc779d7/docs/vendor/mixitup/mixitup.js#L9253-L9280
20,018
octoblu/meshblu
docs/vendor/mixitup/mixitup.js
function(el) { var self = this; self.callActions('beforeCacheDom', arguments); self.dom.el = el; self.callActions('afterCacheDom', arguments); }
javascript
function(el) { var self = this; self.callActions('beforeCacheDom', arguments); self.dom.el = el; self.callActions('afterCacheDom', arguments); }
[ "function", "(", "el", ")", "{", "var", "self", "=", "this", ";", "self", ".", "callActions", "(", "'beforeCacheDom'", ",", "arguments", ")", ";", "self", ".", "dom", ".", "el", "=", "el", ";", "self", ".", "callActions", "(", "'afterCacheDom'", ",", "arguments", ")", ";", "}" ]
Caches references of DOM elements neccessary for the target's functionality. @private @instance @since 3.0.0 @param {Element} el @return {void}
[ "Caches", "references", "of", "DOM", "elements", "neccessary", "for", "the", "target", "s", "functionality", "." ]
4e7a5a0460b4eb097dfe9ff2db15853eccc779d7
https://github.com/octoblu/meshblu/blob/4e7a5a0460b4eb097dfe9ff2db15853eccc779d7/docs/vendor/mixitup/mixitup.js#L9292-L9300
20,019
octoblu/meshblu
docs/vendor/mixitup/mixitup.js
function(moveData) { var self = this, posIn = moveData.posIn, isFading = self.mixer.effectsIn.opacity !== 1, transformValues = []; self.callActions('beforeApplyStylesIn', arguments); transformValues.push('translate(' + posIn.x + 'px, ' + posIn.y + 'px)'); if (self.mixer.config.animation.animateResizeTargets) { if (moveData.statusChange !== 'show') { // Don't apply posIn width or height or showing, as will be 0 self.dom.el.style.width = posIn.width + 'px'; self.dom.el.style.height = posIn.height + 'px'; } self.dom.el.style.marginRight = posIn.marginRight + 'px'; self.dom.el.style.marginBottom = posIn.marginBottom + 'px'; } isFading && (self.dom.el.style.opacity = posIn.opacity); if (moveData.statusChange === 'show') { transformValues = transformValues.concat(self.mixer.transformIn); } self.dom.el.style[mixitup.features.transformProp] = transformValues.join(' '); self.callActions('afterApplyStylesIn', arguments); }
javascript
function(moveData) { var self = this, posIn = moveData.posIn, isFading = self.mixer.effectsIn.opacity !== 1, transformValues = []; self.callActions('beforeApplyStylesIn', arguments); transformValues.push('translate(' + posIn.x + 'px, ' + posIn.y + 'px)'); if (self.mixer.config.animation.animateResizeTargets) { if (moveData.statusChange !== 'show') { // Don't apply posIn width or height or showing, as will be 0 self.dom.el.style.width = posIn.width + 'px'; self.dom.el.style.height = posIn.height + 'px'; } self.dom.el.style.marginRight = posIn.marginRight + 'px'; self.dom.el.style.marginBottom = posIn.marginBottom + 'px'; } isFading && (self.dom.el.style.opacity = posIn.opacity); if (moveData.statusChange === 'show') { transformValues = transformValues.concat(self.mixer.transformIn); } self.dom.el.style[mixitup.features.transformProp] = transformValues.join(' '); self.callActions('afterApplyStylesIn', arguments); }
[ "function", "(", "moveData", ")", "{", "var", "self", "=", "this", ",", "posIn", "=", "moveData", ".", "posIn", ",", "isFading", "=", "self", ".", "mixer", ".", "effectsIn", ".", "opacity", "!==", "1", ",", "transformValues", "=", "[", "]", ";", "self", ".", "callActions", "(", "'beforeApplyStylesIn'", ",", "arguments", ")", ";", "transformValues", ".", "push", "(", "'translate('", "+", "posIn", ".", "x", "+", "'px, '", "+", "posIn", ".", "y", "+", "'px)'", ")", ";", "if", "(", "self", ".", "mixer", ".", "config", ".", "animation", ".", "animateResizeTargets", ")", "{", "if", "(", "moveData", ".", "statusChange", "!==", "'show'", ")", "{", "// Don't apply posIn width or height or showing, as will be 0", "self", ".", "dom", ".", "el", ".", "style", ".", "width", "=", "posIn", ".", "width", "+", "'px'", ";", "self", ".", "dom", ".", "el", ".", "style", ".", "height", "=", "posIn", ".", "height", "+", "'px'", ";", "}", "self", ".", "dom", ".", "el", ".", "style", ".", "marginRight", "=", "posIn", ".", "marginRight", "+", "'px'", ";", "self", ".", "dom", ".", "el", ".", "style", ".", "marginBottom", "=", "posIn", ".", "marginBottom", "+", "'px'", ";", "}", "isFading", "&&", "(", "self", ".", "dom", ".", "el", ".", "style", ".", "opacity", "=", "posIn", ".", "opacity", ")", ";", "if", "(", "moveData", ".", "statusChange", "===", "'show'", ")", "{", "transformValues", "=", "transformValues", ".", "concat", "(", "self", ".", "mixer", ".", "transformIn", ")", ";", "}", "self", ".", "dom", ".", "el", ".", "style", "[", "mixitup", ".", "features", ".", "transformProp", "]", "=", "transformValues", ".", "join", "(", "' '", ")", ";", "self", ".", "callActions", "(", "'afterApplyStylesIn'", ",", "arguments", ")", ";", "}" ]
Applies the initial styling to a target element before any transition is applied. @private @instance @param {mixitup.IMoveData} moveData @return {void}
[ "Applies", "the", "initial", "styling", "to", "a", "target", "element", "before", "any", "transition", "is", "applied", "." ]
4e7a5a0460b4eb097dfe9ff2db15853eccc779d7
https://github.com/octoblu/meshblu/blob/4e7a5a0460b4eb097dfe9ff2db15853eccc779d7/docs/vendor/mixitup/mixitup.js#L9474-L9505
20,020
octoblu/meshblu
docs/vendor/mixitup/mixitup.js
function(property, staggerIndex, duration) { var self = this, delay = self.getDelay(staggerIndex), rule = ''; rule = property + ' ' + (duration > 0 ? duration : self.mixer.config.animation.duration) + 'ms ' + delay + 'ms ' + (property === 'opacity' ? 'linear' : self.mixer.config.animation.easing); return self.callFilters('ruleWriteTransitionRule', rule, arguments); }
javascript
function(property, staggerIndex, duration) { var self = this, delay = self.getDelay(staggerIndex), rule = ''; rule = property + ' ' + (duration > 0 ? duration : self.mixer.config.animation.duration) + 'ms ' + delay + 'ms ' + (property === 'opacity' ? 'linear' : self.mixer.config.animation.easing); return self.callFilters('ruleWriteTransitionRule', rule, arguments); }
[ "function", "(", "property", ",", "staggerIndex", ",", "duration", ")", "{", "var", "self", "=", "this", ",", "delay", "=", "self", ".", "getDelay", "(", "staggerIndex", ")", ",", "rule", "=", "''", ";", "rule", "=", "property", "+", "' '", "+", "(", "duration", ">", "0", "?", "duration", ":", "self", ".", "mixer", ".", "config", ".", "animation", ".", "duration", ")", "+", "'ms '", "+", "delay", "+", "'ms '", "+", "(", "property", "===", "'opacity'", "?", "'linear'", ":", "self", ".", "mixer", ".", "config", ".", "animation", ".", "easing", ")", ";", "return", "self", ".", "callFilters", "(", "'ruleWriteTransitionRule'", ",", "rule", ",", "arguments", ")", ";", "}" ]
Combines the name of a CSS property with the appropriate duration and delay values to created a valid transition rule. @private @instance @since 3.0.0 @param {string} property @param {number} staggerIndex @param {number} duration @return {string}
[ "Combines", "the", "name", "of", "a", "CSS", "property", "with", "the", "appropriate", "duration", "and", "delay", "values", "to", "created", "a", "valid", "transition", "rule", "." ]
4e7a5a0460b4eb097dfe9ff2db15853eccc779d7
https://github.com/octoblu/meshblu/blob/4e7a5a0460b4eb097dfe9ff2db15853eccc779d7/docs/vendor/mixitup/mixitup.js#L9658-L9669
20,021
octoblu/meshblu
docs/vendor/mixitup/mixitup.js
function(methodName) { var self = this, instance = null, args = Array.prototype.slice.call(arguments), tasks = [], i = -1; this.callActions('beforeMixitup'); args.shift(); for (i = 0; instance = self[i]; i++) { tasks.push(instance[methodName].apply(instance, args)); } return self.callFilters('promiseMixitup', h.all(tasks, mixitup.libraries), arguments); }
javascript
function(methodName) { var self = this, instance = null, args = Array.prototype.slice.call(arguments), tasks = [], i = -1; this.callActions('beforeMixitup'); args.shift(); for (i = 0; instance = self[i]; i++) { tasks.push(instance[methodName].apply(instance, args)); } return self.callFilters('promiseMixitup', h.all(tasks, mixitup.libraries), arguments); }
[ "function", "(", "methodName", ")", "{", "var", "self", "=", "this", ",", "instance", "=", "null", ",", "args", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ")", ",", "tasks", "=", "[", "]", ",", "i", "=", "-", "1", ";", "this", ".", "callActions", "(", "'beforeMixitup'", ")", ";", "args", ".", "shift", "(", ")", ";", "for", "(", "i", "=", "0", ";", "instance", "=", "self", "[", "i", "]", ";", "i", "++", ")", "{", "tasks", ".", "push", "(", "instance", "[", "methodName", "]", ".", "apply", "(", "instance", ",", "args", ")", ")", ";", "}", "return", "self", ".", "callFilters", "(", "'promiseMixitup'", ",", "h", ".", "all", "(", "tasks", ",", "mixitup", ".", "libraries", ")", ",", "arguments", ")", ";", "}" ]
Calls a method on all instances in the collection by passing the method name as a string followed by any applicable parameters to be curried into to the method. @example .mixitup(methodName[,arg1][,arg2..]); @example var collection = new Collection([mixer1, mixer2]); return collection.mixitup('filter', '.category-a') .then(function(states) { state.forEach(function(state) { console.log(state.activeFilter.selector); // .category-a }); }); @public @instance @since 3.0.0 @param {string} methodName @return {Promise<Array<mixitup.State>>}
[ "Calls", "a", "method", "on", "all", "instances", "in", "the", "collection", "by", "passing", "the", "method", "name", "as", "a", "string", "followed", "by", "any", "applicable", "parameters", "to", "be", "curried", "into", "to", "the", "method", "." ]
4e7a5a0460b4eb097dfe9ff2db15853eccc779d7
https://github.com/octoblu/meshblu/blob/4e7a5a0460b4eb097dfe9ff2db15853eccc779d7/docs/vendor/mixitup/mixitup.js#L9950-L9966
20,022
sbyrnes/likely.js
likely.js
buildModelWithBias
function buildModelWithBias(inputArray, bias, rowLabels, colLabels) { var model = new Model($M(inputArray), rowLabels, colLabels); model.estimated = train(sylvester.Matrix.create(inputArray), bias); return model }
javascript
function buildModelWithBias(inputArray, bias, rowLabels, colLabels) { var model = new Model($M(inputArray), rowLabels, colLabels); model.estimated = train(sylvester.Matrix.create(inputArray), bias); return model }
[ "function", "buildModelWithBias", "(", "inputArray", ",", "bias", ",", "rowLabels", ",", "colLabels", ")", "{", "var", "model", "=", "new", "Model", "(", "$M", "(", "inputArray", ")", ",", "rowLabels", ",", "colLabels", ")", ";", "model", ".", "estimated", "=", "train", "(", "sylvester", ".", "Matrix", ".", "create", "(", "inputArray", ")", ",", "bias", ")", ";", "return", "model", "}" ]
Builds a complete model from the input array with bias @param inputArray A two dimensional array of the input, where each cell is the rating given to Col by Row @param bias A two dimensional matrix of the bias of the inputArray @param [optional] rowLabels A one dimensional array of string labels for each row of inputArray @param [optional] colLabels A one dimensional array of string labels for each column of inputArray @returns Model An instance of a Model object
[ "Builds", "a", "complete", "model", "from", "the", "input", "array", "with", "bias" ]
15077ae61b66eb6a61438cac8cb1dc9ec4edf558
https://github.com/sbyrnes/likely.js/blob/15077ae61b66eb6a61438cac8cb1dc9ec4edf558/likely.js#L35-L41
20,023
sbyrnes/likely.js
likely.js
train
function train(inputMatrix, bias) { N = inputMatrix.rows(); // number of rows M = inputMatrix.cols(); // number of columns // Generate random P and Q based on the dimensions of inputMatrix var P_model = generateRandomMatrix(N, K); var Q_model = generateRandomMatrix(K, M); var i = 0 for(i = 0; i < DESCENT_STEPS; i++) { //console.log('------------------ Iteration --------------------'); // Calculate error var error = calculateError(P_model.x(Q_model), inputMatrix, bias); P_prime = P_model.elements; Q_prime = Q_model.elements; // For debugging //console.log('P: ' + JSON.stringify(P_prime)); //console.log('Q: ' + JSON.stringify(Q_prime)); // Update P and Q to reduce error for (var row = 0; row < N; row++) { for (var col = 0; col < M; col++) { for(var feature = 0; feature < K; feature++) { // update formulas will change values in the opposite direction of the gradient. // P Update Formula // p_ik = p_ik + alpha * (e_ij * q_kj - beta * p_ik) // Reverse Gradient: alpha * e_ij * q_kj -- Note that we omit the 2* factor since it's not necessary for convergence. // Regularization factor: alpha * beta * p_ik var p_prev = P_prime[row][feature]; P_prime[row][feature] = P_prime[row][feature] + ALPHA*(error.e(row+1, col+1)*Q_prime[feature][col] - BETA * P_prime[row][feature]); //console.log('P['+row+']['+feature+'] ('+p_prev+') <- ('+P_prime[row][feature]+')'); // Q Update Formula // q_kj = q_kj + alpha x (e_ij x p_ik - beta x q_kj) // Reverse Gradient: alpha * e_ij * p_ik -- Note that we omit the 2* factor since it's not necessary for convergence. // Regularization factor: alpha * beta * q_kj var q_prev = Q_prime[feature][col]; Q_prime[feature][col] = Q_prime[feature][col] + ALPHA *(error.e(row+1, col+1)*P_prime[row][feature] - BETA * Q_prime[feature][col]); //console.log('Q['+feature+']['+col+'] ('+q_prev+') <- ('+Q_prime[feature][col]+')'); } } } // if we've already reached the error threshold, no need to descend further var totError = calculateTotalError(error); if(totError < MAX_ERROR) { //console.log('Reached error threshold early, no more descent needed.'); break; } } //console.log('Descent steps used: ' + i); // produce the final estimation by multiplying P and Q var finalModel = P_model.x(Q_model); // if we were considering bias, we have to add it back in if(bias) { // add back the overall average finalModel = finalModel.map(function(x) { return x + bias.average; }); var finalElements = finalModel.elements; // add back the row bias from each row for(var i = 1; i <= finalModel.rows(); i++) { for(var j = 1; j <= finalModel.cols(); j++) { finalElements[i-1][j-1] += bias.rowBiases.e(i); } } // add back the column bias from each column for(var i = 1; i <= finalModel.rows(); i++) { for(var j = 1; j <= finalModel.cols(); j++) { finalElements[i-1][j-1] += bias.colBiases.e(j); } } } return finalModel; }
javascript
function train(inputMatrix, bias) { N = inputMatrix.rows(); // number of rows M = inputMatrix.cols(); // number of columns // Generate random P and Q based on the dimensions of inputMatrix var P_model = generateRandomMatrix(N, K); var Q_model = generateRandomMatrix(K, M); var i = 0 for(i = 0; i < DESCENT_STEPS; i++) { //console.log('------------------ Iteration --------------------'); // Calculate error var error = calculateError(P_model.x(Q_model), inputMatrix, bias); P_prime = P_model.elements; Q_prime = Q_model.elements; // For debugging //console.log('P: ' + JSON.stringify(P_prime)); //console.log('Q: ' + JSON.stringify(Q_prime)); // Update P and Q to reduce error for (var row = 0; row < N; row++) { for (var col = 0; col < M; col++) { for(var feature = 0; feature < K; feature++) { // update formulas will change values in the opposite direction of the gradient. // P Update Formula // p_ik = p_ik + alpha * (e_ij * q_kj - beta * p_ik) // Reverse Gradient: alpha * e_ij * q_kj -- Note that we omit the 2* factor since it's not necessary for convergence. // Regularization factor: alpha * beta * p_ik var p_prev = P_prime[row][feature]; P_prime[row][feature] = P_prime[row][feature] + ALPHA*(error.e(row+1, col+1)*Q_prime[feature][col] - BETA * P_prime[row][feature]); //console.log('P['+row+']['+feature+'] ('+p_prev+') <- ('+P_prime[row][feature]+')'); // Q Update Formula // q_kj = q_kj + alpha x (e_ij x p_ik - beta x q_kj) // Reverse Gradient: alpha * e_ij * p_ik -- Note that we omit the 2* factor since it's not necessary for convergence. // Regularization factor: alpha * beta * q_kj var q_prev = Q_prime[feature][col]; Q_prime[feature][col] = Q_prime[feature][col] + ALPHA *(error.e(row+1, col+1)*P_prime[row][feature] - BETA * Q_prime[feature][col]); //console.log('Q['+feature+']['+col+'] ('+q_prev+') <- ('+Q_prime[feature][col]+')'); } } } // if we've already reached the error threshold, no need to descend further var totError = calculateTotalError(error); if(totError < MAX_ERROR) { //console.log('Reached error threshold early, no more descent needed.'); break; } } //console.log('Descent steps used: ' + i); // produce the final estimation by multiplying P and Q var finalModel = P_model.x(Q_model); // if we were considering bias, we have to add it back in if(bias) { // add back the overall average finalModel = finalModel.map(function(x) { return x + bias.average; }); var finalElements = finalModel.elements; // add back the row bias from each row for(var i = 1; i <= finalModel.rows(); i++) { for(var j = 1; j <= finalModel.cols(); j++) { finalElements[i-1][j-1] += bias.rowBiases.e(i); } } // add back the column bias from each column for(var i = 1; i <= finalModel.rows(); i++) { for(var j = 1; j <= finalModel.cols(); j++) { finalElements[i-1][j-1] += bias.colBiases.e(j); } } } return finalModel; }
[ "function", "train", "(", "inputMatrix", ",", "bias", ")", "{", "N", "=", "inputMatrix", ".", "rows", "(", ")", ";", "// number of rows ", "M", "=", "inputMatrix", ".", "cols", "(", ")", ";", "// number of columns", "// Generate random P and Q based on the dimensions of inputMatrix", "var", "P_model", "=", "generateRandomMatrix", "(", "N", ",", "K", ")", ";", "var", "Q_model", "=", "generateRandomMatrix", "(", "K", ",", "M", ")", ";", "var", "i", "=", "0", "for", "(", "i", "=", "0", ";", "i", "<", "DESCENT_STEPS", ";", "i", "++", ")", "{", "//console.log('------------------ Iteration --------------------');", "// Calculate error", "var", "error", "=", "calculateError", "(", "P_model", ".", "x", "(", "Q_model", ")", ",", "inputMatrix", ",", "bias", ")", ";", "P_prime", "=", "P_model", ".", "elements", ";", "Q_prime", "=", "Q_model", ".", "elements", ";", "// For debugging", "//console.log('P: ' + JSON.stringify(P_prime));", "//console.log('Q: ' + JSON.stringify(Q_prime));", "// Update P and Q to reduce error", "for", "(", "var", "row", "=", "0", ";", "row", "<", "N", ";", "row", "++", ")", "{", "for", "(", "var", "col", "=", "0", ";", "col", "<", "M", ";", "col", "++", ")", "{", "for", "(", "var", "feature", "=", "0", ";", "feature", "<", "K", ";", "feature", "++", ")", "{", "// update formulas will change values in the opposite direction of the gradient.", "// P Update Formula", "// p_ik = p_ik + alpha * (e_ij * q_kj - beta * p_ik)", "// Reverse Gradient: alpha * e_ij * q_kj -- Note that we omit the 2* factor since it's not necessary for convergence.", "// Regularization factor: alpha * beta * p_ik ", "var", "p_prev", "=", "P_prime", "[", "row", "]", "[", "feature", "]", ";", "P_prime", "[", "row", "]", "[", "feature", "]", "=", "P_prime", "[", "row", "]", "[", "feature", "]", "+", "ALPHA", "*", "(", "error", ".", "e", "(", "row", "+", "1", ",", "col", "+", "1", ")", "*", "Q_prime", "[", "feature", "]", "[", "col", "]", "-", "BETA", "*", "P_prime", "[", "row", "]", "[", "feature", "]", ")", ";", "//console.log('P['+row+']['+feature+'] ('+p_prev+') <- ('+P_prime[row][feature]+')');", "// Q Update Formula", "// q_kj = q_kj + alpha x (e_ij x p_ik - beta x q_kj)", "// Reverse Gradient: alpha * e_ij * p_ik -- Note that we omit the 2* factor since it's not necessary for convergence.", "// Regularization factor: alpha * beta * q_kj ", "var", "q_prev", "=", "Q_prime", "[", "feature", "]", "[", "col", "]", ";", "Q_prime", "[", "feature", "]", "[", "col", "]", "=", "Q_prime", "[", "feature", "]", "[", "col", "]", "+", "ALPHA", "*", "(", "error", ".", "e", "(", "row", "+", "1", ",", "col", "+", "1", ")", "*", "P_prime", "[", "row", "]", "[", "feature", "]", "-", "BETA", "*", "Q_prime", "[", "feature", "]", "[", "col", "]", ")", ";", "//console.log('Q['+feature+']['+col+'] ('+q_prev+') <- ('+Q_prime[feature][col]+')');\t\t\t\t\t\t\t\t \t ", "}", "}", "}", "// if we've already reached the error threshold, no need to descend further", "var", "totError", "=", "calculateTotalError", "(", "error", ")", ";", "if", "(", "totError", "<", "MAX_ERROR", ")", "{", "//console.log('Reached error threshold early, no more descent needed.');", "break", ";", "}", "}", "//console.log('Descent steps used: ' + i);", "// produce the final estimation by multiplying P and Q", "var", "finalModel", "=", "P_model", ".", "x", "(", "Q_model", ")", ";", "// if we were considering bias, we have to add it back in", "if", "(", "bias", ")", "{", "// add back the overall average", "finalModel", "=", "finalModel", ".", "map", "(", "function", "(", "x", ")", "{", "return", "x", "+", "bias", ".", "average", ";", "}", ")", ";", "var", "finalElements", "=", "finalModel", ".", "elements", ";", "// add back the row bias from each row", "for", "(", "var", "i", "=", "1", ";", "i", "<=", "finalModel", ".", "rows", "(", ")", ";", "i", "++", ")", "{", "for", "(", "var", "j", "=", "1", ";", "j", "<=", "finalModel", ".", "cols", "(", ")", ";", "j", "++", ")", "{", "finalElements", "[", "i", "-", "1", "]", "[", "j", "-", "1", "]", "+=", "bias", ".", "rowBiases", ".", "e", "(", "i", ")", ";", "}", "}", "// add back the column bias from each column", "for", "(", "var", "i", "=", "1", ";", "i", "<=", "finalModel", ".", "rows", "(", ")", ";", "i", "++", ")", "{", "for", "(", "var", "j", "=", "1", ";", "j", "<=", "finalModel", ".", "cols", "(", ")", ";", "j", "++", ")", "{", "finalElements", "[", "i", "-", "1", "]", "[", "j", "-", "1", "]", "+=", "bias", ".", "colBiases", ".", "e", "(", "j", ")", ";", "}", "}", "}", "return", "finalModel", ";", "}" ]
Trains the model on the given input by composing two matrices P and Q which approximate the input through their product. @param inputMatrix A two dimensional array representing input values @returns Model A model entity, with estimated values based on the input
[ "Trains", "the", "model", "on", "the", "given", "input", "by", "composing", "two", "matrices", "P", "and", "Q", "which", "approximate", "the", "input", "through", "their", "product", "." ]
15077ae61b66eb6a61438cac8cb1dc9ec4edf558
https://github.com/sbyrnes/likely.js/blob/15077ae61b66eb6a61438cac8cb1dc9ec4edf558/likely.js#L49-L147
20,024
sbyrnes/likely.js
likely.js
calculateError
function calculateError(estimated, input, bias) { var adjustedInput = input.dup(); var adjustedElements = adjustedInput.elements; // If bias adjustment is provided, adjust for it if(bias) { // subtract the row and column bias from each row for(var i = 0; i <= adjustedInput.rows()-1; i++) { for(var j = 0; j <= adjustedInput.cols()-1; j++) { if(adjustedElements[i][j] == 0) continue; // skip zeroes adjustedElements[i][j] -= bias.average; adjustedElements[i][j] -= bias.rowBiases.e(i+1); adjustedElements[i][j] -= bias.colBiases.e(j+1); } } } var estimatedElements = estimated.elements; // Error is (R - R') // (but we ignore error on the zero entries since they are unknown) for(var i = 0; i <= adjustedInput.rows()-1; i++) { for(var j = 0; j <= adjustedInput.cols()-1; j++) { if(adjustedElements[i][j] == 0) continue; // skip zeroes adjustedElements[i][j] -= estimatedElements[i][j]; } } // Error is (R - R') return adjustedInput; }
javascript
function calculateError(estimated, input, bias) { var adjustedInput = input.dup(); var adjustedElements = adjustedInput.elements; // If bias adjustment is provided, adjust for it if(bias) { // subtract the row and column bias from each row for(var i = 0; i <= adjustedInput.rows()-1; i++) { for(var j = 0; j <= adjustedInput.cols()-1; j++) { if(adjustedElements[i][j] == 0) continue; // skip zeroes adjustedElements[i][j] -= bias.average; adjustedElements[i][j] -= bias.rowBiases.e(i+1); adjustedElements[i][j] -= bias.colBiases.e(j+1); } } } var estimatedElements = estimated.elements; // Error is (R - R') // (but we ignore error on the zero entries since they are unknown) for(var i = 0; i <= adjustedInput.rows()-1; i++) { for(var j = 0; j <= adjustedInput.cols()-1; j++) { if(adjustedElements[i][j] == 0) continue; // skip zeroes adjustedElements[i][j] -= estimatedElements[i][j]; } } // Error is (R - R') return adjustedInput; }
[ "function", "calculateError", "(", "estimated", ",", "input", ",", "bias", ")", "{", "var", "adjustedInput", "=", "input", ".", "dup", "(", ")", ";", "var", "adjustedElements", "=", "adjustedInput", ".", "elements", ";", "// If bias adjustment is provided, adjust for it", "if", "(", "bias", ")", "{", "// subtract the row and column bias from each row", "for", "(", "var", "i", "=", "0", ";", "i", "<=", "adjustedInput", ".", "rows", "(", ")", "-", "1", ";", "i", "++", ")", "{", "for", "(", "var", "j", "=", "0", ";", "j", "<=", "adjustedInput", ".", "cols", "(", ")", "-", "1", ";", "j", "++", ")", "{", "if", "(", "adjustedElements", "[", "i", "]", "[", "j", "]", "==", "0", ")", "continue", ";", "// skip zeroes", "adjustedElements", "[", "i", "]", "[", "j", "]", "-=", "bias", ".", "average", ";", "adjustedElements", "[", "i", "]", "[", "j", "]", "-=", "bias", ".", "rowBiases", ".", "e", "(", "i", "+", "1", ")", ";", "adjustedElements", "[", "i", "]", "[", "j", "]", "-=", "bias", ".", "colBiases", ".", "e", "(", "j", "+", "1", ")", ";", "}", "}", "}", "var", "estimatedElements", "=", "estimated", ".", "elements", ";", "// Error is (R - R')", "// (but we ignore error on the zero entries since they are unknown)", "for", "(", "var", "i", "=", "0", ";", "i", "<=", "adjustedInput", ".", "rows", "(", ")", "-", "1", ";", "i", "++", ")", "{", "for", "(", "var", "j", "=", "0", ";", "j", "<=", "adjustedInput", ".", "cols", "(", ")", "-", "1", ";", "j", "++", ")", "{", "if", "(", "adjustedElements", "[", "i", "]", "[", "j", "]", "==", "0", ")", "continue", ";", "// skip zeroes", "adjustedElements", "[", "i", "]", "[", "j", "]", "-=", "estimatedElements", "[", "i", "]", "[", "j", "]", ";", "}", "}", "// Error is (R - R')", "return", "adjustedInput", ";", "}" ]
Computes the error from model matrices P and Q against the given input. @param estimated A matrix of the estimated values. @param input A matrix of the input values @returns A matrix of size input.rows by input.columns where each entry is the difference between the input and estimated values.
[ "Computes", "the", "error", "from", "model", "matrices", "P", "and", "Q", "against", "the", "given", "input", "." ]
15077ae61b66eb6a61438cac8cb1dc9ec4edf558
https://github.com/sbyrnes/likely.js/blob/15077ae61b66eb6a61438cac8cb1dc9ec4edf558/likely.js#L166-L208
20,025
sbyrnes/likely.js
likely.js
calculateTotalError
function calculateTotalError(errorMatrix) { var totError = 0.0; for(var i = 1; i <= errorMatrix.rows(); i++) { for(var j = 1; j <= errorMatrix.cols(); j++) { totError += Math.pow(errorMatrix.e(i, j), 2); } } return totError; }
javascript
function calculateTotalError(errorMatrix) { var totError = 0.0; for(var i = 1; i <= errorMatrix.rows(); i++) { for(var j = 1; j <= errorMatrix.cols(); j++) { totError += Math.pow(errorMatrix.e(i, j), 2); } } return totError; }
[ "function", "calculateTotalError", "(", "errorMatrix", ")", "{", "var", "totError", "=", "0.0", ";", "for", "(", "var", "i", "=", "1", ";", "i", "<=", "errorMatrix", ".", "rows", "(", ")", ";", "i", "++", ")", "{", "for", "(", "var", "j", "=", "1", ";", "j", "<=", "errorMatrix", ".", "cols", "(", ")", ";", "j", "++", ")", "{", "totError", "+=", "Math", ".", "pow", "(", "errorMatrix", ".", "e", "(", "i", ",", "j", ")", ",", "2", ")", ";", "}", "}", "return", "totError", ";", "}" ]
Computes the total error based on a matrix of error values. @param errorMatrix A matrix of the error values. @returns float Total error, defined as the sum of the squared errors.
[ "Computes", "the", "total", "error", "based", "on", "a", "matrix", "of", "error", "values", "." ]
15077ae61b66eb6a61438cac8cb1dc9ec4edf558
https://github.com/sbyrnes/likely.js/blob/15077ae61b66eb6a61438cac8cb1dc9ec4edf558/likely.js#L226-L238
20,026
sbyrnes/likely.js
likely.js
calculateBias
function calculateBias(input) { var inputMatrix = $M(input); var average = calculateMatrixAverage(inputMatrix); var rowAverages = calculateRowAverage(inputMatrix); var colAverages = calculateColumnAverage(inputMatrix); var rowBiases = new Array(); var colBiases = new Array(); // The row bias is the difference between the row average and the overall average for(var i = 1; i <= rowAverages.dimensions().cols; i++) { rowBiases[i-1] = rowAverages.e(i) - average; } // the column bias is the difference between the column average and the overall average for(var i = 1; i <= colAverages.dimensions().cols; i++) { colBiases[i-1] = colAverages.e(i) - average; } var biases = new Bias(average, $V(rowBiases), $V(colBiases)); return biases; }
javascript
function calculateBias(input) { var inputMatrix = $M(input); var average = calculateMatrixAverage(inputMatrix); var rowAverages = calculateRowAverage(inputMatrix); var colAverages = calculateColumnAverage(inputMatrix); var rowBiases = new Array(); var colBiases = new Array(); // The row bias is the difference between the row average and the overall average for(var i = 1; i <= rowAverages.dimensions().cols; i++) { rowBiases[i-1] = rowAverages.e(i) - average; } // the column bias is the difference between the column average and the overall average for(var i = 1; i <= colAverages.dimensions().cols; i++) { colBiases[i-1] = colAverages.e(i) - average; } var biases = new Bias(average, $V(rowBiases), $V(colBiases)); return biases; }
[ "function", "calculateBias", "(", "input", ")", "{", "var", "inputMatrix", "=", "$M", "(", "input", ")", ";", "var", "average", "=", "calculateMatrixAverage", "(", "inputMatrix", ")", ";", "var", "rowAverages", "=", "calculateRowAverage", "(", "inputMatrix", ")", ";", "var", "colAverages", "=", "calculateColumnAverage", "(", "inputMatrix", ")", ";", "var", "rowBiases", "=", "new", "Array", "(", ")", ";", "var", "colBiases", "=", "new", "Array", "(", ")", ";", "// The row bias is the difference between the row average and the overall average", "for", "(", "var", "i", "=", "1", ";", "i", "<=", "rowAverages", ".", "dimensions", "(", ")", ".", "cols", ";", "i", "++", ")", "{", "rowBiases", "[", "i", "-", "1", "]", "=", "rowAverages", ".", "e", "(", "i", ")", "-", "average", ";", "}", "// the column bias is the difference between the column average and the overall average", "for", "(", "var", "i", "=", "1", ";", "i", "<=", "colAverages", ".", "dimensions", "(", ")", ".", "cols", ";", "i", "++", ")", "{", "colBiases", "[", "i", "-", "1", "]", "=", "colAverages", ".", "e", "(", "i", ")", "-", "average", ";", "}", "var", "biases", "=", "new", "Bias", "(", "average", ",", "$V", "(", "rowBiases", ")", ",", "$V", "(", "colBiases", ")", ")", ";", "return", "biases", ";", "}" ]
Computes the biases from a matrix of values. @param input A matrix of the input values @returns Bias Object containing the average, bias for rows and bias for columns.
[ "Computes", "the", "biases", "from", "a", "matrix", "of", "values", "." ]
15077ae61b66eb6a61438cac8cb1dc9ec4edf558
https://github.com/sbyrnes/likely.js/blob/15077ae61b66eb6a61438cac8cb1dc9ec4edf558/likely.js#L245-L270
20,027
sbyrnes/likely.js
likely.js
Bias
function Bias(average, rowBiases, colBiases) { this.average = average; // Overall value average this.rowBiases = rowBiases; // Bias for each row this.colBiases = colBiases; // Bias for each column }
javascript
function Bias(average, rowBiases, colBiases) { this.average = average; // Overall value average this.rowBiases = rowBiases; // Bias for each row this.colBiases = colBiases; // Bias for each column }
[ "function", "Bias", "(", "average", ",", "rowBiases", ",", "colBiases", ")", "{", "this", ".", "average", "=", "average", ";", "// Overall value average", "this", ".", "rowBiases", "=", "rowBiases", ";", "// Bias for each row", "this", ".", "colBiases", "=", "colBiases", ";", "// Bias for each column", "}" ]
Bias representation object. Contains all bias elements.
[ "Bias", "representation", "object", ".", "Contains", "all", "bias", "elements", "." ]
15077ae61b66eb6a61438cac8cb1dc9ec4edf558
https://github.com/sbyrnes/likely.js/blob/15077ae61b66eb6a61438cac8cb1dc9ec4edf558/likely.js#L275-L279
20,028
sbyrnes/likely.js
likely.js
calculateMatrixAverage
function calculateMatrixAverage(inputMatrix) { var cells = inputMatrix.rows() * inputMatrix.cols(); var sum = 0; for(var i = 1; i <= inputMatrix.rows(); i++) { for(var j = 1; j <= inputMatrix.cols(); j++) { sum += inputMatrix.e(i, j); } } return sum/cells; }
javascript
function calculateMatrixAverage(inputMatrix) { var cells = inputMatrix.rows() * inputMatrix.cols(); var sum = 0; for(var i = 1; i <= inputMatrix.rows(); i++) { for(var j = 1; j <= inputMatrix.cols(); j++) { sum += inputMatrix.e(i, j); } } return sum/cells; }
[ "function", "calculateMatrixAverage", "(", "inputMatrix", ")", "{", "var", "cells", "=", "inputMatrix", ".", "rows", "(", ")", "*", "inputMatrix", ".", "cols", "(", ")", ";", "var", "sum", "=", "0", ";", "for", "(", "var", "i", "=", "1", ";", "i", "<=", "inputMatrix", ".", "rows", "(", ")", ";", "i", "++", ")", "{", "for", "(", "var", "j", "=", "1", ";", "j", "<=", "inputMatrix", ".", "cols", "(", ")", ";", "j", "++", ")", "{", "sum", "+=", "inputMatrix", ".", "e", "(", "i", ",", "j", ")", ";", "}", "}", "return", "sum", "/", "cells", ";", "}" ]
Computes the overall average value from a matrix of values. @param input A matrix of the input values @returns float Average value.
[ "Computes", "the", "overall", "average", "value", "from", "a", "matrix", "of", "values", "." ]
15077ae61b66eb6a61438cac8cb1dc9ec4edf558
https://github.com/sbyrnes/likely.js/blob/15077ae61b66eb6a61438cac8cb1dc9ec4edf558/likely.js#L286-L300
20,029
sbyrnes/likely.js
likely.js
calculateColumnAverage
function calculateColumnAverage(inputMatrix) { var rows = inputMatrix.rows(); var averages = new Array(); for(var i = 1; i <= inputMatrix.cols(); i++) { var sum = 0; for(var j = 1; j <= inputMatrix.rows(); j++) { sum += inputMatrix.e(j, i); } averages[i-1] = sum/rows; } return $V(averages); }
javascript
function calculateColumnAverage(inputMatrix) { var rows = inputMatrix.rows(); var averages = new Array(); for(var i = 1; i <= inputMatrix.cols(); i++) { var sum = 0; for(var j = 1; j <= inputMatrix.rows(); j++) { sum += inputMatrix.e(j, i); } averages[i-1] = sum/rows; } return $V(averages); }
[ "function", "calculateColumnAverage", "(", "inputMatrix", ")", "{", "var", "rows", "=", "inputMatrix", ".", "rows", "(", ")", ";", "var", "averages", "=", "new", "Array", "(", ")", ";", "for", "(", "var", "i", "=", "1", ";", "i", "<=", "inputMatrix", ".", "cols", "(", ")", ";", "i", "++", ")", "{", "var", "sum", "=", "0", ";", "for", "(", "var", "j", "=", "1", ";", "j", "<=", "inputMatrix", ".", "rows", "(", ")", ";", "j", "++", ")", "{", "sum", "+=", "inputMatrix", ".", "e", "(", "j", ",", "i", ")", ";", "}", "averages", "[", "i", "-", "1", "]", "=", "sum", "/", "rows", ";", "}", "return", "$V", "(", "averages", ")", ";", "}" ]
Computes the average value for each column of a matrix of values. @param input A matrix of the input values @returns Vector Average value for each column. Vector[i] is the average for column i.
[ "Computes", "the", "average", "value", "for", "each", "column", "of", "a", "matrix", "of", "values", "." ]
15077ae61b66eb6a61438cac8cb1dc9ec4edf558
https://github.com/sbyrnes/likely.js/blob/15077ae61b66eb6a61438cac8cb1dc9ec4edf558/likely.js#L307-L323
20,030
sbyrnes/likely.js
likely.js
Model
function Model(inputMatrix, rowLabels, colLabels) { this.rowLabels = rowLabels; // labels for the rows this.colLabels = colLabels; // labels for the columns this.input = inputMatrix; // input data // estimated data, initialized to all zeros this.estimated = sylvester.Matrix.Zeros(this.input.rows(),this.input.cols()); }
javascript
function Model(inputMatrix, rowLabels, colLabels) { this.rowLabels = rowLabels; // labels for the rows this.colLabels = colLabels; // labels for the columns this.input = inputMatrix; // input data // estimated data, initialized to all zeros this.estimated = sylvester.Matrix.Zeros(this.input.rows(),this.input.cols()); }
[ "function", "Model", "(", "inputMatrix", ",", "rowLabels", ",", "colLabels", ")", "{", "this", ".", "rowLabels", "=", "rowLabels", ";", "// labels for the rows", "this", ".", "colLabels", "=", "colLabels", ";", "// labels for the columns", "this", ".", "input", "=", "inputMatrix", ";", "// input data", "// estimated data, initialized to all zeros", "this", ".", "estimated", "=", "sylvester", ".", "Matrix", ".", "Zeros", "(", "this", ".", "input", ".", "rows", "(", ")", ",", "this", ".", "input", ".", "cols", "(", ")", ")", ";", "}" ]
Model representation object. Contains both input and estimated values.
[ "Model", "representation", "object", ".", "Contains", "both", "input", "and", "estimated", "values", "." ]
15077ae61b66eb6a61438cac8cb1dc9ec4edf558
https://github.com/sbyrnes/likely.js/blob/15077ae61b66eb6a61438cac8cb1dc9ec4edf558/likely.js#L351-L358
20,031
sbyrnes/likely.js
likely.js
function(row) { var rowIndex = row; // assume row is a number // If we're using labels we have to look up the row index if(this.rowLabels) { rowIndex = findInArray(this.rowLabels, row); } // estimates for this user var ratingElements = this.estimated.row(rowIndex+1).elements; // build a two dimensional array from the ratings and indexes // [[index, rating], [index, rating]] var outputArray = new Array(); for(var i=0; i<ratingElements.length; i++) { outputArray[i] = [i, ratingElements[i]]; // if we have column labels, use those if(this.colLabels) { outputArray[i][0] = this.colLabels[i]; } } // Sort the array by index return outputArray.sort(function(a, b) {return a[1] < b[1]}) }
javascript
function(row) { var rowIndex = row; // assume row is a number // If we're using labels we have to look up the row index if(this.rowLabels) { rowIndex = findInArray(this.rowLabels, row); } // estimates for this user var ratingElements = this.estimated.row(rowIndex+1).elements; // build a two dimensional array from the ratings and indexes // [[index, rating], [index, rating]] var outputArray = new Array(); for(var i=0; i<ratingElements.length; i++) { outputArray[i] = [i, ratingElements[i]]; // if we have column labels, use those if(this.colLabels) { outputArray[i][0] = this.colLabels[i]; } } // Sort the array by index return outputArray.sort(function(a, b) {return a[1] < b[1]}) }
[ "function", "(", "row", ")", "{", "var", "rowIndex", "=", "row", ";", "// assume row is a number", "// If we're using labels we have to look up the row index", "if", "(", "this", ".", "rowLabels", ")", "{", "rowIndex", "=", "findInArray", "(", "this", ".", "rowLabels", ",", "row", ")", ";", "}", "// estimates for this user", "var", "ratingElements", "=", "this", ".", "estimated", ".", "row", "(", "rowIndex", "+", "1", ")", ".", "elements", ";", "// build a two dimensional array from the ratings and indexes", "// [[index, rating], [index, rating]]", "var", "outputArray", "=", "new", "Array", "(", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "ratingElements", ".", "length", ";", "i", "++", ")", "{", "outputArray", "[", "i", "]", "=", "[", "i", ",", "ratingElements", "[", "i", "]", "]", ";", "// if we have column labels, use those", "if", "(", "this", ".", "colLabels", ")", "{", "outputArray", "[", "i", "]", "[", "0", "]", "=", "this", ".", "colLabels", "[", "i", "]", ";", "}", "}", "// Sort the array by index", "return", "outputArray", ".", "sort", "(", "function", "(", "a", ",", "b", ")", "{", "return", "a", "[", "1", "]", "<", "b", "[", "1", "]", "}", ")", "}" ]
Returns all items for a given row, sorted by rating. @param row The row to return values for @returns Array An array of arrays, each containing two entries. [0] is the index and [1] is the value, sorted by value.
[ "Returns", "all", "items", "for", "a", "given", "row", "sorted", "by", "rating", "." ]
15077ae61b66eb6a61438cac8cb1dc9ec4edf558
https://github.com/sbyrnes/likely.js/blob/15077ae61b66eb6a61438cac8cb1dc9ec4edf558/likely.js#L365-L393
20,032
sbyrnes/likely.js
likely.js
function(row) { var recommendedItems = new Array(); var allItems = this.rankAllItems(row); var rowIndex = row; // assume row is a number // If we're using labels we have to look up the row index if(this.rowLabels) { rowIndex = findInArray(this.rowLabels, row); } for(var i=0; i< allItems.length; i++) { // look up the value in the input var colIndex = allItems[i][0]; // see if we're using column labels or not if(this.colLabels) { colIndex = findInArray(this.colLabels, allItems[i][0]); } var inputRating = this.input.e(rowIndex+1, colIndex+1); // if there was no rating its a recommendation so add it if(inputRating == 0) { recommendedItems.push(allItems[i]); } } return recommendedItems; }
javascript
function(row) { var recommendedItems = new Array(); var allItems = this.rankAllItems(row); var rowIndex = row; // assume row is a number // If we're using labels we have to look up the row index if(this.rowLabels) { rowIndex = findInArray(this.rowLabels, row); } for(var i=0; i< allItems.length; i++) { // look up the value in the input var colIndex = allItems[i][0]; // see if we're using column labels or not if(this.colLabels) { colIndex = findInArray(this.colLabels, allItems[i][0]); } var inputRating = this.input.e(rowIndex+1, colIndex+1); // if there was no rating its a recommendation so add it if(inputRating == 0) { recommendedItems.push(allItems[i]); } } return recommendedItems; }
[ "function", "(", "row", ")", "{", "var", "recommendedItems", "=", "new", "Array", "(", ")", ";", "var", "allItems", "=", "this", ".", "rankAllItems", "(", "row", ")", ";", "var", "rowIndex", "=", "row", ";", "// assume row is a number", "// If we're using labels we have to look up the row index", "if", "(", "this", ".", "rowLabels", ")", "{", "rowIndex", "=", "findInArray", "(", "this", ".", "rowLabels", ",", "row", ")", ";", "}", "for", "(", "var", "i", "=", "0", ";", "i", "<", "allItems", ".", "length", ";", "i", "++", ")", "{", "// look up the value in the input", "var", "colIndex", "=", "allItems", "[", "i", "]", "[", "0", "]", ";", "// see if we're using column labels or not", "if", "(", "this", ".", "colLabels", ")", "{", "colIndex", "=", "findInArray", "(", "this", ".", "colLabels", ",", "allItems", "[", "i", "]", "[", "0", "]", ")", ";", "}", "var", "inputRating", "=", "this", ".", "input", ".", "e", "(", "rowIndex", "+", "1", ",", "colIndex", "+", "1", ")", ";", "// if there was no rating its a recommendation so add it", "if", "(", "inputRating", "==", "0", ")", "{", "recommendedItems", ".", "push", "(", "allItems", "[", "i", "]", ")", ";", "}", "}", "return", "recommendedItems", ";", "}" ]
Returns all items for the given row where there was no input value, sorted by rating. @param row The row to return values for @returns Array An array of arrays, each containing two entries. [0] is the index and [1] is the value, sorted by value.
[ "Returns", "all", "items", "for", "the", "given", "row", "where", "there", "was", "no", "input", "value", "sorted", "by", "rating", "." ]
15077ae61b66eb6a61438cac8cb1dc9ec4edf558
https://github.com/sbyrnes/likely.js/blob/15077ae61b66eb6a61438cac8cb1dc9ec4edf558/likely.js#L400-L432
20,033
frictionlessdata/tableschema-js
src/table.js
createCsvDelimiterDetector
function createCsvDelimiterDetector(csvParser) { const detector = PassThrough() const sniffer = new CSVSniffer() let done = false detector.on('data', (chunk) => { if (!done) { const result = sniffer.sniff(chunk.toString()) csvParser.options.delimiter = result.delimiter done = true } }) return detector }
javascript
function createCsvDelimiterDetector(csvParser) { const detector = PassThrough() const sniffer = new CSVSniffer() let done = false detector.on('data', (chunk) => { if (!done) { const result = sniffer.sniff(chunk.toString()) csvParser.options.delimiter = result.delimiter done = true } }) return detector }
[ "function", "createCsvDelimiterDetector", "(", "csvParser", ")", "{", "const", "detector", "=", "PassThrough", "(", ")", "const", "sniffer", "=", "new", "CSVSniffer", "(", ")", "let", "done", "=", "false", "detector", ".", "on", "(", "'data'", ",", "(", "chunk", ")", "=>", "{", "if", "(", "!", "done", ")", "{", "const", "result", "=", "sniffer", ".", "sniff", "(", "chunk", ".", "toString", "(", ")", ")", "csvParser", ".", "options", ".", "delimiter", "=", "result", ".", "delimiter", "done", "=", "true", "}", "}", ")", "return", "detector", "}" ]
Detects the CSV delimiter, updating the received `csvParser` options. It will use the first chunk to detect the CSV delimiter, and update it on `csvParser.options.delimiter`. After this is finished, no further processing will be done. @param {module:csv/parse} csvParser - The csv.parse() instance @return {module:stream/PassThrough}
[ "Detects", "the", "CSV", "delimiter", "updating", "the", "received", "csvParser", "options", "." ]
fb088a6346315eda7cd51b1a9e3a57dd31cdf872
https://github.com/frictionlessdata/tableschema-js/blob/fb088a6346315eda7cd51b1a9e3a57dd31cdf872/src/table.js#L330-L344
20,034
namics/gondel
packages/plugins/media-queries/dist/index.js
getComponentsInEventRegistry
function getComponentsInEventRegistry(eventRegistry, namespace) { var selector = Object.keys(eventRegistry) .map(function (componentName) { return "[data-" + namespace + "-name=\"" + componentName + "\"]"; }) .join(","); if (!selector) { return []; } var componentElements = document.documentElement.querySelectorAll(selector); var components = []; for (var i = 0; i < componentElements.length; i++) { var component = getComponentByDomNode(componentElements[i], namespace); if (component) { components.push(component); } } return components; }
javascript
function getComponentsInEventRegistry(eventRegistry, namespace) { var selector = Object.keys(eventRegistry) .map(function (componentName) { return "[data-" + namespace + "-name=\"" + componentName + "\"]"; }) .join(","); if (!selector) { return []; } var componentElements = document.documentElement.querySelectorAll(selector); var components = []; for (var i = 0; i < componentElements.length; i++) { var component = getComponentByDomNode(componentElements[i], namespace); if (component) { components.push(component); } } return components; }
[ "function", "getComponentsInEventRegistry", "(", "eventRegistry", ",", "namespace", ")", "{", "var", "selector", "=", "Object", ".", "keys", "(", "eventRegistry", ")", ".", "map", "(", "function", "(", "componentName", ")", "{", "return", "\"[data-\"", "+", "namespace", "+", "\"-name=\\\"\"", "+", "componentName", "+", "\"\\\"]\"", ";", "}", ")", ".", "join", "(", "\",\"", ")", ";", "if", "(", "!", "selector", ")", "{", "return", "[", "]", ";", "}", "var", "componentElements", "=", "document", ".", "documentElement", ".", "querySelectorAll", "(", "selector", ")", ";", "var", "components", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "componentElements", ".", "length", ";", "i", "++", ")", "{", "var", "component", "=", "getComponentByDomNode", "(", "componentElements", "[", "i", "]", ",", "namespace", ")", ";", "if", "(", "component", ")", "{", "components", ".", "push", "(", "component", ")", ";", "}", "}", "return", "components", ";", "}" ]
This function returns all components for the given eventRegistry which can be found in the dom.
[ "This", "function", "returns", "all", "components", "for", "the", "given", "eventRegistry", "which", "can", "be", "found", "in", "the", "dom", "." ]
34257f71f47b820e53a49ee22b4f96a0ede2ab05
https://github.com/namics/gondel/blob/34257f71f47b820e53a49ee22b4f96a0ede2ab05/packages/plugins/media-queries/dist/index.js#L13-L29
20,035
namics/gondel
packages/plugins/media-queries/dist/index.js
fireViewportChangeEvent
function fireViewportChangeEvent(viewport, eventRegistry, namespace) { var components = getComponentsInEventRegistry(eventRegistry, namespace); var handlerResults = []; components.forEach(function (component) { Object.keys(eventRegistry[component._componentName]).forEach(function (selector) { if (selector === "" || viewport === selector) { eventRegistry[component._componentName][selector].forEach(function (handlerOption) { handlerResults.push(component[handlerOption.handlerName].call(component, { viewport: viewport })); }); } }); }); handlerResults.forEach(function (handlerResults) { return function () { if (typeof handlerResults === "function") { handlerResults(); } }; }); }
javascript
function fireViewportChangeEvent(viewport, eventRegistry, namespace) { var components = getComponentsInEventRegistry(eventRegistry, namespace); var handlerResults = []; components.forEach(function (component) { Object.keys(eventRegistry[component._componentName]).forEach(function (selector) { if (selector === "" || viewport === selector) { eventRegistry[component._componentName][selector].forEach(function (handlerOption) { handlerResults.push(component[handlerOption.handlerName].call(component, { viewport: viewport })); }); } }); }); handlerResults.forEach(function (handlerResults) { return function () { if (typeof handlerResults === "function") { handlerResults(); } }; }); }
[ "function", "fireViewportChangeEvent", "(", "viewport", ",", "eventRegistry", ",", "namespace", ")", "{", "var", "components", "=", "getComponentsInEventRegistry", "(", "eventRegistry", ",", "namespace", ")", ";", "var", "handlerResults", "=", "[", "]", ";", "components", ".", "forEach", "(", "function", "(", "component", ")", "{", "Object", ".", "keys", "(", "eventRegistry", "[", "component", ".", "_componentName", "]", ")", ".", "forEach", "(", "function", "(", "selector", ")", "{", "if", "(", "selector", "===", "\"\"", "||", "viewport", "===", "selector", ")", "{", "eventRegistry", "[", "component", ".", "_componentName", "]", "[", "selector", "]", ".", "forEach", "(", "function", "(", "handlerOption", ")", "{", "handlerResults", ".", "push", "(", "component", "[", "handlerOption", ".", "handlerName", "]", ".", "call", "(", "component", ",", "{", "viewport", ":", "viewport", "}", ")", ")", ";", "}", ")", ";", "}", "}", ")", ";", "}", ")", ";", "handlerResults", ".", "forEach", "(", "function", "(", "handlerResults", ")", "{", "return", "function", "(", ")", "{", "if", "(", "typeof", "handlerResults", "===", "\"function\"", ")", "{", "handlerResults", "(", ")", ";", "}", "}", ";", "}", ")", ";", "}" ]
This function fire's a custom gondel event to all registered components
[ "This", "function", "fire", "s", "a", "custom", "gondel", "event", "to", "all", "registered", "components" ]
34257f71f47b820e53a49ee22b4f96a0ede2ab05
https://github.com/namics/gondel/blob/34257f71f47b820e53a49ee22b4f96a0ede2ab05/packages/plugins/media-queries/dist/index.js#L33-L50
20,036
namics/gondel
packages/plugins/media-queries/dist/index.js
convertBreakpointsToEm
function convertBreakpointsToEm(breakpointsInPx) { var breakpointsInEm = {}; var breakpointNames = Object.keys(breakpointsInPx); breakpointNames.forEach(function (breakpointName) { breakpointsInEm[breakpointName] = px2em(breakpointsInPx[breakpointName]); }); return breakpointsInEm; }
javascript
function convertBreakpointsToEm(breakpointsInPx) { var breakpointsInEm = {}; var breakpointNames = Object.keys(breakpointsInPx); breakpointNames.forEach(function (breakpointName) { breakpointsInEm[breakpointName] = px2em(breakpointsInPx[breakpointName]); }); return breakpointsInEm; }
[ "function", "convertBreakpointsToEm", "(", "breakpointsInPx", ")", "{", "var", "breakpointsInEm", "=", "{", "}", ";", "var", "breakpointNames", "=", "Object", ".", "keys", "(", "breakpointsInPx", ")", ";", "breakpointNames", ".", "forEach", "(", "function", "(", "breakpointName", ")", "{", "breakpointsInEm", "[", "breakpointName", "]", "=", "px2em", "(", "breakpointsInPx", "[", "breakpointName", "]", ")", ";", "}", ")", ";", "return", "breakpointsInEm", ";", "}" ]
Converts the given pixel breakpoint object into a em breakpoint object
[ "Converts", "the", "given", "pixel", "breakpoint", "object", "into", "a", "em", "breakpoint", "object" ]
34257f71f47b820e53a49ee22b4f96a0ede2ab05
https://github.com/namics/gondel/blob/34257f71f47b820e53a49ee22b4f96a0ede2ab05/packages/plugins/media-queries/dist/index.js#L60-L67
20,037
namics/gondel
packages/plugins/media-queries/dist/index.js
generateMediaQueries
function generateMediaQueries(breakPoints, unit) { // Sort breakpoints by size var breakpointNames = Object.keys(breakPoints).sort(function (breakpointNameA, breakpointNameB) { if (breakPoints[breakpointNameA] > breakPoints[breakpointNameB]) { return 1; } if (breakPoints[breakpointNameA] < breakPoints[breakpointNameB]) { return -1; } return 0; }); // Convert breakpoints from 980 into (min-width: 700) and (max-width: 980) // by using the previous breakpoint return breakpointNames.map(function (breakpointName, i) { // If this is the first breakpoint we don't need a min value var min = breakpointNames[i - 1] === undefined ? undefined : breakPoints[breakpointNames[i - 1]] + 1; // If this is the last breakpoint we don't need a max value var max = breakPoints[breakpointName] === Infinity ? undefined : breakPoints[breakpointName]; var queryString; if (min && max) { queryString = "(min-width: " + min + unit + ") and (max-width: " + max + unit + ")"; } else if (min) { queryString = "(min-width: " + min + unit + ")"; } else if (max) { queryString = "(max-width: " + max + unit + ")"; } else { // This should only happen if the user did a miss configuration // with only a single breakpoint which is set to infinity throw new Error("The smallest provided viewport must not be set to Infinity"); } return { name: breakpointName, query: queryString, min: min, max: max }; }); }
javascript
function generateMediaQueries(breakPoints, unit) { // Sort breakpoints by size var breakpointNames = Object.keys(breakPoints).sort(function (breakpointNameA, breakpointNameB) { if (breakPoints[breakpointNameA] > breakPoints[breakpointNameB]) { return 1; } if (breakPoints[breakpointNameA] < breakPoints[breakpointNameB]) { return -1; } return 0; }); // Convert breakpoints from 980 into (min-width: 700) and (max-width: 980) // by using the previous breakpoint return breakpointNames.map(function (breakpointName, i) { // If this is the first breakpoint we don't need a min value var min = breakpointNames[i - 1] === undefined ? undefined : breakPoints[breakpointNames[i - 1]] + 1; // If this is the last breakpoint we don't need a max value var max = breakPoints[breakpointName] === Infinity ? undefined : breakPoints[breakpointName]; var queryString; if (min && max) { queryString = "(min-width: " + min + unit + ") and (max-width: " + max + unit + ")"; } else if (min) { queryString = "(min-width: " + min + unit + ")"; } else if (max) { queryString = "(max-width: " + max + unit + ")"; } else { // This should only happen if the user did a miss configuration // with only a single breakpoint which is set to infinity throw new Error("The smallest provided viewport must not be set to Infinity"); } return { name: breakpointName, query: queryString, min: min, max: max }; }); }
[ "function", "generateMediaQueries", "(", "breakPoints", ",", "unit", ")", "{", "// Sort breakpoints by size", "var", "breakpointNames", "=", "Object", ".", "keys", "(", "breakPoints", ")", ".", "sort", "(", "function", "(", "breakpointNameA", ",", "breakpointNameB", ")", "{", "if", "(", "breakPoints", "[", "breakpointNameA", "]", ">", "breakPoints", "[", "breakpointNameB", "]", ")", "{", "return", "1", ";", "}", "if", "(", "breakPoints", "[", "breakpointNameA", "]", "<", "breakPoints", "[", "breakpointNameB", "]", ")", "{", "return", "-", "1", ";", "}", "return", "0", ";", "}", ")", ";", "// Convert breakpoints from 980 into (min-width: 700) and (max-width: 980)", "// by using the previous breakpoint", "return", "breakpointNames", ".", "map", "(", "function", "(", "breakpointName", ",", "i", ")", "{", "// If this is the first breakpoint we don't need a min value", "var", "min", "=", "breakpointNames", "[", "i", "-", "1", "]", "===", "undefined", "?", "undefined", ":", "breakPoints", "[", "breakpointNames", "[", "i", "-", "1", "]", "]", "+", "1", ";", "// If this is the last breakpoint we don't need a max value", "var", "max", "=", "breakPoints", "[", "breakpointName", "]", "===", "Infinity", "?", "undefined", ":", "breakPoints", "[", "breakpointName", "]", ";", "var", "queryString", ";", "if", "(", "min", "&&", "max", ")", "{", "queryString", "=", "\"(min-width: \"", "+", "min", "+", "unit", "+", "\") and (max-width: \"", "+", "max", "+", "unit", "+", "\")\"", ";", "}", "else", "if", "(", "min", ")", "{", "queryString", "=", "\"(min-width: \"", "+", "min", "+", "unit", "+", "\")\"", ";", "}", "else", "if", "(", "max", ")", "{", "queryString", "=", "\"(max-width: \"", "+", "max", "+", "unit", "+", "\")\"", ";", "}", "else", "{", "// This should only happen if the user did a miss configuration", "// with only a single breakpoint which is set to infinity", "throw", "new", "Error", "(", "\"The smallest provided viewport must not be set to Infinity\"", ")", ";", "}", "return", "{", "name", ":", "breakpointName", ",", "query", ":", "queryString", ",", "min", ":", "min", ",", "max", ":", "max", "}", ";", "}", ")", ";", "}" ]
This function generate mediaQueries from breakPoints
[ "This", "function", "generate", "mediaQueries", "from", "breakPoints" ]
34257f71f47b820e53a49ee22b4f96a0ede2ab05
https://github.com/namics/gondel/blob/34257f71f47b820e53a49ee22b4f96a0ede2ab05/packages/plugins/media-queries/dist/index.js#L77-L112
20,038
namics/gondel
packages/plugins/media-queries/dist/index.js
setupViewportChangeEvent
function setupViewportChangeEvent(mediaQueries, eventRegistry, namespace) { var _loop_1 = function (viewport) { matchMedia(viewport.query).addListener(function (mediaQueryList) { if (mediaQueryList.matches) { fireViewportChangeEvent(viewport.name, eventRegistry, namespace); } }); }; for (var _i = 0, mediaQueries_1 = mediaQueries; _i < mediaQueries_1.length; _i++) { var viewport = mediaQueries_1[_i]; _loop_1(viewport); } }
javascript
function setupViewportChangeEvent(mediaQueries, eventRegistry, namespace) { var _loop_1 = function (viewport) { matchMedia(viewport.query).addListener(function (mediaQueryList) { if (mediaQueryList.matches) { fireViewportChangeEvent(viewport.name, eventRegistry, namespace); } }); }; for (var _i = 0, mediaQueries_1 = mediaQueries; _i < mediaQueries_1.length; _i++) { var viewport = mediaQueries_1[_i]; _loop_1(viewport); } }
[ "function", "setupViewportChangeEvent", "(", "mediaQueries", ",", "eventRegistry", ",", "namespace", ")", "{", "var", "_loop_1", "=", "function", "(", "viewport", ")", "{", "matchMedia", "(", "viewport", ".", "query", ")", ".", "addListener", "(", "function", "(", "mediaQueryList", ")", "{", "if", "(", "mediaQueryList", ".", "matches", ")", "{", "fireViewportChangeEvent", "(", "viewport", ".", "name", ",", "eventRegistry", ",", "namespace", ")", ";", "}", "}", ")", ";", "}", ";", "for", "(", "var", "_i", "=", "0", ",", "mediaQueries_1", "=", "mediaQueries", ";", "_i", "<", "mediaQueries_1", ".", "length", ";", "_i", "++", ")", "{", "var", "viewport", "=", "mediaQueries_1", "[", "_i", "]", ";", "_loop_1", "(", "viewport", ")", ";", "}", "}" ]
Use enquire.js to listen for viewport changes Once a viewport changed call all gondel plugins which are listening
[ "Use", "enquire", ".", "js", "to", "listen", "for", "viewport", "changes", "Once", "a", "viewport", "changed", "call", "all", "gondel", "plugins", "which", "are", "listening" ]
34257f71f47b820e53a49ee22b4f96a0ede2ab05
https://github.com/namics/gondel/blob/34257f71f47b820e53a49ee22b4f96a0ede2ab05/packages/plugins/media-queries/dist/index.js#L117-L129
20,039
namics/gondel
packages/plugins/media-queries/dist/index.js
setupCurrentViewportHelper
function setupCurrentViewportHelper(mediaQueries) { var _loop_2 = function (viewport) { var viewportMediaQueryList = matchMedia(viewport.query); // Set initial viewport if (viewportMediaQueryList.matches) { currentViewport = viewport.name; } // Watch for media query changes viewportMediaQueryList.addListener(function (mediaQueryList) { if (mediaQueryList.matches) { currentViewport = viewport.name; } }); }; for (var _i = 0, mediaQueries_2 = mediaQueries; _i < mediaQueries_2.length; _i++) { var viewport = mediaQueries_2[_i]; _loop_2(viewport); } }
javascript
function setupCurrentViewportHelper(mediaQueries) { var _loop_2 = function (viewport) { var viewportMediaQueryList = matchMedia(viewport.query); // Set initial viewport if (viewportMediaQueryList.matches) { currentViewport = viewport.name; } // Watch for media query changes viewportMediaQueryList.addListener(function (mediaQueryList) { if (mediaQueryList.matches) { currentViewport = viewport.name; } }); }; for (var _i = 0, mediaQueries_2 = mediaQueries; _i < mediaQueries_2.length; _i++) { var viewport = mediaQueries_2[_i]; _loop_2(viewport); } }
[ "function", "setupCurrentViewportHelper", "(", "mediaQueries", ")", "{", "var", "_loop_2", "=", "function", "(", "viewport", ")", "{", "var", "viewportMediaQueryList", "=", "matchMedia", "(", "viewport", ".", "query", ")", ";", "// Set initial viewport", "if", "(", "viewportMediaQueryList", ".", "matches", ")", "{", "currentViewport", "=", "viewport", ".", "name", ";", "}", "// Watch for media query changes", "viewportMediaQueryList", ".", "addListener", "(", "function", "(", "mediaQueryList", ")", "{", "if", "(", "mediaQueryList", ".", "matches", ")", "{", "currentViewport", "=", "viewport", ".", "name", ";", "}", "}", ")", ";", "}", ";", "for", "(", "var", "_i", "=", "0", ",", "mediaQueries_2", "=", "mediaQueries", ";", "_i", "<", "mediaQueries_2", ".", "length", ";", "_i", "++", ")", "{", "var", "viewport", "=", "mediaQueries_2", "[", "_i", "]", ";", "_loop_2", "(", "viewport", ")", ";", "}", "}" ]
Use enquire.js to listen for viewport changes for the getCurrentViewport helper method
[ "Use", "enquire", ".", "js", "to", "listen", "for", "viewport", "changes", "for", "the", "getCurrentViewport", "helper", "method" ]
34257f71f47b820e53a49ee22b4f96a0ede2ab05
https://github.com/namics/gondel/blob/34257f71f47b820e53a49ee22b4f96a0ede2ab05/packages/plugins/media-queries/dist/index.js#L134-L152
20,040
namics/gondel
packages/plugins/resize/dist/index.js
startResizeWatching
function startResizeWatching(event) { var components = getComponentsInEventRegistry(eventRegistry, namespace); isRunning = true; // The resize listener is fired very often // for performance optimisations we search and store // all components during the initial start event componentInformation = components.map(function (component) { var size = component.__resizeSize || { width: 0, height: 0 }; var gondelComponentHandlers = eventRegistry[component._componentName]; return { component: component, node: component._ctx, selectors: Object.keys(gondelComponentHandlers).map(function (selector) { return gondelComponentHandlers[selector].map(function (handlerOption) { return component[handlerOption.handlerName]; }); }), width: size.width, height: size.height }; }); fireResizeEvent(event); }
javascript
function startResizeWatching(event) { var components = getComponentsInEventRegistry(eventRegistry, namespace); isRunning = true; // The resize listener is fired very often // for performance optimisations we search and store // all components during the initial start event componentInformation = components.map(function (component) { var size = component.__resizeSize || { width: 0, height: 0 }; var gondelComponentHandlers = eventRegistry[component._componentName]; return { component: component, node: component._ctx, selectors: Object.keys(gondelComponentHandlers).map(function (selector) { return gondelComponentHandlers[selector].map(function (handlerOption) { return component[handlerOption.handlerName]; }); }), width: size.width, height: size.height }; }); fireResizeEvent(event); }
[ "function", "startResizeWatching", "(", "event", ")", "{", "var", "components", "=", "getComponentsInEventRegistry", "(", "eventRegistry", ",", "namespace", ")", ";", "isRunning", "=", "true", ";", "// The resize listener is fired very often", "// for performance optimisations we search and store", "// all components during the initial start event", "componentInformation", "=", "components", ".", "map", "(", "function", "(", "component", ")", "{", "var", "size", "=", "component", ".", "__resizeSize", "||", "{", "width", ":", "0", ",", "height", ":", "0", "}", ";", "var", "gondelComponentHandlers", "=", "eventRegistry", "[", "component", ".", "_componentName", "]", ";", "return", "{", "component", ":", "component", ",", "node", ":", "component", ".", "_ctx", ",", "selectors", ":", "Object", ".", "keys", "(", "gondelComponentHandlers", ")", ".", "map", "(", "function", "(", "selector", ")", "{", "return", "gondelComponentHandlers", "[", "selector", "]", ".", "map", "(", "function", "(", "handlerOption", ")", "{", "return", "component", "[", "handlerOption", ".", "handlerName", "]", ";", "}", ")", ";", "}", ")", ",", "width", ":", "size", ".", "width", ",", "height", ":", "size", ".", "height", "}", ";", "}", ")", ";", "fireResizeEvent", "(", "event", ")", ";", "}" ]
This handler is called if a new resize event happens. A resize event is new if no resize occurred for 250ms
[ "This", "handler", "is", "called", "if", "a", "new", "resize", "event", "happens", ".", "A", "resize", "event", "is", "new", "if", "no", "resize", "occurred", "for", "250ms" ]
34257f71f47b820e53a49ee22b4f96a0ede2ab05
https://github.com/namics/gondel/blob/34257f71f47b820e53a49ee22b4f96a0ede2ab05/packages/plugins/resize/dist/index.js#L49-L72
20,041
namics/gondel
packages/plugins/resize/dist/index.js
fireComponentResizeEvent
function fireComponentResizeEvent(event) { frameIsRequested = false; if (!componentInformation) { return; } var newSizes = componentInformation.map(function (_a) { var node = _a.node; return ({ width: node.clientWidth, height: node.clientHeight }); }); var handlerResults = []; componentInformation.forEach(function (componentInformation, i) { var newSize = newSizes[i]; // Skip if the size did not change if (newSize.width === componentInformation.width && newSize.height === componentInformation.height) { return; } // Skip if the component is not running anymore if (componentInformation.component._stopped) { return; } componentInformation.component.__resizeSize = newSize; componentInformation.width = newSize.width; componentInformation.height = newSize.height; componentInformation.selectors.forEach(function (selector) { return selector.forEach(function (handler) { return handlerResults.push(handler.call(componentInformation.component, event, newSize)); }); }); }); handlerResults.forEach(function (handlerResult) { if (typeof handlerResult === "function") { handlerResult(); } }); }
javascript
function fireComponentResizeEvent(event) { frameIsRequested = false; if (!componentInformation) { return; } var newSizes = componentInformation.map(function (_a) { var node = _a.node; return ({ width: node.clientWidth, height: node.clientHeight }); }); var handlerResults = []; componentInformation.forEach(function (componentInformation, i) { var newSize = newSizes[i]; // Skip if the size did not change if (newSize.width === componentInformation.width && newSize.height === componentInformation.height) { return; } // Skip if the component is not running anymore if (componentInformation.component._stopped) { return; } componentInformation.component.__resizeSize = newSize; componentInformation.width = newSize.width; componentInformation.height = newSize.height; componentInformation.selectors.forEach(function (selector) { return selector.forEach(function (handler) { return handlerResults.push(handler.call(componentInformation.component, event, newSize)); }); }); }); handlerResults.forEach(function (handlerResult) { if (typeof handlerResult === "function") { handlerResult(); } }); }
[ "function", "fireComponentResizeEvent", "(", "event", ")", "{", "frameIsRequested", "=", "false", ";", "if", "(", "!", "componentInformation", ")", "{", "return", ";", "}", "var", "newSizes", "=", "componentInformation", ".", "map", "(", "function", "(", "_a", ")", "{", "var", "node", "=", "_a", ".", "node", ";", "return", "(", "{", "width", ":", "node", ".", "clientWidth", ",", "height", ":", "node", ".", "clientHeight", "}", ")", ";", "}", ")", ";", "var", "handlerResults", "=", "[", "]", ";", "componentInformation", ".", "forEach", "(", "function", "(", "componentInformation", ",", "i", ")", "{", "var", "newSize", "=", "newSizes", "[", "i", "]", ";", "// Skip if the size did not change", "if", "(", "newSize", ".", "width", "===", "componentInformation", ".", "width", "&&", "newSize", ".", "height", "===", "componentInformation", ".", "height", ")", "{", "return", ";", "}", "// Skip if the component is not running anymore", "if", "(", "componentInformation", ".", "component", ".", "_stopped", ")", "{", "return", ";", "}", "componentInformation", ".", "component", ".", "__resizeSize", "=", "newSize", ";", "componentInformation", ".", "width", "=", "newSize", ".", "width", ";", "componentInformation", ".", "height", "=", "newSize", ".", "height", ";", "componentInformation", ".", "selectors", ".", "forEach", "(", "function", "(", "selector", ")", "{", "return", "selector", ".", "forEach", "(", "function", "(", "handler", ")", "{", "return", "handlerResults", ".", "push", "(", "handler", ".", "call", "(", "componentInformation", ".", "component", ",", "event", ",", "newSize", ")", ")", ";", "}", ")", ";", "}", ")", ";", "}", ")", ";", "handlerResults", ".", "forEach", "(", "function", "(", "handlerResult", ")", "{", "if", "(", "typeof", "handlerResult", "===", "\"function\"", ")", "{", "handlerResult", "(", ")", ";", "}", "}", ")", ";", "}" ]
Check which modules changed in size, are still running and call their event handler
[ "Check", "which", "modules", "changed", "in", "size", "are", "still", "running", "and", "call", "their", "event", "handler" ]
34257f71f47b820e53a49ee22b4f96a0ede2ab05
https://github.com/namics/gondel/blob/34257f71f47b820e53a49ee22b4f96a0ede2ab05/packages/plugins/resize/dist/index.js#L90-L128
20,042
namics/gondel
packages/plugins/resize/dist/index.js
fireWindowResizeEvent
function fireWindowResizeEvent(event) { frameIsRequested = false; if (!componentInformation) { return; } var handlerResults = []; componentInformation.forEach(function (componentInformation, i) { // Skip if the component is not running anymore if (componentInformation.component._stopped) { return; } componentInformation.selectors.forEach(function (selector) { return selector.forEach(function (handler) { return handlerResults.push(handler.call(componentInformation.component, event)); }); }); }); handlerResults.forEach(function (handlerResult) { if (typeof handlerResult === "function") { handlerResult(); } }); }
javascript
function fireWindowResizeEvent(event) { frameIsRequested = false; if (!componentInformation) { return; } var handlerResults = []; componentInformation.forEach(function (componentInformation, i) { // Skip if the component is not running anymore if (componentInformation.component._stopped) { return; } componentInformation.selectors.forEach(function (selector) { return selector.forEach(function (handler) { return handlerResults.push(handler.call(componentInformation.component, event)); }); }); }); handlerResults.forEach(function (handlerResult) { if (typeof handlerResult === "function") { handlerResult(); } }); }
[ "function", "fireWindowResizeEvent", "(", "event", ")", "{", "frameIsRequested", "=", "false", ";", "if", "(", "!", "componentInformation", ")", "{", "return", ";", "}", "var", "handlerResults", "=", "[", "]", ";", "componentInformation", ".", "forEach", "(", "function", "(", "componentInformation", ",", "i", ")", "{", "// Skip if the component is not running anymore", "if", "(", "componentInformation", ".", "component", ".", "_stopped", ")", "{", "return", ";", "}", "componentInformation", ".", "selectors", ".", "forEach", "(", "function", "(", "selector", ")", "{", "return", "selector", ".", "forEach", "(", "function", "(", "handler", ")", "{", "return", "handlerResults", ".", "push", "(", "handler", ".", "call", "(", "componentInformation", ".", "component", ",", "event", ")", ")", ";", "}", ")", ";", "}", ")", ";", "}", ")", ";", "handlerResults", ".", "forEach", "(", "function", "(", "handlerResult", ")", "{", "if", "(", "typeof", "handlerResult", "===", "\"function\"", ")", "{", "handlerResult", "(", ")", ";", "}", "}", ")", ";", "}" ]
Check if the components are still running and call their event handler
[ "Check", "if", "the", "components", "are", "still", "running", "and", "call", "their", "event", "handler" ]
34257f71f47b820e53a49ee22b4f96a0ede2ab05
https://github.com/namics/gondel/blob/34257f71f47b820e53a49ee22b4f96a0ede2ab05/packages/plugins/resize/dist/index.js#L132-L154
20,043
namics/gondel
packages/plugins/data/dist/DataDecorator.js
convertPropertyKeyToDataAttributeKey
function convertPropertyKeyToDataAttributeKey(propertyKey) { if (propertyKey.substr(0, 1) === "_") { propertyKey = propertyKey.substr(1); } if (propertyKey.substr(0, 4) !== "data") { throw new Error(propertyKey + "\" has an invalid format please use @data dataSomeProp (data-some-prop) for valid bindings."); } return propertyKey.replace(/([a-zA-Z])(?=[A-Z])/g, "$1-").toLowerCase(); }
javascript
function convertPropertyKeyToDataAttributeKey(propertyKey) { if (propertyKey.substr(0, 1) === "_") { propertyKey = propertyKey.substr(1); } if (propertyKey.substr(0, 4) !== "data") { throw new Error(propertyKey + "\" has an invalid format please use @data dataSomeProp (data-some-prop) for valid bindings."); } return propertyKey.replace(/([a-zA-Z])(?=[A-Z])/g, "$1-").toLowerCase(); }
[ "function", "convertPropertyKeyToDataAttributeKey", "(", "propertyKey", ")", "{", "if", "(", "propertyKey", ".", "substr", "(", "0", ",", "1", ")", "===", "\"_\"", ")", "{", "propertyKey", "=", "propertyKey", ".", "substr", "(", "1", ")", ";", "}", "if", "(", "propertyKey", ".", "substr", "(", "0", ",", "4", ")", "!==", "\"data\"", ")", "{", "throw", "new", "Error", "(", "propertyKey", "+", "\"\\\" has an invalid format please use @data dataSomeProp (data-some-prop) for valid bindings.\"", ")", ";", "}", "return", "propertyKey", ".", "replace", "(", "/", "([a-zA-Z])(?=[A-Z])", "/", "g", ",", "\"$1-\"", ")", ".", "toLowerCase", "(", ")", ";", "}" ]
Will convert any possible property to a valid data attribute @param {string} propertyKey the prop to convert
[ "Will", "convert", "any", "possible", "property", "to", "a", "valid", "data", "attribute" ]
34257f71f47b820e53a49ee22b4f96a0ede2ab05
https://github.com/namics/gondel/blob/34257f71f47b820e53a49ee22b4f96a0ede2ab05/packages/plugins/data/dist/DataDecorator.js#L40-L48
20,044
namics/gondel
packages/core/dist/GondelEventRegistry.js
function (element, selector) { var elementPrototype = window.Element.prototype; /* istanbul ignore next : Browser polyfill can't be tested */ var elementMatches = elementPrototype.matches || elementPrototype.matchesSelector || elementPrototype.mozMatchesSelector || elementPrototype.msMatchesSelector || elementPrototype.webkitMatchesSelector; // Cache the function and call it return (matchesCssSelector = function (element, selector) { return elementMatches.call(element, selector); })(element, selector); }
javascript
function (element, selector) { var elementPrototype = window.Element.prototype; /* istanbul ignore next : Browser polyfill can't be tested */ var elementMatches = elementPrototype.matches || elementPrototype.matchesSelector || elementPrototype.mozMatchesSelector || elementPrototype.msMatchesSelector || elementPrototype.webkitMatchesSelector; // Cache the function and call it return (matchesCssSelector = function (element, selector) { return elementMatches.call(element, selector); })(element, selector); }
[ "function", "(", "element", ",", "selector", ")", "{", "var", "elementPrototype", "=", "window", ".", "Element", ".", "prototype", ";", "/* istanbul ignore next : Browser polyfill can't be tested */", "var", "elementMatches", "=", "elementPrototype", ".", "matches", "||", "elementPrototype", ".", "matchesSelector", "||", "elementPrototype", ".", "mozMatchesSelector", "||", "elementPrototype", ".", "msMatchesSelector", "||", "elementPrototype", ".", "webkitMatchesSelector", ";", "// Cache the function and call it", "return", "(", "matchesCssSelector", "=", "function", "(", "element", ",", "selector", ")", "{", "return", "elementMatches", ".", "call", "(", "element", ",", "selector", ")", ";", "}", ")", "(", "element", ",", "selector", ")", ";", "}" ]
Polyfill for element.prototype.matches
[ "Polyfill", "for", "element", ".", "prototype", ".", "matches" ]
34257f71f47b820e53a49ee22b4f96a0ede2ab05
https://github.com/namics/gondel/blob/34257f71f47b820e53a49ee22b4f96a0ede2ab05/packages/core/dist/GondelEventRegistry.js#L16-L28
20,045
namics/gondel
packages/core/dist/GondelEventRegistry.js
handleEvent
function handleEvent(namespace, attributeName, eventHandlerRegistry, event) { var target = event.target; var handlers = getHandlers(attributeName, eventHandlerRegistry, target); executeHandlers(handlers, event, namespace); }
javascript
function handleEvent(namespace, attributeName, eventHandlerRegistry, event) { var target = event.target; var handlers = getHandlers(attributeName, eventHandlerRegistry, target); executeHandlers(handlers, event, namespace); }
[ "function", "handleEvent", "(", "namespace", ",", "attributeName", ",", "eventHandlerRegistry", ",", "event", ")", "{", "var", "target", "=", "event", ".", "target", ";", "var", "handlers", "=", "getHandlers", "(", "attributeName", ",", "eventHandlerRegistry", ",", "target", ")", ";", "executeHandlers", "(", "handlers", ",", "event", ",", "namespace", ")", ";", "}" ]
The handler which will catch every event at the documentElement
[ "The", "handler", "which", "will", "catch", "every", "event", "at", "the", "documentElement" ]
34257f71f47b820e53a49ee22b4f96a0ede2ab05
https://github.com/namics/gondel/blob/34257f71f47b820e53a49ee22b4f96a0ede2ab05/packages/core/dist/GondelEventRegistry.js#L96-L100
20,046
namics/gondel
packages/core/dist/GondelComponentStarter.js
getNewComponents
function getNewComponents(components, registry) { var componentNameHelper = {}; components.forEach(function (component) { return (componentNameHelper[component._componentName] = true); }); var componentNames = Object.keys(componentNameHelper); return componentNames.filter(function (componentName) { return !registry._activeComponents[componentName]; }); }
javascript
function getNewComponents(components, registry) { var componentNameHelper = {}; components.forEach(function (component) { return (componentNameHelper[component._componentName] = true); }); var componentNames = Object.keys(componentNameHelper); return componentNames.filter(function (componentName) { return !registry._activeComponents[componentName]; }); }
[ "function", "getNewComponents", "(", "components", ",", "registry", ")", "{", "var", "componentNameHelper", "=", "{", "}", ";", "components", ".", "forEach", "(", "function", "(", "component", ")", "{", "return", "(", "componentNameHelper", "[", "component", ".", "_componentName", "]", "=", "true", ")", ";", "}", ")", ";", "var", "componentNames", "=", "Object", ".", "keys", "(", "componentNameHelper", ")", ";", "return", "componentNames", ".", "filter", "(", "function", "(", "componentName", ")", "{", "return", "!", "registry", ".", "_activeComponents", "[", "componentName", "]", ";", "}", ")", ";", "}" ]
Filters the given component list and returns the names of those components which have never been started before
[ "Filters", "the", "given", "component", "list", "and", "returns", "the", "names", "of", "those", "components", "which", "have", "never", "been", "started", "before" ]
34257f71f47b820e53a49ee22b4f96a0ede2ab05
https://github.com/namics/gondel/blob/34257f71f47b820e53a49ee22b4f96a0ede2ab05/packages/core/dist/GondelComponentStarter.js#L128-L133
20,047
micro-analytics/micro-analytics-cli
packages/adapter-flat-file-db/index.js
getAll
async function getAll(options) { const data = {}; const keys = filterPaths(await module.exports.keys(), options); for (let key of keys) { data[key] = await module.exports.get(key, { before: options.before, after: options.after, }); } await Promise.all(keys); return data; }
javascript
async function getAll(options) { const data = {}; const keys = filterPaths(await module.exports.keys(), options); for (let key of keys) { data[key] = await module.exports.get(key, { before: options.before, after: options.after, }); } await Promise.all(keys); return data; }
[ "async", "function", "getAll", "(", "options", ")", "{", "const", "data", "=", "{", "}", ";", "const", "keys", "=", "filterPaths", "(", "await", "module", ".", "exports", ".", "keys", "(", ")", ",", "options", ")", ";", "for", "(", "let", "key", "of", "keys", ")", "{", "data", "[", "key", "]", "=", "await", "module", ".", "exports", ".", "get", "(", "key", ",", "{", "before", ":", "options", ".", "before", ",", "after", ":", "options", ".", "after", ",", "}", ")", ";", "}", "await", "Promise", ".", "all", "(", "keys", ")", ";", "return", "data", ";", "}" ]
Get all values starting with a certain pathname and filter their views
[ "Get", "all", "values", "starting", "with", "a", "certain", "pathname", "and", "filter", "their", "views" ]
65a2f302747ad650fb1363b961e5a69552d631d1
https://github.com/micro-analytics/micro-analytics-cli/blob/65a2f302747ad650fb1363b961e5a69552d631d1/packages/adapter-flat-file-db/index.js#L57-L71
20,048
multiformats/js-multiaddr
src/codec.js
bufferToString
function bufferToString (buf) { const a = bufferToTuples(buf) const b = tuplesToStringTuples(a) return stringTuplesToString(b) }
javascript
function bufferToString (buf) { const a = bufferToTuples(buf) const b = tuplesToStringTuples(a) return stringTuplesToString(b) }
[ "function", "bufferToString", "(", "buf", ")", "{", "const", "a", "=", "bufferToTuples", "(", "buf", ")", "const", "b", "=", "tuplesToStringTuples", "(", "a", ")", "return", "stringTuplesToString", "(", "b", ")", "}" ]
Buffer -> String
[ "Buffer", "-", ">", "String" ]
2bb0f1d80080942255d5c9a45d8bc552e0a9e232
https://github.com/multiformats/js-multiaddr/blob/2bb0f1d80080942255d5c9a45d8bc552e0a9e232/src/codec.js#L171-L175
20,049
multiformats/js-multiaddr
src/codec.js
stringToBuffer
function stringToBuffer (str) { str = cleanPath(str) const a = stringToStringTuples(str) const b = stringTuplesToTuples(a) return tuplesToBuffer(b) }
javascript
function stringToBuffer (str) { str = cleanPath(str) const a = stringToStringTuples(str) const b = stringTuplesToTuples(a) return tuplesToBuffer(b) }
[ "function", "stringToBuffer", "(", "str", ")", "{", "str", "=", "cleanPath", "(", "str", ")", "const", "a", "=", "stringToStringTuples", "(", "str", ")", "const", "b", "=", "stringTuplesToTuples", "(", "a", ")", "return", "tuplesToBuffer", "(", "b", ")", "}" ]
String -> Buffer
[ "String", "-", ">", "Buffer" ]
2bb0f1d80080942255d5c9a45d8bc552e0a9e232
https://github.com/multiformats/js-multiaddr/blob/2bb0f1d80080942255d5c9a45d8bc552e0a9e232/src/codec.js#L178-L184
20,050
multiformats/js-multiaddr
src/codec.js
fromBuffer
function fromBuffer (buf) { const err = validateBuffer(buf) if (err) throw err return Buffer.from(buf) // copy }
javascript
function fromBuffer (buf) { const err = validateBuffer(buf) if (err) throw err return Buffer.from(buf) // copy }
[ "function", "fromBuffer", "(", "buf", ")", "{", "const", "err", "=", "validateBuffer", "(", "buf", ")", "if", "(", "err", ")", "throw", "err", "return", "Buffer", ".", "from", "(", "buf", ")", "// copy", "}" ]
Buffer -> Buffer
[ "Buffer", "-", ">", "Buffer" ]
2bb0f1d80080942255d5c9a45d8bc552e0a9e232
https://github.com/multiformats/js-multiaddr/blob/2bb0f1d80080942255d5c9a45d8bc552e0a9e232/src/codec.js#L192-L196
20,051
web-push-libs/encrypted-content-encoding
nodejs/ece.js
decrypt
function decrypt(buffer, params, keyLookupCallback) { var header = parseParams(params); if (header.version === 'aes128gcm') { var headerLength = readHeader(buffer, header); buffer = buffer.slice(headerLength); } var key = deriveKeyAndNonce(header, MODE_DECRYPT, keyLookupCallback); var start = 0; var result = new Buffer(0); var chunkSize = header.rs; if (header.version !== 'aes128gcm') { chunkSize += TAG_LENGTH; } for (var i = 0; start < buffer.length; ++i) { var end = start + chunkSize; if (header.version !== 'aes128gcm' && end === buffer.length) { throw new Error('Truncated payload'); } end = Math.min(end, buffer.length); if (end - start <= TAG_LENGTH) { throw new Error('Invalid block: too small at ' + i); } var block = decryptRecord(key, i, buffer.slice(start, end), header, end >= buffer.length); result = Buffer.concat([result, block]); start = end; } return result; }
javascript
function decrypt(buffer, params, keyLookupCallback) { var header = parseParams(params); if (header.version === 'aes128gcm') { var headerLength = readHeader(buffer, header); buffer = buffer.slice(headerLength); } var key = deriveKeyAndNonce(header, MODE_DECRYPT, keyLookupCallback); var start = 0; var result = new Buffer(0); var chunkSize = header.rs; if (header.version !== 'aes128gcm') { chunkSize += TAG_LENGTH; } for (var i = 0; start < buffer.length; ++i) { var end = start + chunkSize; if (header.version !== 'aes128gcm' && end === buffer.length) { throw new Error('Truncated payload'); } end = Math.min(end, buffer.length); if (end - start <= TAG_LENGTH) { throw new Error('Invalid block: too small at ' + i); } var block = decryptRecord(key, i, buffer.slice(start, end), header, end >= buffer.length); result = Buffer.concat([result, block]); start = end; } return result; }
[ "function", "decrypt", "(", "buffer", ",", "params", ",", "keyLookupCallback", ")", "{", "var", "header", "=", "parseParams", "(", "params", ")", ";", "if", "(", "header", ".", "version", "===", "'aes128gcm'", ")", "{", "var", "headerLength", "=", "readHeader", "(", "buffer", ",", "header", ")", ";", "buffer", "=", "buffer", ".", "slice", "(", "headerLength", ")", ";", "}", "var", "key", "=", "deriveKeyAndNonce", "(", "header", ",", "MODE_DECRYPT", ",", "keyLookupCallback", ")", ";", "var", "start", "=", "0", ";", "var", "result", "=", "new", "Buffer", "(", "0", ")", ";", "var", "chunkSize", "=", "header", ".", "rs", ";", "if", "(", "header", ".", "version", "!==", "'aes128gcm'", ")", "{", "chunkSize", "+=", "TAG_LENGTH", ";", "}", "for", "(", "var", "i", "=", "0", ";", "start", "<", "buffer", ".", "length", ";", "++", "i", ")", "{", "var", "end", "=", "start", "+", "chunkSize", ";", "if", "(", "header", ".", "version", "!==", "'aes128gcm'", "&&", "end", "===", "buffer", ".", "length", ")", "{", "throw", "new", "Error", "(", "'Truncated payload'", ")", ";", "}", "end", "=", "Math", ".", "min", "(", "end", ",", "buffer", ".", "length", ")", ";", "if", "(", "end", "-", "start", "<=", "TAG_LENGTH", ")", "{", "throw", "new", "Error", "(", "'Invalid block: too small at '", "+", "i", ")", ";", "}", "var", "block", "=", "decryptRecord", "(", "key", ",", "i", ",", "buffer", ".", "slice", "(", "start", ",", "end", ")", ",", "header", ",", "end", ">=", "buffer", ".", "length", ")", ";", "result", "=", "Buffer", ".", "concat", "(", "[", "result", ",", "block", "]", ")", ";", "start", "=", "end", ";", "}", "return", "result", ";", "}" ]
Decrypt some bytes. This uses the parameters to determine the key and block size, which are described in the draft. Binary values are base64url encoded. |params.version| contains the version of encoding to use: aes128gcm is the latest, but aesgcm is also accepted (though the latter might disappear in a future release). If omitted, assume aes128gcm. If |params.key| is specified, that value is used as the key. If the version is aes128gcm, the keyid is extracted from the header and used as the ECDH public key of the sender. For version aesgcm , |params.dh| needs to be provided with the public key of the sender. The |params.privateKey| includes the private key of the receiver.
[ "Decrypt", "some", "bytes", ".", "This", "uses", "the", "parameters", "to", "determine", "the", "key", "and", "block", "size", "which", "are", "described", "in", "the", "draft", ".", "Binary", "values", "are", "base64url", "encoded", "." ]
849aebea751752e17fc84a64ce1bbf65dc994e6c
https://github.com/web-push-libs/encrypted-content-encoding/blob/849aebea751752e17fc84a64ce1bbf65dc994e6c/nodejs/ece.js#L366-L396
20,052
web-push-libs/encrypted-content-encoding
nodejs/ece.js
encrypt
function encrypt(buffer, params, keyLookupCallback) { if (!Buffer.isBuffer(buffer)) { throw new Error('buffer argument must be a Buffer'); } var header = parseParams(params); if (!header.salt) { header.salt = crypto.randomBytes(KEY_LENGTH); } var result; if (header.version === 'aes128gcm') { // Save the DH public key in the header unless keyid is set. if (header.privateKey && !header.keyid) { header.keyid = header.privateKey.getPublicKey(); } result = writeHeader(header); } else { // No header on other versions result = new Buffer(0); } var key = deriveKeyAndNonce(header, MODE_ENCRYPT, keyLookupCallback); var start = 0; var padSize = PAD_SIZE[header.version]; var overhead = padSize; if (header.version === 'aes128gcm') { overhead += TAG_LENGTH; } var pad = isNaN(parseInt(params.pad, 10)) ? 0 : parseInt(params.pad, 10); var counter = 0; var last = false; while (!last) { // Pad so that at least one data byte is in a block. var recordPad = Math.min(header.rs - overhead - 1, pad); if (header.version !== 'aes128gcm') { recordPad = Math.min((1 << (padSize * 8)) - 1, recordPad); } if (pad > 0 && recordPad === 0) { ++recordPad; // Deal with perverse case of rs=overhead+1 with padding. } pad -= recordPad; var end = start + header.rs - overhead - recordPad; if (header.version !== 'aes128gcm') { // The > here ensures that we write out a padding-only block at the end // of a buffer. last = end > buffer.length; } else { last = end >= buffer.length; } last = last && pad <= 0; var block = encryptRecord(key, counter, buffer.slice(start, end), recordPad, header, last); result = Buffer.concat([result, block]); start = end; ++counter; } return result; }
javascript
function encrypt(buffer, params, keyLookupCallback) { if (!Buffer.isBuffer(buffer)) { throw new Error('buffer argument must be a Buffer'); } var header = parseParams(params); if (!header.salt) { header.salt = crypto.randomBytes(KEY_LENGTH); } var result; if (header.version === 'aes128gcm') { // Save the DH public key in the header unless keyid is set. if (header.privateKey && !header.keyid) { header.keyid = header.privateKey.getPublicKey(); } result = writeHeader(header); } else { // No header on other versions result = new Buffer(0); } var key = deriveKeyAndNonce(header, MODE_ENCRYPT, keyLookupCallback); var start = 0; var padSize = PAD_SIZE[header.version]; var overhead = padSize; if (header.version === 'aes128gcm') { overhead += TAG_LENGTH; } var pad = isNaN(parseInt(params.pad, 10)) ? 0 : parseInt(params.pad, 10); var counter = 0; var last = false; while (!last) { // Pad so that at least one data byte is in a block. var recordPad = Math.min(header.rs - overhead - 1, pad); if (header.version !== 'aes128gcm') { recordPad = Math.min((1 << (padSize * 8)) - 1, recordPad); } if (pad > 0 && recordPad === 0) { ++recordPad; // Deal with perverse case of rs=overhead+1 with padding. } pad -= recordPad; var end = start + header.rs - overhead - recordPad; if (header.version !== 'aes128gcm') { // The > here ensures that we write out a padding-only block at the end // of a buffer. last = end > buffer.length; } else { last = end >= buffer.length; } last = last && pad <= 0; var block = encryptRecord(key, counter, buffer.slice(start, end), recordPad, header, last); result = Buffer.concat([result, block]); start = end; ++counter; } return result; }
[ "function", "encrypt", "(", "buffer", ",", "params", ",", "keyLookupCallback", ")", "{", "if", "(", "!", "Buffer", ".", "isBuffer", "(", "buffer", ")", ")", "{", "throw", "new", "Error", "(", "'buffer argument must be a Buffer'", ")", ";", "}", "var", "header", "=", "parseParams", "(", "params", ")", ";", "if", "(", "!", "header", ".", "salt", ")", "{", "header", ".", "salt", "=", "crypto", ".", "randomBytes", "(", "KEY_LENGTH", ")", ";", "}", "var", "result", ";", "if", "(", "header", ".", "version", "===", "'aes128gcm'", ")", "{", "// Save the DH public key in the header unless keyid is set.", "if", "(", "header", ".", "privateKey", "&&", "!", "header", ".", "keyid", ")", "{", "header", ".", "keyid", "=", "header", ".", "privateKey", ".", "getPublicKey", "(", ")", ";", "}", "result", "=", "writeHeader", "(", "header", ")", ";", "}", "else", "{", "// No header on other versions", "result", "=", "new", "Buffer", "(", "0", ")", ";", "}", "var", "key", "=", "deriveKeyAndNonce", "(", "header", ",", "MODE_ENCRYPT", ",", "keyLookupCallback", ")", ";", "var", "start", "=", "0", ";", "var", "padSize", "=", "PAD_SIZE", "[", "header", ".", "version", "]", ";", "var", "overhead", "=", "padSize", ";", "if", "(", "header", ".", "version", "===", "'aes128gcm'", ")", "{", "overhead", "+=", "TAG_LENGTH", ";", "}", "var", "pad", "=", "isNaN", "(", "parseInt", "(", "params", ".", "pad", ",", "10", ")", ")", "?", "0", ":", "parseInt", "(", "params", ".", "pad", ",", "10", ")", ";", "var", "counter", "=", "0", ";", "var", "last", "=", "false", ";", "while", "(", "!", "last", ")", "{", "// Pad so that at least one data byte is in a block.", "var", "recordPad", "=", "Math", ".", "min", "(", "header", ".", "rs", "-", "overhead", "-", "1", ",", "pad", ")", ";", "if", "(", "header", ".", "version", "!==", "'aes128gcm'", ")", "{", "recordPad", "=", "Math", ".", "min", "(", "(", "1", "<<", "(", "padSize", "*", "8", ")", ")", "-", "1", ",", "recordPad", ")", ";", "}", "if", "(", "pad", ">", "0", "&&", "recordPad", "===", "0", ")", "{", "++", "recordPad", ";", "// Deal with perverse case of rs=overhead+1 with padding.", "}", "pad", "-=", "recordPad", ";", "var", "end", "=", "start", "+", "header", ".", "rs", "-", "overhead", "-", "recordPad", ";", "if", "(", "header", ".", "version", "!==", "'aes128gcm'", ")", "{", "// The > here ensures that we write out a padding-only block at the end", "// of a buffer.", "last", "=", "end", ">", "buffer", ".", "length", ";", "}", "else", "{", "last", "=", "end", ">=", "buffer", ".", "length", ";", "}", "last", "=", "last", "&&", "pad", "<=", "0", ";", "var", "block", "=", "encryptRecord", "(", "key", ",", "counter", ",", "buffer", ".", "slice", "(", "start", ",", "end", ")", ",", "recordPad", ",", "header", ",", "last", ")", ";", "result", "=", "Buffer", ".", "concat", "(", "[", "result", ",", "block", "]", ")", ";", "start", "=", "end", ";", "++", "counter", ";", "}", "return", "result", ";", "}" ]
Encrypt some bytes. This uses the parameters to determine the key and block size, which are described in the draft. |params.version| contains the version of encoding to use: aes128gcm is the latest, but aesgcm is also accepted (though the latter two might disappear in a future release). If omitted, assume aes128gcm. If |params.key| is specified, that value is used as the key. For Diffie-Hellman (WebPush), |params.dh| includes the public key of the receiver. |params.privateKey| is used to establish a shared secret. Key pairs can be created using |crypto.createECDH()|.
[ "Encrypt", "some", "bytes", ".", "This", "uses", "the", "parameters", "to", "determine", "the", "key", "and", "block", "size", "which", "are", "described", "in", "the", "draft", "." ]
849aebea751752e17fc84a64ce1bbf65dc994e6c
https://github.com/web-push-libs/encrypted-content-encoding/blob/849aebea751752e17fc84a64ce1bbf65dc994e6c/nodejs/ece.js#L459-L519
20,053
EnotionZ/gpio
lib/gpio.js
function(path, interval, fn) { if(typeof fn === 'undefined') { fn = interval; interval = 100; } if(typeof interval !== 'number') return false; if(typeof fn !== 'function') return false; var value; var readTimer = setInterval(function() { _read(path, function(val) { if(value !== val) { if(typeof value !== 'undefined') fn(val); value = val; } }); }, interval); this.stop = function() { clearInterval(readTimer); }; }
javascript
function(path, interval, fn) { if(typeof fn === 'undefined') { fn = interval; interval = 100; } if(typeof interval !== 'number') return false; if(typeof fn !== 'function') return false; var value; var readTimer = setInterval(function() { _read(path, function(val) { if(value !== val) { if(typeof value !== 'undefined') fn(val); value = val; } }); }, interval); this.stop = function() { clearInterval(readTimer); }; }
[ "function", "(", "path", ",", "interval", ",", "fn", ")", "{", "if", "(", "typeof", "fn", "===", "'undefined'", ")", "{", "fn", "=", "interval", ";", "interval", "=", "100", ";", "}", "if", "(", "typeof", "interval", "!==", "'number'", ")", "return", "false", ";", "if", "(", "typeof", "fn", "!==", "'function'", ")", "return", "false", ";", "var", "value", ";", "var", "readTimer", "=", "setInterval", "(", "function", "(", ")", "{", "_read", "(", "path", ",", "function", "(", "val", ")", "{", "if", "(", "value", "!==", "val", ")", "{", "if", "(", "typeof", "value", "!==", "'undefined'", ")", "fn", "(", "val", ")", ";", "value", "=", "val", ";", "}", "}", ")", ";", "}", ",", "interval", ")", ";", "this", ".", "stop", "=", "function", "(", ")", "{", "clearInterval", "(", "readTimer", ")", ";", "}", ";", "}" ]
fs.watch doesn't get fired because the file never gets 'accessed' when setting header via hardware manually watching value changes
[ "fs", ".", "watch", "doesn", "t", "get", "fired", "because", "the", "file", "never", "gets", "accessed", "when", "setting", "header", "via", "hardware", "manually", "watching", "value", "changes" ]
2336386afc7b1eeea5ef0317e75e10af2d2767ad
https://github.com/EnotionZ/gpio/blob/2336386afc7b1eeea5ef0317e75e10af2d2767ad/lib/gpio.js#L74-L93
20,054
straker/livingcss
lib/parseComments.js
parse_description
function parse_description(str, data) { if (data.errors && data.errors.length) { return null; } var result = str.match(/^\s+([\s\S]+)?/); if (result) { return { source: result[0], data: {description: result[1] === undefined ? '' : result[1].replace(trimNewlineRegex, '')} }; } return null; }
javascript
function parse_description(str, data) { if (data.errors && data.errors.length) { return null; } var result = str.match(/^\s+([\s\S]+)?/); if (result) { return { source: result[0], data: {description: result[1] === undefined ? '' : result[1].replace(trimNewlineRegex, '')} }; } return null; }
[ "function", "parse_description", "(", "str", ",", "data", ")", "{", "if", "(", "data", ".", "errors", "&&", "data", ".", "errors", ".", "length", ")", "{", "return", "null", ";", "}", "var", "result", "=", "str", ".", "match", "(", "/", "^\\s+([\\s\\S]+)?", "/", ")", ";", "if", "(", "result", ")", "{", "return", "{", "source", ":", "result", "[", "0", "]", ",", "data", ":", "{", "description", ":", "result", "[", "1", "]", "===", "undefined", "?", "''", ":", "result", "[", "1", "]", ".", "replace", "(", "trimNewlineRegex", ",", "''", ")", "}", "}", ";", "}", "return", "null", ";", "}" ]
remove any trailing and preceding newline characters. Modified from PARSERS.parse_description. @see https://github.com/yavorskiy/comment-parser/blob/master/parser.js
[ "remove", "any", "trailing", "and", "preceding", "newline", "characters", ".", "Modified", "from", "PARSERS", ".", "parse_description", "." ]
d3722bb40c428be74127ed9993935781fff60e75
https://github.com/straker/livingcss/blob/d3722bb40c428be74127ed9993935781fff60e75/lib/parseComments.js#L46-L59
20,055
straker/livingcss
lib/generate.js
generate
function generate(dest, template, context, options) { options = options || {}; // find all root sections (sections with no parent) by removing all number // indices but keeping the named indices for (var i = 0; i < context.sections.length; ) { if (context.sections[i].parent) { context.sections.splice(i, 1); } else { i++; } } // sort root sections by section order if (context.sectionOrder) { utils.sortCategoryBy(context.sections, context.sectionOrder); } if (typeof options.preprocess !== 'undefined' && typeof options.preprocess !== 'function') { throw new SyntaxError('options.preprocess must be a function'); } // if no preprocess function then resolve a promise var preprocess = (options.preprocess ? options.preprocess(context, template, Handlebars) : Promise.resolve()); // if the user returned anything but false we'll resolve a promise if (!(preprocess instanceof Promise)) { preprocess = (preprocess !== false ? Promise.resolve() : Promise.reject()); } return preprocess .then(function() { // inline all stylesheets for polymer shared styles to work // @see https://www.polymer-project.org/1.0/docs/devguide/styling#style-modules return utils.readFiles(context.stylesheets, function(data, file) { context.parsedStylesheets = context.parsedStylesheets || []; context.parsedStylesheets.push(utils.fixSVGIssue(data)); }); }) .then(function success() { var html = Handlebars.compile(template)(context); if (options.minify) { html = minify(html, { collapseWhitespace: true }); } // output the file and create any necessary directories // @see http://stackoverflow.com/questions/16316330/how-to-write-file-if-parent-folder-dosent-exists mkdirp(path.dirname(dest), function(err) { if (err) { throw err; } fs.writeFile(dest, html, 'utf8', function(err) { if (err) { throw err; } }); }); }) .catch(function(err) { if (err) { console.error(err.stack); } }); }
javascript
function generate(dest, template, context, options) { options = options || {}; // find all root sections (sections with no parent) by removing all number // indices but keeping the named indices for (var i = 0; i < context.sections.length; ) { if (context.sections[i].parent) { context.sections.splice(i, 1); } else { i++; } } // sort root sections by section order if (context.sectionOrder) { utils.sortCategoryBy(context.sections, context.sectionOrder); } if (typeof options.preprocess !== 'undefined' && typeof options.preprocess !== 'function') { throw new SyntaxError('options.preprocess must be a function'); } // if no preprocess function then resolve a promise var preprocess = (options.preprocess ? options.preprocess(context, template, Handlebars) : Promise.resolve()); // if the user returned anything but false we'll resolve a promise if (!(preprocess instanceof Promise)) { preprocess = (preprocess !== false ? Promise.resolve() : Promise.reject()); } return preprocess .then(function() { // inline all stylesheets for polymer shared styles to work // @see https://www.polymer-project.org/1.0/docs/devguide/styling#style-modules return utils.readFiles(context.stylesheets, function(data, file) { context.parsedStylesheets = context.parsedStylesheets || []; context.parsedStylesheets.push(utils.fixSVGIssue(data)); }); }) .then(function success() { var html = Handlebars.compile(template)(context); if (options.minify) { html = minify(html, { collapseWhitespace: true }); } // output the file and create any necessary directories // @see http://stackoverflow.com/questions/16316330/how-to-write-file-if-parent-folder-dosent-exists mkdirp(path.dirname(dest), function(err) { if (err) { throw err; } fs.writeFile(dest, html, 'utf8', function(err) { if (err) { throw err; } }); }); }) .catch(function(err) { if (err) { console.error(err.stack); } }); }
[ "function", "generate", "(", "dest", ",", "template", ",", "context", ",", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "// find all root sections (sections with no parent) by removing all number", "// indices but keeping the named indices", "for", "(", "var", "i", "=", "0", ";", "i", "<", "context", ".", "sections", ".", "length", ";", ")", "{", "if", "(", "context", ".", "sections", "[", "i", "]", ".", "parent", ")", "{", "context", ".", "sections", ".", "splice", "(", "i", ",", "1", ")", ";", "}", "else", "{", "i", "++", ";", "}", "}", "// sort root sections by section order", "if", "(", "context", ".", "sectionOrder", ")", "{", "utils", ".", "sortCategoryBy", "(", "context", ".", "sections", ",", "context", ".", "sectionOrder", ")", ";", "}", "if", "(", "typeof", "options", ".", "preprocess", "!==", "'undefined'", "&&", "typeof", "options", ".", "preprocess", "!==", "'function'", ")", "{", "throw", "new", "SyntaxError", "(", "'options.preprocess must be a function'", ")", ";", "}", "// if no preprocess function then resolve a promise", "var", "preprocess", "=", "(", "options", ".", "preprocess", "?", "options", ".", "preprocess", "(", "context", ",", "template", ",", "Handlebars", ")", ":", "Promise", ".", "resolve", "(", ")", ")", ";", "// if the user returned anything but false we'll resolve a promise", "if", "(", "!", "(", "preprocess", "instanceof", "Promise", ")", ")", "{", "preprocess", "=", "(", "preprocess", "!==", "false", "?", "Promise", ".", "resolve", "(", ")", ":", "Promise", ".", "reject", "(", ")", ")", ";", "}", "return", "preprocess", ".", "then", "(", "function", "(", ")", "{", "// inline all stylesheets for polymer shared styles to work", "// @see https://www.polymer-project.org/1.0/docs/devguide/styling#style-modules", "return", "utils", ".", "readFiles", "(", "context", ".", "stylesheets", ",", "function", "(", "data", ",", "file", ")", "{", "context", ".", "parsedStylesheets", "=", "context", ".", "parsedStylesheets", "||", "[", "]", ";", "context", ".", "parsedStylesheets", ".", "push", "(", "utils", ".", "fixSVGIssue", "(", "data", ")", ")", ";", "}", ")", ";", "}", ")", ".", "then", "(", "function", "success", "(", ")", "{", "var", "html", "=", "Handlebars", ".", "compile", "(", "template", ")", "(", "context", ")", ";", "if", "(", "options", ".", "minify", ")", "{", "html", "=", "minify", "(", "html", ",", "{", "collapseWhitespace", ":", "true", "}", ")", ";", "}", "// output the file and create any necessary directories", "// @see http://stackoverflow.com/questions/16316330/how-to-write-file-if-parent-folder-dosent-exists", "mkdirp", "(", "path", ".", "dirname", "(", "dest", ")", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "throw", "err", ";", "}", "fs", ".", "writeFile", "(", "dest", ",", "html", ",", "'utf8'", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "throw", "err", ";", "}", "}", ")", ";", "}", ")", ";", "}", ")", ".", "catch", "(", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "console", ".", "error", "(", "err", ".", "stack", ")", ";", "}", "}", ")", ";", "}" ]
Generate an HTML page. @param {string} dest - Path of the file for the generated HTML. @param {string} template - Handlebars template. @param {object} context - Context to pass to handlebars. @param {string} context.page - Name of the current page. @param {object[]} context.pages - List of pages. @param {object[]} context.sections - List of sections for the page. @param {object[]} context.sections - List of all sections. @param {string[]} context.stylesheets - List of stylesheets to load in the style guide. @param {string[]} context.scripts - List of scripts to load in the style guide. @param {object[]} context.sortOrder - List of pages and their sections in the order they should be sorted. @param {object} [options={}] - Configuration options.
[ "Generate", "an", "HTML", "page", "." ]
d3722bb40c428be74127ed9993935781fff60e75
https://github.com/straker/livingcss/blob/d3722bb40c428be74127ed9993935781fff60e75/lib/generate.js#L23-L95
20,056
straker/livingcss
lib/utils.js
globWithPromsie
function globWithPromsie(pattern) { return new Promise((resolve, reject) => { glob(pattern, function(err, files) { if (err) { reject(err); } if (files.length === 0) { console.warn('pattern "' + pattern + '" does not match any file'); } resolve(files); }); }); }
javascript
function globWithPromsie(pattern) { return new Promise((resolve, reject) => { glob(pattern, function(err, files) { if (err) { reject(err); } if (files.length === 0) { console.warn('pattern "' + pattern + '" does not match any file'); } resolve(files); }); }); }
[ "function", "globWithPromsie", "(", "pattern", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "glob", "(", "pattern", ",", "function", "(", "err", ",", "files", ")", "{", "if", "(", "err", ")", "{", "reject", "(", "err", ")", ";", "}", "if", "(", "files", ".", "length", "===", "0", ")", "{", "console", ".", "warn", "(", "'pattern \"'", "+", "pattern", "+", "'\" does not match any file'", ")", ";", "}", "resolve", "(", "files", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Read a glob string and return a promise. @param {string} pattern - Glob file pattern @returns Promise
[ "Read", "a", "glob", "string", "and", "return", "a", "promise", "." ]
d3722bb40c428be74127ed9993935781fff60e75
https://github.com/straker/livingcss/blob/d3722bb40c428be74127ed9993935781fff60e75/lib/utils.js#L32-L46
20,057
infinum/mobx-collection-store
dist/utils.js
getProp
function getProp(obj, key) { var path = [].concat(key); var val = obj; for (var _i = 0, path_1 = path; _i < path_1.length; _i++) { var pathKey = path_1[_i]; if (val[pathKey] === undefined) { return undefined; } val = val[pathKey]; } return val; }
javascript
function getProp(obj, key) { var path = [].concat(key); var val = obj; for (var _i = 0, path_1 = path; _i < path_1.length; _i++) { var pathKey = path_1[_i]; if (val[pathKey] === undefined) { return undefined; } val = val[pathKey]; } return val; }
[ "function", "getProp", "(", "obj", ",", "key", ")", "{", "var", "path", "=", "[", "]", ".", "concat", "(", "key", ")", ";", "var", "val", "=", "obj", ";", "for", "(", "var", "_i", "=", "0", ",", "path_1", "=", "path", ";", "_i", "<", "path_1", ".", "length", ";", "_i", "++", ")", "{", "var", "pathKey", "=", "path_1", "[", "_i", "]", ";", "if", "(", "val", "[", "pathKey", "]", "===", "undefined", ")", "{", "return", "undefined", ";", "}", "val", "=", "val", "[", "pathKey", "]", ";", "}", "return", "val", ";", "}" ]
Get the specific nested property @export @template T Type of the property value @param {object} obj Source object @param {(string|Array<string>)} key Key value @returns {T} The nested property value
[ "Get", "the", "specific", "nested", "property" ]
9a7d8320e29f037b54c76b445f0d9ffa78e7435e
https://github.com/infinum/mobx-collection-store/blob/9a7d8320e29f037b54c76b445f0d9ffa78e7435e/dist/utils.js#L40-L51
20,058
infinum/mobx-collection-store
dist/utils.js
setProp
function setProp(obj, key, value) { var path = [].concat(key); var lastKey = path.pop(); var val = obj; for (var _i = 0, path_2 = path; _i < path_2.length; _i++) { var pathKey = path_2[_i]; if (typeof val[pathKey] !== 'object') { val[pathKey] = {}; } val = val[pathKey]; } val[lastKey] = value; return obj; }
javascript
function setProp(obj, key, value) { var path = [].concat(key); var lastKey = path.pop(); var val = obj; for (var _i = 0, path_2 = path; _i < path_2.length; _i++) { var pathKey = path_2[_i]; if (typeof val[pathKey] !== 'object') { val[pathKey] = {}; } val = val[pathKey]; } val[lastKey] = value; return obj; }
[ "function", "setProp", "(", "obj", ",", "key", ",", "value", ")", "{", "var", "path", "=", "[", "]", ".", "concat", "(", "key", ")", ";", "var", "lastKey", "=", "path", ".", "pop", "(", ")", ";", "var", "val", "=", "obj", ";", "for", "(", "var", "_i", "=", "0", ",", "path_2", "=", "path", ";", "_i", "<", "path_2", ".", "length", ";", "_i", "++", ")", "{", "var", "pathKey", "=", "path_2", "[", "_i", "]", ";", "if", "(", "typeof", "val", "[", "pathKey", "]", "!==", "'object'", ")", "{", "val", "[", "pathKey", "]", "=", "{", "}", ";", "}", "val", "=", "val", "[", "pathKey", "]", ";", "}", "val", "[", "lastKey", "]", "=", "value", ";", "return", "obj", ";", "}" ]
Set the specific nested property @export @param {object} obj Destination object @param {(string|Array<string>)} key Key value @param {value} any Value to be set
[ "Set", "the", "specific", "nested", "property" ]
9a7d8320e29f037b54c76b445f0d9ffa78e7435e
https://github.com/infinum/mobx-collection-store/blob/9a7d8320e29f037b54c76b445f0d9ffa78e7435e/dist/utils.js#L61-L74
20,059
infinum/mobx-collection-store
dist/utils.js
matchModel
function matchModel(item, type, id) { /* istanbul ignore next */ return getType(item) === type && getProp(item, item.static.idAttribute) === id; }
javascript
function matchModel(item, type, id) { /* istanbul ignore next */ return getType(item) === type && getProp(item, item.static.idAttribute) === id; }
[ "function", "matchModel", "(", "item", ",", "type", ",", "id", ")", "{", "/* istanbul ignore next */", "return", "getType", "(", "item", ")", "===", "type", "&&", "getProp", "(", "item", ",", "item", ".", "static", ".", "idAttribute", ")", "===", "id", ";", "}" ]
Match a model to defined parameters @private @param {IModel} item - Model that's beeing matched @param {IType} type - Model type to match @param {(string|number)} id - Model ID to match @returns {boolean} True if the model matches the parameters @memberOf Collection
[ "Match", "a", "model", "to", "defined", "parameters" ]
9a7d8320e29f037b54c76b445f0d9ffa78e7435e
https://github.com/infinum/mobx-collection-store/blob/9a7d8320e29f037b54c76b445f0d9ffa78e7435e/dist/utils.js#L87-L90
20,060
dfilatov/vow
lib/vow.js
function() { var script = doc.createElement('script'); script.onreadystatechange = function() { script.parentNode.removeChild(script); script = script.onreadystatechange = null; callFns(); }; (doc.documentElement || doc.body).appendChild(script); }
javascript
function() { var script = doc.createElement('script'); script.onreadystatechange = function() { script.parentNode.removeChild(script); script = script.onreadystatechange = null; callFns(); }; (doc.documentElement || doc.body).appendChild(script); }
[ "function", "(", ")", "{", "var", "script", "=", "doc", ".", "createElement", "(", "'script'", ")", ";", "script", ".", "onreadystatechange", "=", "function", "(", ")", "{", "script", ".", "parentNode", ".", "removeChild", "(", "script", ")", ";", "script", "=", "script", ".", "onreadystatechange", "=", "null", ";", "callFns", "(", ")", ";", "}", ";", "(", "doc", ".", "documentElement", "||", "doc", ".", "body", ")", ".", "appendChild", "(", "script", ")", ";", "}" ]
ie6-ie8
[ "ie6", "-", "ie8" ]
5e0fb3596f52ec35f3889c888d3f01a7057a17b3
https://github.com/dfilatov/vow/blob/5e0fb3596f52ec35f3889c888d3f01a7057a17b3/lib/vow.js#L84-L92
20,061
dfilatov/vow
lib/vow.js
function(reason) { if(this._promise.isResolved()) { return; } if(vow.isPromise(reason)) { reason = reason.then(function(val) { var defer = vow.defer(); defer.reject(val); return defer.promise(); }); this._promise._resolve(reason); } else { this._promise._reject(reason); } }
javascript
function(reason) { if(this._promise.isResolved()) { return; } if(vow.isPromise(reason)) { reason = reason.then(function(val) { var defer = vow.defer(); defer.reject(val); return defer.promise(); }); this._promise._resolve(reason); } else { this._promise._reject(reason); } }
[ "function", "(", "reason", ")", "{", "if", "(", "this", ".", "_promise", ".", "isResolved", "(", ")", ")", "{", "return", ";", "}", "if", "(", "vow", ".", "isPromise", "(", "reason", ")", ")", "{", "reason", "=", "reason", ".", "then", "(", "function", "(", "val", ")", "{", "var", "defer", "=", "vow", ".", "defer", "(", ")", ";", "defer", ".", "reject", "(", "val", ")", ";", "return", "defer", ".", "promise", "(", ")", ";", "}", ")", ";", "this", ".", "_promise", ".", "_resolve", "(", "reason", ")", ";", "}", "else", "{", "this", ".", "_promise", ".", "_reject", "(", "reason", ")", ";", "}", "}" ]
Rejects the corresponding promise with the given `reason`. @param {*} reason @example ```js var defer = vow.defer(), promise = defer.promise(); promise.fail(function(reason) { // reason is "'something is wrong'" here }); defer.reject('something is wrong'); ```
[ "Rejects", "the", "corresponding", "promise", "with", "the", "given", "reason", "." ]
5e0fb3596f52ec35f3889c888d3f01a7057a17b3
https://github.com/dfilatov/vow/blob/5e0fb3596f52ec35f3889c888d3f01a7057a17b3/lib/vow.js#L229-L245
20,062
dfilatov/vow
lib/vow.js
function(onFulfilled, onRejected, onProgress, ctx) { this._shouldEmitUnhandledRejection = false; var defer = new Deferred(); this._addCallbacks(defer, onFulfilled, onRejected, onProgress, ctx); return defer.promise(); }
javascript
function(onFulfilled, onRejected, onProgress, ctx) { this._shouldEmitUnhandledRejection = false; var defer = new Deferred(); this._addCallbacks(defer, onFulfilled, onRejected, onProgress, ctx); return defer.promise(); }
[ "function", "(", "onFulfilled", ",", "onRejected", ",", "onProgress", ",", "ctx", ")", "{", "this", ".", "_shouldEmitUnhandledRejection", "=", "false", ";", "var", "defer", "=", "new", "Deferred", "(", ")", ";", "this", ".", "_addCallbacks", "(", "defer", ",", "onFulfilled", ",", "onRejected", ",", "onProgress", ",", "ctx", ")", ";", "return", "defer", ".", "promise", "(", ")", ";", "}" ]
Adds reactions to the promise. @param {Function} [onFulfilled] Callback that will be invoked with a provided value after the promise has been fulfilled @param {Function} [onRejected] Callback that will be invoked with a provided reason after the promise has been rejected @param {Function} [onProgress] Callback that will be invoked with a provided value after the promise has been notified @param {Object} [ctx] Context of the callbacks execution @returns {vow:Promise} A new promise, see https://github.com/promises-aplus/promises-spec for details
[ "Adds", "reactions", "to", "the", "promise", "." ]
5e0fb3596f52ec35f3889c888d3f01a7057a17b3
https://github.com/dfilatov/vow/blob/5e0fb3596f52ec35f3889c888d3f01a7057a17b3/lib/vow.js#L392-L397
20,063
dfilatov/vow
lib/vow.js
function(onFulfilled, onRejected, ctx) { return this.then( function(val) { return onFulfilled.apply(this, val); }, onRejected, ctx); }
javascript
function(onFulfilled, onRejected, ctx) { return this.then( function(val) { return onFulfilled.apply(this, val); }, onRejected, ctx); }
[ "function", "(", "onFulfilled", ",", "onRejected", ",", "ctx", ")", "{", "return", "this", ".", "then", "(", "function", "(", "val", ")", "{", "return", "onFulfilled", ".", "apply", "(", "this", ",", "val", ")", ";", "}", ",", "onRejected", ",", "ctx", ")", ";", "}" ]
Like `promise.then`, but "spreads" the array into a variadic value handler. It is useful with the `vow.all` and the `vow.allResolved` methods. @param {Function} [onFulfilled] Callback that will be invoked with a provided value after the promise has been fulfilled @param {Function} [onRejected] Callback that will be invoked with a provided reason after the promise has been rejected @param {Object} [ctx] Context of the callbacks execution @returns {vow:Promise} @example ```js var defer1 = vow.defer(), defer2 = vow.defer(); vow.all([defer1.promise(), defer2.promise()]).spread(function(arg1, arg2) { // arg1 is "1", arg2 is "'two'" here }); defer1.resolve(1); defer2.resolve('two'); ```
[ "Like", "promise", ".", "then", "but", "spreads", "the", "array", "into", "a", "variadic", "value", "handler", ".", "It", "is", "useful", "with", "the", "vow", ".", "all", "and", "the", "vow", ".", "allResolved", "methods", "." ]
5e0fb3596f52ec35f3889c888d3f01a7057a17b3
https://github.com/dfilatov/vow/blob/5e0fb3596f52ec35f3889c888d3f01a7057a17b3/lib/vow.js#L489-L496
20,064
dfilatov/vow
lib/vow.js
function(onFulfilled, onRejected, onProgress, ctx) { this .then(onFulfilled, onRejected, onProgress, ctx) .fail(throwException); }
javascript
function(onFulfilled, onRejected, onProgress, ctx) { this .then(onFulfilled, onRejected, onProgress, ctx) .fail(throwException); }
[ "function", "(", "onFulfilled", ",", "onRejected", ",", "onProgress", ",", "ctx", ")", "{", "this", ".", "then", "(", "onFulfilled", ",", "onRejected", ",", "onProgress", ",", "ctx", ")", ".", "fail", "(", "throwException", ")", ";", "}" ]
Like `then`, but terminates a chain of promises. If the promise has been rejected, this method throws it's "reason" as an exception in a future turn of the event loop. @param {Function} [onFulfilled] Callback that will be invoked with a provided value after the promise has been fulfilled @param {Function} [onRejected] Callback that will be invoked with a provided reason after the promise has been rejected @param {Function} [onProgress] Callback that will be invoked with a provided value after the promise has been notified @param {Object} [ctx] Context of the callbacks execution @example ```js var defer = vow.defer(); defer.reject(Error('Internal error')); defer.promise().done(); // exception to be thrown ```
[ "Like", "then", "but", "terminates", "a", "chain", "of", "promises", ".", "If", "the", "promise", "has", "been", "rejected", "this", "method", "throws", "it", "s", "reason", "as", "an", "exception", "in", "a", "future", "turn", "of", "the", "event", "loop", "." ]
5e0fb3596f52ec35f3889c888d3f01a7057a17b3
https://github.com/dfilatov/vow/blob/5e0fb3596f52ec35f3889c888d3f01a7057a17b3/lib/vow.js#L514-L518
20,065
dfilatov/vow
lib/vow.js
function(delay) { var timer, promise = this.then(function(val) { var defer = new Deferred(); timer = setTimeout( function() { defer.resolve(val); }, delay); return defer.promise(); }); promise.always(function() { clearTimeout(timer); }); return promise; }
javascript
function(delay) { var timer, promise = this.then(function(val) { var defer = new Deferred(); timer = setTimeout( function() { defer.resolve(val); }, delay); return defer.promise(); }); promise.always(function() { clearTimeout(timer); }); return promise; }
[ "function", "(", "delay", ")", "{", "var", "timer", ",", "promise", "=", "this", ".", "then", "(", "function", "(", "val", ")", "{", "var", "defer", "=", "new", "Deferred", "(", ")", ";", "timer", "=", "setTimeout", "(", "function", "(", ")", "{", "defer", ".", "resolve", "(", "val", ")", ";", "}", ",", "delay", ")", ";", "return", "defer", ".", "promise", "(", ")", ";", "}", ")", ";", "promise", ".", "always", "(", "function", "(", ")", "{", "clearTimeout", "(", "timer", ")", ";", "}", ")", ";", "return", "promise", ";", "}" ]
Returns a new promise that will be fulfilled in `delay` milliseconds if the promise is fulfilled, or immediately rejected if the promise is rejected. @param {Number} delay @returns {vow:Promise}
[ "Returns", "a", "new", "promise", "that", "will", "be", "fulfilled", "in", "delay", "milliseconds", "if", "the", "promise", "is", "fulfilled", "or", "immediately", "rejected", "if", "the", "promise", "is", "rejected", "." ]
5e0fb3596f52ec35f3889c888d3f01a7057a17b3
https://github.com/dfilatov/vow/blob/5e0fb3596f52ec35f3889c888d3f01a7057a17b3/lib/vow.js#L527-L545
20,066
dfilatov/vow
lib/vow.js
function(timeout) { var defer = new Deferred(), timer = setTimeout( function() { defer.reject(new vow.TimedOutError('timed out')); }, timeout); this.then( function(val) { defer.resolve(val); }, function(reason) { defer.reject(reason); }); defer.promise().always(function() { clearTimeout(timer); }); return defer.promise(); }
javascript
function(timeout) { var defer = new Deferred(), timer = setTimeout( function() { defer.reject(new vow.TimedOutError('timed out')); }, timeout); this.then( function(val) { defer.resolve(val); }, function(reason) { defer.reject(reason); }); defer.promise().always(function() { clearTimeout(timer); }); return defer.promise(); }
[ "function", "(", "timeout", ")", "{", "var", "defer", "=", "new", "Deferred", "(", ")", ",", "timer", "=", "setTimeout", "(", "function", "(", ")", "{", "defer", ".", "reject", "(", "new", "vow", ".", "TimedOutError", "(", "'timed out'", ")", ")", ";", "}", ",", "timeout", ")", ";", "this", ".", "then", "(", "function", "(", "val", ")", "{", "defer", ".", "resolve", "(", "val", ")", ";", "}", ",", "function", "(", "reason", ")", "{", "defer", ".", "reject", "(", "reason", ")", ";", "}", ")", ";", "defer", ".", "promise", "(", ")", ".", "always", "(", "function", "(", ")", "{", "clearTimeout", "(", "timer", ")", ";", "}", ")", ";", "return", "defer", ".", "promise", "(", ")", ";", "}" ]
Returns a new promise that will be rejected in `timeout` milliseconds if the promise is not resolved beforehand. @param {Number} timeout @returns {vow:Promise} @example ```js var defer = vow.defer(), promiseWithTimeout1 = defer.promise().timeout(50), promiseWithTimeout2 = defer.promise().timeout(200); setTimeout( function() { defer.resolve('ok'); }, 100); promiseWithTimeout1.fail(function(reason) { // promiseWithTimeout to be rejected in 50ms }); promiseWithTimeout2.then(function(value) { // promiseWithTimeout to be fulfilled with "'ok'" value }); ```
[ "Returns", "a", "new", "promise", "that", "will", "be", "rejected", "in", "timeout", "milliseconds", "if", "the", "promise", "is", "not", "resolved", "beforehand", "." ]
5e0fb3596f52ec35f3889c888d3f01a7057a17b3
https://github.com/dfilatov/vow/blob/5e0fb3596f52ec35f3889c888d3f01a7057a17b3/lib/vow.js#L575-L596
20,067
dfilatov/vow
lib/vow.js
function(value, onFulfilled, onRejected, onProgress, ctx) { return vow.cast(value).then(onFulfilled, onRejected, onProgress, ctx); }
javascript
function(value, onFulfilled, onRejected, onProgress, ctx) { return vow.cast(value).then(onFulfilled, onRejected, onProgress, ctx); }
[ "function", "(", "value", ",", "onFulfilled", ",", "onRejected", ",", "onProgress", ",", "ctx", ")", "{", "return", "vow", ".", "cast", "(", "value", ")", ".", "then", "(", "onFulfilled", ",", "onRejected", ",", "onProgress", ",", "ctx", ")", ";", "}" ]
Static equivalent to `promise.then`. If `value` is not a promise, then `value` is treated as a fulfilled promise. @param {*} value @param {Function} [onFulfilled] Callback that will be invoked with a provided value after the promise has been fulfilled @param {Function} [onRejected] Callback that will be invoked with a provided reason after the promise has been rejected @param {Function} [onProgress] Callback that will be invoked with a provided value after the promise has been notified @param {Object} [ctx] Context of the callbacks execution @returns {vow:Promise}
[ "Static", "equivalent", "to", "promise", ".", "then", ".", "If", "value", "is", "not", "a", "promise", "then", "value", "is", "treated", "as", "a", "fulfilled", "promise", "." ]
5e0fb3596f52ec35f3889c888d3f01a7057a17b3
https://github.com/dfilatov/vow/blob/5e0fb3596f52ec35f3889c888d3f01a7057a17b3/lib/vow.js#L885-L887
20,068
dfilatov/vow
lib/vow.js
function(value, onFulfilled, onRejected, ctx) { return vow.when(value).spread(onFulfilled, onRejected, ctx); }
javascript
function(value, onFulfilled, onRejected, ctx) { return vow.when(value).spread(onFulfilled, onRejected, ctx); }
[ "function", "(", "value", ",", "onFulfilled", ",", "onRejected", ",", "ctx", ")", "{", "return", "vow", ".", "when", "(", "value", ")", ".", "spread", "(", "onFulfilled", ",", "onRejected", ",", "ctx", ")", ";", "}" ]
Static equivalent to `promise.spread`. If `value` is not a promise, then `value` is treated as a fulfilled promise. @param {*} value @param {Function} [onFulfilled] Callback that will be invoked with a provided value after the promise has been fulfilled @param {Function} [onRejected] Callback that will be invoked with a provided reason after the promise has been rejected @param {Object} [ctx] Context of the callbacks execution @returns {vow:Promise}
[ "Static", "equivalent", "to", "promise", ".", "spread", ".", "If", "value", "is", "not", "a", "promise", "then", "value", "is", "treated", "as", "a", "fulfilled", "promise", "." ]
5e0fb3596f52ec35f3889c888d3f01a7057a17b3
https://github.com/dfilatov/vow/blob/5e0fb3596f52ec35f3889c888d3f01a7057a17b3/lib/vow.js#L938-L940
20,069
dfilatov/vow
lib/vow.js
function(value, onFulfilled, onRejected, onProgress, ctx) { vow.when(value).done(onFulfilled, onRejected, onProgress, ctx); }
javascript
function(value, onFulfilled, onRejected, onProgress, ctx) { vow.when(value).done(onFulfilled, onRejected, onProgress, ctx); }
[ "function", "(", "value", ",", "onFulfilled", ",", "onRejected", ",", "onProgress", ",", "ctx", ")", "{", "vow", ".", "when", "(", "value", ")", ".", "done", "(", "onFulfilled", ",", "onRejected", ",", "onProgress", ",", "ctx", ")", ";", "}" ]
Static equivalent to `promise.done`. If `value` is not a promise, then `value` is treated as a fulfilled promise. @param {*} value @param {Function} [onFulfilled] Callback that will be invoked with a provided value after the promise has been fulfilled @param {Function} [onRejected] Callback that will be invoked with a provided reason after the promise has been rejected @param {Function} [onProgress] Callback that will be invoked with a provided value after the promise has been notified @param {Object} [ctx] Context of the callbacks execution
[ "Static", "equivalent", "to", "promise", ".", "done", ".", "If", "value", "is", "not", "a", "promise", "then", "value", "is", "treated", "as", "a", "fulfilled", "promise", "." ]
5e0fb3596f52ec35f3889c888d3f01a7057a17b3
https://github.com/dfilatov/vow/blob/5e0fb3596f52ec35f3889c888d3f01a7057a17b3/lib/vow.js#L952-L954
20,070
dfilatov/vow
lib/vow.js
function(fn, args) { var len = Math.max(arguments.length - 1, 0), callArgs; if(len) { // optimization for V8 callArgs = Array(len); var i = 0; while(i < len) { callArgs[i++] = arguments[i]; } } try { return vow.resolve(callArgs? fn.apply(global, callArgs) : fn.call(global)); } catch(e) { return vow.reject(e); } }
javascript
function(fn, args) { var len = Math.max(arguments.length - 1, 0), callArgs; if(len) { // optimization for V8 callArgs = Array(len); var i = 0; while(i < len) { callArgs[i++] = arguments[i]; } } try { return vow.resolve(callArgs? fn.apply(global, callArgs) : fn.call(global)); } catch(e) { return vow.reject(e); } }
[ "function", "(", "fn", ",", "args", ")", "{", "var", "len", "=", "Math", ".", "max", "(", "arguments", ".", "length", "-", "1", ",", "0", ")", ",", "callArgs", ";", "if", "(", "len", ")", "{", "// optimization for V8", "callArgs", "=", "Array", "(", "len", ")", ";", "var", "i", "=", "0", ";", "while", "(", "i", "<", "len", ")", "{", "callArgs", "[", "i", "++", "]", "=", "arguments", "[", "i", "]", ";", "}", "}", "try", "{", "return", "vow", ".", "resolve", "(", "callArgs", "?", "fn", ".", "apply", "(", "global", ",", "callArgs", ")", ":", "fn", ".", "call", "(", "global", ")", ")", ";", "}", "catch", "(", "e", ")", "{", "return", "vow", ".", "reject", "(", "e", ")", ";", "}", "}" ]
Invokes the given function `fn` with arguments `args` @param {Function} fn @param {...*} [args] @returns {vow:Promise} @example ```js var promise1 = vow.invoke(function(value) { return value; }, 'ok'), promise2 = vow.invoke(function() { throw Error(); }); promise1.isFulfilled(); // true promise1.valueOf(); // 'ok' promise2.isRejected(); // true promise2.valueOf(); // instance of Error ```
[ "Invokes", "the", "given", "function", "fn", "with", "arguments", "args" ]
5e0fb3596f52ec35f3889c888d3f01a7057a17b3
https://github.com/dfilatov/vow/blob/5e0fb3596f52ec35f3889c888d3f01a7057a17b3/lib/vow.js#L1097-L1116
20,071
dfilatov/vow
lib/vow.js
function(iterable) { var defer = new Deferred(), isPromisesArray = isArray(iterable), keys = isPromisesArray? getArrayKeys(iterable) : getObjectKeys(iterable), len = keys.length, res = isPromisesArray? [] : {}; if(!len) { defer.resolve(res); return defer.promise(); } var i = len; vow._forEach( iterable, function(value, idx) { res[keys[idx]] = value; if(!--i) { defer.resolve(res); } }, defer.reject, defer.notify, defer, keys); return defer.promise(); }
javascript
function(iterable) { var defer = new Deferred(), isPromisesArray = isArray(iterable), keys = isPromisesArray? getArrayKeys(iterable) : getObjectKeys(iterable), len = keys.length, res = isPromisesArray? [] : {}; if(!len) { defer.resolve(res); return defer.promise(); } var i = len; vow._forEach( iterable, function(value, idx) { res[keys[idx]] = value; if(!--i) { defer.resolve(res); } }, defer.reject, defer.notify, defer, keys); return defer.promise(); }
[ "function", "(", "iterable", ")", "{", "var", "defer", "=", "new", "Deferred", "(", ")", ",", "isPromisesArray", "=", "isArray", "(", "iterable", ")", ",", "keys", "=", "isPromisesArray", "?", "getArrayKeys", "(", "iterable", ")", ":", "getObjectKeys", "(", "iterable", ")", ",", "len", "=", "keys", ".", "length", ",", "res", "=", "isPromisesArray", "?", "[", "]", ":", "{", "}", ";", "if", "(", "!", "len", ")", "{", "defer", ".", "resolve", "(", "res", ")", ";", "return", "defer", ".", "promise", "(", ")", ";", "}", "var", "i", "=", "len", ";", "vow", ".", "_forEach", "(", "iterable", ",", "function", "(", "value", ",", "idx", ")", "{", "res", "[", "keys", "[", "idx", "]", "]", "=", "value", ";", "if", "(", "!", "--", "i", ")", "{", "defer", ".", "resolve", "(", "res", ")", ";", "}", "}", ",", "defer", ".", "reject", ",", "defer", ".", "notify", ",", "defer", ",", "keys", ")", ";", "return", "defer", ".", "promise", "(", ")", ";", "}" ]
Returns a promise, that will be fulfilled only after all the items in `iterable` are fulfilled. If any of the `iterable` items gets rejected, the promise will be rejected. @param {Array|Object} iterable @returns {vow:Promise} @example with array: ```js var defer1 = vow.defer(), defer2 = vow.defer(); vow.all([defer1.promise(), defer2.promise(), 3]) .then(function(value) { // value is "[1, 2, 3]" here }); defer1.resolve(1); defer2.resolve(2); ``` @example with object: ```js var defer1 = vow.defer(), defer2 = vow.defer(); vow.all({ p1 : defer1.promise(), p2 : defer2.promise(), p3 : 3 }) .then(function(value) { // value is "{ p1 : 1, p2 : 2, p3 : 3 }" here }); defer1.resolve(1); defer2.resolve(2); ```
[ "Returns", "a", "promise", "that", "will", "be", "fulfilled", "only", "after", "all", "the", "items", "in", "iterable", "are", "fulfilled", ".", "If", "any", "of", "the", "iterable", "items", "gets", "rejected", "the", "promise", "will", "be", "rejected", "." ]
5e0fb3596f52ec35f3889c888d3f01a7057a17b3
https://github.com/dfilatov/vow/blob/5e0fb3596f52ec35f3889c888d3f01a7057a17b3/lib/vow.js#L1155-L1184
20,072
dfilatov/vow
lib/vow.js
function(iterable) { var defer = new Deferred(), isPromisesArray = isArray(iterable), keys = isPromisesArray? getArrayKeys(iterable) : getObjectKeys(iterable), i = keys.length, res = isPromisesArray? [] : {}; if(!i) { defer.resolve(res); return defer.promise(); } var onResolved = function() { --i || defer.resolve(iterable); }; vow._forEach( iterable, onResolved, onResolved, defer.notify, defer, keys); return defer.promise(); }
javascript
function(iterable) { var defer = new Deferred(), isPromisesArray = isArray(iterable), keys = isPromisesArray? getArrayKeys(iterable) : getObjectKeys(iterable), i = keys.length, res = isPromisesArray? [] : {}; if(!i) { defer.resolve(res); return defer.promise(); } var onResolved = function() { --i || defer.resolve(iterable); }; vow._forEach( iterable, onResolved, onResolved, defer.notify, defer, keys); return defer.promise(); }
[ "function", "(", "iterable", ")", "{", "var", "defer", "=", "new", "Deferred", "(", ")", ",", "isPromisesArray", "=", "isArray", "(", "iterable", ")", ",", "keys", "=", "isPromisesArray", "?", "getArrayKeys", "(", "iterable", ")", ":", "getObjectKeys", "(", "iterable", ")", ",", "i", "=", "keys", ".", "length", ",", "res", "=", "isPromisesArray", "?", "[", "]", ":", "{", "}", ";", "if", "(", "!", "i", ")", "{", "defer", ".", "resolve", "(", "res", ")", ";", "return", "defer", ".", "promise", "(", ")", ";", "}", "var", "onResolved", "=", "function", "(", ")", "{", "--", "i", "||", "defer", ".", "resolve", "(", "iterable", ")", ";", "}", ";", "vow", ".", "_forEach", "(", "iterable", ",", "onResolved", ",", "onResolved", ",", "defer", ".", "notify", ",", "defer", ",", "keys", ")", ";", "return", "defer", ".", "promise", "(", ")", ";", "}" ]
Returns a promise, that will be fulfilled only after all the items in `iterable` are resolved. @param {Array|Object} iterable @returns {vow:Promise} @example ```js var defer1 = vow.defer(), defer2 = vow.defer(); vow.allResolved([defer1.promise(), defer2.promise()]).spread(function(promise1, promise2) { promise1.isRejected(); // returns true promise1.valueOf(); // returns "'error'" promise2.isFulfilled(); // returns true promise2.valueOf(); // returns "'ok'" }); defer1.reject('error'); defer2.resolve('ok'); ```
[ "Returns", "a", "promise", "that", "will", "be", "fulfilled", "only", "after", "all", "the", "items", "in", "iterable", "are", "resolved", "." ]
5e0fb3596f52ec35f3889c888d3f01a7057a17b3
https://github.com/dfilatov/vow/blob/5e0fb3596f52ec35f3889c888d3f01a7057a17b3/lib/vow.js#L1208-L1235
20,073
bojand/lounge
lib/model.js
compilePlainObject
function compilePlainObject (schema, options) { class PlainModelInstance extends PlainBaseModel { constructor (data, options = {}) { super(data, options, schema) } } PlainModelInstance.schema = schema // if the user wants to allow modifications if (options.freeze !== false) { Object.freeze(PlainModelInstance) } return PlainModelInstance }
javascript
function compilePlainObject (schema, options) { class PlainModelInstance extends PlainBaseModel { constructor (data, options = {}) { super(data, options, schema) } } PlainModelInstance.schema = schema // if the user wants to allow modifications if (options.freeze !== false) { Object.freeze(PlainModelInstance) } return PlainModelInstance }
[ "function", "compilePlainObject", "(", "schema", ",", "options", ")", "{", "class", "PlainModelInstance", "extends", "PlainBaseModel", "{", "constructor", "(", "data", ",", "options", "=", "{", "}", ")", "{", "super", "(", "data", ",", "options", ",", "schema", ")", "}", "}", "PlainModelInstance", ".", "schema", "=", "schema", "// if the user wants to allow modifications", "if", "(", "options", ".", "freeze", "!==", "false", ")", "{", "Object", ".", "freeze", "(", "PlainModelInstance", ")", "}", "return", "PlainModelInstance", "}" ]
Compiles a schema into a Model @param schema @param options @returns {ObjectInstance} @private
[ "Compiles", "a", "schema", "into", "a", "Model" ]
c25b42b0a41546525adc81e617e57f76188322ce
https://github.com/bojand/lounge/blob/c25b42b0a41546525adc81e617e57f76188322ce/lib/model.js#L29-L44
20,074
nodeca/types
lib/types/sorted_list.js
get_sequence
function get_sequence(self, weight) { if (undefined === self.__sequences__[weight]) { self.__sequences__[weight] = []; } return self.__sequences__[weight]; }
javascript
function get_sequence(self, weight) { if (undefined === self.__sequences__[weight]) { self.__sequences__[weight] = []; } return self.__sequences__[weight]; }
[ "function", "get_sequence", "(", "self", ",", "weight", ")", "{", "if", "(", "undefined", "===", "self", ".", "__sequences__", "[", "weight", "]", ")", "{", "self", ".", "__sequences__", "[", "weight", "]", "=", "[", "]", ";", "}", "return", "self", ".", "__sequences__", "[", "weight", "]", ";", "}" ]
returns sequence array for given weight
[ "returns", "sequence", "array", "for", "given", "weight" ]
c85d3b680fbef7cb5dbdd33f05783bdddfe48c53
https://github.com/nodeca/types/blob/c85d3b680fbef7cb5dbdd33f05783bdddfe48c53/lib/types/sorted_list.js#L31-L37
20,075
redco/goose-parser
lib/tools/wait.js
waitForEvaluate
async function waitForEvaluate(env, evalFunction, checkerFunction, breakerFunction, args, timeout, interval) { args = args || []; checkerFunction = checkerFunction || function(result) { return !!result }; timeout = timeout || 5000; interval = interval || 10; let timeoutId, intervalId; return new Promise((resolve, reject) => { const errorCallback = { fn: ({ error }) => { clearTimeout(timeoutId); clearInterval(intervalId); reject(new Error(`Error during wait with args ${args.toString()}, ${error}`)); }, }; timeoutId = setTimeout(() => { env.removeCallback('error', errorCallback); clearInterval(intervalId); reject(new Error(`Timeout for wait with args ${args.toString()}`)); }, timeout); env.addCallback('error', errorCallback); const evalArgs = args.slice(0); evalArgs.push(evalFunction); intervalId = setInterval(() => { env.evaluateJs(...evalArgs) .then((result) => { if (checkerFunction(result)) { clearTimeout(timeoutId); clearInterval(intervalId); env.removeCallback('error', errorCallback); resolve(); return; } if (breakerFunction()) { clearTimeout(timeoutId); clearInterval(intervalId); env.removeCallback('error', errorCallback); reject(new Error('Function was terminated by breaker')); } }); }, interval); }); }
javascript
async function waitForEvaluate(env, evalFunction, checkerFunction, breakerFunction, args, timeout, interval) { args = args || []; checkerFunction = checkerFunction || function(result) { return !!result }; timeout = timeout || 5000; interval = interval || 10; let timeoutId, intervalId; return new Promise((resolve, reject) => { const errorCallback = { fn: ({ error }) => { clearTimeout(timeoutId); clearInterval(intervalId); reject(new Error(`Error during wait with args ${args.toString()}, ${error}`)); }, }; timeoutId = setTimeout(() => { env.removeCallback('error', errorCallback); clearInterval(intervalId); reject(new Error(`Timeout for wait with args ${args.toString()}`)); }, timeout); env.addCallback('error', errorCallback); const evalArgs = args.slice(0); evalArgs.push(evalFunction); intervalId = setInterval(() => { env.evaluateJs(...evalArgs) .then((result) => { if (checkerFunction(result)) { clearTimeout(timeoutId); clearInterval(intervalId); env.removeCallback('error', errorCallback); resolve(); return; } if (breakerFunction()) { clearTimeout(timeoutId); clearInterval(intervalId); env.removeCallback('error', errorCallback); reject(new Error('Function was terminated by breaker')); } }); }, interval); }); }
[ "async", "function", "waitForEvaluate", "(", "env", ",", "evalFunction", ",", "checkerFunction", ",", "breakerFunction", ",", "args", ",", "timeout", ",", "interval", ")", "{", "args", "=", "args", "||", "[", "]", ";", "checkerFunction", "=", "checkerFunction", "||", "function", "(", "result", ")", "{", "return", "!", "!", "result", "}", ";", "timeout", "=", "timeout", "||", "5000", ";", "interval", "=", "interval", "||", "10", ";", "let", "timeoutId", ",", "intervalId", ";", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "const", "errorCallback", "=", "{", "fn", ":", "(", "{", "error", "}", ")", "=>", "{", "clearTimeout", "(", "timeoutId", ")", ";", "clearInterval", "(", "intervalId", ")", ";", "reject", "(", "new", "Error", "(", "`", "${", "args", ".", "toString", "(", ")", "}", "${", "error", "}", "`", ")", ")", ";", "}", ",", "}", ";", "timeoutId", "=", "setTimeout", "(", "(", ")", "=>", "{", "env", ".", "removeCallback", "(", "'error'", ",", "errorCallback", ")", ";", "clearInterval", "(", "intervalId", ")", ";", "reject", "(", "new", "Error", "(", "`", "${", "args", ".", "toString", "(", ")", "}", "`", ")", ")", ";", "}", ",", "timeout", ")", ";", "env", ".", "addCallback", "(", "'error'", ",", "errorCallback", ")", ";", "const", "evalArgs", "=", "args", ".", "slice", "(", "0", ")", ";", "evalArgs", ".", "push", "(", "evalFunction", ")", ";", "intervalId", "=", "setInterval", "(", "(", ")", "=>", "{", "env", ".", "evaluateJs", "(", "...", "evalArgs", ")", ".", "then", "(", "(", "result", ")", "=>", "{", "if", "(", "checkerFunction", "(", "result", ")", ")", "{", "clearTimeout", "(", "timeoutId", ")", ";", "clearInterval", "(", "intervalId", ")", ";", "env", ".", "removeCallback", "(", "'error'", ",", "errorCallback", ")", ";", "resolve", "(", ")", ";", "return", ";", "}", "if", "(", "breakerFunction", "(", ")", ")", "{", "clearTimeout", "(", "timeoutId", ")", ";", "clearInterval", "(", "intervalId", ")", ";", "env", ".", "removeCallback", "(", "'error'", ",", "errorCallback", ")", ";", "reject", "(", "new", "Error", "(", "'Function was terminated by breaker'", ")", ")", ";", "}", "}", ")", ";", "}", ",", "interval", ")", ";", "}", ")", ";", "}" ]
Wait until function evalFunction expected in checkerFunction result @param {AbstractEnvironment} env @param {Function} evalFunction @param {Function} [checkerFunction] @param {Function} [breakerFunction] @param {Array} [args] @param {number} [timeout] @param {number} [interval] @returns {Promise}
[ "Wait", "until", "function", "evalFunction", "expected", "in", "checkerFunction", "result" ]
b18b184c5a7ce8adccec000578c48644d9307f11
https://github.com/redco/goose-parser/blob/b18b184c5a7ce8adccec000578c48644d9307f11/lib/tools/wait.js#L12-L60
20,076
redco/goose-parser
lib/tools/wait.js
waitForEvent
async function waitForEvent(env, event, breakerFunction, timeout = 5000, interval = 10) { const { type, urlPattern } = event; let intervalId, timeoutId; await new Promise((resolve, reject) => { const callback = { fn: ({ error }) => { clearTimeout(timeoutId); clearInterval(intervalId); if (error) { reject(error); } else { resolve(); } }, urlPattern, }; timeoutId = setTimeout(() => { env.removeCallback(type, callback); clearInterval(intervalId); reject(new Error('Page navigation timeout')); }, timeout); intervalId = setInterval(() => { if (breakerFunction()) { clearTimeout(timeoutId); clearInterval(intervalId); env.removeCallback(type, callback); reject(new Error('Function was terminated by breaker')) } }, interval); env.addCallback(type, callback); }); if (type === 'navigation') { await env._injectFiles(env._getVendors()); } }
javascript
async function waitForEvent(env, event, breakerFunction, timeout = 5000, interval = 10) { const { type, urlPattern } = event; let intervalId, timeoutId; await new Promise((resolve, reject) => { const callback = { fn: ({ error }) => { clearTimeout(timeoutId); clearInterval(intervalId); if (error) { reject(error); } else { resolve(); } }, urlPattern, }; timeoutId = setTimeout(() => { env.removeCallback(type, callback); clearInterval(intervalId); reject(new Error('Page navigation timeout')); }, timeout); intervalId = setInterval(() => { if (breakerFunction()) { clearTimeout(timeoutId); clearInterval(intervalId); env.removeCallback(type, callback); reject(new Error('Function was terminated by breaker')) } }, interval); env.addCallback(type, callback); }); if (type === 'navigation') { await env._injectFiles(env._getVendors()); } }
[ "async", "function", "waitForEvent", "(", "env", ",", "event", ",", "breakerFunction", ",", "timeout", "=", "5000", ",", "interval", "=", "10", ")", "{", "const", "{", "type", ",", "urlPattern", "}", "=", "event", ";", "let", "intervalId", ",", "timeoutId", ";", "await", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "const", "callback", "=", "{", "fn", ":", "(", "{", "error", "}", ")", "=>", "{", "clearTimeout", "(", "timeoutId", ")", ";", "clearInterval", "(", "intervalId", ")", ";", "if", "(", "error", ")", "{", "reject", "(", "error", ")", ";", "}", "else", "{", "resolve", "(", ")", ";", "}", "}", ",", "urlPattern", ",", "}", ";", "timeoutId", "=", "setTimeout", "(", "(", ")", "=>", "{", "env", ".", "removeCallback", "(", "type", ",", "callback", ")", ";", "clearInterval", "(", "intervalId", ")", ";", "reject", "(", "new", "Error", "(", "'Page navigation timeout'", ")", ")", ";", "}", ",", "timeout", ")", ";", "intervalId", "=", "setInterval", "(", "(", ")", "=>", "{", "if", "(", "breakerFunction", "(", ")", ")", "{", "clearTimeout", "(", "timeoutId", ")", ";", "clearInterval", "(", "intervalId", ")", ";", "env", ".", "removeCallback", "(", "type", ",", "callback", ")", ";", "reject", "(", "new", "Error", "(", "'Function was terminated by breaker'", ")", ")", "}", "}", ",", "interval", ")", ";", "env", ".", "addCallback", "(", "type", ",", "callback", ")", ";", "}", ")", ";", "if", "(", "type", "===", "'navigation'", ")", "{", "await", "env", ".", "_injectFiles", "(", "env", ".", "_getVendors", "(", ")", ")", ";", "}", "}" ]
Wait until event happens @param {ChromeEnvironment} env @param {Object} event @param {Function} [breakerFunction] @param {number} [timeout] @param {number} [interval] @returns {Promise}
[ "Wait", "until", "event", "happens" ]
b18b184c5a7ce8adccec000578c48644d9307f11
https://github.com/redco/goose-parser/blob/b18b184c5a7ce8adccec000578c48644d9307f11/lib/tools/wait.js#L71-L109
20,077
mafintosh/hyperlog
lib/replicate.js
function () { var write = function (node, enc, cb) { node.value = encoder.encode(node.value, dag.valueEncoding) stream.node(node, cb) } stream.emit('live') pipe(dag.createReadStream({since: changes, live: true}), through.obj(write)) }
javascript
function () { var write = function (node, enc, cb) { node.value = encoder.encode(node.value, dag.valueEncoding) stream.node(node, cb) } stream.emit('live') pipe(dag.createReadStream({since: changes, live: true}), through.obj(write)) }
[ "function", "(", ")", "{", "var", "write", "=", "function", "(", "node", ",", "enc", ",", "cb", ")", "{", "node", ".", "value", "=", "encoder", ".", "encode", "(", "node", ".", "value", ",", "dag", ".", "valueEncoding", ")", "stream", ".", "node", "(", "node", ",", "cb", ")", "}", "stream", ".", "emit", "(", "'live'", ")", "pipe", "(", "dag", ".", "createReadStream", "(", "{", "since", ":", "changes", ",", "live", ":", "true", "}", ")", ",", "through", ".", "obj", "(", "write", ")", ")", "}" ]
For live replication. Reads live from the local hyperlog and continues to send new nodes to the other end.
[ "For", "live", "replication", ".", "Reads", "live", "from", "the", "local", "hyperlog", "and", "continues", "to", "send", "new", "nodes", "to", "the", "other", "end", "." ]
df15dc61e913f5db6cf7a31c1c1d0da1d1580be9
https://github.com/mafintosh/hyperlog/blob/df15dc61e913f5db6cf7a31c1c1d0da1d1580be9/lib/replicate.js#L81-L89
20,078
mafintosh/hyperlog
lib/replicate.js
function (cb) { if (done || !localSentWants || !localSentHeads || !remoteSentWants || !remoteSentHeads) return cb() done = true if (!live) return stream.finalize(cb) sendChanges() cb() }
javascript
function (cb) { if (done || !localSentWants || !localSentHeads || !remoteSentWants || !remoteSentHeads) return cb() done = true if (!live) return stream.finalize(cb) sendChanges() cb() }
[ "function", "(", "cb", ")", "{", "if", "(", "done", "||", "!", "localSentWants", "||", "!", "localSentHeads", "||", "!", "remoteSentWants", "||", "!", "remoteSentHeads", ")", "return", "cb", "(", ")", "done", "=", "true", "if", "(", "!", "live", ")", "return", "stream", ".", "finalize", "(", "cb", ")", "sendChanges", "(", ")", "cb", "(", ")", "}" ]
Check if replication is finished.
[ "Check", "if", "replication", "is", "finished", "." ]
df15dc61e913f5db6cf7a31c1c1d0da1d1580be9
https://github.com/mafintosh/hyperlog/blob/df15dc61e913f5db6cf7a31c1c1d0da1d1580be9/lib/replicate.js#L92-L98
20,079
mafintosh/hyperlog
lib/replicate.js
function (log, seq, cb) { dag.logs.get(log, seq, function (err, entry) { if (err && err.notFound) return cb() if (err) return cb(err) if (entry.change > changes) return cb() // ensure snapshot entry.log = log entry.seq = seq var i = 0 var loop = function () { if (i < entry.links.length) return sendHave(entry.links[i++], loop) entry.links = noarr // premature opt: less mem yo outgoing.push(entry, cb) } loop() }) }
javascript
function (log, seq, cb) { dag.logs.get(log, seq, function (err, entry) { if (err && err.notFound) return cb() if (err) return cb(err) if (entry.change > changes) return cb() // ensure snapshot entry.log = log entry.seq = seq var i = 0 var loop = function () { if (i < entry.links.length) return sendHave(entry.links[i++], loop) entry.links = noarr // premature opt: less mem yo outgoing.push(entry, cb) } loop() }) }
[ "function", "(", "log", ",", "seq", ",", "cb", ")", "{", "dag", ".", "logs", ".", "get", "(", "log", ",", "seq", ",", "function", "(", "err", ",", "entry", ")", "{", "if", "(", "err", "&&", "err", ".", "notFound", ")", "return", "cb", "(", ")", "if", "(", "err", ")", "return", "cb", "(", "err", ")", "if", "(", "entry", ".", "change", ">", "changes", ")", "return", "cb", "(", ")", "// ensure snapshot", "entry", ".", "log", "=", "log", "entry", ".", "seq", "=", "seq", "var", "i", "=", "0", "var", "loop", "=", "function", "(", ")", "{", "if", "(", "i", "<", "entry", ".", "links", ".", "length", ")", "return", "sendHave", "(", "entry", ".", "links", "[", "i", "++", "]", ",", "loop", ")", "entry", ".", "links", "=", "noarr", "// premature opt: less mem yo", "outgoing", ".", "push", "(", "entry", ",", "cb", ")", "}", "loop", "(", ")", "}", ")", "}" ]
Send a specific entry in a specific log to the other side. If the node links to other nodes, inform the other side we have those, too.
[ "Send", "a", "specific", "entry", "in", "a", "specific", "log", "to", "the", "other", "side", ".", "If", "the", "node", "links", "to", "other", "nodes", "inform", "the", "other", "side", "we", "have", "those", "too", "." ]
df15dc61e913f5db6cf7a31c1c1d0da1d1580be9
https://github.com/mafintosh/hyperlog/blob/df15dc61e913f5db6cf7a31c1c1d0da1d1580be9/lib/replicate.js#L117-L135
20,080
mafintosh/hyperlog
index.js
function (dag, node, logLinks, batch, opts, cb) { if (opts.hash && node.key !== opts.hash) return cb(CHECKSUM_MISMATCH) if (opts.seq && node.seq !== opts.seq) return cb(INVALID_LOG) var log = { change: node.change, node: node.key, links: logLinks } var onclone = function (clone) { if (!opts.log) return cb(null, clone, []) batch.push({type: 'put', key: dag.logs.key(node.log, node.seq), value: messages.Entry.encode(log)}) cb(null, clone) } var done = function () { dag.get(node.key, { valueEncoding: 'binary' }, function (_, clone) { // This node already exists somewhere in the hyperlog; add it to the // log's append-only log, but don't insert it again. if (clone) return onclone(clone) var links = node.links for (var i = 0; i < links.length; i++) batch.push({type: 'del', key: HEADS + links[i]}) batch.push({type: 'put', key: CHANGES + lexint.pack(node.change, 'hex'), value: node.key}) batch.push({type: 'put', key: NODES + node.key, value: messages.Node.encode(node)}) batch.push({type: 'put', key: HEADS + node.key, value: node.key}) batch.push({type: 'put', key: dag.logs.key(node.log, node.seq), value: messages.Entry.encode(log)}) cb(null, node) }) } // Local node; sign it. if (node.log === dag.id) { if (!dag.sign || node.signature) return done() dag.sign(node, function (err, sig) { if (err) return cb(err) if (!node.identity) node.identity = dag.identity node.signature = sig done() }) // Remote node; verify it. } else { if (!dag.verify) return done() dag.verify(node, function (err, valid) { if (err) return cb(err) if (!valid) return cb(INVALID_SIGNATURE) done() }) } }
javascript
function (dag, node, logLinks, batch, opts, cb) { if (opts.hash && node.key !== opts.hash) return cb(CHECKSUM_MISMATCH) if (opts.seq && node.seq !== opts.seq) return cb(INVALID_LOG) var log = { change: node.change, node: node.key, links: logLinks } var onclone = function (clone) { if (!opts.log) return cb(null, clone, []) batch.push({type: 'put', key: dag.logs.key(node.log, node.seq), value: messages.Entry.encode(log)}) cb(null, clone) } var done = function () { dag.get(node.key, { valueEncoding: 'binary' }, function (_, clone) { // This node already exists somewhere in the hyperlog; add it to the // log's append-only log, but don't insert it again. if (clone) return onclone(clone) var links = node.links for (var i = 0; i < links.length; i++) batch.push({type: 'del', key: HEADS + links[i]}) batch.push({type: 'put', key: CHANGES + lexint.pack(node.change, 'hex'), value: node.key}) batch.push({type: 'put', key: NODES + node.key, value: messages.Node.encode(node)}) batch.push({type: 'put', key: HEADS + node.key, value: node.key}) batch.push({type: 'put', key: dag.logs.key(node.log, node.seq), value: messages.Entry.encode(log)}) cb(null, node) }) } // Local node; sign it. if (node.log === dag.id) { if (!dag.sign || node.signature) return done() dag.sign(node, function (err, sig) { if (err) return cb(err) if (!node.identity) node.identity = dag.identity node.signature = sig done() }) // Remote node; verify it. } else { if (!dag.verify) return done() dag.verify(node, function (err, valid) { if (err) return cb(err) if (!valid) return cb(INVALID_SIGNATURE) done() }) } }
[ "function", "(", "dag", ",", "node", ",", "logLinks", ",", "batch", ",", "opts", ",", "cb", ")", "{", "if", "(", "opts", ".", "hash", "&&", "node", ".", "key", "!==", "opts", ".", "hash", ")", "return", "cb", "(", "CHECKSUM_MISMATCH", ")", "if", "(", "opts", ".", "seq", "&&", "node", ".", "seq", "!==", "opts", ".", "seq", ")", "return", "cb", "(", "INVALID_LOG", ")", "var", "log", "=", "{", "change", ":", "node", ".", "change", ",", "node", ":", "node", ".", "key", ",", "links", ":", "logLinks", "}", "var", "onclone", "=", "function", "(", "clone", ")", "{", "if", "(", "!", "opts", ".", "log", ")", "return", "cb", "(", "null", ",", "clone", ",", "[", "]", ")", "batch", ".", "push", "(", "{", "type", ":", "'put'", ",", "key", ":", "dag", ".", "logs", ".", "key", "(", "node", ".", "log", ",", "node", ".", "seq", ")", ",", "value", ":", "messages", ".", "Entry", ".", "encode", "(", "log", ")", "}", ")", "cb", "(", "null", ",", "clone", ")", "}", "var", "done", "=", "function", "(", ")", "{", "dag", ".", "get", "(", "node", ".", "key", ",", "{", "valueEncoding", ":", "'binary'", "}", ",", "function", "(", "_", ",", "clone", ")", "{", "// This node already exists somewhere in the hyperlog; add it to the", "// log's append-only log, but don't insert it again.", "if", "(", "clone", ")", "return", "onclone", "(", "clone", ")", "var", "links", "=", "node", ".", "links", "for", "(", "var", "i", "=", "0", ";", "i", "<", "links", ".", "length", ";", "i", "++", ")", "batch", ".", "push", "(", "{", "type", ":", "'del'", ",", "key", ":", "HEADS", "+", "links", "[", "i", "]", "}", ")", "batch", ".", "push", "(", "{", "type", ":", "'put'", ",", "key", ":", "CHANGES", "+", "lexint", ".", "pack", "(", "node", ".", "change", ",", "'hex'", ")", ",", "value", ":", "node", ".", "key", "}", ")", "batch", ".", "push", "(", "{", "type", ":", "'put'", ",", "key", ":", "NODES", "+", "node", ".", "key", ",", "value", ":", "messages", ".", "Node", ".", "encode", "(", "node", ")", "}", ")", "batch", ".", "push", "(", "{", "type", ":", "'put'", ",", "key", ":", "HEADS", "+", "node", ".", "key", ",", "value", ":", "node", ".", "key", "}", ")", "batch", ".", "push", "(", "{", "type", ":", "'put'", ",", "key", ":", "dag", ".", "logs", ".", "key", "(", "node", ".", "log", ",", "node", ".", "seq", ")", ",", "value", ":", "messages", ".", "Entry", ".", "encode", "(", "log", ")", "}", ")", "cb", "(", "null", ",", "node", ")", "}", ")", "}", "// Local node; sign it.", "if", "(", "node", ".", "log", "===", "dag", ".", "id", ")", "{", "if", "(", "!", "dag", ".", "sign", "||", "node", ".", "signature", ")", "return", "done", "(", ")", "dag", ".", "sign", "(", "node", ",", "function", "(", "err", ",", "sig", ")", "{", "if", "(", "err", ")", "return", "cb", "(", "err", ")", "if", "(", "!", "node", ".", "identity", ")", "node", ".", "identity", "=", "dag", ".", "identity", "node", ".", "signature", "=", "sig", "done", "(", ")", "}", ")", "// Remote node; verify it.", "}", "else", "{", "if", "(", "!", "dag", ".", "verify", ")", "return", "done", "(", ")", "dag", ".", "verify", "(", "node", ",", "function", "(", "err", ",", "valid", ")", "{", "if", "(", "err", ")", "return", "cb", "(", "err", ")", "if", "(", "!", "valid", ")", "return", "cb", "(", "INVALID_SIGNATURE", ")", "done", "(", ")", "}", ")", "}", "}" ]
Adds a new hyperlog node to an existing array of leveldb batch insertions. This includes performing crypto signing and verification. Performs deduplication; returns the existing node if alreay present in the hyperlog.
[ "Adds", "a", "new", "hyperlog", "node", "to", "an", "existing", "array", "of", "leveldb", "batch", "insertions", ".", "This", "includes", "performing", "crypto", "signing", "and", "verification", ".", "Performs", "deduplication", ";", "returns", "the", "existing", "node", "if", "alreay", "present", "in", "the", "hyperlog", "." ]
df15dc61e913f5db6cf7a31c1c1d0da1d1580be9
https://github.com/mafintosh/hyperlog/blob/df15dc61e913f5db6cf7a31c1c1d0da1d1580be9/index.js#L152-L203
20,081
mafintosh/hyperlog
index.js
function (dag, opts) { var since = opts.since || 0 var limit = opts.limit || -1 var wait = null var read = function (size, cb) { if (dag.changes <= since) { wait = cb return } if (!limit) return cb(null, null) dag.db.get(CHANGES + lexint.pack(since + 1, 'hex'), function (err, hash) { if (err) return cb(err) dag.get(hash, opts, function (err, node) { if (err) return cb(err) since = node.change if (limit !== -1) limit-- cb(null, node) }) }) } var kick = function () { if (!wait) return var cb = wait wait = null read(0, cb) } dag.on('add', kick) dag.ready(kick) var rs = from.obj(read) rs.once('close', function () { dag.removeListener('add', kick) }) return rs }
javascript
function (dag, opts) { var since = opts.since || 0 var limit = opts.limit || -1 var wait = null var read = function (size, cb) { if (dag.changes <= since) { wait = cb return } if (!limit) return cb(null, null) dag.db.get(CHANGES + lexint.pack(since + 1, 'hex'), function (err, hash) { if (err) return cb(err) dag.get(hash, opts, function (err, node) { if (err) return cb(err) since = node.change if (limit !== -1) limit-- cb(null, node) }) }) } var kick = function () { if (!wait) return var cb = wait wait = null read(0, cb) } dag.on('add', kick) dag.ready(kick) var rs = from.obj(read) rs.once('close', function () { dag.removeListener('add', kick) }) return rs }
[ "function", "(", "dag", ",", "opts", ")", "{", "var", "since", "=", "opts", ".", "since", "||", "0", "var", "limit", "=", "opts", ".", "limit", "||", "-", "1", "var", "wait", "=", "null", "var", "read", "=", "function", "(", "size", ",", "cb", ")", "{", "if", "(", "dag", ".", "changes", "<=", "since", ")", "{", "wait", "=", "cb", "return", "}", "if", "(", "!", "limit", ")", "return", "cb", "(", "null", ",", "null", ")", "dag", ".", "db", ".", "get", "(", "CHANGES", "+", "lexint", ".", "pack", "(", "since", "+", "1", ",", "'hex'", ")", ",", "function", "(", "err", ",", "hash", ")", "{", "if", "(", "err", ")", "return", "cb", "(", "err", ")", "dag", ".", "get", "(", "hash", ",", "opts", ",", "function", "(", "err", ",", "node", ")", "{", "if", "(", "err", ")", "return", "cb", "(", "err", ")", "since", "=", "node", ".", "change", "if", "(", "limit", "!==", "-", "1", ")", "limit", "--", "cb", "(", "null", ",", "node", ")", "}", ")", "}", ")", "}", "var", "kick", "=", "function", "(", ")", "{", "if", "(", "!", "wait", ")", "return", "var", "cb", "=", "wait", "wait", "=", "null", "read", "(", "0", ",", "cb", ")", "}", "dag", ".", "on", "(", "'add'", ",", "kick", ")", "dag", ".", "ready", "(", "kick", ")", "var", "rs", "=", "from", ".", "obj", "(", "read", ")", "rs", ".", "once", "(", "'close'", ",", "function", "(", ")", "{", "dag", ".", "removeListener", "(", "'add'", ",", "kick", ")", "}", ")", "return", "rs", "}" ]
Produce a readable stream of all nodes added from this point onward, in topographic order.
[ "Produce", "a", "readable", "stream", "of", "all", "nodes", "added", "from", "this", "point", "onward", "in", "topographic", "order", "." ]
df15dc61e913f5db6cf7a31c1c1d0da1d1580be9
https://github.com/mafintosh/hyperlog/blob/df15dc61e913f5db6cf7a31c1c1d0da1d1580be9/index.js#L227-L268
20,082
mafintosh/hyperlog
index.js
function (nodes, batchOps, done) { self.db.batch(batchOps, function (err) { if (err) { nodes.forEach(rejectNode) return done(err) } done(null, nodes) }) }
javascript
function (nodes, batchOps, done) { self.db.batch(batchOps, function (err) { if (err) { nodes.forEach(rejectNode) return done(err) } done(null, nodes) }) }
[ "function", "(", "nodes", ",", "batchOps", ",", "done", ")", "{", "self", ".", "db", ".", "batch", "(", "batchOps", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "nodes", ".", "forEach", "(", "rejectNode", ")", "return", "done", "(", "err", ")", "}", "done", "(", "null", ",", "nodes", ")", "}", ")", "}" ]
10. perform the leveldb batch op
[ "10", ".", "perform", "the", "leveldb", "batch", "op" ]
df15dc61e913f5db6cf7a31c1c1d0da1d1580be9
https://github.com/mafintosh/hyperlog/blob/df15dc61e913f5db6cf7a31c1c1d0da1d1580be9/index.js#L376-L384
20,083
mafintosh/hyperlog
index.js
computeNodeBatchOp
function computeNodeBatchOp (node, done) { var batch = [] var links = logLinks[node.key] addBatchAndDedupe(self, node, links, batch, opts, function (err, newNode) { if (err) return done(err) newNode.value = encoder.decode(newNode.value, opts.valueEncoding || self.valueEncoding) done(null, batch) }) }
javascript
function computeNodeBatchOp (node, done) { var batch = [] var links = logLinks[node.key] addBatchAndDedupe(self, node, links, batch, opts, function (err, newNode) { if (err) return done(err) newNode.value = encoder.decode(newNode.value, opts.valueEncoding || self.valueEncoding) done(null, batch) }) }
[ "function", "computeNodeBatchOp", "(", "node", ",", "done", ")", "{", "var", "batch", "=", "[", "]", "var", "links", "=", "logLinks", "[", "node", ".", "key", "]", "addBatchAndDedupe", "(", "self", ",", "node", ",", "links", ",", "batch", ",", "opts", ",", "function", "(", "err", ",", "newNode", ")", "{", "if", "(", "err", ")", "return", "done", "(", "err", ")", "newNode", ".", "value", "=", "encoder", ".", "decode", "(", "newNode", ".", "value", ",", "opts", ".", "valueEncoding", "||", "self", ".", "valueEncoding", ")", "done", "(", "null", ",", "batch", ")", "}", ")", "}" ]
Create a new leveldb batch operation for this node.
[ "Create", "a", "new", "leveldb", "batch", "operation", "for", "this", "node", "." ]
df15dc61e913f5db6cf7a31c1c1d0da1d1580be9
https://github.com/mafintosh/hyperlog/blob/df15dc61e913f5db6cf7a31c1c1d0da1d1580be9/index.js#L535-L543
20,084
hay/stapes
stapes.js
function() { var args = slice.call(arguments); var object = args.shift(); for (var i = 0, l = args.length; i < l; i++) { var props = args[i]; for (var key in props) { object[key] = props[key]; } } return object; }
javascript
function() { var args = slice.call(arguments); var object = args.shift(); for (var i = 0, l = args.length; i < l; i++) { var props = args[i]; for (var key in props) { object[key] = props[key]; } } return object; }
[ "function", "(", ")", "{", "var", "args", "=", "slice", ".", "call", "(", "arguments", ")", ";", "var", "object", "=", "args", ".", "shift", "(", ")", ";", "for", "(", "var", "i", "=", "0", ",", "l", "=", "args", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "var", "props", "=", "args", "[", "i", "]", ";", "for", "(", "var", "key", "in", "props", ")", "{", "object", "[", "key", "]", "=", "props", "[", "key", "]", ";", "}", "}", "return", "object", ";", "}" ]
Extend an object with more objects
[ "Extend", "an", "object", "with", "more", "objects" ]
4852e68192941a3dde75d335bc7243bebe6099a5
https://github.com/hay/stapes/blob/4852e68192941a3dde75d335bc7243bebe6099a5/stapes.js#L209-L221
20,085
hay/stapes
stapes.js
function() { var args = slice.call(arguments); args.unshift(this); return _.extend.apply(this, args); }
javascript
function() { var args = slice.call(arguments); args.unshift(this); return _.extend.apply(this, args); }
[ "function", "(", ")", "{", "var", "args", "=", "slice", ".", "call", "(", "arguments", ")", ";", "args", ".", "unshift", "(", "this", ")", ";", "return", "_", ".", "extend", ".", "apply", "(", "this", ",", "args", ")", ";", "}" ]
The same as extend, but uses the this value as the scope
[ "The", "same", "as", "extend", "but", "uses", "the", "this", "value", "as", "the", "scope" ]
4852e68192941a3dde75d335bc7243bebe6099a5
https://github.com/hay/stapes/blob/4852e68192941a3dde75d335bc7243bebe6099a5/stapes.js#L224-L228
20,086
Phrogz/svg-path-to-polygons
svg-path-to-polygons.js
compare
function compare(pathData,opts={}) { var polys = svgPathToPolygons(pathData,opts); var minX=Infinity, maxX=-Infinity, minY=Infinity, maxY=-Infinity; polys.forEach(poly => { poly.forEach(pt => { if (pt[0]<minX) minX=pt[0]; if (pt[1]<minY) minY=pt[1]; if (pt[0]>maxX) maxX=pt[0]; if (pt[1]>maxY) maxY=pt[1]; }); }); let dx=maxX-minX, dy=maxY-minY; console.log(` <svg xmlns="http://www.w3.org/2000/svg" width="${dx}px" height="${dy}px" viewBox="${minX} ${minY} ${dx*2} ${dy}"> <style>path,polygon,polyline { fill-opacity:0.2; stroke:black }</style> <path d="${pathData}"/> <g transform="translate(${dx},0)"> ${polys.map(poly => ` <${poly.closed ? 'polygon' : 'polyline'} points="${poly.join(' ')}"/>`).join("\n")} </g> </svg> `.trim()); }
javascript
function compare(pathData,opts={}) { var polys = svgPathToPolygons(pathData,opts); var minX=Infinity, maxX=-Infinity, minY=Infinity, maxY=-Infinity; polys.forEach(poly => { poly.forEach(pt => { if (pt[0]<minX) minX=pt[0]; if (pt[1]<minY) minY=pt[1]; if (pt[0]>maxX) maxX=pt[0]; if (pt[1]>maxY) maxY=pt[1]; }); }); let dx=maxX-minX, dy=maxY-minY; console.log(` <svg xmlns="http://www.w3.org/2000/svg" width="${dx}px" height="${dy}px" viewBox="${minX} ${minY} ${dx*2} ${dy}"> <style>path,polygon,polyline { fill-opacity:0.2; stroke:black }</style> <path d="${pathData}"/> <g transform="translate(${dx},0)"> ${polys.map(poly => ` <${poly.closed ? 'polygon' : 'polyline'} points="${poly.join(' ')}"/>`).join("\n")} </g> </svg> `.trim()); }
[ "function", "compare", "(", "pathData", ",", "opts", "=", "{", "}", ")", "{", "var", "polys", "=", "svgPathToPolygons", "(", "pathData", ",", "opts", ")", ";", "var", "minX", "=", "Infinity", ",", "maxX", "=", "-", "Infinity", ",", "minY", "=", "Infinity", ",", "maxY", "=", "-", "Infinity", ";", "polys", ".", "forEach", "(", "poly", "=>", "{", "poly", ".", "forEach", "(", "pt", "=>", "{", "if", "(", "pt", "[", "0", "]", "<", "minX", ")", "minX", "=", "pt", "[", "0", "]", ";", "if", "(", "pt", "[", "1", "]", "<", "minY", ")", "minY", "=", "pt", "[", "1", "]", ";", "if", "(", "pt", "[", "0", "]", ">", "maxX", ")", "maxX", "=", "pt", "[", "0", "]", ";", "if", "(", "pt", "[", "1", "]", ">", "maxY", ")", "maxY", "=", "pt", "[", "1", "]", ";", "}", ")", ";", "}", ")", ";", "let", "dx", "=", "maxX", "-", "minX", ",", "dy", "=", "maxY", "-", "minY", ";", "console", ".", "log", "(", "`", "${", "dx", "}", "${", "dy", "}", "${", "minX", "}", "${", "minY", "}", "${", "dx", "*", "2", "}", "${", "dy", "}", "${", "pathData", "}", "${", "dx", "}", "${", "polys", ".", "map", "(", "poly", "=>", "`", "${", "poly", ".", "closed", "?", "'polygon'", ":", "'polyline'", "}", "${", "poly", ".", "join", "(", "' '", ")", "}", "`", ")", ".", "join", "(", "\"\\n\"", ")", "}", "`", ".", "trim", "(", ")", ")", ";", "}" ]
OMG YOU FOUND THE SECRET UNDOCUMENTED FEATURE
[ "OMG", "YOU", "FOUND", "THE", "SECRET", "UNDOCUMENTED", "FEATURE" ]
1b55802ee39022315759201f9a13a6d45cbc3942
https://github.com/Phrogz/svg-path-to-polygons/blob/1b55802ee39022315759201f9a13a6d45cbc3942/svg-path-to-polygons.js#L94-L115
20,087
adamgruber/mochawesome-report-generator
lib/src/options.js
_getUserOption
function _getUserOption(userOptions, optToGet, isBool) { const envVar = `MOCHAWESOME_${optToGet.toUpperCase()}`; if (userOptions && typeof userOptions[optToGet] !== 'undefined') { return (isBool && typeof userOptions[optToGet] === 'string') ? userOptions[optToGet] === 'true' : userOptions[optToGet]; } if (typeof process.env[envVar] !== 'undefined') { return isBool ? process.env[envVar] === 'true' : process.env[envVar]; } return undefined; }
javascript
function _getUserOption(userOptions, optToGet, isBool) { const envVar = `MOCHAWESOME_${optToGet.toUpperCase()}`; if (userOptions && typeof userOptions[optToGet] !== 'undefined') { return (isBool && typeof userOptions[optToGet] === 'string') ? userOptions[optToGet] === 'true' : userOptions[optToGet]; } if (typeof process.env[envVar] !== 'undefined') { return isBool ? process.env[envVar] === 'true' : process.env[envVar]; } return undefined; }
[ "function", "_getUserOption", "(", "userOptions", ",", "optToGet", ",", "isBool", ")", "{", "const", "envVar", "=", "`", "${", "optToGet", ".", "toUpperCase", "(", ")", "}", "`", ";", "if", "(", "userOptions", "&&", "typeof", "userOptions", "[", "optToGet", "]", "!==", "'undefined'", ")", "{", "return", "(", "isBool", "&&", "typeof", "userOptions", "[", "optToGet", "]", "===", "'string'", ")", "?", "userOptions", "[", "optToGet", "]", "===", "'true'", ":", "userOptions", "[", "optToGet", "]", ";", "}", "if", "(", "typeof", "process", ".", "env", "[", "envVar", "]", "!==", "'undefined'", ")", "{", "return", "isBool", "?", "process", ".", "env", "[", "envVar", "]", "===", "'true'", ":", "process", ".", "env", "[", "envVar", "]", ";", "}", "return", "undefined", ";", "}" ]
Retrieve the value of a user supplied option. Order of precedence 1. User-supplied option 2. Environment variable @param {object} userOptions Options to parse through @param {string} optToGet Option name @param {boolean} isBool Treat option as Boolean @return {string|boolean|undefined} Option value
[ "Retrieve", "the", "value", "of", "a", "user", "supplied", "option", ".", "Order", "of", "precedence", "1", ".", "User", "-", "supplied", "option", "2", ".", "Environment", "variable" ]
186a31a0dc15d1a81f88ed3afd37bb7010f4c8b8
https://github.com/adamgruber/mochawesome-report-generator/blob/186a31a0dc15d1a81f88ed3afd37bb7010f4c8b8/lib/src/options.js#L167-L180
20,088
adamgruber/mochawesome-report-generator
lib/src/main.js
saveFile
function saveFile(filename, data, overwrite) { if (overwrite) { return fs.outputFile(filename, data) .then(() => filename); } else { return new Promise((resolve, reject) => { fsu.writeFileUnique( filename.replace(fileExtRegex, '{_###}$&'), data, { force: true }, (err, savedFile) => err === null ? resolve(savedFile) : reject(err) ); }); } }
javascript
function saveFile(filename, data, overwrite) { if (overwrite) { return fs.outputFile(filename, data) .then(() => filename); } else { return new Promise((resolve, reject) => { fsu.writeFileUnique( filename.replace(fileExtRegex, '{_###}$&'), data, { force: true }, (err, savedFile) => err === null ? resolve(savedFile) : reject(err) ); }); } }
[ "function", "saveFile", "(", "filename", ",", "data", ",", "overwrite", ")", "{", "if", "(", "overwrite", ")", "{", "return", "fs", ".", "outputFile", "(", "filename", ",", "data", ")", ".", "then", "(", "(", ")", "=>", "filename", ")", ";", "}", "else", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "fsu", ".", "writeFileUnique", "(", "filename", ".", "replace", "(", "fileExtRegex", ",", "'{_###}$&'", ")", ",", "data", ",", "{", "force", ":", "true", "}", ",", "(", "err", ",", "savedFile", ")", "=>", "err", "===", "null", "?", "resolve", "(", "savedFile", ")", ":", "reject", "(", "err", ")", ")", ";", "}", ")", ";", "}", "}" ]
Saves a file @param {string} filename Name of file to save @param {string} data Data to be saved @param {boolean} overwrite Overwrite existing files (default: true) @return {Promise} Resolves with filename if successfully saved
[ "Saves", "a", "file" ]
186a31a0dc15d1a81f88ed3afd37bb7010f4c8b8
https://github.com/adamgruber/mochawesome-report-generator/blob/186a31a0dc15d1a81f88ed3afd37bb7010f4c8b8/lib/src/main.js#L24-L38
20,089
adamgruber/mochawesome-report-generator
lib/src/main.js
openFile
function openFile(filename) { return new Promise((resolve, reject) => { opener(filename, null, err => err === null ? resolve(filename) : reject(err)); }); }
javascript
function openFile(filename) { return new Promise((resolve, reject) => { opener(filename, null, err => err === null ? resolve(filename) : reject(err)); }); }
[ "function", "openFile", "(", "filename", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "opener", "(", "filename", ",", "null", ",", "err", "=>", "err", "===", "null", "?", "resolve", "(", "filename", ")", ":", "reject", "(", "err", ")", ")", ";", "}", ")", ";", "}" ]
Opens a file @param {string} filename Name of file to open @return {Promise} Resolves with filename if successfully opened
[ "Opens", "a", "file" ]
186a31a0dc15d1a81f88ed3afd37bb7010f4c8b8
https://github.com/adamgruber/mochawesome-report-generator/blob/186a31a0dc15d1a81f88ed3afd37bb7010f4c8b8/lib/src/main.js#L47-L51
20,090
adamgruber/mochawesome-report-generator
lib/src/main.js
getOptions
function getOptions(opts) { const mergedOptions = getMergedOptions(opts || {}); // For saving JSON from mochawesome reporter if (mergedOptions.saveJson) { mergedOptions.jsonFile = `${getFilename(mergedOptions)}.json`; } mergedOptions.htmlFile = `${getFilename(mergedOptions)}.html`; return mergedOptions; }
javascript
function getOptions(opts) { const mergedOptions = getMergedOptions(opts || {}); // For saving JSON from mochawesome reporter if (mergedOptions.saveJson) { mergedOptions.jsonFile = `${getFilename(mergedOptions)}.json`; } mergedOptions.htmlFile = `${getFilename(mergedOptions)}.html`; return mergedOptions; }
[ "function", "getOptions", "(", "opts", ")", "{", "const", "mergedOptions", "=", "getMergedOptions", "(", "opts", "||", "{", "}", ")", ";", "// For saving JSON from mochawesome reporter", "if", "(", "mergedOptions", ".", "saveJson", ")", "{", "mergedOptions", ".", "jsonFile", "=", "`", "${", "getFilename", "(", "mergedOptions", ")", "}", "`", ";", "}", "mergedOptions", ".", "htmlFile", "=", "`", "${", "getFilename", "(", "mergedOptions", ")", "}", "`", ";", "return", "mergedOptions", ";", "}" ]
Get report options by extending base options with user provided options @param {Object} opts Report options @return {Object} User options merged with default options
[ "Get", "report", "options", "by", "extending", "base", "options", "with", "user", "provided", "options" ]
186a31a0dc15d1a81f88ed3afd37bb7010f4c8b8
https://github.com/adamgruber/mochawesome-report-generator/blob/186a31a0dc15d1a81f88ed3afd37bb7010f4c8b8/lib/src/main.js#L116-L126
20,091
adamgruber/mochawesome-report-generator
lib/src/main.js
copyAssets
function copyAssets({ assetsDir }) { if (_shouldCopyAssets(assetsDir)) { fs.copySync(distDir, assetsDir, { filter: src => !/inline/.test(src) }); } }
javascript
function copyAssets({ assetsDir }) { if (_shouldCopyAssets(assetsDir)) { fs.copySync(distDir, assetsDir, { filter: src => !/inline/.test(src) }); } }
[ "function", "copyAssets", "(", "{", "assetsDir", "}", ")", "{", "if", "(", "_shouldCopyAssets", "(", "assetsDir", ")", ")", "{", "fs", ".", "copySync", "(", "distDir", ",", "assetsDir", ",", "{", "filter", ":", "src", "=>", "!", "/", "inline", "/", ".", "test", "(", "src", ")", "}", ")", ";", "}", "}" ]
Copy the report assets to the report dir, ignoring inline assets @param {Object} opts Report options
[ "Copy", "the", "report", "assets", "to", "the", "report", "dir", "ignoring", "inline", "assets" ]
186a31a0dc15d1a81f88ed3afd37bb7010f4c8b8
https://github.com/adamgruber/mochawesome-report-generator/blob/186a31a0dc15d1a81f88ed3afd37bb7010f4c8b8/lib/src/main.js#L164-L170
20,092
adamgruber/mochawesome-report-generator
lib/src/main.js
getAssets
function getAssets(reportOptions) { const { assetsDir, cdn, dev, inlineAssets, reportDir } = reportOptions; const relativeAssetsDir = path.relative(reportDir, assetsDir); // Default URLs to assets path const assets = { inlineScripts: null, inlineStyles: null, scriptsUrl: path.join(relativeAssetsDir, 'app.js'), stylesUrl: path.join(relativeAssetsDir, 'app.css') }; // If using inline assets, load files and strings if (inlineAssets) { assets.inlineScripts = loadFile(path.join(distDir, 'app.js')); assets.inlineStyles = loadFile(path.join(distDir, 'app.inline.css')); } // If using CDN, return remote urls if (cdn) { assets.scriptsUrl = `https://unpkg.com/mochawesome-report-generator@${pkg.version}/dist/app.js`; assets.stylesUrl = `https://unpkg.com/mochawesome-report-generator@${pkg.version}/dist/app.css`; } // In DEV mode, return local urls if (dev) { assets.scriptsUrl = 'http://localhost:8080/app.js'; assets.stylesUrl = 'http://localhost:8080/app.css'; } // Copy the assets if needed if (!dev && !cdn && !inlineAssets) { copyAssets(reportOptions); } return assets; }
javascript
function getAssets(reportOptions) { const { assetsDir, cdn, dev, inlineAssets, reportDir } = reportOptions; const relativeAssetsDir = path.relative(reportDir, assetsDir); // Default URLs to assets path const assets = { inlineScripts: null, inlineStyles: null, scriptsUrl: path.join(relativeAssetsDir, 'app.js'), stylesUrl: path.join(relativeAssetsDir, 'app.css') }; // If using inline assets, load files and strings if (inlineAssets) { assets.inlineScripts = loadFile(path.join(distDir, 'app.js')); assets.inlineStyles = loadFile(path.join(distDir, 'app.inline.css')); } // If using CDN, return remote urls if (cdn) { assets.scriptsUrl = `https://unpkg.com/mochawesome-report-generator@${pkg.version}/dist/app.js`; assets.stylesUrl = `https://unpkg.com/mochawesome-report-generator@${pkg.version}/dist/app.css`; } // In DEV mode, return local urls if (dev) { assets.scriptsUrl = 'http://localhost:8080/app.js'; assets.stylesUrl = 'http://localhost:8080/app.css'; } // Copy the assets if needed if (!dev && !cdn && !inlineAssets) { copyAssets(reportOptions); } return assets; }
[ "function", "getAssets", "(", "reportOptions", ")", "{", "const", "{", "assetsDir", ",", "cdn", ",", "dev", ",", "inlineAssets", ",", "reportDir", "}", "=", "reportOptions", ";", "const", "relativeAssetsDir", "=", "path", ".", "relative", "(", "reportDir", ",", "assetsDir", ")", ";", "// Default URLs to assets path", "const", "assets", "=", "{", "inlineScripts", ":", "null", ",", "inlineStyles", ":", "null", ",", "scriptsUrl", ":", "path", ".", "join", "(", "relativeAssetsDir", ",", "'app.js'", ")", ",", "stylesUrl", ":", "path", ".", "join", "(", "relativeAssetsDir", ",", "'app.css'", ")", "}", ";", "// If using inline assets, load files and strings", "if", "(", "inlineAssets", ")", "{", "assets", ".", "inlineScripts", "=", "loadFile", "(", "path", ".", "join", "(", "distDir", ",", "'app.js'", ")", ")", ";", "assets", ".", "inlineStyles", "=", "loadFile", "(", "path", ".", "join", "(", "distDir", ",", "'app.inline.css'", ")", ")", ";", "}", "// If using CDN, return remote urls", "if", "(", "cdn", ")", "{", "assets", ".", "scriptsUrl", "=", "`", "${", "pkg", ".", "version", "}", "`", ";", "assets", ".", "stylesUrl", "=", "`", "${", "pkg", ".", "version", "}", "`", ";", "}", "// In DEV mode, return local urls", "if", "(", "dev", ")", "{", "assets", ".", "scriptsUrl", "=", "'http://localhost:8080/app.js'", ";", "assets", ".", "stylesUrl", "=", "'http://localhost:8080/app.css'", ";", "}", "// Copy the assets if needed", "if", "(", "!", "dev", "&&", "!", "cdn", "&&", "!", "inlineAssets", ")", "{", "copyAssets", "(", "reportOptions", ")", ";", "}", "return", "assets", ";", "}" ]
Get the report assets object @param {Object} reportOptions Options @return {Object} Object with assets props
[ "Get", "the", "report", "assets", "object" ]
186a31a0dc15d1a81f88ed3afd37bb7010f4c8b8
https://github.com/adamgruber/mochawesome-report-generator/blob/186a31a0dc15d1a81f88ed3afd37bb7010f4c8b8/lib/src/main.js#L178-L214
20,093
adamgruber/mochawesome-report-generator
lib/src/main.js
prepare
function prepare(reportData, opts) { // Stringify the data if needed let data = reportData; if (typeof data === 'object') { data = JSON.stringify(reportData); } // Get the options const reportOptions = getOptions(opts); // Stop here if we're not generating an HTML report if (!reportOptions.saveHtml) { return { reportOptions }; } // Get the assets const assets = getAssets(reportOptions); // Render basic template to string // const { styles, scripts } = assets; const renderedHtml = render(React.createElement(MainHTML, { data, options: reportOptions, title: reportOptions.reportPageTitle, useInlineAssets: reportOptions.inlineAssets && !reportOptions.cdn, ...assets })); const html = `<!doctype html>\n${renderedHtml}`; return { html, reportOptions }; }
javascript
function prepare(reportData, opts) { // Stringify the data if needed let data = reportData; if (typeof data === 'object') { data = JSON.stringify(reportData); } // Get the options const reportOptions = getOptions(opts); // Stop here if we're not generating an HTML report if (!reportOptions.saveHtml) { return { reportOptions }; } // Get the assets const assets = getAssets(reportOptions); // Render basic template to string // const { styles, scripts } = assets; const renderedHtml = render(React.createElement(MainHTML, { data, options: reportOptions, title: reportOptions.reportPageTitle, useInlineAssets: reportOptions.inlineAssets && !reportOptions.cdn, ...assets })); const html = `<!doctype html>\n${renderedHtml}`; return { html, reportOptions }; }
[ "function", "prepare", "(", "reportData", ",", "opts", ")", "{", "// Stringify the data if needed", "let", "data", "=", "reportData", ";", "if", "(", "typeof", "data", "===", "'object'", ")", "{", "data", "=", "JSON", ".", "stringify", "(", "reportData", ")", ";", "}", "// Get the options", "const", "reportOptions", "=", "getOptions", "(", "opts", ")", ";", "// Stop here if we're not generating an HTML report", "if", "(", "!", "reportOptions", ".", "saveHtml", ")", "{", "return", "{", "reportOptions", "}", ";", "}", "// Get the assets", "const", "assets", "=", "getAssets", "(", "reportOptions", ")", ";", "// Render basic template to string", "// const { styles, scripts } = assets;", "const", "renderedHtml", "=", "render", "(", "React", ".", "createElement", "(", "MainHTML", ",", "{", "data", ",", "options", ":", "reportOptions", ",", "title", ":", "reportOptions", ".", "reportPageTitle", ",", "useInlineAssets", ":", "reportOptions", ".", "inlineAssets", "&&", "!", "reportOptions", ".", "cdn", ",", "...", "assets", "}", ")", ")", ";", "const", "html", "=", "`", "\\n", "${", "renderedHtml", "}", "`", ";", "return", "{", "html", ",", "reportOptions", "}", ";", "}" ]
Prepare options, assets, and html for saving @param {string} reportData JSON test data @param {Object} opts Report options @return {Object} Prepared data for saving
[ "Prepare", "options", "assets", "and", "html", "for", "saving" ]
186a31a0dc15d1a81f88ed3afd37bb7010f4c8b8
https://github.com/adamgruber/mochawesome-report-generator/blob/186a31a0dc15d1a81f88ed3afd37bb7010f4c8b8/lib/src/main.js#L224-L255
20,094
adamgruber/mochawesome-report-generator
lib/src/main.js
create
function create(data, opts) { const { html, reportOptions } = prepare(data, opts); const { saveJson, saveHtml, autoOpen, overwrite, jsonFile, htmlFile } = reportOptions; const savePromises = []; savePromises.push(saveHtml !== false ? saveFile(htmlFile, html, overwrite) .then(savedHtml => (autoOpen && openFile(savedHtml)) || savedHtml) : null); savePromises.push(saveJson ? saveFile(jsonFile, JSON.stringify(data, null, 2), overwrite) : null); return Promise.all(savePromises); }
javascript
function create(data, opts) { const { html, reportOptions } = prepare(data, opts); const { saveJson, saveHtml, autoOpen, overwrite, jsonFile, htmlFile } = reportOptions; const savePromises = []; savePromises.push(saveHtml !== false ? saveFile(htmlFile, html, overwrite) .then(savedHtml => (autoOpen && openFile(savedHtml)) || savedHtml) : null); savePromises.push(saveJson ? saveFile(jsonFile, JSON.stringify(data, null, 2), overwrite) : null); return Promise.all(savePromises); }
[ "function", "create", "(", "data", ",", "opts", ")", "{", "const", "{", "html", ",", "reportOptions", "}", "=", "prepare", "(", "data", ",", "opts", ")", ";", "const", "{", "saveJson", ",", "saveHtml", ",", "autoOpen", ",", "overwrite", ",", "jsonFile", ",", "htmlFile", "}", "=", "reportOptions", ";", "const", "savePromises", "=", "[", "]", ";", "savePromises", ".", "push", "(", "saveHtml", "!==", "false", "?", "saveFile", "(", "htmlFile", ",", "html", ",", "overwrite", ")", ".", "then", "(", "savedHtml", "=>", "(", "autoOpen", "&&", "openFile", "(", "savedHtml", ")", ")", "||", "savedHtml", ")", ":", "null", ")", ";", "savePromises", ".", "push", "(", "saveJson", "?", "saveFile", "(", "jsonFile", ",", "JSON", ".", "stringify", "(", "data", ",", "null", ",", "2", ")", ",", "overwrite", ")", ":", "null", ")", ";", "return", "Promise", ".", "all", "(", "savePromises", ")", ";", "}" ]
Create the report @param {string} data JSON test data @param {Object} opts Report options @return {Promise} Resolves if report was created successfully
[ "Create", "the", "report" ]
186a31a0dc15d1a81f88ed3afd37bb7010f4c8b8
https://github.com/adamgruber/mochawesome-report-generator/blob/186a31a0dc15d1a81f88ed3afd37bb7010f4c8b8/lib/src/main.js#L265-L288
20,095
adamgruber/mochawesome-report-generator
lib/src/main.js
createSync
function createSync(data, opts) { const { html, reportOptions } = prepare(data, opts); const { autoOpen, htmlFile } = reportOptions; fs.outputFileSync(htmlFile, html); if (autoOpen) opener(htmlFile); }
javascript
function createSync(data, opts) { const { html, reportOptions } = prepare(data, opts); const { autoOpen, htmlFile } = reportOptions; fs.outputFileSync(htmlFile, html); if (autoOpen) opener(htmlFile); }
[ "function", "createSync", "(", "data", ",", "opts", ")", "{", "const", "{", "html", ",", "reportOptions", "}", "=", "prepare", "(", "data", ",", "opts", ")", ";", "const", "{", "autoOpen", ",", "htmlFile", "}", "=", "reportOptions", ";", "fs", ".", "outputFileSync", "(", "htmlFile", ",", "html", ")", ";", "if", "(", "autoOpen", ")", "opener", "(", "htmlFile", ")", ";", "}" ]
Create the report synchronously @param {string} data JSON test data @param {Object} opts Report options
[ "Create", "the", "report", "synchronously" ]
186a31a0dc15d1a81f88ed3afd37bb7010f4c8b8
https://github.com/adamgruber/mochawesome-report-generator/blob/186a31a0dc15d1a81f88ed3afd37bb7010f4c8b8/lib/src/main.js#L297-L302
20,096
adamgruber/mochawesome-report-generator
bin/src/cli-main.js
validateFile
function validateFile(file) { let data; let err = null; // Try to read and parse the file try { data = JSON.parse(fs.readFileSync(file, 'utf-8')); } catch (e) { if (e.code === 'ENOENT') { err = ERRORS.NOT_FOUND; } else if (JsonErrRegex.test(e.message)) { err = ERRORS.INVALID_JSON([ e ]); } else { err = ERRORS.GENERIC; } } // If the file was loaded successfully, // validate the json against the TestReport schema if (data) { const validationResult = t.validate(data, types.TestReport, { strict: true }); if (!validationResult.isValid()) { err = ERRORS.INVALID_JSON(validationResult.errors); } else { validFiles += 1; } } return { filename: file, data, err }; }
javascript
function validateFile(file) { let data; let err = null; // Try to read and parse the file try { data = JSON.parse(fs.readFileSync(file, 'utf-8')); } catch (e) { if (e.code === 'ENOENT') { err = ERRORS.NOT_FOUND; } else if (JsonErrRegex.test(e.message)) { err = ERRORS.INVALID_JSON([ e ]); } else { err = ERRORS.GENERIC; } } // If the file was loaded successfully, // validate the json against the TestReport schema if (data) { const validationResult = t.validate(data, types.TestReport, { strict: true }); if (!validationResult.isValid()) { err = ERRORS.INVALID_JSON(validationResult.errors); } else { validFiles += 1; } } return { filename: file, data, err }; }
[ "function", "validateFile", "(", "file", ")", "{", "let", "data", ";", "let", "err", "=", "null", ";", "// Try to read and parse the file", "try", "{", "data", "=", "JSON", ".", "parse", "(", "fs", ".", "readFileSync", "(", "file", ",", "'utf-8'", ")", ")", ";", "}", "catch", "(", "e", ")", "{", "if", "(", "e", ".", "code", "===", "'ENOENT'", ")", "{", "err", "=", "ERRORS", ".", "NOT_FOUND", ";", "}", "else", "if", "(", "JsonErrRegex", ".", "test", "(", "e", ".", "message", ")", ")", "{", "err", "=", "ERRORS", ".", "INVALID_JSON", "(", "[", "e", "]", ")", ";", "}", "else", "{", "err", "=", "ERRORS", ".", "GENERIC", ";", "}", "}", "// If the file was loaded successfully,", "// validate the json against the TestReport schema", "if", "(", "data", ")", "{", "const", "validationResult", "=", "t", ".", "validate", "(", "data", ",", "types", ".", "TestReport", ",", "{", "strict", ":", "true", "}", ")", ";", "if", "(", "!", "validationResult", ".", "isValid", "(", ")", ")", "{", "err", "=", "ERRORS", ".", "INVALID_JSON", "(", "validationResult", ".", "errors", ")", ";", "}", "else", "{", "validFiles", "+=", "1", ";", "}", "}", "return", "{", "filename", ":", "file", ",", "data", ",", "err", "}", ";", "}" ]
Validate the data file @typedef {Object} File @property {string} filename Name of the file @property {object} data JSON test data @property {object} err Error object @param {string} file File to load/validate @return {File} Validated file with test data, `err` will be null if valid
[ "Validate", "the", "data", "file" ]
186a31a0dc15d1a81f88ed3afd37bb7010f4c8b8
https://github.com/adamgruber/mochawesome-report-generator/blob/186a31a0dc15d1a81f88ed3afd37bb7010f4c8b8/bin/src/cli-main.js#L31-L64
20,097
adamgruber/mochawesome-report-generator
bin/src/cli-main.js
getReportFilename
function getReportFilename({ filename }, { reportFilename }) { return reportFilename || filename.split(path.sep).pop().replace(JsonFileRegex, ''); }
javascript
function getReportFilename({ filename }, { reportFilename }) { return reportFilename || filename.split(path.sep).pop().replace(JsonFileRegex, ''); }
[ "function", "getReportFilename", "(", "{", "filename", "}", ",", "{", "reportFilename", "}", ")", "{", "return", "reportFilename", "||", "filename", ".", "split", "(", "path", ".", "sep", ")", ".", "pop", "(", ")", ".", "replace", "(", "JsonFileRegex", ",", "''", ")", ";", "}" ]
Get the reportFilename option to be passed to `report.create` Returns the `reportFilename` option if provided otherwise it returns the base filename stripped of path and extension @param {Object} file.filename Name of file to be processed @param {Object} args CLI process arguments @return {string} Filename
[ "Get", "the", "reportFilename", "option", "to", "be", "passed", "to", "report", ".", "create" ]
186a31a0dc15d1a81f88ed3afd37bb7010f4c8b8
https://github.com/adamgruber/mochawesome-report-generator/blob/186a31a0dc15d1a81f88ed3afd37bb7010f4c8b8/bin/src/cli-main.js#L128-L130
20,098
adamgruber/mochawesome-report-generator
bin/src/cli-main.js
processArgs
function processArgs(args, files = []) { return args.reduce((acc, arg) => { let stats; try { stats = fs.statSync(arg); } catch (err) { // Do nothing } // If argument is a directory, process the files inside if (stats && stats.isDirectory()) { return processArgs( fs.readdirSync(arg).map(file => path.join(arg, file)), files ); } // If `statSync` failed, validating will handle the error // If the argument is a file, check if its a JSON file before validating if (!stats || JsonFileRegex.test(arg)) { acc.push(validateFile(arg)); } return acc; }, files); }
javascript
function processArgs(args, files = []) { return args.reduce((acc, arg) => { let stats; try { stats = fs.statSync(arg); } catch (err) { // Do nothing } // If argument is a directory, process the files inside if (stats && stats.isDirectory()) { return processArgs( fs.readdirSync(arg).map(file => path.join(arg, file)), files ); } // If `statSync` failed, validating will handle the error // If the argument is a file, check if its a JSON file before validating if (!stats || JsonFileRegex.test(arg)) { acc.push(validateFile(arg)); } return acc; }, files); }
[ "function", "processArgs", "(", "args", ",", "files", "=", "[", "]", ")", "{", "return", "args", ".", "reduce", "(", "(", "acc", ",", "arg", ")", "=>", "{", "let", "stats", ";", "try", "{", "stats", "=", "fs", ".", "statSync", "(", "arg", ")", ";", "}", "catch", "(", "err", ")", "{", "// Do nothing", "}", "// If argument is a directory, process the files inside", "if", "(", "stats", "&&", "stats", ".", "isDirectory", "(", ")", ")", "{", "return", "processArgs", "(", "fs", ".", "readdirSync", "(", "arg", ")", ".", "map", "(", "file", "=>", "path", ".", "join", "(", "arg", ",", "file", ")", ")", ",", "files", ")", ";", "}", "// If `statSync` failed, validating will handle the error", "// If the argument is a file, check if its a JSON file before validating", "if", "(", "!", "stats", "||", "JsonFileRegex", ".", "test", "(", "arg", ")", ")", "{", "acc", ".", "push", "(", "validateFile", "(", "arg", ")", ")", ";", "}", "return", "acc", ";", "}", ",", "files", ")", ";", "}" ]
Process arguments, recursing through any directories, to find and validate JSON files @param {array} args Array of paths @param {array} files Array to populate @return {array} File objects to be processed
[ "Process", "arguments", "recursing", "through", "any", "directories", "to", "find", "and", "validate", "JSON", "files" ]
186a31a0dc15d1a81f88ed3afd37bb7010f4c8b8
https://github.com/adamgruber/mochawesome-report-generator/blob/186a31a0dc15d1a81f88ed3afd37bb7010f4c8b8/bin/src/cli-main.js#L141-L166
20,099
adamgruber/mochawesome-report-generator
bin/src/cli-main.js
marge
function marge(args) { // Reset valid files count validFiles = 0; // Get the array of JSON files to process const files = processArgs(args._); // When there are multiple valid files OR the timestamp option is set // we must force `overwrite` to `false` to ensure all reports are created /* istanbul ignore else */ if (validFiles > 1 || args.timestamp !== false) { args.overwrite = false; } const promises = files.map(file => { // Files with errors we just resolve if (file.err) { return Promise.resolve(file); } // Valid files get created but first we need to pass correct filename option // Default value is name of file // If a filename option was provided, all files get that name const reportFilename = getReportFilename(file, args); return report.create(file.data, Object.assign({}, args, { reportFilename })); }); return Promise.all(promises) .then(handleResolved) .catch(handleError); }
javascript
function marge(args) { // Reset valid files count validFiles = 0; // Get the array of JSON files to process const files = processArgs(args._); // When there are multiple valid files OR the timestamp option is set // we must force `overwrite` to `false` to ensure all reports are created /* istanbul ignore else */ if (validFiles > 1 || args.timestamp !== false) { args.overwrite = false; } const promises = files.map(file => { // Files with errors we just resolve if (file.err) { return Promise.resolve(file); } // Valid files get created but first we need to pass correct filename option // Default value is name of file // If a filename option was provided, all files get that name const reportFilename = getReportFilename(file, args); return report.create(file.data, Object.assign({}, args, { reportFilename })); }); return Promise.all(promises) .then(handleResolved) .catch(handleError); }
[ "function", "marge", "(", "args", ")", "{", "// Reset valid files count", "validFiles", "=", "0", ";", "// Get the array of JSON files to process", "const", "files", "=", "processArgs", "(", "args", ".", "_", ")", ";", "// When there are multiple valid files OR the timestamp option is set", "// we must force `overwrite` to `false` to ensure all reports are created", "/* istanbul ignore else */", "if", "(", "validFiles", ">", "1", "||", "args", ".", "timestamp", "!==", "false", ")", "{", "args", ".", "overwrite", "=", "false", ";", "}", "const", "promises", "=", "files", ".", "map", "(", "file", "=>", "{", "// Files with errors we just resolve", "if", "(", "file", ".", "err", ")", "{", "return", "Promise", ".", "resolve", "(", "file", ")", ";", "}", "// Valid files get created but first we need to pass correct filename option", "// Default value is name of file", "// If a filename option was provided, all files get that name", "const", "reportFilename", "=", "getReportFilename", "(", "file", ",", "args", ")", ";", "return", "report", ".", "create", "(", "file", ".", "data", ",", "Object", ".", "assign", "(", "{", "}", ",", "args", ",", "{", "reportFilename", "}", ")", ")", ";", "}", ")", ";", "return", "Promise", ".", "all", "(", "promises", ")", ".", "then", "(", "handleResolved", ")", ".", "catch", "(", "handleError", ")", ";", "}" ]
Main CLI Program @param {Object} args CLI arguments @return {Promise} Resolved promises with saved files or errors
[ "Main", "CLI", "Program" ]
186a31a0dc15d1a81f88ed3afd37bb7010f4c8b8
https://github.com/adamgruber/mochawesome-report-generator/blob/186a31a0dc15d1a81f88ed3afd37bb7010f4c8b8/bin/src/cli-main.js#L175-L206