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
40,600
lorenwest/monitor-dashboard
lib/js/PageView.js
function(id) { var t = this; // Is there a tour running already? if (t.tourView) { t.tourView.stop(); } // Load the Tour and start it var tour = new UI.Tour({id:id}); tour.fetch(function(err){ if (err) { alert("Error: Cannot open tour id: " + id); console.error(e); return; } // Go to the first page var pages = tour.get('pages'); if (!pages.length) { alert('No pages in tour: ' + tour.get('title')); return; } // Save the current tour, and navigate to it localStorage.currentTour = JSON.stringify(tour); t.navigateTo(pages[0].url); }); }
javascript
function(id) { var t = this; // Is there a tour running already? if (t.tourView) { t.tourView.stop(); } // Load the Tour and start it var tour = new UI.Tour({id:id}); tour.fetch(function(err){ if (err) { alert("Error: Cannot open tour id: " + id); console.error(e); return; } // Go to the first page var pages = tour.get('pages'); if (!pages.length) { alert('No pages in tour: ' + tour.get('title')); return; } // Save the current tour, and navigate to it localStorage.currentTour = JSON.stringify(tour); t.navigateTo(pages[0].url); }); }
[ "function", "(", "id", ")", "{", "var", "t", "=", "this", ";", "// Is there a tour running already?", "if", "(", "t", ".", "tourView", ")", "{", "t", ".", "tourView", ".", "stop", "(", ")", ";", "}", "// Load the Tour and start it", "var", "tour", "=", "new", "UI", ".", "Tour", "(", "{", "id", ":", "id", "}", ")", ";", "tour", ".", "fetch", "(", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "alert", "(", "\"Error: Cannot open tour id: \"", "+", "id", ")", ";", "console", ".", "error", "(", "e", ")", ";", "return", ";", "}", "// Go to the first page", "var", "pages", "=", "tour", ".", "get", "(", "'pages'", ")", ";", "if", "(", "!", "pages", ".", "length", ")", "{", "alert", "(", "'No pages in tour: '", "+", "tour", ".", "get", "(", "'title'", ")", ")", ";", "return", ";", "}", "// Save the current tour, and navigate to it", "localStorage", ".", "currentTour", "=", "JSON", ".", "stringify", "(", "tour", ")", ";", "t", ".", "navigateTo", "(", "pages", "[", "0", "]", ".", "url", ")", ";", "}", ")", ";", "}" ]
Run the tour specified by id
[ "Run", "the", "tour", "specified", "by", "id" ]
a990e03d07096515744332ae0761441f8534369c
https://github.com/lorenwest/monitor-dashboard/blob/a990e03d07096515744332ae0761441f8534369c/lib/js/PageView.js#L505-L533
40,601
lorenwest/monitor-dashboard
lib/js/PageView.js
function() { var t = this, isEditMode = t.$el.hasClass('edit-mode'), text = isEditMode ? 'Lock Components' : 'Edit Components', icon = isEditMode ? 'lock' : 'edit'; t.$('.nm-pvm-lock').text(text); t.$('.nm-pvm-edit i').attr('class', 'icon-' + icon); }
javascript
function() { var t = this, isEditMode = t.$el.hasClass('edit-mode'), text = isEditMode ? 'Lock Components' : 'Edit Components', icon = isEditMode ? 'lock' : 'edit'; t.$('.nm-pvm-lock').text(text); t.$('.nm-pvm-edit i').attr('class', 'icon-' + icon); }
[ "function", "(", ")", "{", "var", "t", "=", "this", ",", "isEditMode", "=", "t", ".", "$el", ".", "hasClass", "(", "'edit-mode'", ")", ",", "text", "=", "isEditMode", "?", "'Lock Components'", ":", "'Edit Components'", ",", "icon", "=", "isEditMode", "?", "'lock'", ":", "'edit'", ";", "t", ".", "$", "(", "'.nm-pvm-lock'", ")", ".", "text", "(", "text", ")", ";", "t", ".", "$", "(", "'.nm-pvm-edit i'", ")", ".", "attr", "(", "'class'", ",", "'icon-'", "+", "icon", ")", ";", "}" ]
This sets the edit menu text and icon
[ "This", "sets", "the", "edit", "menu", "text", "and", "icon" ]
a990e03d07096515744332ae0761441f8534369c
https://github.com/lorenwest/monitor-dashboard/blob/a990e03d07096515744332ae0761441f8534369c/lib/js/PageView.js#L542-L549
40,602
lorenwest/monitor-dashboard
lib/js/PageView.js
function() { var t = this; // Show if loaded if (aboutTemplate) { return t.showDialog('#nm-pv-about'); } UI.loadTemplate('', 'About', function(error, template) { if (error) {return;} t.$el.append(template.apply(t)); t.$('.modal a').attr({target: '_blank'}); t.$('.colorPicker').miniColors({opacity: true}); t.showDialog('#nm-pv-about'); }); }
javascript
function() { var t = this; // Show if loaded if (aboutTemplate) { return t.showDialog('#nm-pv-about'); } UI.loadTemplate('', 'About', function(error, template) { if (error) {return;} t.$el.append(template.apply(t)); t.$('.modal a').attr({target: '_blank'}); t.$('.colorPicker').miniColors({opacity: true}); t.showDialog('#nm-pv-about'); }); }
[ "function", "(", ")", "{", "var", "t", "=", "this", ";", "// Show if loaded", "if", "(", "aboutTemplate", ")", "{", "return", "t", ".", "showDialog", "(", "'#nm-pv-about'", ")", ";", "}", "UI", ".", "loadTemplate", "(", "''", ",", "'About'", ",", "function", "(", "error", ",", "template", ")", "{", "if", "(", "error", ")", "{", "return", ";", "}", "t", ".", "$el", ".", "append", "(", "template", ".", "apply", "(", "t", ")", ")", ";", "t", ".", "$", "(", "'.modal a'", ")", ".", "attr", "(", "{", "target", ":", "'_blank'", "}", ")", ";", "t", ".", "$", "(", "'.colorPicker'", ")", ".", "miniColors", "(", "{", "opacity", ":", "true", "}", ")", ";", "t", ".", "showDialog", "(", "'#nm-pv-about'", ")", ";", "}", ")", ";", "}" ]
This shows the about page
[ "This", "shows", "the", "about", "page" ]
a990e03d07096515744332ae0761441f8534369c
https://github.com/lorenwest/monitor-dashboard/blob/a990e03d07096515744332ae0761441f8534369c/lib/js/PageView.js#L552-L568
40,603
lorenwest/monitor-dashboard
lib/js/PageView.js
function() { var t = this; UI.hideToolTips(); t.leftJustify(); t.centerPage(); t.model.save(function(error){ if (error) { console.error("Page save error:", error); } }); t.unlockPage(); t.setDirty(false); }
javascript
function() { var t = this; UI.hideToolTips(); t.leftJustify(); t.centerPage(); t.model.save(function(error){ if (error) { console.error("Page save error:", error); } }); t.unlockPage(); t.setDirty(false); }
[ "function", "(", ")", "{", "var", "t", "=", "this", ";", "UI", ".", "hideToolTips", "(", ")", ";", "t", ".", "leftJustify", "(", ")", ";", "t", ".", "centerPage", "(", ")", ";", "t", ".", "model", ".", "save", "(", "function", "(", "error", ")", "{", "if", "(", "error", ")", "{", "console", ".", "error", "(", "\"Page save error:\"", ",", "error", ")", ";", "}", "}", ")", ";", "t", ".", "unlockPage", "(", ")", ";", "t", ".", "setDirty", "(", "false", ")", ";", "}" ]
Persist the page to the backend
[ "Persist", "the", "page", "to", "the", "backend" ]
a990e03d07096515744332ae0761441f8534369c
https://github.com/lorenwest/monitor-dashboard/blob/a990e03d07096515744332ae0761441f8534369c/lib/js/PageView.js#L571-L583
40,604
lorenwest/monitor-dashboard
lib/js/JsonView.js
function() { var t = this; t.$el.html(''); // Output the heading if specified if (t.options.heading) { $(t.template.heading({value:t.options.heading})).appendTo(t.$el); } // If a non-object, just print it t.json = t.isBackbone ? t.model.toJSON() : t.model; if (typeof t.json !== 'object') { $(t.template.line({name:'value', value:t.json})).appendTo(t.$el); return; } t.keys = _.keys(t.json); // Info about each element, keyed by element name // div - The jQuery selector of the element outer div // span - The jQuery selector of the data value span // value - The element raw value // isBackbone - Is the element an instance of a Backbone model? // strValue - The currently displayed value // isArray - True of the element is an array (or collection) // innerDiv - The container for the inner view for objects // innerView - The inner view if the element is an object t.elems = {}; // Layout the tree (without element data) for (var elemName in t.json) { var elem = t.elems[elemName] = {}; elem.value = t.getElemValue(elemName); elem.isBackbone = elem.value instanceof Backbone.Model || elem.value instanceof Backbone.Collection; elem.div = $(t.template.line({name:elemName, value: ' '})).appendTo(t.$el); elem.span = $('.data', elem.div); // Render a sub-element as another JsonView if (elem.value !== null && typeof elem.value === 'object') { elem.div.addClass('open-close').data({elemName:elemName}); $('i', elem.div).html(''); elem.innerDiv = $(t.template.inner()).appendTo(t.$el); elem.innerView = new JsonView({ model: elem.value, closedOnInit: t.closedOnInit }); elem.innerView.render(); elem.innerView.$el.appendTo(elem.innerDiv); elem.isArray = _.isArray(elem.value); $(t.template.endInner({symbol:elem.isArray ? "]" : "}"})).appendTo(elem.innerDiv); } } // Bind the change handler if (t.isBackbone) { t.model.bind('change', t.setData, t); } // Add element data to the tree t.setData(); // Reset for future renders t.closedOnInit = false; }
javascript
function() { var t = this; t.$el.html(''); // Output the heading if specified if (t.options.heading) { $(t.template.heading({value:t.options.heading})).appendTo(t.$el); } // If a non-object, just print it t.json = t.isBackbone ? t.model.toJSON() : t.model; if (typeof t.json !== 'object') { $(t.template.line({name:'value', value:t.json})).appendTo(t.$el); return; } t.keys = _.keys(t.json); // Info about each element, keyed by element name // div - The jQuery selector of the element outer div // span - The jQuery selector of the data value span // value - The element raw value // isBackbone - Is the element an instance of a Backbone model? // strValue - The currently displayed value // isArray - True of the element is an array (or collection) // innerDiv - The container for the inner view for objects // innerView - The inner view if the element is an object t.elems = {}; // Layout the tree (without element data) for (var elemName in t.json) { var elem = t.elems[elemName] = {}; elem.value = t.getElemValue(elemName); elem.isBackbone = elem.value instanceof Backbone.Model || elem.value instanceof Backbone.Collection; elem.div = $(t.template.line({name:elemName, value: ' '})).appendTo(t.$el); elem.span = $('.data', elem.div); // Render a sub-element as another JsonView if (elem.value !== null && typeof elem.value === 'object') { elem.div.addClass('open-close').data({elemName:elemName}); $('i', elem.div).html(''); elem.innerDiv = $(t.template.inner()).appendTo(t.$el); elem.innerView = new JsonView({ model: elem.value, closedOnInit: t.closedOnInit }); elem.innerView.render(); elem.innerView.$el.appendTo(elem.innerDiv); elem.isArray = _.isArray(elem.value); $(t.template.endInner({symbol:elem.isArray ? "]" : "}"})).appendTo(elem.innerDiv); } } // Bind the change handler if (t.isBackbone) { t.model.bind('change', t.setData, t); } // Add element data to the tree t.setData(); // Reset for future renders t.closedOnInit = false; }
[ "function", "(", ")", "{", "var", "t", "=", "this", ";", "t", ".", "$el", ".", "html", "(", "''", ")", ";", "// Output the heading if specified", "if", "(", "t", ".", "options", ".", "heading", ")", "{", "$", "(", "t", ".", "template", ".", "heading", "(", "{", "value", ":", "t", ".", "options", ".", "heading", "}", ")", ")", ".", "appendTo", "(", "t", ".", "$el", ")", ";", "}", "// If a non-object, just print it", "t", ".", "json", "=", "t", ".", "isBackbone", "?", "t", ".", "model", ".", "toJSON", "(", ")", ":", "t", ".", "model", ";", "if", "(", "typeof", "t", ".", "json", "!==", "'object'", ")", "{", "$", "(", "t", ".", "template", ".", "line", "(", "{", "name", ":", "'value'", ",", "value", ":", "t", ".", "json", "}", ")", ")", ".", "appendTo", "(", "t", ".", "$el", ")", ";", "return", ";", "}", "t", ".", "keys", "=", "_", ".", "keys", "(", "t", ".", "json", ")", ";", "// Info about each element, keyed by element name", "// div - The jQuery selector of the element outer div", "// span - The jQuery selector of the data value span", "// value - The element raw value", "// isBackbone - Is the element an instance of a Backbone model?", "// strValue - The currently displayed value", "// isArray - True of the element is an array (or collection)", "// innerDiv - The container for the inner view for objects", "// innerView - The inner view if the element is an object", "t", ".", "elems", "=", "{", "}", ";", "// Layout the tree (without element data)", "for", "(", "var", "elemName", "in", "t", ".", "json", ")", "{", "var", "elem", "=", "t", ".", "elems", "[", "elemName", "]", "=", "{", "}", ";", "elem", ".", "value", "=", "t", ".", "getElemValue", "(", "elemName", ")", ";", "elem", ".", "isBackbone", "=", "elem", ".", "value", "instanceof", "Backbone", ".", "Model", "||", "elem", ".", "value", "instanceof", "Backbone", ".", "Collection", ";", "elem", ".", "div", "=", "$", "(", "t", ".", "template", ".", "line", "(", "{", "name", ":", "elemName", ",", "value", ":", "' '", "}", ")", ")", ".", "appendTo", "(", "t", ".", "$el", ")", ";", "elem", ".", "span", "=", "$", "(", "'.data'", ",", "elem", ".", "div", ")", ";", "// Render a sub-element as another JsonView", "if", "(", "elem", ".", "value", "!==", "null", "&&", "typeof", "elem", ".", "value", "===", "'object'", ")", "{", "elem", ".", "div", ".", "addClass", "(", "'open-close'", ")", ".", "data", "(", "{", "elemName", ":", "elemName", "}", ")", ";", "$", "(", "'i'", ",", "elem", ".", "div", ")", ".", "html", "(", "''", ")", ";", "elem", ".", "innerDiv", "=", "$", "(", "t", ".", "template", ".", "inner", "(", ")", ")", ".", "appendTo", "(", "t", ".", "$el", ")", ";", "elem", ".", "innerView", "=", "new", "JsonView", "(", "{", "model", ":", "elem", ".", "value", ",", "closedOnInit", ":", "t", ".", "closedOnInit", "}", ")", ";", "elem", ".", "innerView", ".", "render", "(", ")", ";", "elem", ".", "innerView", ".", "$el", ".", "appendTo", "(", "elem", ".", "innerDiv", ")", ";", "elem", ".", "isArray", "=", "_", ".", "isArray", "(", "elem", ".", "value", ")", ";", "$", "(", "t", ".", "template", ".", "endInner", "(", "{", "symbol", ":", "elem", ".", "isArray", "?", "\"]\"", ":", "\"}\"", "}", ")", ")", ".", "appendTo", "(", "elem", ".", "innerDiv", ")", ";", "}", "}", "// Bind the change handler", "if", "(", "t", ".", "isBackbone", ")", "{", "t", ".", "model", ".", "bind", "(", "'change'", ",", "t", ".", "setData", ",", "t", ")", ";", "}", "// Add element data to the tree", "t", ".", "setData", "(", ")", ";", "// Reset for future renders", "t", ".", "closedOnInit", "=", "false", ";", "}" ]
Render new HTML
[ "Render", "new", "HTML" ]
a990e03d07096515744332ae0761441f8534369c
https://github.com/lorenwest/monitor-dashboard/blob/a990e03d07096515744332ae0761441f8534369c/lib/js/JsonView.js#L56-L118
40,605
lorenwest/monitor-dashboard
lib/js/JsonView.js
function(elemName) { var t = this; if (t.isBackbone) { return t.model instanceof Backbone.Collection ? t.model.at(elemName) : t.model.get(elemName); } return t.model[elemName]; }
javascript
function(elemName) { var t = this; if (t.isBackbone) { return t.model instanceof Backbone.Collection ? t.model.at(elemName) : t.model.get(elemName); } return t.model[elemName]; }
[ "function", "(", "elemName", ")", "{", "var", "t", "=", "this", ";", "if", "(", "t", ".", "isBackbone", ")", "{", "return", "t", ".", "model", "instanceof", "Backbone", ".", "Collection", "?", "t", ".", "model", ".", "at", "(", "elemName", ")", ":", "t", ".", "model", ".", "get", "(", "elemName", ")", ";", "}", "return", "t", ".", "model", "[", "elemName", "]", ";", "}" ]
Get the value of the element with the specified name
[ "Get", "the", "value", "of", "the", "element", "with", "the", "specified", "name" ]
a990e03d07096515744332ae0761441f8534369c
https://github.com/lorenwest/monitor-dashboard/blob/a990e03d07096515744332ae0761441f8534369c/lib/js/JsonView.js#L152-L158
40,606
lorenwest/monitor-dashboard
lib/js/JsonView.js
function(elem) { var t = this, strValue; // Catch recursive stringify try {strValue = JSON.stringify(elem.value);} catch (e) {strValue = "{object}";} // Set if the value changed if (strValue !== elem.strValue) { var priorStrValue = elem.strValue; elem.strValue = strValue; // Set the value of this element or the inner element elem.span.text(strValue); if (elem.innerView) { elem.innerView.model = elem.value; elem.innerView.setData(); // Set the inner element open or closed var isClosed = false; if (priorStrValue) { isClosed = elem.innerView.isClosed; } else { isClosed = t.closedOnInit ? true : strValue.length < AUTO_CLOSE_CHARS; } t.toggleClosed(elem, isClosed); } } }
javascript
function(elem) { var t = this, strValue; // Catch recursive stringify try {strValue = JSON.stringify(elem.value);} catch (e) {strValue = "{object}";} // Set if the value changed if (strValue !== elem.strValue) { var priorStrValue = elem.strValue; elem.strValue = strValue; // Set the value of this element or the inner element elem.span.text(strValue); if (elem.innerView) { elem.innerView.model = elem.value; elem.innerView.setData(); // Set the inner element open or closed var isClosed = false; if (priorStrValue) { isClosed = elem.innerView.isClosed; } else { isClosed = t.closedOnInit ? true : strValue.length < AUTO_CLOSE_CHARS; } t.toggleClosed(elem, isClosed); } } }
[ "function", "(", "elem", ")", "{", "var", "t", "=", "this", ",", "strValue", ";", "// Catch recursive stringify", "try", "{", "strValue", "=", "JSON", ".", "stringify", "(", "elem", ".", "value", ")", ";", "}", "catch", "(", "e", ")", "{", "strValue", "=", "\"{object}\"", ";", "}", "// Set if the value changed", "if", "(", "strValue", "!==", "elem", ".", "strValue", ")", "{", "var", "priorStrValue", "=", "elem", ".", "strValue", ";", "elem", ".", "strValue", "=", "strValue", ";", "// Set the value of this element or the inner element", "elem", ".", "span", ".", "text", "(", "strValue", ")", ";", "if", "(", "elem", ".", "innerView", ")", "{", "elem", ".", "innerView", ".", "model", "=", "elem", ".", "value", ";", "elem", ".", "innerView", ".", "setData", "(", ")", ";", "// Set the inner element open or closed", "var", "isClosed", "=", "false", ";", "if", "(", "priorStrValue", ")", "{", "isClosed", "=", "elem", ".", "innerView", ".", "isClosed", ";", "}", "else", "{", "isClosed", "=", "t", ".", "closedOnInit", "?", "true", ":", "strValue", ".", "length", "<", "AUTO_CLOSE_CHARS", ";", "}", "t", ".", "toggleClosed", "(", "elem", ",", "isClosed", ")", ";", "}", "}", "}" ]
Set the DOM element value to the JSON.stringify format
[ "Set", "the", "DOM", "element", "value", "to", "the", "JSON", ".", "stringify", "format" ]
a990e03d07096515744332ae0761441f8534369c
https://github.com/lorenwest/monitor-dashboard/blob/a990e03d07096515744332ae0761441f8534369c/lib/js/JsonView.js#L161-L190
40,607
lorenwest/monitor-dashboard
lib/js/TourView.js
function() { // Compute the amount of play left to go t.playLeft = t.playEnd - Date.now(); // Done playing if (t.playLeft <= 0) { clearInterval(t.timer); t.next(); } // Set the progress bar width t.setProgress(); }
javascript
function() { // Compute the amount of play left to go t.playLeft = t.playEnd - Date.now(); // Done playing if (t.playLeft <= 0) { clearInterval(t.timer); t.next(); } // Set the progress bar width t.setProgress(); }
[ "function", "(", ")", "{", "// Compute the amount of play left to go", "t", ".", "playLeft", "=", "t", ".", "playEnd", "-", "Date", ".", "now", "(", ")", ";", "// Done playing", "if", "(", "t", ".", "playLeft", "<=", "0", ")", "{", "clearInterval", "(", "t", ".", "timer", ")", ";", "t", ".", "next", "(", ")", ";", "}", "// Set the progress bar width", "t", ".", "setProgress", "(", ")", ";", "}" ]
Run at each animation interval
[ "Run", "at", "each", "animation", "interval" ]
a990e03d07096515744332ae0761441f8534369c
https://github.com/lorenwest/monitor-dashboard/blob/a990e03d07096515744332ae0761441f8534369c/lib/js/TourView.js#L157-L169
40,608
lorenwest/monitor-dashboard
lib/js/TourView.js
function(e) { var t = this, target = $(e.currentTarget), index = target.attr('data-index'); // Save the index. If a tour has many instances of the // same page, it needs to know which instance. localStorage.tourPageIndex = index; // Navigate to the page UI.pageView.navigateTo(target.attr('href')); }
javascript
function(e) { var t = this, target = $(e.currentTarget), index = target.attr('data-index'); // Save the index. If a tour has many instances of the // same page, it needs to know which instance. localStorage.tourPageIndex = index; // Navigate to the page UI.pageView.navigateTo(target.attr('href')); }
[ "function", "(", "e", ")", "{", "var", "t", "=", "this", ",", "target", "=", "$", "(", "e", ".", "currentTarget", ")", ",", "index", "=", "target", ".", "attr", "(", "'data-index'", ")", ";", "// Save the index. If a tour has many instances of the", "// same page, it needs to know which instance.", "localStorage", ".", "tourPageIndex", "=", "index", ";", "// Navigate to the page", "UI", ".", "pageView", ".", "navigateTo", "(", "target", ".", "attr", "(", "'href'", ")", ")", ";", "}" ]
Select a page
[ "Select", "a", "page" ]
a990e03d07096515744332ae0761441f8534369c
https://github.com/lorenwest/monitor-dashboard/blob/a990e03d07096515744332ae0761441f8534369c/lib/js/TourView.js#L213-L224
40,609
lorenwest/monitor-dashboard
lib/template/app/lib/view/SampleView.js
function(options) { var t = this; t.options = options; t.monitor = options.monitor; // Call this to set the initial height/width to something // other than the size of the inner view elements. options.component.setDefaultSize({ width: 400, height: 300 }); // Set monitor defaults. If your view is for a specific probe, // then set the probeClass and any default probe initialization // parameters. if (!t.monitor.get('probeClass')) { t.monitor.set({ probeClass: '{{shortAppName}}SampleProbe' }); } // Update the view on monitor change. The monitor isn't in // a connected state, so this will be called when connected. if (t.monitor != null) { t.monitor.on('change', t.onchange, t); } }
javascript
function(options) { var t = this; t.options = options; t.monitor = options.monitor; // Call this to set the initial height/width to something // other than the size of the inner view elements. options.component.setDefaultSize({ width: 400, height: 300 }); // Set monitor defaults. If your view is for a specific probe, // then set the probeClass and any default probe initialization // parameters. if (!t.monitor.get('probeClass')) { t.monitor.set({ probeClass: '{{shortAppName}}SampleProbe' }); } // Update the view on monitor change. The monitor isn't in // a connected state, so this will be called when connected. if (t.monitor != null) { t.monitor.on('change', t.onchange, t); } }
[ "function", "(", "options", ")", "{", "var", "t", "=", "this", ";", "t", ".", "options", "=", "options", ";", "t", ".", "monitor", "=", "options", ".", "monitor", ";", "// Call this to set the initial height/width to something", "// other than the size of the inner view elements.", "options", ".", "component", ".", "setDefaultSize", "(", "{", "width", ":", "400", ",", "height", ":", "300", "}", ")", ";", "// Set monitor defaults. If your view is for a specific probe,", "// then set the probeClass and any default probe initialization", "// parameters.", "if", "(", "!", "t", ".", "monitor", ".", "get", "(", "'probeClass'", ")", ")", "{", "t", ".", "monitor", ".", "set", "(", "{", "probeClass", ":", "'{{shortAppName}}SampleProbe'", "}", ")", ";", "}", "// Update the view on monitor change. The monitor isn't in", "// a connected state, so this will be called when connected.", "if", "(", "t", ".", "monitor", "!=", "null", ")", "{", "t", ".", "monitor", ".", "on", "(", "'change'", ",", "t", ".", "onchange", ",", "t", ")", ";", "}", "}" ]
Add your view to the categories listed in these tags Called by the Backbone.View constructor
[ "Add", "your", "view", "to", "the", "categories", "listed", "in", "these", "tags", "Called", "by", "the", "Backbone", ".", "View", "constructor" ]
a990e03d07096515744332ae0761441f8534369c
https://github.com/lorenwest/monitor-dashboard/blob/a990e03d07096515744332ae0761441f8534369c/lib/template/app/lib/view/SampleView.js#L37-L63
40,610
lorenwest/monitor-dashboard
lib/template/app/lib/view/SampleView.js
function() { var t = this; // Append a monitor picker t.monitorPicker = new UI.MonitorPicker({ el: t.$el, hideProbe: true, // Set false for the user to select the probe class model: t.options.monitor }); t.monitorPicker.render(); }
javascript
function() { var t = this; // Append a monitor picker t.monitorPicker = new UI.MonitorPicker({ el: t.$el, hideProbe: true, // Set false for the user to select the probe class model: t.options.monitor }); t.monitorPicker.render(); }
[ "function", "(", ")", "{", "var", "t", "=", "this", ";", "// Append a monitor picker", "t", ".", "monitorPicker", "=", "new", "UI", ".", "MonitorPicker", "(", "{", "el", ":", "t", ".", "$el", ",", "hideProbe", ":", "true", ",", "// Set false for the user to select the probe class", "model", ":", "t", ".", "options", ".", "monitor", "}", ")", ";", "t", ".", "monitorPicker", ".", "render", "(", ")", ";", "}" ]
This is called when the settings page is opened. The options element of this view is set to the above options prior to calling render, so it doesn't have to be set in an initialize method.
[ "This", "is", "called", "when", "the", "settings", "page", "is", "opened", ".", "The", "options", "element", "of", "this", "view", "is", "set", "to", "the", "above", "options", "prior", "to", "calling", "render", "so", "it", "doesn", "t", "have", "to", "be", "set", "in", "an", "initialize", "method", "." ]
a990e03d07096515744332ae0761441f8534369c
https://github.com/lorenwest/monitor-dashboard/blob/a990e03d07096515744332ae0761441f8534369c/lib/template/app/lib/view/SampleView.js#L107-L117
40,611
lorenwest/monitor-dashboard
lib/js/NetworkMap.js
function() { var t = this, map = {}, router = Monitor.getRouter(), hostName = Monitor.getRouter().getHostName(), appName = Monitor.Config.Monitor.appName, appInstance = process.env.NODE_APP_INSTANCE; // Add this process to the map map[hostName] = {}; map[hostName][appName] = { instances: [appInstance], probeClasses: _.keys(Probe.classes) }; // Process all known connections var connections = router.findConnections(); connections.forEach(function(connection) { hostName = connection.get('hostName') || connection.get('remoteHostName'); appName = connection.get('remoteAppName') || ''; appInstance = connection.get('remoteAppInstance') || ''; // Don't add to the map not yet connected if (connection.connecting || !connection.connected) { return; } // Add the hostname to the map var host = map[hostName]; if (!host) { host = map[hostName] = {}; } // Add the app to the map var app = host[appName]; if (!app) { app = host[appName] = { instances: [appInstance], probeClasses: connection.get('remoteProbeClasses') }; } else { app.instances.push(appInstance); } }); log.info('buildMap', map); // Set the map if it's changed. This method is called whenever // connections come and go - including firewalled connections which // aren't visible in the map. Only update if the map has changed. if (!_.isEqual(map, t.get('map'))) { log.info('mapChanged'); t.set({ map: map, updateSequence: t.updateSequence++ }); } else { log.info('mapNotChanged'); } }
javascript
function() { var t = this, map = {}, router = Monitor.getRouter(), hostName = Monitor.getRouter().getHostName(), appName = Monitor.Config.Monitor.appName, appInstance = process.env.NODE_APP_INSTANCE; // Add this process to the map map[hostName] = {}; map[hostName][appName] = { instances: [appInstance], probeClasses: _.keys(Probe.classes) }; // Process all known connections var connections = router.findConnections(); connections.forEach(function(connection) { hostName = connection.get('hostName') || connection.get('remoteHostName'); appName = connection.get('remoteAppName') || ''; appInstance = connection.get('remoteAppInstance') || ''; // Don't add to the map not yet connected if (connection.connecting || !connection.connected) { return; } // Add the hostname to the map var host = map[hostName]; if (!host) { host = map[hostName] = {}; } // Add the app to the map var app = host[appName]; if (!app) { app = host[appName] = { instances: [appInstance], probeClasses: connection.get('remoteProbeClasses') }; } else { app.instances.push(appInstance); } }); log.info('buildMap', map); // Set the map if it's changed. This method is called whenever // connections come and go - including firewalled connections which // aren't visible in the map. Only update if the map has changed. if (!_.isEqual(map, t.get('map'))) { log.info('mapChanged'); t.set({ map: map, updateSequence: t.updateSequence++ }); } else { log.info('mapNotChanged'); } }
[ "function", "(", ")", "{", "var", "t", "=", "this", ",", "map", "=", "{", "}", ",", "router", "=", "Monitor", ".", "getRouter", "(", ")", ",", "hostName", "=", "Monitor", ".", "getRouter", "(", ")", ".", "getHostName", "(", ")", ",", "appName", "=", "Monitor", ".", "Config", ".", "Monitor", ".", "appName", ",", "appInstance", "=", "process", ".", "env", ".", "NODE_APP_INSTANCE", ";", "// Add this process to the map", "map", "[", "hostName", "]", "=", "{", "}", ";", "map", "[", "hostName", "]", "[", "appName", "]", "=", "{", "instances", ":", "[", "appInstance", "]", ",", "probeClasses", ":", "_", ".", "keys", "(", "Probe", ".", "classes", ")", "}", ";", "// Process all known connections", "var", "connections", "=", "router", ".", "findConnections", "(", ")", ";", "connections", ".", "forEach", "(", "function", "(", "connection", ")", "{", "hostName", "=", "connection", ".", "get", "(", "'hostName'", ")", "||", "connection", ".", "get", "(", "'remoteHostName'", ")", ";", "appName", "=", "connection", ".", "get", "(", "'remoteAppName'", ")", "||", "''", ";", "appInstance", "=", "connection", ".", "get", "(", "'remoteAppInstance'", ")", "||", "''", ";", "// Don't add to the map not yet connected", "if", "(", "connection", ".", "connecting", "||", "!", "connection", ".", "connected", ")", "{", "return", ";", "}", "// Add the hostname to the map", "var", "host", "=", "map", "[", "hostName", "]", ";", "if", "(", "!", "host", ")", "{", "host", "=", "map", "[", "hostName", "]", "=", "{", "}", ";", "}", "// Add the app to the map", "var", "app", "=", "host", "[", "appName", "]", ";", "if", "(", "!", "app", ")", "{", "app", "=", "host", "[", "appName", "]", "=", "{", "instances", ":", "[", "appInstance", "]", ",", "probeClasses", ":", "connection", ".", "get", "(", "'remoteProbeClasses'", ")", "}", ";", "}", "else", "{", "app", ".", "instances", ".", "push", "(", "appInstance", ")", ";", "}", "}", ")", ";", "log", ".", "info", "(", "'buildMap'", ",", "map", ")", ";", "// Set the map if it's changed. This method is called whenever", "// connections come and go - including firewalled connections which", "// aren't visible in the map. Only update if the map has changed.", "if", "(", "!", "_", ".", "isEqual", "(", "map", ",", "t", ".", "get", "(", "'map'", ")", ")", ")", "{", "log", ".", "info", "(", "'mapChanged'", ")", ";", "t", ".", "set", "(", "{", "map", ":", "map", ",", "updateSequence", ":", "t", ".", "updateSequence", "++", "}", ")", ";", "}", "else", "{", "log", ".", "info", "(", "'mapNotChanged'", ")", ";", "}", "}" ]
This builds a new site map, and sets it into the map property if it is different from the current map.
[ "This", "builds", "a", "new", "site", "map", "and", "sets", "it", "into", "the", "map", "property", "if", "it", "is", "different", "from", "the", "current", "map", "." ]
a990e03d07096515744332ae0761441f8534369c
https://github.com/lorenwest/monitor-dashboard/blob/a990e03d07096515744332ae0761441f8534369c/lib/js/NetworkMap.js#L77-L135
40,612
flint-bot/flint
lib/flint.js
Flint
function Flint(options) { EventEmitter.call(this); this.id = options.id || u.genUUID64(); /** * Options Object * * @memberof Flint * @instance * @namespace options * @property {string} token - Spark Token. * @property {string} webhookUrl - URL that is used for SPark API to send callbacks. * @property {string} [webhookSecret] - If specified, inbound webhooks are authorized before being processed. * @property {string} [messageFormat=text] - Default Spark message format to use with bot.say(). * @property {number} [maxPageItems=50] - Max results that the paginator uses. * @property {number} [maxConcurrent=3] - Max concurrent sessions to the Spark API * @property {number} [minTime=600] - Min time between consecutive request starts. * @property {number} [requeueMinTime=minTime*10] - Min time between consecutive request starts of requests that have been re-queued. * @property {number} [requeueMaxRetry=3] - Msx number of atteempts to make for failed request. * @property {array} [requeueCodes=[429,500,503]] - Array of http result codes that should be retried. * @property {number} [requestTimeout=20000] - Timeout for an individual request recieving a response. * @property {number} [queueSize=10000] - Size of the buffer that holds outbound requests. * @property {number} [requeueSize=10000] - Size of the buffer that holds outbound re-queue requests. * @property {string} [id=random] - The id this instance of flint uses. * @property {string} [webhookRequestJSONLocation=body] - The property under the Request to find the JSON contents. * @property {Boolean} [removeWebhooksOnStart=true] - If you wish to have the bot remove all account webhooks when starting. */ this.options = options; this.active = false; this.initialized = false; this.storageActive = false; this.isBotAccount = false; this.isUserAccount = false; this.person = {}; this.email; // define location in webhook request to find json values of incoming webhook. // note: this is typically 'request.body' but depending on express/restify configuration, it may be 'request.params' this.options.webhookRequestJSONLocation = this.options.webhookRequestJSONLocation || 'body'; // define if flint remove all webhooks attached to token on start (if not defined, defaults to true) this.options.removeWebhooksOnStart = typeof this.options.removeWebhooksOnStart === 'boolean' ? this.options.removeWebhooksOnStart : true; // define default messageFormat used with bot.say (if not defined, defaults to 'text') if(typeof this.options.messageFormat === 'string' && _.includes(['text', 'markdown', 'html'], _.toLower(this.options.messageFormat))) { this.messageFormat = _.toLower(this.options.messageFormat); } else { this.messageFormat = 'text'; } this.batchDelay = options.minTime * 2; this.auditInterval; this.auditDelay = 300; this.auditCounter = 0; this.logs = []; this.logMax = 1000; this.lexicon = []; this.bots = []; this.spark = {}; this.webhook = {}; // register internal events this.on('error', err => { if(err) { console.err(err.stack); } }); this.on('start', () => { require('./logs')(this); this.initialize(); }); }
javascript
function Flint(options) { EventEmitter.call(this); this.id = options.id || u.genUUID64(); /** * Options Object * * @memberof Flint * @instance * @namespace options * @property {string} token - Spark Token. * @property {string} webhookUrl - URL that is used for SPark API to send callbacks. * @property {string} [webhookSecret] - If specified, inbound webhooks are authorized before being processed. * @property {string} [messageFormat=text] - Default Spark message format to use with bot.say(). * @property {number} [maxPageItems=50] - Max results that the paginator uses. * @property {number} [maxConcurrent=3] - Max concurrent sessions to the Spark API * @property {number} [minTime=600] - Min time between consecutive request starts. * @property {number} [requeueMinTime=minTime*10] - Min time between consecutive request starts of requests that have been re-queued. * @property {number} [requeueMaxRetry=3] - Msx number of atteempts to make for failed request. * @property {array} [requeueCodes=[429,500,503]] - Array of http result codes that should be retried. * @property {number} [requestTimeout=20000] - Timeout for an individual request recieving a response. * @property {number} [queueSize=10000] - Size of the buffer that holds outbound requests. * @property {number} [requeueSize=10000] - Size of the buffer that holds outbound re-queue requests. * @property {string} [id=random] - The id this instance of flint uses. * @property {string} [webhookRequestJSONLocation=body] - The property under the Request to find the JSON contents. * @property {Boolean} [removeWebhooksOnStart=true] - If you wish to have the bot remove all account webhooks when starting. */ this.options = options; this.active = false; this.initialized = false; this.storageActive = false; this.isBotAccount = false; this.isUserAccount = false; this.person = {}; this.email; // define location in webhook request to find json values of incoming webhook. // note: this is typically 'request.body' but depending on express/restify configuration, it may be 'request.params' this.options.webhookRequestJSONLocation = this.options.webhookRequestJSONLocation || 'body'; // define if flint remove all webhooks attached to token on start (if not defined, defaults to true) this.options.removeWebhooksOnStart = typeof this.options.removeWebhooksOnStart === 'boolean' ? this.options.removeWebhooksOnStart : true; // define default messageFormat used with bot.say (if not defined, defaults to 'text') if(typeof this.options.messageFormat === 'string' && _.includes(['text', 'markdown', 'html'], _.toLower(this.options.messageFormat))) { this.messageFormat = _.toLower(this.options.messageFormat); } else { this.messageFormat = 'text'; } this.batchDelay = options.minTime * 2; this.auditInterval; this.auditDelay = 300; this.auditCounter = 0; this.logs = []; this.logMax = 1000; this.lexicon = []; this.bots = []; this.spark = {}; this.webhook = {}; // register internal events this.on('error', err => { if(err) { console.err(err.stack); } }); this.on('start', () => { require('./logs')(this); this.initialize(); }); }
[ "function", "Flint", "(", "options", ")", "{", "EventEmitter", ".", "call", "(", "this", ")", ";", "this", ".", "id", "=", "options", ".", "id", "||", "u", ".", "genUUID64", "(", ")", ";", "/**\n * Options Object\n *\n * @memberof Flint\n * @instance\n * @namespace options\n * @property {string} token - Spark Token.\n * @property {string} webhookUrl - URL that is used for SPark API to send callbacks.\n * @property {string} [webhookSecret] - If specified, inbound webhooks are authorized before being processed.\n * @property {string} [messageFormat=text] - Default Spark message format to use with bot.say().\n * @property {number} [maxPageItems=50] - Max results that the paginator uses.\n * @property {number} [maxConcurrent=3] - Max concurrent sessions to the Spark API\n * @property {number} [minTime=600] - Min time between consecutive request starts.\n * @property {number} [requeueMinTime=minTime*10] - Min time between consecutive request starts of requests that have been re-queued.\n * @property {number} [requeueMaxRetry=3] - Msx number of atteempts to make for failed request.\n * @property {array} [requeueCodes=[429,500,503]] - Array of http result codes that should be retried.\n * @property {number} [requestTimeout=20000] - Timeout for an individual request recieving a response.\n * @property {number} [queueSize=10000] - Size of the buffer that holds outbound requests.\n * @property {number} [requeueSize=10000] - Size of the buffer that holds outbound re-queue requests.\n * @property {string} [id=random] - The id this instance of flint uses.\n * @property {string} [webhookRequestJSONLocation=body] - The property under the Request to find the JSON contents.\n * @property {Boolean} [removeWebhooksOnStart=true] - If you wish to have the bot remove all account webhooks when starting.\n */", "this", ".", "options", "=", "options", ";", "this", ".", "active", "=", "false", ";", "this", ".", "initialized", "=", "false", ";", "this", ".", "storageActive", "=", "false", ";", "this", ".", "isBotAccount", "=", "false", ";", "this", ".", "isUserAccount", "=", "false", ";", "this", ".", "person", "=", "{", "}", ";", "this", ".", "email", ";", "// define location in webhook request to find json values of incoming webhook.", "// note: this is typically 'request.body' but depending on express/restify configuration, it may be 'request.params'", "this", ".", "options", ".", "webhookRequestJSONLocation", "=", "this", ".", "options", ".", "webhookRequestJSONLocation", "||", "'body'", ";", "// define if flint remove all webhooks attached to token on start (if not defined, defaults to true)", "this", ".", "options", ".", "removeWebhooksOnStart", "=", "typeof", "this", ".", "options", ".", "removeWebhooksOnStart", "===", "'boolean'", "?", "this", ".", "options", ".", "removeWebhooksOnStart", ":", "true", ";", "// define default messageFormat used with bot.say (if not defined, defaults to 'text')", "if", "(", "typeof", "this", ".", "options", ".", "messageFormat", "===", "'string'", "&&", "_", ".", "includes", "(", "[", "'text'", ",", "'markdown'", ",", "'html'", "]", ",", "_", ".", "toLower", "(", "this", ".", "options", ".", "messageFormat", ")", ")", ")", "{", "this", ".", "messageFormat", "=", "_", ".", "toLower", "(", "this", ".", "options", ".", "messageFormat", ")", ";", "}", "else", "{", "this", ".", "messageFormat", "=", "'text'", ";", "}", "this", ".", "batchDelay", "=", "options", ".", "minTime", "*", "2", ";", "this", ".", "auditInterval", ";", "this", ".", "auditDelay", "=", "300", ";", "this", ".", "auditCounter", "=", "0", ";", "this", ".", "logs", "=", "[", "]", ";", "this", ".", "logMax", "=", "1000", ";", "this", ".", "lexicon", "=", "[", "]", ";", "this", ".", "bots", "=", "[", "]", ";", "this", ".", "spark", "=", "{", "}", ";", "this", ".", "webhook", "=", "{", "}", ";", "// register internal events", "this", ".", "on", "(", "'error'", ",", "err", "=>", "{", "if", "(", "err", ")", "{", "console", ".", "err", "(", "err", ".", "stack", ")", ";", "}", "}", ")", ";", "this", ".", "on", "(", "'start'", ",", "(", ")", "=>", "{", "require", "(", "'./logs'", ")", "(", "this", ")", ";", "this", ".", "initialize", "(", ")", ";", "}", ")", ";", "}" ]
Creates an instance of Flint. @constructor Flint @param {Object} options - Configuration object containing Flint settings. @property {string} id - Flint UUID @property {boolean} active - Flint active state @property {boolean} intialized - Flint fully initialized @property {boolean} isBotAccount - Is Flint attached to Spark using a bot account? @property {boolean} isUserAccount - Is Flint attached to Spark using a user account? @property {object} person - Flint person object @property {string} email - Flint email @property {object} spark - The Spark instance used by flint @example var options = { webhookUrl: 'http://myserver.com/flint', token: 'Tm90aGluZyB0byBzZWUgaGVyZS4uLiBNb3ZlIGFsb25nLi4u' }; var flint = new Flint(options);
[ "Creates", "an", "instance", "of", "Flint", "." ]
718923a17e794e28328aed1a2b24d75748b81fbc
https://github.com/flint-bot/flint/blob/718923a17e794e28328aed1a2b24d75748b81fbc/lib/flint.js#L40-L113
40,613
flint-bot/flint
lib/flint.js
runActions
function runActions(matched, bot, trigger, id) { // process preference logic if(matched.length > 1) { matched = _.sortBy(matched, match => match.preference); var prefLow = matched[0].preference; var prefHigh = matched[matched.length - 1].preference; if(prefLow !== prefHigh) { matched = _.filter(matched, match => (match.preference === prefLow)); } } _.forEach(matched, lex => { // for regex if(lex.phrase instanceof RegExp && typeof lex.action === 'function') { // define trigger.args, trigger.phrase trigger.args = trigger.text.split(' '); trigger.phrase = lex.phrase; // run action lex.action(bot, trigger, id); return true; } // for string else if (typeof lex.phrase === 'string' && typeof lex.action === 'function') { // find index of match var args = _.toLower(trigger.text).split(' '); var indexOfMatch = args.indexOf(lex.phrase) !== -1 ? args.indexOf(lex.phrase) : 0; // define trigger.args, trigger.phrase trigger.args = trigger.text.split(' '); trigger.args = trigger.args.slice(indexOfMatch, trigger.args.length); trigger.phrase = lex.phrase; // run action lex.action(bot, trigger, id); return true; } // for nothing... else { return false; } }); }
javascript
function runActions(matched, bot, trigger, id) { // process preference logic if(matched.length > 1) { matched = _.sortBy(matched, match => match.preference); var prefLow = matched[0].preference; var prefHigh = matched[matched.length - 1].preference; if(prefLow !== prefHigh) { matched = _.filter(matched, match => (match.preference === prefLow)); } } _.forEach(matched, lex => { // for regex if(lex.phrase instanceof RegExp && typeof lex.action === 'function') { // define trigger.args, trigger.phrase trigger.args = trigger.text.split(' '); trigger.phrase = lex.phrase; // run action lex.action(bot, trigger, id); return true; } // for string else if (typeof lex.phrase === 'string' && typeof lex.action === 'function') { // find index of match var args = _.toLower(trigger.text).split(' '); var indexOfMatch = args.indexOf(lex.phrase) !== -1 ? args.indexOf(lex.phrase) : 0; // define trigger.args, trigger.phrase trigger.args = trigger.text.split(' '); trigger.args = trigger.args.slice(indexOfMatch, trigger.args.length); trigger.phrase = lex.phrase; // run action lex.action(bot, trigger, id); return true; } // for nothing... else { return false; } }); }
[ "function", "runActions", "(", "matched", ",", "bot", ",", "trigger", ",", "id", ")", "{", "// process preference logic", "if", "(", "matched", ".", "length", ">", "1", ")", "{", "matched", "=", "_", ".", "sortBy", "(", "matched", ",", "match", "=>", "match", ".", "preference", ")", ";", "var", "prefLow", "=", "matched", "[", "0", "]", ".", "preference", ";", "var", "prefHigh", "=", "matched", "[", "matched", ".", "length", "-", "1", "]", ".", "preference", ";", "if", "(", "prefLow", "!==", "prefHigh", ")", "{", "matched", "=", "_", ".", "filter", "(", "matched", ",", "match", "=>", "(", "match", ".", "preference", "===", "prefLow", ")", ")", ";", "}", "}", "_", ".", "forEach", "(", "matched", ",", "lex", "=>", "{", "// for regex", "if", "(", "lex", ".", "phrase", "instanceof", "RegExp", "&&", "typeof", "lex", ".", "action", "===", "'function'", ")", "{", "// define trigger.args, trigger.phrase", "trigger", ".", "args", "=", "trigger", ".", "text", ".", "split", "(", "' '", ")", ";", "trigger", ".", "phrase", "=", "lex", ".", "phrase", ";", "// run action", "lex", ".", "action", "(", "bot", ",", "trigger", ",", "id", ")", ";", "return", "true", ";", "}", "// for string", "else", "if", "(", "typeof", "lex", ".", "phrase", "===", "'string'", "&&", "typeof", "lex", ".", "action", "===", "'function'", ")", "{", "// find index of match", "var", "args", "=", "_", ".", "toLower", "(", "trigger", ".", "text", ")", ".", "split", "(", "' '", ")", ";", "var", "indexOfMatch", "=", "args", ".", "indexOf", "(", "lex", ".", "phrase", ")", "!==", "-", "1", "?", "args", ".", "indexOf", "(", "lex", ".", "phrase", ")", ":", "0", ";", "// define trigger.args, trigger.phrase", "trigger", ".", "args", "=", "trigger", ".", "text", ".", "split", "(", "' '", ")", ";", "trigger", ".", "args", "=", "trigger", ".", "args", ".", "slice", "(", "indexOfMatch", ",", "trigger", ".", "args", ".", "length", ")", ";", "trigger", ".", "phrase", "=", "lex", ".", "phrase", ";", "// run action", "lex", ".", "action", "(", "bot", ",", "trigger", ",", "id", ")", ";", "return", "true", ";", "}", "// for nothing...", "else", "{", "return", "false", ";", "}", "}", ")", ";", "}" ]
function to run the action
[ "function", "to", "run", "the", "action" ]
718923a17e794e28328aed1a2b24d75748b81fbc
https://github.com/flint-bot/flint/blob/718923a17e794e28328aed1a2b24d75748b81fbc/lib/flint.js#L1432-L1477
40,614
flint-bot/flint
lib/bot.js
markdownFormat
function markdownFormat(str) { // if string... if(str && typeof str === 'string') { // process characters that do not render visibly in markdown str = str.replace(/\<(?!@)/g, '&lt;'); str = str.split('').reverse().join('').replace(/\>(?!.*@\<)/g, ';tg&').split('').reverse().join(''); return str; } // else return empty else { return ''; } }
javascript
function markdownFormat(str) { // if string... if(str && typeof str === 'string') { // process characters that do not render visibly in markdown str = str.replace(/\<(?!@)/g, '&lt;'); str = str.split('').reverse().join('').replace(/\>(?!.*@\<)/g, ';tg&').split('').reverse().join(''); return str; } // else return empty else { return ''; } }
[ "function", "markdownFormat", "(", "str", ")", "{", "// if string...", "if", "(", "str", "&&", "typeof", "str", "===", "'string'", ")", "{", "// process characters that do not render visibly in markdown", "str", "=", "str", ".", "replace", "(", "/", "\\<(?!@)", "/", "g", ",", "'&lt;'", ")", ";", "str", "=", "str", ".", "split", "(", "''", ")", ".", "reverse", "(", ")", ".", "join", "(", "''", ")", ".", "replace", "(", "/", "\\>(?!.*@\\<)", "/", "g", ",", "';tg&'", ")", ".", "split", "(", "''", ")", ".", "reverse", "(", ")", ".", "join", "(", "''", ")", ";", "return", "str", ";", "}", "// else return empty", "else", "{", "return", "''", ";", "}", "}" ]
format makrdown type
[ "format", "makrdown", "type" ]
718923a17e794e28328aed1a2b24d75748b81fbc
https://github.com/flint-bot/flint/blob/718923a17e794e28328aed1a2b24d75748b81fbc/lib/bot.js#L17-L32
40,615
flint-bot/flint
lib/bot.js
Bot
function Bot(flint) { EventEmitter.call(this); this.id = u.genUUID64(); this.flint = flint; this.options = flint.options; this.debug = function(message) { message = util.format.apply(null, Array.prototype.slice.call(arguments)); if(typeof flint.debugger === 'function') { flint.debugger(message, this.id); } else { _debug(message); } }; //randomize distribution of when audit event should take place for this bot instance... this.auditTrigger = Math.floor((Math.random() * this.flint.auditDelay)) + 1; this.spark = this.flint.spark; this.batchDelay = this.flint.batchDelay; this.active = false; this.room = {}; this.team = {}; this.person = this.flint.person; this.membership = {}; this.memberships = []; this.email = this.flint.email; this.isLocked = false; this.isModerator = false; this.isGroup = false; this.isDirect = false; this.isTeam = false; this.lastActivity = moment().utc().toDate(); this.on('error', err => { if(err) { this.debug(err.stack); } }); }
javascript
function Bot(flint) { EventEmitter.call(this); this.id = u.genUUID64(); this.flint = flint; this.options = flint.options; this.debug = function(message) { message = util.format.apply(null, Array.prototype.slice.call(arguments)); if(typeof flint.debugger === 'function') { flint.debugger(message, this.id); } else { _debug(message); } }; //randomize distribution of when audit event should take place for this bot instance... this.auditTrigger = Math.floor((Math.random() * this.flint.auditDelay)) + 1; this.spark = this.flint.spark; this.batchDelay = this.flint.batchDelay; this.active = false; this.room = {}; this.team = {}; this.person = this.flint.person; this.membership = {}; this.memberships = []; this.email = this.flint.email; this.isLocked = false; this.isModerator = false; this.isGroup = false; this.isDirect = false; this.isTeam = false; this.lastActivity = moment().utc().toDate(); this.on('error', err => { if(err) { this.debug(err.stack); } }); }
[ "function", "Bot", "(", "flint", ")", "{", "EventEmitter", ".", "call", "(", "this", ")", ";", "this", ".", "id", "=", "u", ".", "genUUID64", "(", ")", ";", "this", ".", "flint", "=", "flint", ";", "this", ".", "options", "=", "flint", ".", "options", ";", "this", ".", "debug", "=", "function", "(", "message", ")", "{", "message", "=", "util", ".", "format", ".", "apply", "(", "null", ",", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ")", ")", ";", "if", "(", "typeof", "flint", ".", "debugger", "===", "'function'", ")", "{", "flint", ".", "debugger", "(", "message", ",", "this", ".", "id", ")", ";", "}", "else", "{", "_debug", "(", "message", ")", ";", "}", "}", ";", "//randomize distribution of when audit event should take place for this bot instance...", "this", ".", "auditTrigger", "=", "Math", ".", "floor", "(", "(", "Math", ".", "random", "(", ")", "*", "this", ".", "flint", ".", "auditDelay", ")", ")", "+", "1", ";", "this", ".", "spark", "=", "this", ".", "flint", ".", "spark", ";", "this", ".", "batchDelay", "=", "this", ".", "flint", ".", "batchDelay", ";", "this", ".", "active", "=", "false", ";", "this", ".", "room", "=", "{", "}", ";", "this", ".", "team", "=", "{", "}", ";", "this", ".", "person", "=", "this", ".", "flint", ".", "person", ";", "this", ".", "membership", "=", "{", "}", ";", "this", ".", "memberships", "=", "[", "]", ";", "this", ".", "email", "=", "this", ".", "flint", ".", "email", ";", "this", ".", "isLocked", "=", "false", ";", "this", ".", "isModerator", "=", "false", ";", "this", ".", "isGroup", "=", "false", ";", "this", ".", "isDirect", "=", "false", ";", "this", ".", "isTeam", "=", "false", ";", "this", ".", "lastActivity", "=", "moment", "(", ")", ".", "utc", "(", ")", ".", "toDate", "(", ")", ";", "this", ".", "on", "(", "'error'", ",", "err", "=>", "{", "if", "(", "err", ")", "{", "this", ".", "debug", "(", "err", ".", "stack", ")", ";", "}", "}", ")", ";", "}" ]
Creates a Bot instance that is then attached to a Spark Room. @constructor @param {Object} flint - The flint object this Bot spawns under. @property {string} id - Bot UUID @property {boolean} active - Bot active state @property {object} person - Bot Person Object @property {string} email - Bot email @property {object} team - Bot team object @property {object} room - Bot room object @property {object} membership - Bot membership object @property {boolean} isLocked - If bot is locked @property {boolean} isModerator - If bot is a moderator @property {boolean} isGroup - If bot is in Group Room @property {boolean} isDirect - If bot is in 1:1/Direct Room @property {string} isDirectTo - Recipient Email if bot is in 1:1/Direct Room @property {boolean} isTeam - If bot is in Team Room @property {date} lastActivity - Last bot activity
[ "Creates", "a", "Bot", "instance", "that", "is", "then", "attached", "to", "a", "Spark", "Room", "." ]
718923a17e794e28328aed1a2b24d75748b81fbc
https://github.com/flint-bot/flint/blob/718923a17e794e28328aed1a2b24d75748b81fbc/lib/bot.js#L59-L101
40,616
flint-bot/flint
storage/redis_old.js
initRedis
function initRedis() { return when.promise((resolve, reject) => { redis.get(name, (err, res) => { if(err) { memStore = {}; } else if(res) { memStore = JSON.parse(res); } else { memStore = {}; } resolve(true); }); }); }
javascript
function initRedis() { return when.promise((resolve, reject) => { redis.get(name, (err, res) => { if(err) { memStore = {}; } else if(res) { memStore = JSON.parse(res); } else { memStore = {}; } resolve(true); }); }); }
[ "function", "initRedis", "(", ")", "{", "return", "when", ".", "promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "redis", ".", "get", "(", "name", ",", "(", "err", ",", "res", ")", "=>", "{", "if", "(", "err", ")", "{", "memStore", "=", "{", "}", ";", "}", "else", "if", "(", "res", ")", "{", "memStore", "=", "JSON", ".", "parse", "(", "res", ")", ";", "}", "else", "{", "memStore", "=", "{", "}", ";", "}", "resolve", "(", "true", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
load memStore state from redis
[ "load", "memStore", "state", "from", "redis" ]
718923a17e794e28328aed1a2b24d75748b81fbc
https://github.com/flint-bot/flint/blob/718923a17e794e28328aed1a2b24d75748b81fbc/storage/redis_old.js#L17-L30
40,617
flint-bot/flint
storage/redis_old.js
syncRedis
function syncRedis() { // if memStore has changed... if(JSON.stringify(memCache) !== JSON.stringify(memStore)) { return when.promise((resolve, reject) => { var serializedStore = JSON.stringify(memStore); redis.set(name, serializedStore, err => { if(err) { reject(err); } else { resolve(true); } }); }) .delay(syncInterval) .catch(err => { console.log(err.stack); return when(true); }) .finally(() => { memCache = _.cloneDeep(memStore); if(active) syncRedis(memStore); return when(true); }); } // else memStore has not changed... else { return when(true) .delay(syncInterval) .then(() => { if(active) syncRedis(memStore); return when(true); }); } }
javascript
function syncRedis() { // if memStore has changed... if(JSON.stringify(memCache) !== JSON.stringify(memStore)) { return when.promise((resolve, reject) => { var serializedStore = JSON.stringify(memStore); redis.set(name, serializedStore, err => { if(err) { reject(err); } else { resolve(true); } }); }) .delay(syncInterval) .catch(err => { console.log(err.stack); return when(true); }) .finally(() => { memCache = _.cloneDeep(memStore); if(active) syncRedis(memStore); return when(true); }); } // else memStore has not changed... else { return when(true) .delay(syncInterval) .then(() => { if(active) syncRedis(memStore); return when(true); }); } }
[ "function", "syncRedis", "(", ")", "{", "// if memStore has changed...", "if", "(", "JSON", ".", "stringify", "(", "memCache", ")", "!==", "JSON", ".", "stringify", "(", "memStore", ")", ")", "{", "return", "when", ".", "promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "var", "serializedStore", "=", "JSON", ".", "stringify", "(", "memStore", ")", ";", "redis", ".", "set", "(", "name", ",", "serializedStore", ",", "err", "=>", "{", "if", "(", "err", ")", "{", "reject", "(", "err", ")", ";", "}", "else", "{", "resolve", "(", "true", ")", ";", "}", "}", ")", ";", "}", ")", ".", "delay", "(", "syncInterval", ")", ".", "catch", "(", "err", "=>", "{", "console", ".", "log", "(", "err", ".", "stack", ")", ";", "return", "when", "(", "true", ")", ";", "}", ")", ".", "finally", "(", "(", ")", "=>", "{", "memCache", "=", "_", ".", "cloneDeep", "(", "memStore", ")", ";", "if", "(", "active", ")", "syncRedis", "(", "memStore", ")", ";", "return", "when", "(", "true", ")", ";", "}", ")", ";", "}", "// else memStore has not changed...", "else", "{", "return", "when", "(", "true", ")", ".", "delay", "(", "syncInterval", ")", ".", "then", "(", "(", ")", "=>", "{", "if", "(", "active", ")", "syncRedis", "(", "memStore", ")", ";", "return", "when", "(", "true", ")", ";", "}", ")", ";", "}", "}" ]
start periodicly sync of memStore state to redis
[ "start", "periodicly", "sync", "of", "memStore", "state", "to", "redis" ]
718923a17e794e28328aed1a2b24d75748b81fbc
https://github.com/flint-bot/flint/blob/718923a17e794e28328aed1a2b24d75748b81fbc/storage/redis_old.js#L33-L67
40,618
dominhhai/koa-log4js
koa-logger.js
getKoaLogger
function getKoaLogger (logger4js, options) { if (typeof options === 'object') { options = options || {} } else if (options) { options = { format: options } } else { options = {} } let thislogger = logger4js let level = levels.getLevel(options.level, levels.INFO) let fmt = options.format || DEFAULT_FORMAT let nolog = options.nolog ? createNoLogCondition(options.nolog) : null return async (ctx, next) => { // mount safety if (ctx.request._logging) { await next() return } // nologs if (nolog && nolog.test(ctx.originalUrl)) { await next() return } if (thislogger.isLevelEnabled(level) || options.level === 'auto') { let start = new Date() let writeHead = ctx.response.writeHead // flag as logging ctx.request._logging = true // proxy for statusCode. ctx.response.writeHead = function (code, headers) { ctx.response.writeHead = writeHead ctx.response.writeHead(code, headers) ctx.response.__statusCode = code ctx.response.__headers = headers || {} // status code response level handling if (options.level === 'auto') { level = levels.INFO if (code >= 300) level = levels.WARN if (code >= 400) level = levels.ERROR } else { level = levels.getLevel(options.level, levels.INFO) } } await next() // hook on end request to emit the log entry of the HTTP request. ctx.response.responseTime = new Date() - start // status code response level handling if (ctx.res.statusCode && options.level === 'auto') { level = levels.INFO if (ctx.res.statusCode >= 300) level = levels.WARN if (ctx.res.statusCode >= 400) level = levels.ERROR } if (thislogger.isLevelEnabled(level)) { let combinedTokens = assembleTokens(ctx, options.tokens || []) if (typeof fmt === 'function') { let line = fmt(ctx, function (str) { return format(str, combinedTokens) }) if (line) thislogger.log(level, line) } else { thislogger.log(level, format(fmt, combinedTokens)) } } } else { // ensure next gets always called await next() } } }
javascript
function getKoaLogger (logger4js, options) { if (typeof options === 'object') { options = options || {} } else if (options) { options = { format: options } } else { options = {} } let thislogger = logger4js let level = levels.getLevel(options.level, levels.INFO) let fmt = options.format || DEFAULT_FORMAT let nolog = options.nolog ? createNoLogCondition(options.nolog) : null return async (ctx, next) => { // mount safety if (ctx.request._logging) { await next() return } // nologs if (nolog && nolog.test(ctx.originalUrl)) { await next() return } if (thislogger.isLevelEnabled(level) || options.level === 'auto') { let start = new Date() let writeHead = ctx.response.writeHead // flag as logging ctx.request._logging = true // proxy for statusCode. ctx.response.writeHead = function (code, headers) { ctx.response.writeHead = writeHead ctx.response.writeHead(code, headers) ctx.response.__statusCode = code ctx.response.__headers = headers || {} // status code response level handling if (options.level === 'auto') { level = levels.INFO if (code >= 300) level = levels.WARN if (code >= 400) level = levels.ERROR } else { level = levels.getLevel(options.level, levels.INFO) } } await next() // hook on end request to emit the log entry of the HTTP request. ctx.response.responseTime = new Date() - start // status code response level handling if (ctx.res.statusCode && options.level === 'auto') { level = levels.INFO if (ctx.res.statusCode >= 300) level = levels.WARN if (ctx.res.statusCode >= 400) level = levels.ERROR } if (thislogger.isLevelEnabled(level)) { let combinedTokens = assembleTokens(ctx, options.tokens || []) if (typeof fmt === 'function') { let line = fmt(ctx, function (str) { return format(str, combinedTokens) }) if (line) thislogger.log(level, line) } else { thislogger.log(level, format(fmt, combinedTokens)) } } } else { // ensure next gets always called await next() } } }
[ "function", "getKoaLogger", "(", "logger4js", ",", "options", ")", "{", "if", "(", "typeof", "options", "===", "'object'", ")", "{", "options", "=", "options", "||", "{", "}", "}", "else", "if", "(", "options", ")", "{", "options", "=", "{", "format", ":", "options", "}", "}", "else", "{", "options", "=", "{", "}", "}", "let", "thislogger", "=", "logger4js", "let", "level", "=", "levels", ".", "getLevel", "(", "options", ".", "level", ",", "levels", ".", "INFO", ")", "let", "fmt", "=", "options", ".", "format", "||", "DEFAULT_FORMAT", "let", "nolog", "=", "options", ".", "nolog", "?", "createNoLogCondition", "(", "options", ".", "nolog", ")", ":", "null", "return", "async", "(", "ctx", ",", "next", ")", "=>", "{", "// mount safety", "if", "(", "ctx", ".", "request", ".", "_logging", ")", "{", "await", "next", "(", ")", "return", "}", "// nologs", "if", "(", "nolog", "&&", "nolog", ".", "test", "(", "ctx", ".", "originalUrl", ")", ")", "{", "await", "next", "(", ")", "return", "}", "if", "(", "thislogger", ".", "isLevelEnabled", "(", "level", ")", "||", "options", ".", "level", "===", "'auto'", ")", "{", "let", "start", "=", "new", "Date", "(", ")", "let", "writeHead", "=", "ctx", ".", "response", ".", "writeHead", "// flag as logging", "ctx", ".", "request", ".", "_logging", "=", "true", "// proxy for statusCode.", "ctx", ".", "response", ".", "writeHead", "=", "function", "(", "code", ",", "headers", ")", "{", "ctx", ".", "response", ".", "writeHead", "=", "writeHead", "ctx", ".", "response", ".", "writeHead", "(", "code", ",", "headers", ")", "ctx", ".", "response", ".", "__statusCode", "=", "code", "ctx", ".", "response", ".", "__headers", "=", "headers", "||", "{", "}", "// status code response level handling", "if", "(", "options", ".", "level", "===", "'auto'", ")", "{", "level", "=", "levels", ".", "INFO", "if", "(", "code", ">=", "300", ")", "level", "=", "levels", ".", "WARN", "if", "(", "code", ">=", "400", ")", "level", "=", "levels", ".", "ERROR", "}", "else", "{", "level", "=", "levels", ".", "getLevel", "(", "options", ".", "level", ",", "levels", ".", "INFO", ")", "}", "}", "await", "next", "(", ")", "// hook on end request to emit the log entry of the HTTP request.", "ctx", ".", "response", ".", "responseTime", "=", "new", "Date", "(", ")", "-", "start", "// status code response level handling", "if", "(", "ctx", ".", "res", ".", "statusCode", "&&", "options", ".", "level", "===", "'auto'", ")", "{", "level", "=", "levels", ".", "INFO", "if", "(", "ctx", ".", "res", ".", "statusCode", ">=", "300", ")", "level", "=", "levels", ".", "WARN", "if", "(", "ctx", ".", "res", ".", "statusCode", ">=", "400", ")", "level", "=", "levels", ".", "ERROR", "}", "if", "(", "thislogger", ".", "isLevelEnabled", "(", "level", ")", ")", "{", "let", "combinedTokens", "=", "assembleTokens", "(", "ctx", ",", "options", ".", "tokens", "||", "[", "]", ")", "if", "(", "typeof", "fmt", "===", "'function'", ")", "{", "let", "line", "=", "fmt", "(", "ctx", ",", "function", "(", "str", ")", "{", "return", "format", "(", "str", ",", "combinedTokens", ")", "}", ")", "if", "(", "line", ")", "thislogger", ".", "log", "(", "level", ",", "line", ")", "}", "else", "{", "thislogger", ".", "log", "(", "level", ",", "format", "(", "fmt", ",", "combinedTokens", ")", ")", "}", "}", "}", "else", "{", "// ensure next gets always called", "await", "next", "(", ")", "}", "}", "}" ]
Log requests with the given `options` or a `format` string. Use for Koa v1 Options: - `format` Format string, see below for tokens - `level` A log4js levels instance. Supports also 'auto' Tokens: - `:req[header]` ex: `:req[Accept]` - `:res[header]` ex: `:res[Content-Length]` - `:http-version` - `:response-time` - `:remote-addr` - `:date` - `:method` - `:url` - `:referrer` - `:user-agent` - `:status` @param {String|Function|Object} format or options @return {Function} @api public
[ "Log", "requests", "with", "the", "given", "options", "or", "a", "format", "string", ".", "Use", "for", "Koa", "v1" ]
c129c9e7d1145553ecbf14938022aac7998a0710
https://github.com/dominhhai/koa-log4js/blob/c129c9e7d1145553ecbf14938022aac7998a0710/koa-logger.js#L36-L111
40,619
dominhhai/koa-log4js
koa-logger.js
format
function format (str, tokens) { for (let i = 0; i < tokens.length; i++) { str = str.replace(tokens[i].token, tokens[i].replacement) } return str }
javascript
function format (str, tokens) { for (let i = 0; i < tokens.length; i++) { str = str.replace(tokens[i].token, tokens[i].replacement) } return str }
[ "function", "format", "(", "str", ",", "tokens", ")", "{", "for", "(", "let", "i", "=", "0", ";", "i", "<", "tokens", ".", "length", ";", "i", "++", ")", "{", "str", "=", "str", ".", "replace", "(", "tokens", "[", "i", "]", ".", "token", ",", "tokens", "[", "i", "]", ".", "replacement", ")", "}", "return", "str", "}" ]
Return formatted log line. @param {String} str @param {IncomingMessage} req @param {ServerResponse} res @return {String} @api private
[ "Return", "formatted", "log", "line", "." ]
c129c9e7d1145553ecbf14938022aac7998a0710
https://github.com/dominhhai/koa-log4js/blob/c129c9e7d1145553ecbf14938022aac7998a0710/koa-logger.js#L198-L203
40,620
dominhhai/koa-log4js
koa-logger.js
createNoLogCondition
function createNoLogCondition (nolog) { let regexp = null if (nolog) { if (nolog instanceof RegExp) { regexp = nolog } if (typeof nolog === 'string') { regexp = new RegExp(nolog) } if (Array.isArray(nolog)) { let regexpsAsStrings = nolog.map((o) => (o.source ? o.source : o)) regexp = new RegExp(regexpsAsStrings.join('|')) } } return regexp }
javascript
function createNoLogCondition (nolog) { let regexp = null if (nolog) { if (nolog instanceof RegExp) { regexp = nolog } if (typeof nolog === 'string') { regexp = new RegExp(nolog) } if (Array.isArray(nolog)) { let regexpsAsStrings = nolog.map((o) => (o.source ? o.source : o)) regexp = new RegExp(regexpsAsStrings.join('|')) } } return regexp }
[ "function", "createNoLogCondition", "(", "nolog", ")", "{", "let", "regexp", "=", "null", "if", "(", "nolog", ")", "{", "if", "(", "nolog", "instanceof", "RegExp", ")", "{", "regexp", "=", "nolog", "}", "if", "(", "typeof", "nolog", "===", "'string'", ")", "{", "regexp", "=", "new", "RegExp", "(", "nolog", ")", "}", "if", "(", "Array", ".", "isArray", "(", "nolog", ")", ")", "{", "let", "regexpsAsStrings", "=", "nolog", ".", "map", "(", "(", "o", ")", "=>", "(", "o", ".", "source", "?", "o", ".", "source", ":", "o", ")", ")", "regexp", "=", "new", "RegExp", "(", "regexpsAsStrings", ".", "join", "(", "'|'", ")", ")", "}", "}", "return", "regexp", "}" ]
Return RegExp Object about nolog @param {String} nolog @return {RegExp} @api private syntax 1. String 1.1 "\\.gif" NOT LOGGING http://example.com/hoge.gif and http://example.com/hoge.gif?fuga LOGGING http://example.com/hoge.agif 1.2 in "\\.gif|\\.jpg$" NOT LOGGING http://example.com/hoge.gif and http://example.com/hoge.gif?fuga and http://example.com/hoge.jpg?fuga LOGGING http://example.com/hoge.agif, http://example.com/hoge.ajpg and http://example.com/hoge.jpg?hoge 1.3 in "\\.(gif|jpe?g|png)$" NOT LOGGING http://example.com/hoge.gif and http://example.com/hoge.jpeg LOGGING http://example.com/hoge.gif?uid=2 and http://example.com/hoge.jpg?pid=3 2. RegExp 2.1 in /\.(gif|jpe?g|png)$/ SAME AS 1.3 3. Array 3.1 ["\\.jpg$", "\\.png", "\\.gif"] SAME AS "\\.jpg|\\.png|\\.gif"
[ "Return", "RegExp", "Object", "about", "nolog" ]
c129c9e7d1145553ecbf14938022aac7998a0710
https://github.com/dominhhai/koa-log4js/blob/c129c9e7d1145553ecbf14938022aac7998a0710/koa-logger.js#L232-L250
40,621
BioPhoton/angular1-star-rating
chore/gulp/helper.js
log
function log(msg, color) { if (typeof(msg) === 'object') { for (var item in msg) { if (msg.hasOwnProperty(item)) { if(color && color in $.util.colors) { $.util.log($.util.colors[color](msg[item])); } $.util.log($.util.colors.lightgreen(msg[item])); } } } else { $.util.log($.util.colors.green(msg)); } }
javascript
function log(msg, color) { if (typeof(msg) === 'object') { for (var item in msg) { if (msg.hasOwnProperty(item)) { if(color && color in $.util.colors) { $.util.log($.util.colors[color](msg[item])); } $.util.log($.util.colors.lightgreen(msg[item])); } } } else { $.util.log($.util.colors.green(msg)); } }
[ "function", "log", "(", "msg", ",", "color", ")", "{", "if", "(", "typeof", "(", "msg", ")", "===", "'object'", ")", "{", "for", "(", "var", "item", "in", "msg", ")", "{", "if", "(", "msg", ".", "hasOwnProperty", "(", "item", ")", ")", "{", "if", "(", "color", "&&", "color", "in", "$", ".", "util", ".", "colors", ")", "{", "$", ".", "util", ".", "log", "(", "$", ".", "util", ".", "colors", "[", "color", "]", "(", "msg", "[", "item", "]", ")", ")", ";", "}", "$", ".", "util", ".", "log", "(", "$", ".", "util", ".", "colors", ".", "lightgreen", "(", "msg", "[", "item", "]", ")", ")", ";", "}", "}", "}", "else", "{", "$", ".", "util", ".", "log", "(", "$", ".", "util", ".", "colors", ".", "green", "(", "msg", ")", ")", ";", "}", "}" ]
Log a message or series of messages using chalk's green color. Can pass in a string, object or array.
[ "Log", "a", "message", "or", "series", "of", "messages", "using", "chalk", "s", "green", "color", ".", "Can", "pass", "in", "a", "string", "object", "or", "array", "." ]
dfff7d9a399f59ad0b8dd8a8309360d4930664a4
https://github.com/BioPhoton/angular1-star-rating/blob/dfff7d9a399f59ad0b8dd8a8309360d4930664a4/chore/gulp/helper.js#L73-L86
40,622
BioPhoton/angular1-star-rating
chore/gulp/helper.js
clean
function clean(path, done) { log('Cleaning: ' + $.util.colors.green(path)); return del(path, done); }
javascript
function clean(path, done) { log('Cleaning: ' + $.util.colors.green(path)); return del(path, done); }
[ "function", "clean", "(", "path", ",", "done", ")", "{", "log", "(", "'Cleaning: '", "+", "$", ".", "util", ".", "colors", ".", "green", "(", "path", ")", ")", ";", "return", "del", "(", "path", ",", "done", ")", ";", "}" ]
Delete all files in a given path @param {Array} path - array of paths to delete @param {Function} done - callback when complete
[ "Delete", "all", "files", "in", "a", "given", "path" ]
dfff7d9a399f59ad0b8dd8a8309360d4930664a4
https://github.com/BioPhoton/angular1-star-rating/blob/dfff7d9a399f59ad0b8dd8a8309360d4930664a4/chore/gulp/helper.js#L117-L120
40,623
BioPhoton/angular1-star-rating
chore/gulp/helper.js
bytediffFormatter
function bytediffFormatter(data) { var difference = (data.savings > 0) ? ' smaller.' : ' larger.'; return data.fileName + ' went from ' + (data.startSize / 1000).toFixed(2) + ' kB to ' + (data.endSize / 1000).toFixed(2) + ' kB and is ' + formatPercent(1 - data.percent, 2) + '%' + difference; }
javascript
function bytediffFormatter(data) { var difference = (data.savings > 0) ? ' smaller.' : ' larger.'; return data.fileName + ' went from ' + (data.startSize / 1000).toFixed(2) + ' kB to ' + (data.endSize / 1000).toFixed(2) + ' kB and is ' + formatPercent(1 - data.percent, 2) + '%' + difference; }
[ "function", "bytediffFormatter", "(", "data", ")", "{", "var", "difference", "=", "(", "data", ".", "savings", ">", "0", ")", "?", "' smaller.'", ":", "' larger.'", ";", "return", "data", ".", "fileName", "+", "' went from '", "+", "(", "data", ".", "startSize", "/", "1000", ")", ".", "toFixed", "(", "2", ")", "+", "' kB to '", "+", "(", "data", ".", "endSize", "/", "1000", ")", ".", "toFixed", "(", "2", ")", "+", "' kB and is '", "+", "formatPercent", "(", "1", "-", "data", ".", "percent", ",", "2", ")", "+", "'%'", "+", "difference", ";", "}" ]
Formatter for bytediff to display the size changes after processing @param {Object} data - byte data @return {String} Difference in bytes, formatted
[ "Formatter", "for", "bytediff", "to", "display", "the", "size", "changes", "after", "processing" ]
dfff7d9a399f59ad0b8dd8a8309360d4930664a4
https://github.com/BioPhoton/angular1-star-rating/blob/dfff7d9a399f59ad0b8dd8a8309360d4930664a4/chore/gulp/helper.js#L144-L150
40,624
devanandb/webpack-mix
src/config.js
function() { let options = {}; tap(Mix.paths.root('.babelrc'), babelrc => { if (File.exists(babelrc)) { options = JSON.parse(File.find(babelrc).read()); } }); if (this.babelConfig) { options = webpackMerge.smart(options, this.babelConfig); } return webpackMerge.smart( { cacheDirectory: true, presets: [ [ 'env', { modules: false, targets: { browsers: ['> 2%'], uglify: true } } ] ], plugins: [ 'transform-object-rest-spread', [ 'transform-runtime', { polyfill: false, helpers: false } ] ] }, options ); }
javascript
function() { let options = {}; tap(Mix.paths.root('.babelrc'), babelrc => { if (File.exists(babelrc)) { options = JSON.parse(File.find(babelrc).read()); } }); if (this.babelConfig) { options = webpackMerge.smart(options, this.babelConfig); } return webpackMerge.smart( { cacheDirectory: true, presets: [ [ 'env', { modules: false, targets: { browsers: ['> 2%'], uglify: true } } ] ], plugins: [ 'transform-object-rest-spread', [ 'transform-runtime', { polyfill: false, helpers: false } ] ] }, options ); }
[ "function", "(", ")", "{", "let", "options", "=", "{", "}", ";", "tap", "(", "Mix", ".", "paths", ".", "root", "(", "'.babelrc'", ")", ",", "babelrc", "=>", "{", "if", "(", "File", ".", "exists", "(", "babelrc", ")", ")", "{", "options", "=", "JSON", ".", "parse", "(", "File", ".", "find", "(", "babelrc", ")", ".", "read", "(", ")", ")", ";", "}", "}", ")", ";", "if", "(", "this", ".", "babelConfig", ")", "{", "options", "=", "webpackMerge", ".", "smart", "(", "options", ",", "this", ".", "babelConfig", ")", ";", "}", "return", "webpackMerge", ".", "smart", "(", "{", "cacheDirectory", ":", "true", ",", "presets", ":", "[", "[", "'env'", ",", "{", "modules", ":", "false", ",", "targets", ":", "{", "browsers", ":", "[", "'> 2%'", "]", ",", "uglify", ":", "true", "}", "}", "]", "]", ",", "plugins", ":", "[", "'transform-object-rest-spread'", ",", "[", "'transform-runtime'", ",", "{", "polyfill", ":", "false", ",", "helpers", ":", "false", "}", "]", "]", "}", ",", "options", ")", ";", "}" ]
The default Babel configuration. @type {Object}
[ "The", "default", "Babel", "configuration", "." ]
0f61f71cf302acfcfb9f2e42004404f95eefbef4
https://github.com/devanandb/webpack-mix/blob/0f61f71cf302acfcfb9f2e42004404f95eefbef4/src/config.js#L139-L180
40,625
devanandb/webpack-mix
src/webpackPlugins/MixDefinitionsPlugin.js
MixDefinitionsPlugin
function MixDefinitionsPlugin(envPath) { expand( dotenv.config({ path: envPath || Mix.paths.root('.env') }) ); }
javascript
function MixDefinitionsPlugin(envPath) { expand( dotenv.config({ path: envPath || Mix.paths.root('.env') }) ); }
[ "function", "MixDefinitionsPlugin", "(", "envPath", ")", "{", "expand", "(", "dotenv", ".", "config", "(", "{", "path", ":", "envPath", "||", "Mix", ".", "paths", ".", "root", "(", "'.env'", ")", "}", ")", ")", ";", "}" ]
Create a new plugin instance. @param {string} envPath
[ "Create", "a", "new", "plugin", "instance", "." ]
0f61f71cf302acfcfb9f2e42004404f95eefbef4
https://github.com/devanandb/webpack-mix/blob/0f61f71cf302acfcfb9f2e42004404f95eefbef4/src/webpackPlugins/MixDefinitionsPlugin.js#L10-L16
40,626
ghybs/leaflet-defaulticon-compatibility
src/Icon.Default.compatibility.js
function (name) { // @option imagePath: String // `Icon.Default` will try to auto-detect the location of // the blue icon images. If you are placing these images in a // non-standard way, set this option to point to the right // path, before any marker is added to a map. // Caution: do not use this option with inline base64 image(s). var imagePath = this.options.imagePath || L.Icon.Default.imagePath || ''; // Deprecated (IconDefault.imagePath), backwards-compatibility only if (this._needsInit) { // Modifying imagePath option after _getIconUrl has been called // once in this instance of IconDefault will no longer have any // effect. this._initializeOptions(imagePath); } return imagePath + L.Icon.prototype._getIconUrl.call(this, name); }
javascript
function (name) { // @option imagePath: String // `Icon.Default` will try to auto-detect the location of // the blue icon images. If you are placing these images in a // non-standard way, set this option to point to the right // path, before any marker is added to a map. // Caution: do not use this option with inline base64 image(s). var imagePath = this.options.imagePath || L.Icon.Default.imagePath || ''; // Deprecated (IconDefault.imagePath), backwards-compatibility only if (this._needsInit) { // Modifying imagePath option after _getIconUrl has been called // once in this instance of IconDefault will no longer have any // effect. this._initializeOptions(imagePath); } return imagePath + L.Icon.prototype._getIconUrl.call(this, name); }
[ "function", "(", "name", ")", "{", "// @option imagePath: String", "// `Icon.Default` will try to auto-detect the location of", "// the blue icon images. If you are placing these images in a", "// non-standard way, set this option to point to the right", "// path, before any marker is added to a map.", "// Caution: do not use this option with inline base64 image(s).", "var", "imagePath", "=", "this", ".", "options", ".", "imagePath", "||", "L", ".", "Icon", ".", "Default", ".", "imagePath", "||", "''", ";", "// Deprecated (IconDefault.imagePath), backwards-compatibility only", "if", "(", "this", ".", "_needsInit", ")", "{", "// Modifying imagePath option after _getIconUrl has been called", "// once in this instance of IconDefault will no longer have any", "// effect.", "this", ".", "_initializeOptions", "(", "imagePath", ")", ";", "}", "return", "imagePath", "+", "L", ".", "Icon", ".", "prototype", ".", "_getIconUrl", ".", "call", "(", "this", ",", "name", ")", ";", "}" ]
Override to make sure options are retrieved from CSS.
[ "Override", "to", "make", "sure", "options", "are", "retrieved", "from", "CSS", "." ]
23ebe7654149e1b41c9904a62a6a93822896852e
https://github.com/ghybs/leaflet-defaulticon-compatibility/blob/23ebe7654149e1b41c9904a62a6a93822896852e/src/Icon.Default.compatibility.js#L28-L46
40,627
ghybs/leaflet-defaulticon-compatibility
src/Icon.Default.compatibility.js
function (imagePath) { this._setOptions('icon', _detectIconOptions, imagePath); this._setOptions('shadow', _detectIconOptions, imagePath); this._setOptions('popup', _detectDivOverlayOptions); this._setOptions('tooltip', _detectDivOverlayOptions); this._needsInit = false; }
javascript
function (imagePath) { this._setOptions('icon', _detectIconOptions, imagePath); this._setOptions('shadow', _detectIconOptions, imagePath); this._setOptions('popup', _detectDivOverlayOptions); this._setOptions('tooltip', _detectDivOverlayOptions); this._needsInit = false; }
[ "function", "(", "imagePath", ")", "{", "this", ".", "_setOptions", "(", "'icon'", ",", "_detectIconOptions", ",", "imagePath", ")", ";", "this", ".", "_setOptions", "(", "'shadow'", ",", "_detectIconOptions", ",", "imagePath", ")", ";", "this", ".", "_setOptions", "(", "'popup'", ",", "_detectDivOverlayOptions", ")", ";", "this", ".", "_setOptions", "(", "'tooltip'", ",", "_detectDivOverlayOptions", ")", ";", "this", ".", "_needsInit", "=", "false", ";", "}" ]
Initialize all necessary options for this instance.
[ "Initialize", "all", "necessary", "options", "for", "this", "instance", "." ]
23ebe7654149e1b41c9904a62a6a93822896852e
https://github.com/ghybs/leaflet-defaulticon-compatibility/blob/23ebe7654149e1b41c9904a62a6a93822896852e/src/Icon.Default.compatibility.js#L49-L55
40,628
ghybs/leaflet-defaulticon-compatibility
src/Icon.Default.compatibility.js
function (name, detectorFn, imagePath) { var options = this.options, prefix = options.classNamePrefix, optionValues = detectorFn(prefix + name, imagePath); for (var optionName in optionValues) { options[name + optionName] = options[name + optionName] || optionValues[optionName]; } }
javascript
function (name, detectorFn, imagePath) { var options = this.options, prefix = options.classNamePrefix, optionValues = detectorFn(prefix + name, imagePath); for (var optionName in optionValues) { options[name + optionName] = options[name + optionName] || optionValues[optionName]; } }
[ "function", "(", "name", ",", "detectorFn", ",", "imagePath", ")", "{", "var", "options", "=", "this", ".", "options", ",", "prefix", "=", "options", ".", "classNamePrefix", ",", "optionValues", "=", "detectorFn", "(", "prefix", "+", "name", ",", "imagePath", ")", ";", "for", "(", "var", "optionName", "in", "optionValues", ")", "{", "options", "[", "name", "+", "optionName", "]", "=", "options", "[", "name", "+", "optionName", "]", "||", "optionValues", "[", "optionName", "]", ";", "}", "}" ]
Retrieve values from CSS and assign to this instance options.
[ "Retrieve", "values", "from", "CSS", "and", "assign", "to", "this", "instance", "options", "." ]
23ebe7654149e1b41c9904a62a6a93822896852e
https://github.com/ghybs/leaflet-defaulticon-compatibility/blob/23ebe7654149e1b41c9904a62a6a93822896852e/src/Icon.Default.compatibility.js#L58-L66
40,629
ghybs/leaflet-defaulticon-compatibility
src/Icon.Default.compatibility.js
_getStyle
function _getStyle(el, style) { return L.DomUtil.getStyle(el, style) || L.DomUtil.getStyle(el, _kebabToCamelCase(style)); }
javascript
function _getStyle(el, style) { return L.DomUtil.getStyle(el, style) || L.DomUtil.getStyle(el, _kebabToCamelCase(style)); }
[ "function", "_getStyle", "(", "el", ",", "style", ")", "{", "return", "L", ".", "DomUtil", ".", "getStyle", "(", "el", ",", "style", ")", "||", "L", ".", "DomUtil", ".", "getStyle", "(", "el", ",", "_kebabToCamelCase", "(", "style", ")", ")", ";", "}" ]
Factorize style reading fallback for IE8.
[ "Factorize", "style", "reading", "fallback", "for", "IE8", "." ]
23ebe7654149e1b41c9904a62a6a93822896852e
https://github.com/ghybs/leaflet-defaulticon-compatibility/blob/23ebe7654149e1b41c9904a62a6a93822896852e/src/Icon.Default.compatibility.js#L134-L136
40,630
gocanto/lazy-vue
src/js/image.js
fadeIn
function fadeIn(el) { el.style.opacity = 0; el.style.display = "block"; (function fadeIn() { let val = parseFloat(el.style.opacity); if (! ((val += .1) > 1)) { el.style.opacity = val; setTimeout(fadeIn, 40); } })(); }
javascript
function fadeIn(el) { el.style.opacity = 0; el.style.display = "block"; (function fadeIn() { let val = parseFloat(el.style.opacity); if (! ((val += .1) > 1)) { el.style.opacity = val; setTimeout(fadeIn, 40); } })(); }
[ "function", "fadeIn", "(", "el", ")", "{", "el", ".", "style", ".", "opacity", "=", "0", ";", "el", ".", "style", ".", "display", "=", "\"block\"", ";", "(", "function", "fadeIn", "(", ")", "{", "let", "val", "=", "parseFloat", "(", "el", ".", "style", ".", "opacity", ")", ";", "if", "(", "!", "(", "(", "val", "+=", ".1", ")", ">", "1", ")", ")", "{", "el", ".", "style", ".", "opacity", "=", "val", ";", "setTimeout", "(", "fadeIn", ",", "40", ")", ";", "}", "}", ")", "(", ")", ";", "}" ]
Apply a fade in effect to a given element. @param {Object} el @return {Void}
[ "Apply", "a", "fade", "in", "effect", "to", "a", "given", "element", "." ]
c2113455c6a662ad627f52357958b1a0997ddcb3
https://github.com/gocanto/lazy-vue/blob/c2113455c6a662ad627f52357958b1a0997ddcb3/src/js/image.js#L27-L39
40,631
linkedin/Fiber
src/fiber.js
copy
function copy(from, to) { var name; for (name in from) { if (from.hasOwnProperty(name)) { to[name] = from[name]; } } }
javascript
function copy(from, to) { var name; for (name in from) { if (from.hasOwnProperty(name)) { to[name] = from[name]; } } }
[ "function", "copy", "(", "from", ",", "to", ")", "{", "var", "name", ";", "for", "(", "name", "in", "from", ")", "{", "if", "(", "from", ".", "hasOwnProperty", "(", "name", ")", ")", "{", "to", "[", "name", "]", "=", "from", "[", "name", "]", ";", "}", "}", "}" ]
Helper function to copy properties from one object to the other.
[ "Helper", "function", "to", "copy", "properties", "from", "one", "object", "to", "the", "other", "." ]
e930b220a95246357b4929b37a6a5e9e6679843f
https://github.com/linkedin/Fiber/blob/e930b220a95246357b4929b37a6a5e9e6679843f/src/fiber.js#L54-L61
40,632
Foxandxss/koa-unless
index.js
matchesCustom
function matchesCustom(ctx, opts) { if (opts.custom) { return opts.custom.call(ctx); } return false; }
javascript
function matchesCustom(ctx, opts) { if (opts.custom) { return opts.custom.call(ctx); } return false; }
[ "function", "matchesCustom", "(", "ctx", ",", "opts", ")", "{", "if", "(", "opts", ".", "custom", ")", "{", "return", "opts", ".", "custom", ".", "call", "(", "ctx", ")", ";", "}", "return", "false", ";", "}" ]
Returns boolean indicating whether the custom function returns true. @param ctx - Koa context @param opts - unless configuration @returns {boolean}
[ "Returns", "boolean", "indicating", "whether", "the", "custom", "function", "returns", "true", "." ]
d692252c06b5f2572fe70187722b9be0dba2014f
https://github.com/Foxandxss/koa-unless/blob/d692252c06b5f2572fe70187722b9be0dba2014f/index.js#L38-L43
40,633
Foxandxss/koa-unless
index.js
matchesPath
function matchesPath(requestedUrl, opts) { var paths = !opts.path || Array.isArray(opts.path) ? opts.path : [opts.path]; if (paths) { return paths.some(function(p) { return (typeof p === 'string' && p === requestedUrl.pathname) || (p instanceof RegExp && !! p.exec(requestedUrl.pathname)); }); } return false; }
javascript
function matchesPath(requestedUrl, opts) { var paths = !opts.path || Array.isArray(opts.path) ? opts.path : [opts.path]; if (paths) { return paths.some(function(p) { return (typeof p === 'string' && p === requestedUrl.pathname) || (p instanceof RegExp && !! p.exec(requestedUrl.pathname)); }); } return false; }
[ "function", "matchesPath", "(", "requestedUrl", ",", "opts", ")", "{", "var", "paths", "=", "!", "opts", ".", "path", "||", "Array", ".", "isArray", "(", "opts", ".", "path", ")", "?", "opts", ".", "path", ":", "[", "opts", ".", "path", "]", ";", "if", "(", "paths", ")", "{", "return", "paths", ".", "some", "(", "function", "(", "p", ")", "{", "return", "(", "typeof", "p", "===", "'string'", "&&", "p", "===", "requestedUrl", ".", "pathname", ")", "||", "(", "p", "instanceof", "RegExp", "&&", "!", "!", "p", ".", "exec", "(", "requestedUrl", ".", "pathname", ")", ")", ";", "}", ")", ";", "}", "return", "false", ";", "}" ]
Returns boolean indicating whether the requestUrl matches against the paths configured. @param requestedUrl - url requested by user @param opts - unless configuration @returns {boolean}
[ "Returns", "boolean", "indicating", "whether", "the", "requestUrl", "matches", "against", "the", "paths", "configured", "." ]
d692252c06b5f2572fe70187722b9be0dba2014f
https://github.com/Foxandxss/koa-unless/blob/d692252c06b5f2572fe70187722b9be0dba2014f/index.js#L52-L64
40,634
Foxandxss/koa-unless
index.js
matchesExtension
function matchesExtension(requestedUrl, opts) { var exts = !opts.ext || Array.isArray(opts.ext) ? opts.ext : [opts.ext]; if (exts) { return exts.some(function(ext) { return requestedUrl.pathname.substr(ext.length * -1) === ext; }); } }
javascript
function matchesExtension(requestedUrl, opts) { var exts = !opts.ext || Array.isArray(opts.ext) ? opts.ext : [opts.ext]; if (exts) { return exts.some(function(ext) { return requestedUrl.pathname.substr(ext.length * -1) === ext; }); } }
[ "function", "matchesExtension", "(", "requestedUrl", ",", "opts", ")", "{", "var", "exts", "=", "!", "opts", ".", "ext", "||", "Array", ".", "isArray", "(", "opts", ".", "ext", ")", "?", "opts", ".", "ext", ":", "[", "opts", ".", "ext", "]", ";", "if", "(", "exts", ")", "{", "return", "exts", ".", "some", "(", "function", "(", "ext", ")", "{", "return", "requestedUrl", ".", "pathname", ".", "substr", "(", "ext", ".", "length", "*", "-", "1", ")", "===", "ext", ";", "}", ")", ";", "}", "}" ]
Returns boolean indicating whether the requestUrl ends with the configured extensions. @param requestedUrl - url requested by user @param opts - unless configuration @returns {boolean}
[ "Returns", "boolean", "indicating", "whether", "the", "requestUrl", "ends", "with", "the", "configured", "extensions", "." ]
d692252c06b5f2572fe70187722b9be0dba2014f
https://github.com/Foxandxss/koa-unless/blob/d692252c06b5f2572fe70187722b9be0dba2014f/index.js#L73-L82
40,635
Foxandxss/koa-unless
index.js
matchesMethod
function matchesMethod(method, opts) { var methods = !opts.method || Array.isArray(opts.method) ? opts.method : [opts.method]; if (methods) { return !!~methods.indexOf(method); } }
javascript
function matchesMethod(method, opts) { var methods = !opts.method || Array.isArray(opts.method) ? opts.method : [opts.method]; if (methods) { return !!~methods.indexOf(method); } }
[ "function", "matchesMethod", "(", "method", ",", "opts", ")", "{", "var", "methods", "=", "!", "opts", ".", "method", "||", "Array", ".", "isArray", "(", "opts", ".", "method", ")", "?", "opts", ".", "method", ":", "[", "opts", ".", "method", "]", ";", "if", "(", "methods", ")", "{", "return", "!", "!", "~", "methods", ".", "indexOf", "(", "method", ")", ";", "}", "}" ]
Returns boolean indicating whether the request method matches the configured methods. @param requestedUrl - url requested by user @param opts - unless configuration @returns {boolean}
[ "Returns", "boolean", "indicating", "whether", "the", "request", "method", "matches", "the", "configured", "methods", "." ]
d692252c06b5f2572fe70187722b9be0dba2014f
https://github.com/Foxandxss/koa-unless/blob/d692252c06b5f2572fe70187722b9be0dba2014f/index.js#L91-L98
40,636
Skellington-Closet/slack-mock
examples/slack-app/controller.js
startRtm
function startRtm (token) { api.rtm.start(token, (err, bot) => { if (err) { return console.log(err) } bot.on(/hello/, (bot, message) => { bot.reply(message, 'GO CUBS') }) bot.on(/howdy/, (bot, message) => { bot.reply(message, 'GO TRIBE') }) }) }
javascript
function startRtm (token) { api.rtm.start(token, (err, bot) => { if (err) { return console.log(err) } bot.on(/hello/, (bot, message) => { bot.reply(message, 'GO CUBS') }) bot.on(/howdy/, (bot, message) => { bot.reply(message, 'GO TRIBE') }) }) }
[ "function", "startRtm", "(", "token", ")", "{", "api", ".", "rtm", ".", "start", "(", "token", ",", "(", "err", ",", "bot", ")", "=>", "{", "if", "(", "err", ")", "{", "return", "console", ".", "log", "(", "err", ")", "}", "bot", ".", "on", "(", "/", "hello", "/", ",", "(", "bot", ",", "message", ")", "=>", "{", "bot", ".", "reply", "(", "message", ",", "'GO CUBS'", ")", "}", ")", "bot", ".", "on", "(", "/", "howdy", "/", ",", "(", "bot", ",", "message", ")", "=>", "{", "bot", ".", "reply", "(", "message", ",", "'GO TRIBE'", ")", "}", ")", "}", ")", "}" ]
starts the rtm connection
[ "starts", "the", "rtm", "connection" ]
7bf3eb5073a8a2c071ece360a7b8729390a37024
https://github.com/Skellington-Closet/slack-mock/blob/7bf3eb5073a8a2c071ece360a7b8729390a37024/examples/slack-app/controller.js#L64-L78
40,637
Skellington-Closet/slack-mock
src/mocker/rtm.js
sendToClient
function sendToClient (message, client) { return new Promise((resolve, reject) => { try { client.send(JSON.stringify(message), (e) => { if (e) { logger.error(`could not send rtm message to client`, e) return reject(e) } }) } catch (e) { logger.error(`could not send rtm message to client`, e) return reject(e) } resolve() }) }
javascript
function sendToClient (message, client) { return new Promise((resolve, reject) => { try { client.send(JSON.stringify(message), (e) => { if (e) { logger.error(`could not send rtm message to client`, e) return reject(e) } }) } catch (e) { logger.error(`could not send rtm message to client`, e) return reject(e) } resolve() }) }
[ "function", "sendToClient", "(", "message", ",", "client", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "try", "{", "client", ".", "send", "(", "JSON", ".", "stringify", "(", "message", ")", ",", "(", "e", ")", "=>", "{", "if", "(", "e", ")", "{", "logger", ".", "error", "(", "`", "`", ",", "e", ")", "return", "reject", "(", "e", ")", "}", "}", ")", "}", "catch", "(", "e", ")", "{", "logger", ".", "error", "(", "`", "`", ",", "e", ")", "return", "reject", "(", "e", ")", "}", "resolve", "(", ")", "}", ")", "}" ]
sends the given message to the given client
[ "sends", "the", "given", "message", "to", "the", "given", "client" ]
7bf3eb5073a8a2c071ece360a7b8729390a37024
https://github.com/Skellington-Closet/slack-mock/blob/7bf3eb5073a8a2c071ece360a7b8729390a37024/src/mocker/rtm.js#L66-L82
40,638
CSS-Tricks/AnythingZoomer
demo/page.js
scrollableElement
function scrollableElement(els) { for (var i = 0, argLength = arguments.length; i <argLength; i++) { var el = arguments[i], $scrollElement = $(el); if ($scrollElement.scrollTop()> 0) { return el; } else { $scrollElement.scrollTop(1); var isScrollable = $scrollElement.scrollTop()> 0; $scrollElement.scrollTop(0); if (isScrollable) { return el; } } } return []; }
javascript
function scrollableElement(els) { for (var i = 0, argLength = arguments.length; i <argLength; i++) { var el = arguments[i], $scrollElement = $(el); if ($scrollElement.scrollTop()> 0) { return el; } else { $scrollElement.scrollTop(1); var isScrollable = $scrollElement.scrollTop()> 0; $scrollElement.scrollTop(0); if (isScrollable) { return el; } } } return []; }
[ "function", "scrollableElement", "(", "els", ")", "{", "for", "(", "var", "i", "=", "0", ",", "argLength", "=", "arguments", ".", "length", ";", "i", "<", "argLength", ";", "i", "++", ")", "{", "var", "el", "=", "arguments", "[", "i", "]", ",", "$scrollElement", "=", "$", "(", "el", ")", ";", "if", "(", "$scrollElement", ".", "scrollTop", "(", ")", ">", "0", ")", "{", "return", "el", ";", "}", "else", "{", "$scrollElement", ".", "scrollTop", "(", "1", ")", ";", "var", "isScrollable", "=", "$scrollElement", ".", "scrollTop", "(", ")", ">", "0", ";", "$scrollElement", ".", "scrollTop", "(", "0", ")", ";", "if", "(", "isScrollable", ")", "{", "return", "el", ";", "}", "}", "}", "return", "[", "]", ";", "}" ]
use the first element that is "scrollable"
[ "use", "the", "first", "element", "that", "is", "scrollable" ]
5028f2ed79d5af7c4d66c0c63ef8325a6ba049c1
https://github.com/CSS-Tricks/AnythingZoomer/blob/5028f2ed79d5af7c4d66c0c63ef8325a6ba049c1/demo/page.js#L43-L59
40,639
arthurvaverko/ngx-highlight
dist/vendor.bundle.js
instantiationError
function instantiationError(injector, originalException, originalStack, key) { return injectionError(injector, key, function () { var /** @type {?} */ first = stringify(this.keys[0].token); return getOriginalError(this).message + ": Error during instantiation of " + first + "!" + constructResolvingPath(this.keys) + "."; }, originalException); }
javascript
function instantiationError(injector, originalException, originalStack, key) { return injectionError(injector, key, function () { var /** @type {?} */ first = stringify(this.keys[0].token); return getOriginalError(this).message + ": Error during instantiation of " + first + "!" + constructResolvingPath(this.keys) + "."; }, originalException); }
[ "function", "instantiationError", "(", "injector", ",", "originalException", ",", "originalStack", ",", "key", ")", "{", "return", "injectionError", "(", "injector", ",", "key", ",", "function", "(", ")", "{", "var", "/** @type {?} */", "first", "=", "stringify", "(", "this", ".", "keys", "[", "0", "]", ".", "token", ")", ";", "return", "getOriginalError", "(", "this", ")", ".", "message", "+", "\": Error during instantiation of \"", "+", "first", "+", "\"!\"", "+", "constructResolvingPath", "(", "this", ".", "keys", ")", "+", "\".\"", ";", "}", ",", "originalException", ")", ";", "}" ]
Thrown when a constructing type returns with an Error. The `InstantiationError` class contains the original error plus the dependency graph which caused this object to be instantiated. ### Example ([live demo](http://plnkr.co/edit/7aWYdcqTQsP0eNqEdUAf?p=preview)) ```typescript class A { constructor() { throw new Error('message'); } } var injector = Injector.resolveAndCreate([A]); try { injector.get(A); } catch (e) { expect(e instanceof InstantiationError).toBe(true); expect(e.originalException.message).toEqual("message"); expect(e.originalStack).toBeDefined(); } ``` @param {?} injector @param {?} originalException @param {?} originalStack @param {?} key @return {?}
[ "Thrown", "when", "a", "constructing", "type", "returns", "with", "an", "Error", "." ]
4e98e58e0d718a093cfe4d31ac03a21b3d1e1405
https://github.com/arthurvaverko/ngx-highlight/blob/4e98e58e0d718a093cfe4d31ac03a21b3d1e1405/dist/vendor.bundle.js#L1541-L1546
40,640
arthurvaverko/ngx-highlight
dist/vendor.bundle.js
templateVisitAll
function templateVisitAll(visitor, asts, context) { if (context === void 0) { context = null; } var /** @type {?} */ result = []; var /** @type {?} */ visit = visitor.visit ? function (ast) { return visitor.visit(ast, context) || ast.visit(visitor, context); } : function (ast) { return ast.visit(visitor, context); }; asts.forEach(function (ast) { var /** @type {?} */ astResult = visit(ast); if (astResult) { result.push(astResult); } }); return result; }
javascript
function templateVisitAll(visitor, asts, context) { if (context === void 0) { context = null; } var /** @type {?} */ result = []; var /** @type {?} */ visit = visitor.visit ? function (ast) { return visitor.visit(ast, context) || ast.visit(visitor, context); } : function (ast) { return ast.visit(visitor, context); }; asts.forEach(function (ast) { var /** @type {?} */ astResult = visit(ast); if (astResult) { result.push(astResult); } }); return result; }
[ "function", "templateVisitAll", "(", "visitor", ",", "asts", ",", "context", ")", "{", "if", "(", "context", "===", "void", "0", ")", "{", "context", "=", "null", ";", "}", "var", "/** @type {?} */", "result", "=", "[", "]", ";", "var", "/** @type {?} */", "visit", "=", "visitor", ".", "visit", "?", "function", "(", "ast", ")", "{", "return", "visitor", ".", "visit", "(", "ast", ",", "context", ")", "||", "ast", ".", "visit", "(", "visitor", ",", "context", ")", ";", "}", ":", "function", "(", "ast", ")", "{", "return", "ast", ".", "visit", "(", "visitor", ",", "context", ")", ";", "}", ";", "asts", ".", "forEach", "(", "function", "(", "ast", ")", "{", "var", "/** @type {?} */", "astResult", "=", "visit", "(", "ast", ")", ";", "if", "(", "astResult", ")", "{", "result", ".", "push", "(", "astResult", ")", ";", "}", "}", ")", ";", "return", "result", ";", "}" ]
Visit every node in a list of {\@link TemplateAst}s with the given {\@link TemplateAstVisitor}. @param {?} visitor @param {?} asts @param {?=} context @return {?}
[ "Visit", "every", "node", "in", "a", "list", "of", "{", "\\" ]
4e98e58e0d718a093cfe4d31ac03a21b3d1e1405
https://github.com/arthurvaverko/ngx-highlight/blob/4e98e58e0d718a093cfe4d31ac03a21b3d1e1405/dist/vendor.bundle.js#L24668-L24681
40,641
seeden/mongoose-hrbac
src/index.js
can
function can(rbac, action, resource, cb) { // check existance of permission rbac.getPermission(action, resource, (err, permission) => { if (err) { return cb(err); } if (!permission) { return cb(null, false); } // check user additional permissions if (indexOf(this.permissions, permission.name) !== -1) { return cb(null, true); } if (!this.role) { return cb(null, false); } // check permission inside user role return rbac.can(this.role, action, resource, cb); }); return this; }
javascript
function can(rbac, action, resource, cb) { // check existance of permission rbac.getPermission(action, resource, (err, permission) => { if (err) { return cb(err); } if (!permission) { return cb(null, false); } // check user additional permissions if (indexOf(this.permissions, permission.name) !== -1) { return cb(null, true); } if (!this.role) { return cb(null, false); } // check permission inside user role return rbac.can(this.role, action, resource, cb); }); return this; }
[ "function", "can", "(", "rbac", ",", "action", ",", "resource", ",", "cb", ")", "{", "// check existance of permission", "rbac", ".", "getPermission", "(", "action", ",", "resource", ",", "(", "err", ",", "permission", ")", "=>", "{", "if", "(", "err", ")", "{", "return", "cb", "(", "err", ")", ";", "}", "if", "(", "!", "permission", ")", "{", "return", "cb", "(", "null", ",", "false", ")", ";", "}", "// check user additional permissions", "if", "(", "indexOf", "(", "this", ".", "permissions", ",", "permission", ".", "name", ")", "!==", "-", "1", ")", "{", "return", "cb", "(", "null", ",", "true", ")", ";", "}", "if", "(", "!", "this", ".", "role", ")", "{", "return", "cb", "(", "null", ",", "false", ")", ";", "}", "// check permission inside user role", "return", "rbac", ".", "can", "(", "this", ".", "role", ",", "action", ",", "resource", ",", "cb", ")", ";", "}", ")", ";", "return", "this", ";", "}" ]
Check if user has assigned a specific permission @param {RBAC} rbac Instance of RBAC @param {String} action Name of action @param {String} resource Name of resource @return {Boolean}
[ "Check", "if", "user", "has", "assigned", "a", "specific", "permission" ]
4239f40635d3fead299b8721acfdb7145bc2f9e2
https://github.com/seeden/mongoose-hrbac/blob/4239f40635d3fead299b8721acfdb7145bc2f9e2/src/index.js#L27-L52
40,642
seeden/mongoose-hrbac
src/index.js
addPermission
function addPermission(rbac, action, resource, cb) { rbac.getPermission(action, resource, (err, permission) => { if (err) { return cb(err); } if (!permission) { return cb(new Error('Permission not exists')); } if (indexOf(this.permissions, permission.name) !== -1) { return cb(new Error('Permission is already assigned')); } this.permissions.push(permission.name); return this.save((err2, user) => { if (err2) { return cb(err2); } if (!user) { return cb(new Error('User is undefined')); } return cb(null, true); }); }); return this; }
javascript
function addPermission(rbac, action, resource, cb) { rbac.getPermission(action, resource, (err, permission) => { if (err) { return cb(err); } if (!permission) { return cb(new Error('Permission not exists')); } if (indexOf(this.permissions, permission.name) !== -1) { return cb(new Error('Permission is already assigned')); } this.permissions.push(permission.name); return this.save((err2, user) => { if (err2) { return cb(err2); } if (!user) { return cb(new Error('User is undefined')); } return cb(null, true); }); }); return this; }
[ "function", "addPermission", "(", "rbac", ",", "action", ",", "resource", ",", "cb", ")", "{", "rbac", ".", "getPermission", "(", "action", ",", "resource", ",", "(", "err", ",", "permission", ")", "=>", "{", "if", "(", "err", ")", "{", "return", "cb", "(", "err", ")", ";", "}", "if", "(", "!", "permission", ")", "{", "return", "cb", "(", "new", "Error", "(", "'Permission not exists'", ")", ")", ";", "}", "if", "(", "indexOf", "(", "this", ".", "permissions", ",", "permission", ".", "name", ")", "!==", "-", "1", ")", "{", "return", "cb", "(", "new", "Error", "(", "'Permission is already assigned'", ")", ")", ";", "}", "this", ".", "permissions", ".", "push", "(", "permission", ".", "name", ")", ";", "return", "this", ".", "save", "(", "(", "err2", ",", "user", ")", "=>", "{", "if", "(", "err2", ")", "{", "return", "cb", "(", "err2", ")", ";", "}", "if", "(", "!", "user", ")", "{", "return", "cb", "(", "new", "Error", "(", "'User is undefined'", ")", ")", ";", "}", "return", "cb", "(", "null", ",", "true", ")", ";", "}", ")", ";", "}", ")", ";", "return", "this", ";", "}" ]
Assign additional permissions to the user @param {String|Array} permissions Array of permissions or string representing of permission @param {Function} cb Callback
[ "Assign", "additional", "permissions", "to", "the", "user" ]
4239f40635d3fead299b8721acfdb7145bc2f9e2
https://github.com/seeden/mongoose-hrbac/blob/4239f40635d3fead299b8721acfdb7145bc2f9e2/src/index.js#L59-L88
40,643
seeden/mongoose-hrbac
src/index.js
hasRole
function hasRole(rbac, role, cb) { if (!this.role) { cb(null, false); return this; } // check existance of permission rbac.hasRole(this.role, role, cb); return this; }
javascript
function hasRole(rbac, role, cb) { if (!this.role) { cb(null, false); return this; } // check existance of permission rbac.hasRole(this.role, role, cb); return this; }
[ "function", "hasRole", "(", "rbac", ",", "role", ",", "cb", ")", "{", "if", "(", "!", "this", ".", "role", ")", "{", "cb", "(", "null", ",", "false", ")", ";", "return", "this", ";", "}", "// check existance of permission", "rbac", ".", "hasRole", "(", "this", ".", "role", ",", "role", ",", "cb", ")", ";", "return", "this", ";", "}" ]
Check if user has assigned a specific role @param {RBAC} rbac Instance of RBAC @param {String} name Name of role @return {Boolean} [description]
[ "Check", "if", "user", "has", "assigned", "a", "specific", "role" ]
4239f40635d3fead299b8721acfdb7145bc2f9e2
https://github.com/seeden/mongoose-hrbac/blob/4239f40635d3fead299b8721acfdb7145bc2f9e2/src/index.js#L142-L151
40,644
liorwohl/html5-simple-date-input-polyfill
html5-simple-date-input-polyfill.js
addcalendarExtenderToDateInputs
function addcalendarExtenderToDateInputs () { //get and loop all the input[type=date]s in the page that dont have "haveCal" class yet var dateInputs = document.querySelectorAll('input[type=date]:not(.haveCal)'); [].forEach.call(dateInputs, function (dateInput) { //call calendarExtender function on the input new calendarExtender(dateInput); //mark that it have calendar dateInput.classList.add('haveCal'); }); }
javascript
function addcalendarExtenderToDateInputs () { //get and loop all the input[type=date]s in the page that dont have "haveCal" class yet var dateInputs = document.querySelectorAll('input[type=date]:not(.haveCal)'); [].forEach.call(dateInputs, function (dateInput) { //call calendarExtender function on the input new calendarExtender(dateInput); //mark that it have calendar dateInput.classList.add('haveCal'); }); }
[ "function", "addcalendarExtenderToDateInputs", "(", ")", "{", "//get and loop all the input[type=date]s in the page that dont have \"haveCal\" class yet", "var", "dateInputs", "=", "document", ".", "querySelectorAll", "(", "'input[type=date]:not(.haveCal)'", ")", ";", "[", "]", ".", "forEach", ".", "call", "(", "dateInputs", ",", "function", "(", "dateInput", ")", "{", "//call calendarExtender function on the input", "new", "calendarExtender", "(", "dateInput", ")", ";", "//mark that it have calendar", "dateInput", ".", "classList", ".", "add", "(", "'haveCal'", ")", ";", "}", ")", ";", "}" ]
will add the calendarExtender to all inputs in the page
[ "will", "add", "the", "calendarExtender", "to", "all", "inputs", "in", "the", "page" ]
8882f82c9eb1ef3bff1fdc41a7fb3bb4730c0abe
https://github.com/liorwohl/html5-simple-date-input-polyfill/blob/8882f82c9eb1ef3bff1fdc41a7fb3bb4730c0abe/html5-simple-date-input-polyfill.js#L222-L231
40,645
SamVerschueren/mongoose-seeder
index.js
function(data, done) { try { // Retrieve all the dependencies _.forEach(data._dependencies || {}, function(value, key) { if(this.sandbox[key] !== undefined) { // Do nothing if the dependency is already defined return; } this.sandbox[key] = module.parent.require(value); }.bind(this)); // Remove the dependencies property delete data._dependencies; } catch(e) { // Stop execution and return the MODULE_NOT_FOUND error return done(e); } // Iterate over all the data objects async.eachSeries(Object.keys(data), function(key, next) { _this.result[key] = {}; var value = data[key]; try { if(!value._model) { // Throw an error if the model could not be found throw new Error('Please provide a _model property that describes which database model should be used.'); } var modelName = value._model; // Remove model and unique properties delete value._model; // retrieve the model depending on the name provided var Model = mongoose.model(modelName); async.series([ function(callback) { if(_this.options.dropCollections === true) { // Drop the collection mongoose.connection.db.dropCollection(Model.collection.name, function(err) { callback(); }); } else { callback(); } }, function(callback) { async.eachSeries(Object.keys(value), function(k, innerNext) { var modelData = value[k], data = _this._unwind(modelData); // Create the model Model.create(data, function(err, result) { if(err) { // Do not stop execution if an error occurs return innerNext(err); } _this.result[key][k] = result; innerNext(); }); }, callback); } ], next); } catch(err) { // If the model does not exist, stop the execution return next(err); } }, function(err) { if(err) { // Make sure to not return the result return done(err); } done(undefined, _this.result); }); }
javascript
function(data, done) { try { // Retrieve all the dependencies _.forEach(data._dependencies || {}, function(value, key) { if(this.sandbox[key] !== undefined) { // Do nothing if the dependency is already defined return; } this.sandbox[key] = module.parent.require(value); }.bind(this)); // Remove the dependencies property delete data._dependencies; } catch(e) { // Stop execution and return the MODULE_NOT_FOUND error return done(e); } // Iterate over all the data objects async.eachSeries(Object.keys(data), function(key, next) { _this.result[key] = {}; var value = data[key]; try { if(!value._model) { // Throw an error if the model could not be found throw new Error('Please provide a _model property that describes which database model should be used.'); } var modelName = value._model; // Remove model and unique properties delete value._model; // retrieve the model depending on the name provided var Model = mongoose.model(modelName); async.series([ function(callback) { if(_this.options.dropCollections === true) { // Drop the collection mongoose.connection.db.dropCollection(Model.collection.name, function(err) { callback(); }); } else { callback(); } }, function(callback) { async.eachSeries(Object.keys(value), function(k, innerNext) { var modelData = value[k], data = _this._unwind(modelData); // Create the model Model.create(data, function(err, result) { if(err) { // Do not stop execution if an error occurs return innerNext(err); } _this.result[key][k] = result; innerNext(); }); }, callback); } ], next); } catch(err) { // If the model does not exist, stop the execution return next(err); } }, function(err) { if(err) { // Make sure to not return the result return done(err); } done(undefined, _this.result); }); }
[ "function", "(", "data", ",", "done", ")", "{", "try", "{", "// Retrieve all the dependencies", "_", ".", "forEach", "(", "data", ".", "_dependencies", "||", "{", "}", ",", "function", "(", "value", ",", "key", ")", "{", "if", "(", "this", ".", "sandbox", "[", "key", "]", "!==", "undefined", ")", "{", "// Do nothing if the dependency is already defined", "return", ";", "}", "this", ".", "sandbox", "[", "key", "]", "=", "module", ".", "parent", ".", "require", "(", "value", ")", ";", "}", ".", "bind", "(", "this", ")", ")", ";", "// Remove the dependencies property", "delete", "data", ".", "_dependencies", ";", "}", "catch", "(", "e", ")", "{", "// Stop execution and return the MODULE_NOT_FOUND error", "return", "done", "(", "e", ")", ";", "}", "// Iterate over all the data objects", "async", ".", "eachSeries", "(", "Object", ".", "keys", "(", "data", ")", ",", "function", "(", "key", ",", "next", ")", "{", "_this", ".", "result", "[", "key", "]", "=", "{", "}", ";", "var", "value", "=", "data", "[", "key", "]", ";", "try", "{", "if", "(", "!", "value", ".", "_model", ")", "{", "// Throw an error if the model could not be found", "throw", "new", "Error", "(", "'Please provide a _model property that describes which database model should be used.'", ")", ";", "}", "var", "modelName", "=", "value", ".", "_model", ";", "// Remove model and unique properties", "delete", "value", ".", "_model", ";", "// retrieve the model depending on the name provided", "var", "Model", "=", "mongoose", ".", "model", "(", "modelName", ")", ";", "async", ".", "series", "(", "[", "function", "(", "callback", ")", "{", "if", "(", "_this", ".", "options", ".", "dropCollections", "===", "true", ")", "{", "// Drop the collection", "mongoose", ".", "connection", ".", "db", ".", "dropCollection", "(", "Model", ".", "collection", ".", "name", ",", "function", "(", "err", ")", "{", "callback", "(", ")", ";", "}", ")", ";", "}", "else", "{", "callback", "(", ")", ";", "}", "}", ",", "function", "(", "callback", ")", "{", "async", ".", "eachSeries", "(", "Object", ".", "keys", "(", "value", ")", ",", "function", "(", "k", ",", "innerNext", ")", "{", "var", "modelData", "=", "value", "[", "k", "]", ",", "data", "=", "_this", ".", "_unwind", "(", "modelData", ")", ";", "// Create the model", "Model", ".", "create", "(", "data", ",", "function", "(", "err", ",", "result", ")", "{", "if", "(", "err", ")", "{", "// Do not stop execution if an error occurs", "return", "innerNext", "(", "err", ")", ";", "}", "_this", ".", "result", "[", "key", "]", "[", "k", "]", "=", "result", ";", "innerNext", "(", ")", ";", "}", ")", ";", "}", ",", "callback", ")", ";", "}", "]", ",", "next", ")", ";", "}", "catch", "(", "err", ")", "{", "// If the model does not exist, stop the execution", "return", "next", "(", "err", ")", ";", "}", "}", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "// Make sure to not return the result", "return", "done", "(", "err", ")", ";", "}", "done", "(", "undefined", ",", "_this", ".", "result", ")", ";", "}", ")", ";", "}" ]
The internal method for seeding the database. @param {Object} data The data that should be seeded. @param {Function} done The method that should be called when the seeding is done
[ "The", "internal", "method", "for", "seeding", "the", "database", "." ]
ea08d510228a76e5eafa08e1f94cbe8cf0a6614d
https://github.com/SamVerschueren/mongoose-seeder/blob/ea08d510228a76e5eafa08e1f94cbe8cf0a6614d/index.js#L37-L121
40,646
SamVerschueren/mongoose-seeder
index.js
function(ref) { var keys = ref.split('.'), key = keys.shift(), result = _this.result[key]; if(!result) { // If the result does not exist, return an empty throw new TypeError('Could not read property \'' + key + '\' from undefined'); } // Iterate over all the keys and find the property while((key = keys.shift())) { result = result[key]; } if(_.isObject(result) && !_.isArray(result)) { // Test if the result we have is an object. This means the user wants to reference // to the _id of the object. if(!result._id) { // If no _id property exists, throw a TypeError that the property could not be found throw new TypeError('Could not read property \'_id\' of ' + JSON.stringify(result)); } return result._id; } return result; }
javascript
function(ref) { var keys = ref.split('.'), key = keys.shift(), result = _this.result[key]; if(!result) { // If the result does not exist, return an empty throw new TypeError('Could not read property \'' + key + '\' from undefined'); } // Iterate over all the keys and find the property while((key = keys.shift())) { result = result[key]; } if(_.isObject(result) && !_.isArray(result)) { // Test if the result we have is an object. This means the user wants to reference // to the _id of the object. if(!result._id) { // If no _id property exists, throw a TypeError that the property could not be found throw new TypeError('Could not read property \'_id\' of ' + JSON.stringify(result)); } return result._id; } return result; }
[ "function", "(", "ref", ")", "{", "var", "keys", "=", "ref", ".", "split", "(", "'.'", ")", ",", "key", "=", "keys", ".", "shift", "(", ")", ",", "result", "=", "_this", ".", "result", "[", "key", "]", ";", "if", "(", "!", "result", ")", "{", "// If the result does not exist, return an empty", "throw", "new", "TypeError", "(", "'Could not read property \\''", "+", "key", "+", "'\\' from undefined'", ")", ";", "}", "// Iterate over all the keys and find the property", "while", "(", "(", "key", "=", "keys", ".", "shift", "(", ")", ")", ")", "{", "result", "=", "result", "[", "key", "]", ";", "}", "if", "(", "_", ".", "isObject", "(", "result", ")", "&&", "!", "_", ".", "isArray", "(", "result", ")", ")", "{", "// Test if the result we have is an object. This means the user wants to reference", "// to the _id of the object.", "if", "(", "!", "result", ".", "_id", ")", "{", "// If no _id property exists, throw a TypeError that the property could not be found", "throw", "new", "TypeError", "(", "'Could not read property \\'_id\\' of '", "+", "JSON", ".", "stringify", "(", "result", ")", ")", ";", "}", "return", "result", ".", "_id", ";", "}", "return", "result", ";", "}" ]
This method searches for the _id associated with the object represented by the reference provided. @param {String} ref The string representation of the reference. @return {String} The reference to the object.
[ "This", "method", "searches", "for", "the", "_id", "associated", "with", "the", "object", "represented", "by", "the", "reference", "provided", "." ]
ea08d510228a76e5eafa08e1f94cbe8cf0a6614d
https://github.com/SamVerschueren/mongoose-seeder/blob/ea08d510228a76e5eafa08e1f94cbe8cf0a6614d/index.js#L187-L214
40,647
SamVerschueren/mongoose-seeder
index.js
function(data, options, callback) { if(_.isFunction(options)) { // Set the correct callback function callback = options; options = {}; } // Create a deferred object for the promise var def = Q.defer(); // If no callback is provided, use a noop function callback = callback || function() {}; // Clear earlier results and options _this.result = {}; _this.options = {}; _this.sandbox = vm.createContext(); // Defaulting the options _this.options = _.extend(_.clone(DEFAULT_OPTIONS), options); if(_this.options.dropCollections === true && _this.options.dropDatabase === true) { // Only one of the two flags can be turned on. If both are true, this means the // user set the dropCollections itself and this should have higher priority then // the default values. _this.options.dropDatabase = false; } if(_this.options.dropDatabase === true) { // Make sure to drop the database first mongoose.connection.db.dropDatabase(function(err) { if(err) { // Stop seeding if an error occurred return done(err); } // Start seeding when the database is dropped _this._seed(_.cloneDeep(data), done); }); } else { // Do not drop the entire database, start seeding _this._seed(_.cloneDeep(data), done); } /** * This method will be invoked when the seeding is completed or when something * went wrong. This method will then call the callback and rejects or resolves * the promise object. This way, users of the library can use both. * * @param {*} err [description] * @param {Object} result [description] */ function done(err, result) { if(err) { def.reject(err); callback(err); return; } def.resolve(result); callback(undefined, result); } // Return the promise return def.promise; }
javascript
function(data, options, callback) { if(_.isFunction(options)) { // Set the correct callback function callback = options; options = {}; } // Create a deferred object for the promise var def = Q.defer(); // If no callback is provided, use a noop function callback = callback || function() {}; // Clear earlier results and options _this.result = {}; _this.options = {}; _this.sandbox = vm.createContext(); // Defaulting the options _this.options = _.extend(_.clone(DEFAULT_OPTIONS), options); if(_this.options.dropCollections === true && _this.options.dropDatabase === true) { // Only one of the two flags can be turned on. If both are true, this means the // user set the dropCollections itself and this should have higher priority then // the default values. _this.options.dropDatabase = false; } if(_this.options.dropDatabase === true) { // Make sure to drop the database first mongoose.connection.db.dropDatabase(function(err) { if(err) { // Stop seeding if an error occurred return done(err); } // Start seeding when the database is dropped _this._seed(_.cloneDeep(data), done); }); } else { // Do not drop the entire database, start seeding _this._seed(_.cloneDeep(data), done); } /** * This method will be invoked when the seeding is completed or when something * went wrong. This method will then call the callback and rejects or resolves * the promise object. This way, users of the library can use both. * * @param {*} err [description] * @param {Object} result [description] */ function done(err, result) { if(err) { def.reject(err); callback(err); return; } def.resolve(result); callback(undefined, result); } // Return the promise return def.promise; }
[ "function", "(", "data", ",", "options", ",", "callback", ")", "{", "if", "(", "_", ".", "isFunction", "(", "options", ")", ")", "{", "// Set the correct callback function", "callback", "=", "options", ";", "options", "=", "{", "}", ";", "}", "// Create a deferred object for the promise", "var", "def", "=", "Q", ".", "defer", "(", ")", ";", "// If no callback is provided, use a noop function", "callback", "=", "callback", "||", "function", "(", ")", "{", "}", ";", "// Clear earlier results and options", "_this", ".", "result", "=", "{", "}", ";", "_this", ".", "options", "=", "{", "}", ";", "_this", ".", "sandbox", "=", "vm", ".", "createContext", "(", ")", ";", "// Defaulting the options", "_this", ".", "options", "=", "_", ".", "extend", "(", "_", ".", "clone", "(", "DEFAULT_OPTIONS", ")", ",", "options", ")", ";", "if", "(", "_this", ".", "options", ".", "dropCollections", "===", "true", "&&", "_this", ".", "options", ".", "dropDatabase", "===", "true", ")", "{", "// Only one of the two flags can be turned on. If both are true, this means the", "// user set the dropCollections itself and this should have higher priority then", "// the default values.", "_this", ".", "options", ".", "dropDatabase", "=", "false", ";", "}", "if", "(", "_this", ".", "options", ".", "dropDatabase", "===", "true", ")", "{", "// Make sure to drop the database first", "mongoose", ".", "connection", ".", "db", ".", "dropDatabase", "(", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "// Stop seeding if an error occurred", "return", "done", "(", "err", ")", ";", "}", "// Start seeding when the database is dropped", "_this", ".", "_seed", "(", "_", ".", "cloneDeep", "(", "data", ")", ",", "done", ")", ";", "}", ")", ";", "}", "else", "{", "// Do not drop the entire database, start seeding", "_this", ".", "_seed", "(", "_", ".", "cloneDeep", "(", "data", ")", ",", "done", ")", ";", "}", "/**\n * This method will be invoked when the seeding is completed or when something\n * went wrong. This method will then call the callback and rejects or resolves\n * the promise object. This way, users of the library can use both.\n *\n * @param {*} err [description]\n * @param {Object} result [description]\n */", "function", "done", "(", "err", ",", "result", ")", "{", "if", "(", "err", ")", "{", "def", ".", "reject", "(", "err", ")", ";", "callback", "(", "err", ")", ";", "return", ";", "}", "def", ".", "resolve", "(", "result", ")", ";", "callback", "(", "undefined", ",", "result", ")", ";", "}", "// Return the promise", "return", "def", ".", "promise", ";", "}" ]
Start seeding the database. @param {Object} data The data object that should be inserted in the database. @param {Object} options The options object to provide extras. @param {Function} callback The method that should be called when the seeding is done.
[ "Start", "seeding", "the", "database", "." ]
ea08d510228a76e5eafa08e1f94cbe8cf0a6614d
https://github.com/SamVerschueren/mongoose-seeder/blob/ea08d510228a76e5eafa08e1f94cbe8cf0a6614d/index.js#L225-L291
40,648
SamVerschueren/mongoose-seeder
index.js
done
function done(err, result) { if(err) { def.reject(err); callback(err); return; } def.resolve(result); callback(undefined, result); }
javascript
function done(err, result) { if(err) { def.reject(err); callback(err); return; } def.resolve(result); callback(undefined, result); }
[ "function", "done", "(", "err", ",", "result", ")", "{", "if", "(", "err", ")", "{", "def", ".", "reject", "(", "err", ")", ";", "callback", "(", "err", ")", ";", "return", ";", "}", "def", ".", "resolve", "(", "result", ")", ";", "callback", "(", "undefined", ",", "result", ")", ";", "}" ]
This method will be invoked when the seeding is completed or when something went wrong. This method will then call the callback and rejects or resolves the promise object. This way, users of the library can use both. @param {*} err [description] @param {Object} result [description]
[ "This", "method", "will", "be", "invoked", "when", "the", "seeding", "is", "completed", "or", "when", "something", "went", "wrong", ".", "This", "method", "will", "then", "call", "the", "callback", "and", "rejects", "or", "resolves", "the", "promise", "object", ".", "This", "way", "users", "of", "the", "library", "can", "use", "both", "." ]
ea08d510228a76e5eafa08e1f94cbe8cf0a6614d
https://github.com/SamVerschueren/mongoose-seeder/blob/ea08d510228a76e5eafa08e1f94cbe8cf0a6614d/index.js#L278-L287
40,649
github/webpack-config-github
webpack.config.js
proxyConfig
function proxyConfig(path) { const config = {} const {endpointsExtension} = tryGetGraphQLProjectConfig() if (endpointsExtension) { const graphqlEndpoint = endpointsExtension.getEndpoint() const {url: target, headers} = graphqlEndpoint const changeOrigin = true const pathRewrite = {} pathRewrite[`^${path}`] = '' config[path] = {changeOrigin, headers, pathRewrite, target} } return config }
javascript
function proxyConfig(path) { const config = {} const {endpointsExtension} = tryGetGraphQLProjectConfig() if (endpointsExtension) { const graphqlEndpoint = endpointsExtension.getEndpoint() const {url: target, headers} = graphqlEndpoint const changeOrigin = true const pathRewrite = {} pathRewrite[`^${path}`] = '' config[path] = {changeOrigin, headers, pathRewrite, target} } return config }
[ "function", "proxyConfig", "(", "path", ")", "{", "const", "config", "=", "{", "}", "const", "{", "endpointsExtension", "}", "=", "tryGetGraphQLProjectConfig", "(", ")", "if", "(", "endpointsExtension", ")", "{", "const", "graphqlEndpoint", "=", "endpointsExtension", ".", "getEndpoint", "(", ")", "const", "{", "url", ":", "target", ",", "headers", "}", "=", "graphqlEndpoint", "const", "changeOrigin", "=", "true", "const", "pathRewrite", "=", "{", "}", "pathRewrite", "[", "`", "${", "path", "}", "`", "]", "=", "''", "config", "[", "path", "]", "=", "{", "changeOrigin", ",", "headers", ",", "pathRewrite", ",", "target", "}", "}", "return", "config", "}" ]
Get webpack proxy configuration as per .graphqlconfig.
[ "Get", "webpack", "proxy", "configuration", "as", "per", ".", "graphqlconfig", "." ]
cd56f9465db31ef6c0c2c07077ee2c3d25f97554
https://github.com/github/webpack-config-github/blob/cd56f9465db31ef6c0c2c07077ee2c3d25f97554/webpack.config.js#L315-L332
40,650
assemble/buttons
templates/helpers/helper-prettify.js
function(source, options) { try { return prettify(source, options); } catch (e) { console.error(e); console.warn('HTML beautification failed.'); } }
javascript
function(source, options) { try { return prettify(source, options); } catch (e) { console.error(e); console.warn('HTML beautification failed.'); } }
[ "function", "(", "source", ",", "options", ")", "{", "try", "{", "return", "prettify", "(", "source", ",", "options", ")", ";", "}", "catch", "(", "e", ")", "{", "console", ".", "error", "(", "e", ")", ";", "console", ".", "warn", "(", "'HTML beautification failed.'", ")", ";", "}", "}" ]
Format HTML with js-beautify, pass in options. @param {String} source [The un-prettified HTML.] @param {Object} options [Object of options passed to js-beautify.] @returns {String} [Stunning HTML.]
[ "Format", "HTML", "with", "js", "-", "beautify", "pass", "in", "options", "." ]
7b02517713aa316ae7e9d7c23b46a66cde6c7834
https://github.com/assemble/buttons/blob/7b02517713aa316ae7e9d7c23b46a66cde6c7834/templates/helpers/helper-prettify.js#L56-L63
40,651
assemble/buttons
_demo/assets/js/list-scroll.js
refresh
function refresh() { if( active ) { requestAnimFrame( refresh ); for( var i = 0, len = lists.length; i < len; i++ ) { lists[i].update(); } } }
javascript
function refresh() { if( active ) { requestAnimFrame( refresh ); for( var i = 0, len = lists.length; i < len; i++ ) { lists[i].update(); } } }
[ "function", "refresh", "(", ")", "{", "if", "(", "active", ")", "{", "requestAnimFrame", "(", "refresh", ")", ";", "for", "(", "var", "i", "=", "0", ",", "len", "=", "lists", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "lists", "[", "i", "]", ".", "update", "(", ")", ";", "}", "}", "}" ]
Updates all currently bound lists.
[ "Updates", "all", "currently", "bound", "lists", "." ]
7b02517713aa316ae7e9d7c23b46a66cde6c7834
https://github.com/assemble/buttons/blob/7b02517713aa316ae7e9d7c23b46a66cde6c7834/_demo/assets/js/list-scroll.js#L27-L35
40,652
assemble/buttons
_demo/assets/js/list-scroll.js
add
function add( element, options ) { // Only allow ul/ol if( !element.nodeName || /^(ul|li)$/i.test( element.nodeName ) === false ) { return false; } // Delete duplicates (but continue and re-bind this list to get the // latest properties and list items) else if( contains( element ) ) { remove( element ); } var list = IS_TOUCH_DEVICE ? new TouchList( element ) : new List( element ); // Handle options if( options && options.live ) { list.syncInterval = setInterval( function() { list.sync.call( list ); }, LIVE_INTERVAL ); } // Synchronize the list with the DOM list.sync(); // Add this element to the collection lists.push( list ); // Start refreshing if this was the first list to be added if( lists.length === 1 ) { active = true; refresh(); } }
javascript
function add( element, options ) { // Only allow ul/ol if( !element.nodeName || /^(ul|li)$/i.test( element.nodeName ) === false ) { return false; } // Delete duplicates (but continue and re-bind this list to get the // latest properties and list items) else if( contains( element ) ) { remove( element ); } var list = IS_TOUCH_DEVICE ? new TouchList( element ) : new List( element ); // Handle options if( options && options.live ) { list.syncInterval = setInterval( function() { list.sync.call( list ); }, LIVE_INTERVAL ); } // Synchronize the list with the DOM list.sync(); // Add this element to the collection lists.push( list ); // Start refreshing if this was the first list to be added if( lists.length === 1 ) { active = true; refresh(); } }
[ "function", "add", "(", "element", ",", "options", ")", "{", "// Only allow ul/ol", "if", "(", "!", "element", ".", "nodeName", "||", "/", "^(ul|li)$", "/", "i", ".", "test", "(", "element", ".", "nodeName", ")", "===", "false", ")", "{", "return", "false", ";", "}", "// Delete duplicates (but continue and re-bind this list to get the ", "// latest properties and list items)", "else", "if", "(", "contains", "(", "element", ")", ")", "{", "remove", "(", "element", ")", ";", "}", "var", "list", "=", "IS_TOUCH_DEVICE", "?", "new", "TouchList", "(", "element", ")", ":", "new", "List", "(", "element", ")", ";", "// Handle options", "if", "(", "options", "&&", "options", ".", "live", ")", "{", "list", ".", "syncInterval", "=", "setInterval", "(", "function", "(", ")", "{", "list", ".", "sync", ".", "call", "(", "list", ")", ";", "}", ",", "LIVE_INTERVAL", ")", ";", "}", "// Synchronize the list with the DOM", "list", ".", "sync", "(", ")", ";", "// Add this element to the collection", "lists", ".", "push", "(", "list", ")", ";", "// Start refreshing if this was the first list to be added", "if", "(", "lists", ".", "length", "===", "1", ")", "{", "active", "=", "true", ";", "refresh", "(", ")", ";", "}", "}" ]
Starts monitoring a list and applies classes to each of its contained elements based on its position relative to the list's viewport. @param {HTMLElement} element @param {Object} options Additional arguments; - live; Flags if the DOM should be repeatedly checked for changes repeatedly. Useful if the list contents is changing. Use scarcely as it has an impact on performance.
[ "Starts", "monitoring", "a", "list", "and", "applies", "classes", "to", "each", "of", "its", "contained", "elements", "based", "on", "its", "position", "relative", "to", "the", "list", "s", "viewport", "." ]
7b02517713aa316ae7e9d7c23b46a66cde6c7834
https://github.com/assemble/buttons/blob/7b02517713aa316ae7e9d7c23b46a66cde6c7834/_demo/assets/js/list-scroll.js#L48-L79
40,653
assemble/buttons
_demo/assets/js/list-scroll.js
remove
function remove( element ) { for( var i = 0; i < lists.length; i++ ) { var list = lists[i]; if( list.element == element ) { list.destroy(); lists.splice( i, 1 ); i--; } } // Stopped refreshing if the last list was removed if( lists.length === 0 ) { active = false; } }
javascript
function remove( element ) { for( var i = 0; i < lists.length; i++ ) { var list = lists[i]; if( list.element == element ) { list.destroy(); lists.splice( i, 1 ); i--; } } // Stopped refreshing if the last list was removed if( lists.length === 0 ) { active = false; } }
[ "function", "remove", "(", "element", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "lists", ".", "length", ";", "i", "++", ")", "{", "var", "list", "=", "lists", "[", "i", "]", ";", "if", "(", "list", ".", "element", "==", "element", ")", "{", "list", ".", "destroy", "(", ")", ";", "lists", ".", "splice", "(", "i", ",", "1", ")", ";", "i", "--", ";", "}", "}", "// Stopped refreshing if the last list was removed", "if", "(", "lists", ".", "length", "===", "0", ")", "{", "active", "=", "false", ";", "}", "}" ]
Stops monitoring a list element and removes any classes that were applied to its list items. @param {HTMLElement} element
[ "Stops", "monitoring", "a", "list", "element", "and", "removes", "any", "classes", "that", "were", "applied", "to", "its", "list", "items", "." ]
7b02517713aa316ae7e9d7c23b46a66cde6c7834
https://github.com/assemble/buttons/blob/7b02517713aa316ae7e9d7c23b46a66cde6c7834/_demo/assets/js/list-scroll.js#L87-L102
40,654
assemble/buttons
_demo/assets/js/list-scroll.js
contains
function contains( element ) { for( var i = 0, len = lists.length; i < len; i++ ) { if( lists[i].element == element ) { return true; } } return false; }
javascript
function contains( element ) { for( var i = 0, len = lists.length; i < len; i++ ) { if( lists[i].element == element ) { return true; } } return false; }
[ "function", "contains", "(", "element", ")", "{", "for", "(", "var", "i", "=", "0", ",", "len", "=", "lists", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "if", "(", "lists", "[", "i", "]", ".", "element", "==", "element", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Checks if the specified element has already been bound.
[ "Checks", "if", "the", "specified", "element", "has", "already", "been", "bound", "." ]
7b02517713aa316ae7e9d7c23b46a66cde6c7834
https://github.com/assemble/buttons/blob/7b02517713aa316ae7e9d7c23b46a66cde6c7834/_demo/assets/js/list-scroll.js#L107-L114
40,655
assemble/buttons
_demo/assets/js/list-scroll.js
batch
function batch( target, method, options ) { var i, len; // Selector if( typeof target === 'string' ) { var targets = document.querySelectorAll( target ); for( i = 0, len = targets.length; i < len; i++ ) { method.call( null, targets[i], options ); } } // Array (jQuery) else if( typeof target === 'object' && typeof target.length === 'number' ) { for( i = 0, len = target.length; i < len; i++ ) { method.call( null, target[i], options ); } } // Single element else if( target.nodeName ) { method.call( null, target, options ); } else { throw 'Stroll target was of unexpected type.'; } }
javascript
function batch( target, method, options ) { var i, len; // Selector if( typeof target === 'string' ) { var targets = document.querySelectorAll( target ); for( i = 0, len = targets.length; i < len; i++ ) { method.call( null, targets[i], options ); } } // Array (jQuery) else if( typeof target === 'object' && typeof target.length === 'number' ) { for( i = 0, len = target.length; i < len; i++ ) { method.call( null, target[i], options ); } } // Single element else if( target.nodeName ) { method.call( null, target, options ); } else { throw 'Stroll target was of unexpected type.'; } }
[ "function", "batch", "(", "target", ",", "method", ",", "options", ")", "{", "var", "i", ",", "len", ";", "// Selector", "if", "(", "typeof", "target", "===", "'string'", ")", "{", "var", "targets", "=", "document", ".", "querySelectorAll", "(", "target", ")", ";", "for", "(", "i", "=", "0", ",", "len", "=", "targets", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "method", ".", "call", "(", "null", ",", "targets", "[", "i", "]", ",", "options", ")", ";", "}", "}", "// Array (jQuery)", "else", "if", "(", "typeof", "target", "===", "'object'", "&&", "typeof", "target", ".", "length", "===", "'number'", ")", "{", "for", "(", "i", "=", "0", ",", "len", "=", "target", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "method", ".", "call", "(", "null", ",", "target", "[", "i", "]", ",", "options", ")", ";", "}", "}", "// Single element", "else", "if", "(", "target", ".", "nodeName", ")", "{", "method", ".", "call", "(", "null", ",", "target", ",", "options", ")", ";", "}", "else", "{", "throw", "'Stroll target was of unexpected type.'", ";", "}", "}" ]
Calls 'method' for each DOM element discovered in 'target'. @param target String selector / array of UL elements / jQuery object / single UL element @param method A function to call for each element target
[ "Calls", "method", "for", "each", "DOM", "element", "discovered", "in", "target", "." ]
7b02517713aa316ae7e9d7c23b46a66cde6c7834
https://github.com/assemble/buttons/blob/7b02517713aa316ae7e9d7c23b46a66cde6c7834/_demo/assets/js/list-scroll.js#L124-L148
40,656
assemble/buttons
_demo/assets/js/list-scroll.js
TouchList
function TouchList( element ) { this.element = element; this.element.style.overflow = 'hidden'; this.top = { value: 0, natural: 0 }; this.touch = { value: 0, offset: 0, start: 0, previous: 0, lastMove: Date.now(), accellerateTimeout: -1, isAccellerating: false, isActive: false }; this.velocity = 0; }
javascript
function TouchList( element ) { this.element = element; this.element.style.overflow = 'hidden'; this.top = { value: 0, natural: 0 }; this.touch = { value: 0, offset: 0, start: 0, previous: 0, lastMove: Date.now(), accellerateTimeout: -1, isAccellerating: false, isActive: false }; this.velocity = 0; }
[ "function", "TouchList", "(", "element", ")", "{", "this", ".", "element", "=", "element", ";", "this", ".", "element", ".", "style", ".", "overflow", "=", "'hidden'", ";", "this", ".", "top", "=", "{", "value", ":", "0", ",", "natural", ":", "0", "}", ";", "this", ".", "touch", "=", "{", "value", ":", "0", ",", "offset", ":", "0", ",", "start", ":", "0", ",", "previous", ":", "0", ",", "lastMove", ":", "Date", ".", "now", "(", ")", ",", "accellerateTimeout", ":", "-", "1", ",", "isAccellerating", ":", "false", ",", "isActive", ":", "false", "}", ";", "this", ".", "velocity", "=", "0", ";", "}" ]
A list specifically for touch devices. Simulates the style of scrolling you'd see on a touch device but does not rely on webkit-overflow-scrolling since that makes it impossible to read the up-to-date scroll position.
[ "A", "list", "specifically", "for", "touch", "devices", ".", "Simulates", "the", "style", "of", "scrolling", "you", "d", "see", "on", "a", "touch", "device", "but", "does", "not", "rely", "on", "webkit", "-", "overflow", "-", "scrolling", "since", "that", "makes", "it", "impossible", "to", "read", "the", "up", "-", "to", "-", "date", "scroll", "position", "." ]
7b02517713aa316ae7e9d7c23b46a66cde6c7834
https://github.com/assemble/buttons/blob/7b02517713aa316ae7e9d7c23b46a66cde6c7834/_demo/assets/js/list-scroll.js#L252-L273
40,657
calmh/yardstick
bin/yardstick.js
displayMetrics
function displayMetrics(file) { var prefix = ''; var code = fs.readFileSync(file, 'utf-8'); // We remove any shebang at the start of the file since that isn't valid // Javascript and will trip up the parser. code = code.replace(/^#!.*\n/, ''); var metrics = complexity(code); // Walk the metrics structure and add each member to the table rows. function walk(data, name) { // Fade out anonymous functions. if (name.indexOf('anon@') === 0) { name = name.grey; } rows.push([ prefix + name, data.ecc, data.arity, data.codeLines, data.commentLines, Math.round(100 * data.commentLines / data.codeLines) ]); // Add two spaces to the prefix before the next depth, to illustrate // the hierarchy in the table. prefix += ' '; _.each(data.children, walk); prefix = prefix.slice(0,prefix.length-2); } walk(metrics, path.basename(file).blue.bold); }
javascript
function displayMetrics(file) { var prefix = ''; var code = fs.readFileSync(file, 'utf-8'); // We remove any shebang at the start of the file since that isn't valid // Javascript and will trip up the parser. code = code.replace(/^#!.*\n/, ''); var metrics = complexity(code); // Walk the metrics structure and add each member to the table rows. function walk(data, name) { // Fade out anonymous functions. if (name.indexOf('anon@') === 0) { name = name.grey; } rows.push([ prefix + name, data.ecc, data.arity, data.codeLines, data.commentLines, Math.round(100 * data.commentLines / data.codeLines) ]); // Add two spaces to the prefix before the next depth, to illustrate // the hierarchy in the table. prefix += ' '; _.each(data.children, walk); prefix = prefix.slice(0,prefix.length-2); } walk(metrics, path.basename(file).blue.bold); }
[ "function", "displayMetrics", "(", "file", ")", "{", "var", "prefix", "=", "''", ";", "var", "code", "=", "fs", ".", "readFileSync", "(", "file", ",", "'utf-8'", ")", ";", "// We remove any shebang at the start of the file since that isn't valid", "// Javascript and will trip up the parser.", "code", "=", "code", ".", "replace", "(", "/", "^#!.*\\n", "/", ",", "''", ")", ";", "var", "metrics", "=", "complexity", "(", "code", ")", ";", "// Walk the metrics structure and add each member to the table rows.", "function", "walk", "(", "data", ",", "name", ")", "{", "// Fade out anonymous functions.", "if", "(", "name", ".", "indexOf", "(", "'anon@'", ")", "===", "0", ")", "{", "name", "=", "name", ".", "grey", ";", "}", "rows", ".", "push", "(", "[", "prefix", "+", "name", ",", "data", ".", "ecc", ",", "data", ".", "arity", ",", "data", ".", "codeLines", ",", "data", ".", "commentLines", ",", "Math", ".", "round", "(", "100", "*", "data", ".", "commentLines", "/", "data", ".", "codeLines", ")", "]", ")", ";", "// Add two spaces to the prefix before the next depth, to illustrate", "// the hierarchy in the table.", "prefix", "+=", "' '", ";", "_", ".", "each", "(", "data", ".", "children", ",", "walk", ")", ";", "prefix", "=", "prefix", ".", "slice", "(", "0", ",", "prefix", ".", "length", "-", "2", ")", ";", "}", "walk", "(", "metrics", ",", "path", ".", "basename", "(", "file", ")", ".", "blue", ".", "bold", ")", ";", "}" ]
Analyze a file and add it's metrics to the table.
[ "Analyze", "a", "file", "and", "add", "it", "s", "metrics", "to", "the", "table", "." ]
3d3a8c94532c523a3b8b935bacb1fa444dcd8b3c
https://github.com/calmh/yardstick/blob/3d3a8c94532c523a3b8b935bacb1fa444dcd8b3c/bin/yardstick.js#L22-L53
40,658
calmh/yardstick
bin/yardstick.js
walk
function walk(data, name) { // Fade out anonymous functions. if (name.indexOf('anon@') === 0) { name = name.grey; } rows.push([ prefix + name, data.ecc, data.arity, data.codeLines, data.commentLines, Math.round(100 * data.commentLines / data.codeLines) ]); // Add two spaces to the prefix before the next depth, to illustrate // the hierarchy in the table. prefix += ' '; _.each(data.children, walk); prefix = prefix.slice(0,prefix.length-2); }
javascript
function walk(data, name) { // Fade out anonymous functions. if (name.indexOf('anon@') === 0) { name = name.grey; } rows.push([ prefix + name, data.ecc, data.arity, data.codeLines, data.commentLines, Math.round(100 * data.commentLines / data.codeLines) ]); // Add two spaces to the prefix before the next depth, to illustrate // the hierarchy in the table. prefix += ' '; _.each(data.children, walk); prefix = prefix.slice(0,prefix.length-2); }
[ "function", "walk", "(", "data", ",", "name", ")", "{", "// Fade out anonymous functions.", "if", "(", "name", ".", "indexOf", "(", "'anon@'", ")", "===", "0", ")", "{", "name", "=", "name", ".", "grey", ";", "}", "rows", ".", "push", "(", "[", "prefix", "+", "name", ",", "data", ".", "ecc", ",", "data", ".", "arity", ",", "data", ".", "codeLines", ",", "data", ".", "commentLines", ",", "Math", ".", "round", "(", "100", "*", "data", ".", "commentLines", "/", "data", ".", "codeLines", ")", "]", ")", ";", "// Add two spaces to the prefix before the next depth, to illustrate", "// the hierarchy in the table.", "prefix", "+=", "' '", ";", "_", ".", "each", "(", "data", ".", "children", ",", "walk", ")", ";", "prefix", "=", "prefix", ".", "slice", "(", "0", ",", "prefix", ".", "length", "-", "2", ")", ";", "}" ]
Walk the metrics structure and add each member to the table rows.
[ "Walk", "the", "metrics", "structure", "and", "add", "each", "member", "to", "the", "table", "rows", "." ]
3d3a8c94532c523a3b8b935bacb1fa444dcd8b3c
https://github.com/calmh/yardstick/blob/3d3a8c94532c523a3b8b935bacb1fa444dcd8b3c/bin/yardstick.js#L36-L51
40,659
homerjam/angular-scroll-magic
bower_components/gsap/src/uncompressed/TweenMax.js
function(v) { var t = this.t, //refers to the element's style property filters = t.filter || _getStyle(this.data, "filter") || "", val = (this.s + this.c * v) | 0, skip; if (val === 100) { //for older versions of IE that need to use a filter to apply opacity, we should remove the filter if opacity hits 1 in order to improve performance, but make sure there isn't a transform (matrix) or gradient in the filters. if (filters.indexOf("atrix(") === -1 && filters.indexOf("radient(") === -1 && filters.indexOf("oader(") === -1) { t.removeAttribute("filter"); skip = (!_getStyle(this.data, "filter")); //if a class is applied that has an alpha filter, it will take effect (we don't want that), so re-apply our alpha filter in that case. We must first remove it and then check. } else { t.filter = filters.replace(_alphaFilterExp, ""); skip = true; } } if (!skip) { if (this.xn1) { t.filter = filters = filters || ("alpha(opacity=" + val + ")"); //works around bug in IE7/8 that prevents changes to "visibility" from being applied properly if the filter is changed to a different alpha on the same frame. } if (filters.indexOf("pacity") === -1) { //only used if browser doesn't support the standard opacity style property (IE 7 and 8). We omit the "O" to avoid case-sensitivity issues if (val !== 0 || !this.xn1) { //bugs in IE7/8 won't render the filter properly if opacity is ADDED on the same frame/render as "visibility" changes (this.xn1 is 1 if this tween is an "autoAlpha" tween) t.filter = filters + " alpha(opacity=" + val + ")"; //we round the value because otherwise, bugs in IE7/8 can prevent "visibility" changes from being applied properly. } } else { t.filter = filters.replace(_opacityExp, "opacity=" + val); } } }
javascript
function(v) { var t = this.t, //refers to the element's style property filters = t.filter || _getStyle(this.data, "filter") || "", val = (this.s + this.c * v) | 0, skip; if (val === 100) { //for older versions of IE that need to use a filter to apply opacity, we should remove the filter if opacity hits 1 in order to improve performance, but make sure there isn't a transform (matrix) or gradient in the filters. if (filters.indexOf("atrix(") === -1 && filters.indexOf("radient(") === -1 && filters.indexOf("oader(") === -1) { t.removeAttribute("filter"); skip = (!_getStyle(this.data, "filter")); //if a class is applied that has an alpha filter, it will take effect (we don't want that), so re-apply our alpha filter in that case. We must first remove it and then check. } else { t.filter = filters.replace(_alphaFilterExp, ""); skip = true; } } if (!skip) { if (this.xn1) { t.filter = filters = filters || ("alpha(opacity=" + val + ")"); //works around bug in IE7/8 that prevents changes to "visibility" from being applied properly if the filter is changed to a different alpha on the same frame. } if (filters.indexOf("pacity") === -1) { //only used if browser doesn't support the standard opacity style property (IE 7 and 8). We omit the "O" to avoid case-sensitivity issues if (val !== 0 || !this.xn1) { //bugs in IE7/8 won't render the filter properly if opacity is ADDED on the same frame/render as "visibility" changes (this.xn1 is 1 if this tween is an "autoAlpha" tween) t.filter = filters + " alpha(opacity=" + val + ")"; //we round the value because otherwise, bugs in IE7/8 can prevent "visibility" changes from being applied properly. } } else { t.filter = filters.replace(_opacityExp, "opacity=" + val); } } }
[ "function", "(", "v", ")", "{", "var", "t", "=", "this", ".", "t", ",", "//refers to the element's style property", "filters", "=", "t", ".", "filter", "||", "_getStyle", "(", "this", ".", "data", ",", "\"filter\"", ")", "||", "\"\"", ",", "val", "=", "(", "this", ".", "s", "+", "this", ".", "c", "*", "v", ")", "|", "0", ",", "skip", ";", "if", "(", "val", "===", "100", ")", "{", "//for older versions of IE that need to use a filter to apply opacity, we should remove the filter if opacity hits 1 in order to improve performance, but make sure there isn't a transform (matrix) or gradient in the filters.", "if", "(", "filters", ".", "indexOf", "(", "\"atrix(\"", ")", "===", "-", "1", "&&", "filters", ".", "indexOf", "(", "\"radient(\"", ")", "===", "-", "1", "&&", "filters", ".", "indexOf", "(", "\"oader(\"", ")", "===", "-", "1", ")", "{", "t", ".", "removeAttribute", "(", "\"filter\"", ")", ";", "skip", "=", "(", "!", "_getStyle", "(", "this", ".", "data", ",", "\"filter\"", ")", ")", ";", "//if a class is applied that has an alpha filter, it will take effect (we don't want that), so re-apply our alpha filter in that case. We must first remove it and then check.", "}", "else", "{", "t", ".", "filter", "=", "filters", ".", "replace", "(", "_alphaFilterExp", ",", "\"\"", ")", ";", "skip", "=", "true", ";", "}", "}", "if", "(", "!", "skip", ")", "{", "if", "(", "this", ".", "xn1", ")", "{", "t", ".", "filter", "=", "filters", "=", "filters", "||", "(", "\"alpha(opacity=\"", "+", "val", "+", "\")\"", ")", ";", "//works around bug in IE7/8 that prevents changes to \"visibility\" from being applied properly if the filter is changed to a different alpha on the same frame.", "}", "if", "(", "filters", ".", "indexOf", "(", "\"pacity\"", ")", "===", "-", "1", ")", "{", "//only used if browser doesn't support the standard opacity style property (IE 7 and 8). We omit the \"O\" to avoid case-sensitivity issues", "if", "(", "val", "!==", "0", "||", "!", "this", ".", "xn1", ")", "{", "//bugs in IE7/8 won't render the filter properly if opacity is ADDED on the same frame/render as \"visibility\" changes (this.xn1 is 1 if this tween is an \"autoAlpha\" tween)", "t", ".", "filter", "=", "filters", "+", "\" alpha(opacity=\"", "+", "val", "+", "\")\"", ";", "//we round the value because otherwise, bugs in IE7/8 can prevent \"visibility\" changes from being applied properly.", "}", "}", "else", "{", "t", ".", "filter", "=", "filters", ".", "replace", "(", "_opacityExp", ",", "\"opacity=\"", "+", "val", ")", ";", "}", "}", "}" ]
opacity-related
[ "opacity", "-", "related" ]
82b2a1d14497fa74d060be53b0e042f1c496351b
https://github.com/homerjam/angular-scroll-magic/blob/82b2a1d14497fa74d060be53b0e042f1c496351b/bower_components/gsap/src/uncompressed/TweenMax.js#L4488-L4514
40,660
hashchange/jquery.documentsize
dist/jquery.documentsize.js
isVisualViewport
function isVisualViewport ( name ) { var viewport = isString( name ) && name.toLowerCase(); if ( name && !viewport ) throw new Error( "Invalid viewport option: " + name ); if ( viewport && viewport !== "visual" && viewport !== "layout" ) throw new Error( "Invalid viewport name: " + name ); return viewport === "visual"; }
javascript
function isVisualViewport ( name ) { var viewport = isString( name ) && name.toLowerCase(); if ( name && !viewport ) throw new Error( "Invalid viewport option: " + name ); if ( viewport && viewport !== "visual" && viewport !== "layout" ) throw new Error( "Invalid viewport name: " + name ); return viewport === "visual"; }
[ "function", "isVisualViewport", "(", "name", ")", "{", "var", "viewport", "=", "isString", "(", "name", ")", "&&", "name", ".", "toLowerCase", "(", ")", ";", "if", "(", "name", "&&", "!", "viewport", ")", "throw", "new", "Error", "(", "\"Invalid viewport option: \"", "+", "name", ")", ";", "if", "(", "viewport", "&&", "viewport", "!==", "\"visual\"", "&&", "viewport", "!==", "\"layout\"", ")", "throw", "new", "Error", "(", "\"Invalid viewport name: \"", "+", "name", ")", ";", "return", "viewport", "===", "\"visual\"", ";", "}" ]
Checks if the argument is the name of the visual viewport. The check is case-insensitive. Expects a string. Tolerates falsy values, returning false then (argument is not naming the visual viewport). Throws an error for everything else. Also throws an error if the viewport name is a string but not recognized (typo alert). Helper for getWindowQueryConfig(). @param {string} [name] strings "visual", "layout" (case-insensitive) @returns {boolean}
[ "Checks", "if", "the", "argument", "is", "the", "name", "of", "the", "visual", "viewport", ".", "The", "check", "is", "case", "-", "insensitive", "." ]
4f9c24f054f604b165082bbe5b3b424ad042a729
https://github.com/hashchange/jquery.documentsize/blob/4f9c24f054f604b165082bbe5b3b424ad042a729/dist/jquery.documentsize.js#L340-L347
40,661
hashchange/jquery.documentsize
dist/jquery.documentsize.js
restoreGlobalDocument
function restoreGlobalDocument ( previousState ) { if ( previousState.documentElement.modified ) document.documentElement.style.overflowX = previousState.documentElement.styleOverflowX; if ( previousState.body.modified ) document.body.style.overflowX = previousState.body.styleOverflowX; }
javascript
function restoreGlobalDocument ( previousState ) { if ( previousState.documentElement.modified ) document.documentElement.style.overflowX = previousState.documentElement.styleOverflowX; if ( previousState.body.modified ) document.body.style.overflowX = previousState.body.styleOverflowX; }
[ "function", "restoreGlobalDocument", "(", "previousState", ")", "{", "if", "(", "previousState", ".", "documentElement", ".", "modified", ")", "document", ".", "documentElement", ".", "style", ".", "overflowX", "=", "previousState", ".", "documentElement", ".", "styleOverflowX", ";", "if", "(", "previousState", ".", "body", ".", "modified", ")", "document", ".", "body", ".", "style", ".", "overflowX", "=", "previousState", ".", "body", ".", "styleOverflowX", ";", "}" ]
Restores the body and documentElement styles to their initial state, which is passed in as an argument. Works with the global document. Used only if iframe creation or access has failed for some reason. @param {Object} previousState the initial state, as returned by prepareGlobalDocument()
[ "Restores", "the", "body", "and", "documentElement", "styles", "to", "their", "initial", "state", "which", "is", "passed", "in", "as", "an", "argument", ".", "Works", "with", "the", "global", "document", "." ]
4f9c24f054f604b165082bbe5b3b424ad042a729
https://github.com/hashchange/jquery.documentsize/blob/4f9c24f054f604b165082bbe5b3b424ad042a729/dist/jquery.documentsize.js#L560-L565
40,662
hashchange/jquery.documentsize
dist/jquery.documentsize.js
guessDocumentSize
function guessDocumentSize( dimension, _document ) { var ddE = _document.documentElement; return Math.max( ddE.body[ "scroll" + dimension ], _document[ "scroll" + dimension ], ddE.body[ "offset" + dimension ], _document[ "offset" + dimension ], _document[ "client" + dimension ] ); }
javascript
function guessDocumentSize( dimension, _document ) { var ddE = _document.documentElement; return Math.max( ddE.body[ "scroll" + dimension ], _document[ "scroll" + dimension ], ddE.body[ "offset" + dimension ], _document[ "offset" + dimension ], _document[ "client" + dimension ] ); }
[ "function", "guessDocumentSize", "(", "dimension", ",", "_document", ")", "{", "var", "ddE", "=", "_document", ".", "documentElement", ";", "return", "Math", ".", "max", "(", "ddE", ".", "body", "[", "\"scroll\"", "+", "dimension", "]", ",", "_document", "[", "\"scroll\"", "+", "dimension", "]", ",", "ddE", ".", "body", "[", "\"offset\"", "+", "dimension", "]", ",", "_document", "[", "\"offset\"", "+", "dimension", "]", ",", "_document", "[", "\"client\"", "+", "dimension", "]", ")", ";", "}" ]
Returns a best guess for the window width or height. Used as a fallback for unsupported browsers which are too broken to even run the feature test. The conventional jQuery method of guessing the document size is used here: every conceivable value is queried and the largest one is picked. @param {string} dimension accepted values are "Width" or "Height" (capitalized first letter!) @param {Document} [_document]
[ "Returns", "a", "best", "guess", "for", "the", "window", "width", "or", "height", ".", "Used", "as", "a", "fallback", "for", "unsupported", "browsers", "which", "are", "too", "broken", "to", "even", "run", "the", "feature", "test", "." ]
4f9c24f054f604b165082bbe5b3b424ad042a729
https://github.com/hashchange/jquery.documentsize/blob/4f9c24f054f604b165082bbe5b3b424ad042a729/dist/jquery.documentsize.js#L577-L585
40,663
hashchange/jquery.documentsize
dist/jquery.documentsize.js
getWindowInnerSize
function getWindowInnerSize ( dimension, _window ) { var size = ( _window || window ).visualViewport ? ( _window || window ).visualViewport[ dimension.toLowerCase() ] : ( _window || window )[ "inner" + dimension]; // Check for fractions. Exclude undefined return values in browsers which don't support window.innerWidth/Height. if ( size ) checkForFractions( size ); return size; }
javascript
function getWindowInnerSize ( dimension, _window ) { var size = ( _window || window ).visualViewport ? ( _window || window ).visualViewport[ dimension.toLowerCase() ] : ( _window || window )[ "inner" + dimension]; // Check for fractions. Exclude undefined return values in browsers which don't support window.innerWidth/Height. if ( size ) checkForFractions( size ); return size; }
[ "function", "getWindowInnerSize", "(", "dimension", ",", "_window", ")", "{", "var", "size", "=", "(", "_window", "||", "window", ")", ".", "visualViewport", "?", "(", "_window", "||", "window", ")", ".", "visualViewport", "[", "dimension", ".", "toLowerCase", "(", ")", "]", ":", "(", "_window", "||", "window", ")", "[", "\"inner\"", "+", "dimension", "]", ";", "// Check for fractions. Exclude undefined return values in browsers which don't support window.innerWidth/Height.", "if", "(", "size", ")", "checkForFractions", "(", "size", ")", ";", "return", "size", ";", "}" ]
Returns window.visualViewport.width if available, or window.innerWidth otherwise, for width. Likewise, it returns window.visualViewport.height or window.innerHeight for height. The dimension argument determines whether width or height is returned. Along the way, the return value is examined to see if the browser supports sub-pixel accuracy (floating-point values). If the visualViewport API is available, it is preferred over window.innerWidth/Height. That's because Chrome, from version 62, has changed the behaviour of window.innerWidth/Height, which used to return the size of the visual viewport. In Chrome, it now returns the size of the layout viewport, breaking compatibility with all other browsers and its own past behaviour. Other browsers may follow suit, though. See - https://www.quirksmode.org/blog/archives/2017/09/chrome_breaks_v.html - https://developers.google.com/web/updates/2017/09/visual-viewport-api - https://bugs.chromium.org/p/chromium/issues/detail?id=767388#c8 @param {string} dimension must be "Width" or "Height" (upper case!) @param {Window} [_window=window] @returns {number}
[ "Returns", "window", ".", "visualViewport", ".", "width", "if", "available", "or", "window", ".", "innerWidth", "otherwise", "for", "width", ".", "Likewise", "it", "returns", "window", ".", "visualViewport", ".", "height", "or", "window", ".", "innerHeight", "for", "height", ".", "The", "dimension", "argument", "determines", "whether", "width", "or", "height", "is", "returned", "." ]
4f9c24f054f604b165082bbe5b3b424ad042a729
https://github.com/hashchange/jquery.documentsize/blob/4f9c24f054f604b165082bbe5b3b424ad042a729/dist/jquery.documentsize.js#L634-L642
40,664
hashchange/jquery.documentsize
dist/jquery.documentsize.js
getIEVersion
function getIEVersion () { var userAgent, userAgentTestRx; if ( ieVersion === undefined ) { ieVersion = false; userAgent = navigator && navigator.userAgent; if ( navigator && navigator.appName === "Microsoft Internet Explorer" && userAgent ) { userAgentTestRx = new RegExp( "MSIE ([0-9]{1,}[\.0-9]{0,})" ); // jshint ignore:line if ( userAgentTestRx.exec( userAgent ) != null ) ieVersion = parseFloat( RegExp.$1 ); } } return ieVersion; }
javascript
function getIEVersion () { var userAgent, userAgentTestRx; if ( ieVersion === undefined ) { ieVersion = false; userAgent = navigator && navigator.userAgent; if ( navigator && navigator.appName === "Microsoft Internet Explorer" && userAgent ) { userAgentTestRx = new RegExp( "MSIE ([0-9]{1,}[\.0-9]{0,})" ); // jshint ignore:line if ( userAgentTestRx.exec( userAgent ) != null ) ieVersion = parseFloat( RegExp.$1 ); } } return ieVersion; }
[ "function", "getIEVersion", "(", ")", "{", "var", "userAgent", ",", "userAgentTestRx", ";", "if", "(", "ieVersion", "===", "undefined", ")", "{", "ieVersion", "=", "false", ";", "userAgent", "=", "navigator", "&&", "navigator", ".", "userAgent", ";", "if", "(", "navigator", "&&", "navigator", ".", "appName", "===", "\"Microsoft Internet Explorer\"", "&&", "userAgent", ")", "{", "userAgentTestRx", "=", "new", "RegExp", "(", "\"MSIE ([0-9]{1,}[\\.0-9]{0,})\"", ")", ";", "// jshint ignore:line", "if", "(", "userAgentTestRx", ".", "exec", "(", "userAgent", ")", "!=", "null", ")", "ieVersion", "=", "parseFloat", "(", "RegExp", ".", "$1", ")", ";", "}", "}", "return", "ieVersion", ";", "}" ]
Returns the IE version, or false if the browser is not IE. The result is determined by browser sniffing, rather than a test tailored to the use case. The function must only be called as a last resort, for scenarios where there is no alternative to browser sniffing. These scenarios include: - Preventing IE6 and IE7 from crashing - Preventing IE9 from blocking or delaying the load event The test follows the MSDN recommendation at https://msdn.microsoft.com/en-us/library/ms537509(v=vs.85).aspx#parsingua The result is cached. @returns {number|boolean}
[ "Returns", "the", "IE", "version", "or", "false", "if", "the", "browser", "is", "not", "IE", "." ]
4f9c24f054f604b165082bbe5b3b424ad042a729
https://github.com/hashchange/jquery.documentsize/blob/4f9c24f054f604b165082bbe5b3b424ad042a729/dist/jquery.documentsize.js#L739-L755
40,665
hashchange/jquery.documentsize
demo/load-event/js/libs/bootstrap-multiselect/bootstrap-multiselect.js
function() { this.$container = $(this.options.buttonContainer); this.$container.on('show.bs.dropdown', this.options.onDropdownShow); this.$container.on('hide.bs.dropdown', this.options.onDropdownHide); this.$container.on('shown.bs.dropdown', this.options.onDropdownShown); this.$container.on('hidden.bs.dropdown', this.options.onDropdownHidden); }
javascript
function() { this.$container = $(this.options.buttonContainer); this.$container.on('show.bs.dropdown', this.options.onDropdownShow); this.$container.on('hide.bs.dropdown', this.options.onDropdownHide); this.$container.on('shown.bs.dropdown', this.options.onDropdownShown); this.$container.on('hidden.bs.dropdown', this.options.onDropdownHidden); }
[ "function", "(", ")", "{", "this", ".", "$container", "=", "$", "(", "this", ".", "options", ".", "buttonContainer", ")", ";", "this", ".", "$container", ".", "on", "(", "'show.bs.dropdown'", ",", "this", ".", "options", ".", "onDropdownShow", ")", ";", "this", ".", "$container", ".", "on", "(", "'hide.bs.dropdown'", ",", "this", ".", "options", ".", "onDropdownHide", ")", ";", "this", ".", "$container", ".", "on", "(", "'shown.bs.dropdown'", ",", "this", ".", "options", ".", "onDropdownShown", ")", ";", "this", ".", "$container", ".", "on", "(", "'hidden.bs.dropdown'", ",", "this", ".", "options", ".", "onDropdownHidden", ")", ";", "}" ]
Builds the container of the multiselect.
[ "Builds", "the", "container", "of", "the", "multiselect", "." ]
4f9c24f054f604b165082bbe5b3b424ad042a729
https://github.com/hashchange/jquery.documentsize/blob/4f9c24f054f604b165082bbe5b3b424ad042a729/demo/load-event/js/libs/bootstrap-multiselect/bootstrap-multiselect.js#L351-L357
40,666
hashchange/jquery.documentsize
demo/load-event/js/libs/bootstrap-multiselect/bootstrap-multiselect.js
function() { if (typeof this.options.selectAllValue === 'number') { this.options.selectAllValue = this.options.selectAllValue.toString(); } var alreadyHasSelectAll = this.hasSelectAll(); if (!alreadyHasSelectAll && this.options.includeSelectAllOption && this.options.multiple && $('option', this.$select).length > this.options.includeSelectAllIfMoreThan) { // Check whether to add a divider after the select all. if (this.options.includeSelectAllDivider) { this.$ul.prepend($(this.options.templates.divider)); } var $li = $(this.options.templates.li); $('label', $li).addClass("checkbox"); if (this.options.enableHTML) { $('label', $li).html(" " + this.options.selectAllText); } else { $('label', $li).text(" " + this.options.selectAllText); } if (this.options.selectAllName) { $('label', $li).prepend('<input type="checkbox" name="' + this.options.selectAllName + '" />'); } else { $('label', $li).prepend('<input type="checkbox" />'); } var $checkbox = $('input', $li); $checkbox.val(this.options.selectAllValue); $li.addClass("multiselect-item multiselect-all"); $checkbox.parent().parent() .addClass('multiselect-all'); this.$ul.prepend($li); $checkbox.prop('checked', false); } }
javascript
function() { if (typeof this.options.selectAllValue === 'number') { this.options.selectAllValue = this.options.selectAllValue.toString(); } var alreadyHasSelectAll = this.hasSelectAll(); if (!alreadyHasSelectAll && this.options.includeSelectAllOption && this.options.multiple && $('option', this.$select).length > this.options.includeSelectAllIfMoreThan) { // Check whether to add a divider after the select all. if (this.options.includeSelectAllDivider) { this.$ul.prepend($(this.options.templates.divider)); } var $li = $(this.options.templates.li); $('label', $li).addClass("checkbox"); if (this.options.enableHTML) { $('label', $li).html(" " + this.options.selectAllText); } else { $('label', $li).text(" " + this.options.selectAllText); } if (this.options.selectAllName) { $('label', $li).prepend('<input type="checkbox" name="' + this.options.selectAllName + '" />'); } else { $('label', $li).prepend('<input type="checkbox" />'); } var $checkbox = $('input', $li); $checkbox.val(this.options.selectAllValue); $li.addClass("multiselect-item multiselect-all"); $checkbox.parent().parent() .addClass('multiselect-all'); this.$ul.prepend($li); $checkbox.prop('checked', false); } }
[ "function", "(", ")", "{", "if", "(", "typeof", "this", ".", "options", ".", "selectAllValue", "===", "'number'", ")", "{", "this", ".", "options", ".", "selectAllValue", "=", "this", ".", "options", ".", "selectAllValue", ".", "toString", "(", ")", ";", "}", "var", "alreadyHasSelectAll", "=", "this", ".", "hasSelectAll", "(", ")", ";", "if", "(", "!", "alreadyHasSelectAll", "&&", "this", ".", "options", ".", "includeSelectAllOption", "&&", "this", ".", "options", ".", "multiple", "&&", "$", "(", "'option'", ",", "this", ".", "$select", ")", ".", "length", ">", "this", ".", "options", ".", "includeSelectAllIfMoreThan", ")", "{", "// Check whether to add a divider after the select all.", "if", "(", "this", ".", "options", ".", "includeSelectAllDivider", ")", "{", "this", ".", "$ul", ".", "prepend", "(", "$", "(", "this", ".", "options", ".", "templates", ".", "divider", ")", ")", ";", "}", "var", "$li", "=", "$", "(", "this", ".", "options", ".", "templates", ".", "li", ")", ";", "$", "(", "'label'", ",", "$li", ")", ".", "addClass", "(", "\"checkbox\"", ")", ";", "if", "(", "this", ".", "options", ".", "enableHTML", ")", "{", "$", "(", "'label'", ",", "$li", ")", ".", "html", "(", "\" \"", "+", "this", ".", "options", ".", "selectAllText", ")", ";", "}", "else", "{", "$", "(", "'label'", ",", "$li", ")", ".", "text", "(", "\" \"", "+", "this", ".", "options", ".", "selectAllText", ")", ";", "}", "if", "(", "this", ".", "options", ".", "selectAllName", ")", "{", "$", "(", "'label'", ",", "$li", ")", ".", "prepend", "(", "'<input type=\"checkbox\" name=\"'", "+", "this", ".", "options", ".", "selectAllName", "+", "'\" />'", ")", ";", "}", "else", "{", "$", "(", "'label'", ",", "$li", ")", ".", "prepend", "(", "'<input type=\"checkbox\" />'", ")", ";", "}", "var", "$checkbox", "=", "$", "(", "'input'", ",", "$li", ")", ";", "$checkbox", ".", "val", "(", "this", ".", "options", ".", "selectAllValue", ")", ";", "$li", ".", "addClass", "(", "\"multiselect-item multiselect-all\"", ")", ";", "$checkbox", ".", "parent", "(", ")", ".", "parent", "(", ")", ".", "addClass", "(", "'multiselect-all'", ")", ";", "this", ".", "$ul", ".", "prepend", "(", "$li", ")", ";", "$checkbox", ".", "prop", "(", "'checked'", ",", "false", ")", ";", "}", "}" ]
Build the selct all. Checks if a select all has already been created.
[ "Build", "the", "selct", "all", "." ]
4f9c24f054f604b165082bbe5b3b424ad042a729
https://github.com/hashchange/jquery.documentsize/blob/4f9c24f054f604b165082bbe5b3b424ad042a729/demo/load-event/js/libs/bootstrap-multiselect/bootstrap-multiselect.js#L778-L821
40,667
hashchange/jquery.documentsize
demo/load-event/js/libs/bootstrap-multiselect/bootstrap-multiselect.js
function (justVisible) { var justVisible = typeof justVisible === 'undefined' ? true : justVisible; if(justVisible) { var visibleCheckboxes = $("li input[type='checkbox']:not(:disabled)", this.$ul).filter(":visible"); visibleCheckboxes.prop('checked', false); var values = visibleCheckboxes.map(function() { return $(this).val(); }).get(); $("option:enabled", this.$select).filter(function(index) { return $.inArray($(this).val(), values) !== -1; }).prop('selected', false); if (this.options.selectedClass) { $("li:not(.divider):not(.disabled)", this.$ul).filter(":visible").removeClass(this.options.selectedClass); } } else { $("li input[type='checkbox']:enabled", this.$ul).prop('checked', false); $("option:enabled", this.$select).prop('selected', false); if (this.options.selectedClass) { $("li:not(.divider):not(.disabled)", this.$ul).removeClass(this.options.selectedClass); } } }
javascript
function (justVisible) { var justVisible = typeof justVisible === 'undefined' ? true : justVisible; if(justVisible) { var visibleCheckboxes = $("li input[type='checkbox']:not(:disabled)", this.$ul).filter(":visible"); visibleCheckboxes.prop('checked', false); var values = visibleCheckboxes.map(function() { return $(this).val(); }).get(); $("option:enabled", this.$select).filter(function(index) { return $.inArray($(this).val(), values) !== -1; }).prop('selected', false); if (this.options.selectedClass) { $("li:not(.divider):not(.disabled)", this.$ul).filter(":visible").removeClass(this.options.selectedClass); } } else { $("li input[type='checkbox']:enabled", this.$ul).prop('checked', false); $("option:enabled", this.$select).prop('selected', false); if (this.options.selectedClass) { $("li:not(.divider):not(.disabled)", this.$ul).removeClass(this.options.selectedClass); } } }
[ "function", "(", "justVisible", ")", "{", "var", "justVisible", "=", "typeof", "justVisible", "===", "'undefined'", "?", "true", ":", "justVisible", ";", "if", "(", "justVisible", ")", "{", "var", "visibleCheckboxes", "=", "$", "(", "\"li input[type='checkbox']:not(:disabled)\"", ",", "this", ".", "$ul", ")", ".", "filter", "(", "\":visible\"", ")", ";", "visibleCheckboxes", ".", "prop", "(", "'checked'", ",", "false", ")", ";", "var", "values", "=", "visibleCheckboxes", ".", "map", "(", "function", "(", ")", "{", "return", "$", "(", "this", ")", ".", "val", "(", ")", ";", "}", ")", ".", "get", "(", ")", ";", "$", "(", "\"option:enabled\"", ",", "this", ".", "$select", ")", ".", "filter", "(", "function", "(", "index", ")", "{", "return", "$", ".", "inArray", "(", "$", "(", "this", ")", ".", "val", "(", ")", ",", "values", ")", "!==", "-", "1", ";", "}", ")", ".", "prop", "(", "'selected'", ",", "false", ")", ";", "if", "(", "this", ".", "options", ".", "selectedClass", ")", "{", "$", "(", "\"li:not(.divider):not(.disabled)\"", ",", "this", ".", "$ul", ")", ".", "filter", "(", "\":visible\"", ")", ".", "removeClass", "(", "this", ".", "options", ".", "selectedClass", ")", ";", "}", "}", "else", "{", "$", "(", "\"li input[type='checkbox']:enabled\"", ",", "this", ".", "$ul", ")", ".", "prop", "(", "'checked'", ",", "false", ")", ";", "$", "(", "\"option:enabled\"", ",", "this", ".", "$select", ")", ".", "prop", "(", "'selected'", ",", "false", ")", ";", "if", "(", "this", ".", "options", ".", "selectedClass", ")", "{", "$", "(", "\"li:not(.divider):not(.disabled)\"", ",", "this", ".", "$ul", ")", ".", "removeClass", "(", "this", ".", "options", ".", "selectedClass", ")", ";", "}", "}", "}" ]
Deselects all options. If justVisible is true or not specified, only visible options are deselected. @param {Boolean} justVisible
[ "Deselects", "all", "options", "." ]
4f9c24f054f604b165082bbe5b3b424ad042a729
https://github.com/hashchange/jquery.documentsize/blob/4f9c24f054f604b165082bbe5b3b424ad042a729/demo/load-event/js/libs/bootstrap-multiselect/bootstrap-multiselect.js#L1130-L1157
40,668
hashchange/jquery.documentsize
demo/load-event/js/libs/bootstrap-multiselect/bootstrap-multiselect.js
function() { this.$ul.html(''); // Important to distinguish between radios and checkboxes. this.options.multiple = this.$select.attr('multiple') === "multiple"; this.buildSelectAll(); this.buildDropdownOptions(); this.buildFilter(); this.updateButtonText(); this.updateSelectAll(); if (this.options.disableIfEmpty && $('option', this.$select).length <= 0) { this.disable(); } else { this.enable(); } if (this.options.dropRight) { this.$ul.addClass('pull-right'); } }
javascript
function() { this.$ul.html(''); // Important to distinguish between radios and checkboxes. this.options.multiple = this.$select.attr('multiple') === "multiple"; this.buildSelectAll(); this.buildDropdownOptions(); this.buildFilter(); this.updateButtonText(); this.updateSelectAll(); if (this.options.disableIfEmpty && $('option', this.$select).length <= 0) { this.disable(); } else { this.enable(); } if (this.options.dropRight) { this.$ul.addClass('pull-right'); } }
[ "function", "(", ")", "{", "this", ".", "$ul", ".", "html", "(", "''", ")", ";", "// Important to distinguish between radios and checkboxes.", "this", ".", "options", ".", "multiple", "=", "this", ".", "$select", ".", "attr", "(", "'multiple'", ")", "===", "\"multiple\"", ";", "this", ".", "buildSelectAll", "(", ")", ";", "this", ".", "buildDropdownOptions", "(", ")", ";", "this", ".", "buildFilter", "(", ")", ";", "this", ".", "updateButtonText", "(", ")", ";", "this", ".", "updateSelectAll", "(", ")", ";", "if", "(", "this", ".", "options", ".", "disableIfEmpty", "&&", "$", "(", "'option'", ",", "this", ".", "$select", ")", ".", "length", "<=", "0", ")", "{", "this", ".", "disable", "(", ")", ";", "}", "else", "{", "this", ".", "enable", "(", ")", ";", "}", "if", "(", "this", ".", "options", ".", "dropRight", ")", "{", "this", ".", "$ul", ".", "addClass", "(", "'pull-right'", ")", ";", "}", "}" ]
Rebuild the plugin. Rebuilds the dropdown, the filter and the select all option.
[ "Rebuild", "the", "plugin", "." ]
4f9c24f054f604b165082bbe5b3b424ad042a729
https://github.com/hashchange/jquery.documentsize/blob/4f9c24f054f604b165082bbe5b3b424ad042a729/demo/load-event/js/libs/bootstrap-multiselect/bootstrap-multiselect.js#L1164-L1187
40,669
hashchange/jquery.documentsize
demo/load-event/js/libs/bootstrap-multiselect/bootstrap-multiselect.js
function() { if (this.hasSelectAll()) { var allBoxes = $("li:not(.multiselect-item):not(.filter-hidden) input:enabled", this.$ul); var allBoxesLength = allBoxes.length; var checkedBoxesLength = allBoxes.filter(":checked").length; var selectAllLi = $("li.multiselect-all", this.$ul); var selectAllInput = selectAllLi.find("input"); if (checkedBoxesLength > 0 && checkedBoxesLength === allBoxesLength) { selectAllInput.prop("checked", true); selectAllLi.addClass(this.options.selectedClass); this.options.onSelectAll(); } else { selectAllInput.prop("checked", false); selectAllLi.removeClass(this.options.selectedClass); } } }
javascript
function() { if (this.hasSelectAll()) { var allBoxes = $("li:not(.multiselect-item):not(.filter-hidden) input:enabled", this.$ul); var allBoxesLength = allBoxes.length; var checkedBoxesLength = allBoxes.filter(":checked").length; var selectAllLi = $("li.multiselect-all", this.$ul); var selectAllInput = selectAllLi.find("input"); if (checkedBoxesLength > 0 && checkedBoxesLength === allBoxesLength) { selectAllInput.prop("checked", true); selectAllLi.addClass(this.options.selectedClass); this.options.onSelectAll(); } else { selectAllInput.prop("checked", false); selectAllLi.removeClass(this.options.selectedClass); } } }
[ "function", "(", ")", "{", "if", "(", "this", ".", "hasSelectAll", "(", ")", ")", "{", "var", "allBoxes", "=", "$", "(", "\"li:not(.multiselect-item):not(.filter-hidden) input:enabled\"", ",", "this", ".", "$ul", ")", ";", "var", "allBoxesLength", "=", "allBoxes", ".", "length", ";", "var", "checkedBoxesLength", "=", "allBoxes", ".", "filter", "(", "\":checked\"", ")", ".", "length", ";", "var", "selectAllLi", "=", "$", "(", "\"li.multiselect-all\"", ",", "this", ".", "$ul", ")", ";", "var", "selectAllInput", "=", "selectAllLi", ".", "find", "(", "\"input\"", ")", ";", "if", "(", "checkedBoxesLength", ">", "0", "&&", "checkedBoxesLength", "===", "allBoxesLength", ")", "{", "selectAllInput", ".", "prop", "(", "\"checked\"", ",", "true", ")", ";", "selectAllLi", ".", "addClass", "(", "this", ".", "options", ".", "selectedClass", ")", ";", "this", ".", "options", ".", "onSelectAll", "(", ")", ";", "}", "else", "{", "selectAllInput", ".", "prop", "(", "\"checked\"", ",", "false", ")", ";", "selectAllLi", ".", "removeClass", "(", "this", ".", "options", ".", "selectedClass", ")", ";", "}", "}", "}" ]
Updates the select all checkbox based on the currently displayed and selected checkboxes.
[ "Updates", "the", "select", "all", "checkbox", "based", "on", "the", "currently", "displayed", "and", "selected", "checkboxes", "." ]
4f9c24f054f604b165082bbe5b3b424ad042a729
https://github.com/hashchange/jquery.documentsize/blob/4f9c24f054f604b165082bbe5b3b424ad042a729/demo/load-event/js/libs/bootstrap-multiselect/bootstrap-multiselect.js#L1283-L1301
40,670
hashchange/jquery.documentsize
demo/load-event/js/libs/detectizr/detectizr-2.2.0.js
extend
function extend(obj, extObj) { var a, b, i; if (arguments.length > 2) { for (a = 1, b = arguments.length; a < b; a += 1) { extend(obj, arguments[a]); } } else { for (i in extObj) { if (extObj.hasOwnProperty(i)) { obj[i] = extObj[i]; } } } return obj; }
javascript
function extend(obj, extObj) { var a, b, i; if (arguments.length > 2) { for (a = 1, b = arguments.length; a < b; a += 1) { extend(obj, arguments[a]); } } else { for (i in extObj) { if (extObj.hasOwnProperty(i)) { obj[i] = extObj[i]; } } } return obj; }
[ "function", "extend", "(", "obj", ",", "extObj", ")", "{", "var", "a", ",", "b", ",", "i", ";", "if", "(", "arguments", ".", "length", ">", "2", ")", "{", "for", "(", "a", "=", "1", ",", "b", "=", "arguments", ".", "length", ";", "a", "<", "b", ";", "a", "+=", "1", ")", "{", "extend", "(", "obj", ",", "arguments", "[", "a", "]", ")", ";", "}", "}", "else", "{", "for", "(", "i", "in", "extObj", ")", "{", "if", "(", "extObj", ".", "hasOwnProperty", "(", "i", ")", ")", "{", "obj", "[", "i", "]", "=", "extObj", "[", "i", "]", ";", "}", "}", "}", "return", "obj", ";", "}" ]
Create Global "extend" method, so Detectizr does not need jQuery.extend
[ "Create", "Global", "extend", "method", "so", "Detectizr", "does", "not", "need", "jQuery", ".", "extend" ]
4f9c24f054f604b165082bbe5b3b424ad042a729
https://github.com/hashchange/jquery.documentsize/blob/4f9c24f054f604b165082bbe5b3b424ad042a729/demo/load-event/js/libs/detectizr/detectizr-2.2.0.js#L59-L73
40,671
hashchange/jquery.documentsize
demo/load-event/js/libs/detectizr/detectizr-2.2.0.js
toCamel
function toCamel(string) { if (string === null || string === undefined) { return ""; } return String(string).replace(/((\s|\-|\.)+[a-z0-9])/g, function($1) { return $1.toUpperCase().replace(/(\s|\-|\.)/g, ""); }); }
javascript
function toCamel(string) { if (string === null || string === undefined) { return ""; } return String(string).replace(/((\s|\-|\.)+[a-z0-9])/g, function($1) { return $1.toUpperCase().replace(/(\s|\-|\.)/g, ""); }); }
[ "function", "toCamel", "(", "string", ")", "{", "if", "(", "string", "===", "null", "||", "string", "===", "undefined", ")", "{", "return", "\"\"", ";", "}", "return", "String", "(", "string", ")", ".", "replace", "(", "/", "((\\s|\\-|\\.)+[a-z0-9])", "/", "g", ",", "function", "(", "$1", ")", "{", "return", "$1", ".", "toUpperCase", "(", ")", ".", "replace", "(", "/", "(\\s|\\-|\\.)", "/", "g", ",", "\"\"", ")", ";", "}", ")", ";", "}" ]
convert string to camelcase
[ "convert", "string", "to", "camelcase" ]
4f9c24f054f604b165082bbe5b3b424ad042a729
https://github.com/hashchange/jquery.documentsize/blob/4f9c24f054f604b165082bbe5b3b424ad042a729/demo/load-event/js/libs/detectizr/detectizr-2.2.0.js#L96-L103
40,672
hashchange/jquery.documentsize
demo/load-event/js/libs/detectizr/detectizr-2.2.0.js
removeClass
function removeClass(element, value) { var class2remove = value || "", cur = element.nodeType === 1 && (element.className ? (" " + element.className + " ").replace(rclass, " ") : ""); if (cur) { while (cur.indexOf(" " + class2remove + " ") >= 0) { cur = cur.replace(" " + class2remove + " ", " "); } element.className = value ? trim(cur) : ""; } }
javascript
function removeClass(element, value) { var class2remove = value || "", cur = element.nodeType === 1 && (element.className ? (" " + element.className + " ").replace(rclass, " ") : ""); if (cur) { while (cur.indexOf(" " + class2remove + " ") >= 0) { cur = cur.replace(" " + class2remove + " ", " "); } element.className = value ? trim(cur) : ""; } }
[ "function", "removeClass", "(", "element", ",", "value", ")", "{", "var", "class2remove", "=", "value", "||", "\"\"", ",", "cur", "=", "element", ".", "nodeType", "===", "1", "&&", "(", "element", ".", "className", "?", "(", "\" \"", "+", "element", ".", "className", "+", "\" \"", ")", ".", "replace", "(", "rclass", ",", "\" \"", ")", ":", "\"\"", ")", ";", "if", "(", "cur", ")", "{", "while", "(", "cur", ".", "indexOf", "(", "\" \"", "+", "class2remove", "+", "\" \"", ")", ">=", "0", ")", "{", "cur", "=", "cur", ".", "replace", "(", "\" \"", "+", "class2remove", "+", "\" \"", ",", "\" \"", ")", ";", "}", "element", ".", "className", "=", "value", "?", "trim", "(", "cur", ")", ":", "\"\"", ";", "}", "}" ]
removeClass function inspired from jQuery.removeClass
[ "removeClass", "function", "inspired", "from", "jQuery", ".", "removeClass" ]
4f9c24f054f604b165082bbe5b3b424ad042a729
https://github.com/hashchange/jquery.documentsize/blob/4f9c24f054f604b165082bbe5b3b424ad042a729/demo/load-event/js/libs/detectizr/detectizr-2.2.0.js#L106-L115
40,673
hashchange/jquery.documentsize
demo/load-event/js/libs/detectizr/detectizr-2.2.0.js
setVersion
function setVersion(versionType, versionFull) { versionType.version = versionFull; var versionArray = versionFull.split("."); if (versionArray.length > 0) { versionArray = versionArray.reverse(); versionType.major = versionArray.pop(); if (versionArray.length > 0) { versionType.minor = versionArray.pop(); if (versionArray.length > 0) { versionArray = versionArray.reverse(); versionType.patch = versionArray.join("."); } else { versionType.patch = "0"; } } else { versionType.minor = "0"; } } else { versionType.major = "0"; } }
javascript
function setVersion(versionType, versionFull) { versionType.version = versionFull; var versionArray = versionFull.split("."); if (versionArray.length > 0) { versionArray = versionArray.reverse(); versionType.major = versionArray.pop(); if (versionArray.length > 0) { versionType.minor = versionArray.pop(); if (versionArray.length > 0) { versionArray = versionArray.reverse(); versionType.patch = versionArray.join("."); } else { versionType.patch = "0"; } } else { versionType.minor = "0"; } } else { versionType.major = "0"; } }
[ "function", "setVersion", "(", "versionType", ",", "versionFull", ")", "{", "versionType", ".", "version", "=", "versionFull", ";", "var", "versionArray", "=", "versionFull", ".", "split", "(", "\".\"", ")", ";", "if", "(", "versionArray", ".", "length", ">", "0", ")", "{", "versionArray", "=", "versionArray", ".", "reverse", "(", ")", ";", "versionType", ".", "major", "=", "versionArray", ".", "pop", "(", ")", ";", "if", "(", "versionArray", ".", "length", ">", "0", ")", "{", "versionType", ".", "minor", "=", "versionArray", ".", "pop", "(", ")", ";", "if", "(", "versionArray", ".", "length", ">", "0", ")", "{", "versionArray", "=", "versionArray", ".", "reverse", "(", ")", ";", "versionType", ".", "patch", "=", "versionArray", ".", "join", "(", "\".\"", ")", ";", "}", "else", "{", "versionType", ".", "patch", "=", "\"0\"", ";", "}", "}", "else", "{", "versionType", ".", "minor", "=", "\"0\"", ";", "}", "}", "else", "{", "versionType", ".", "major", "=", "\"0\"", ";", "}", "}" ]
set version based on versionFull
[ "set", "version", "based", "on", "versionFull" ]
4f9c24f054f604b165082bbe5b3b424ad042a729
https://github.com/hashchange/jquery.documentsize/blob/4f9c24f054f604b165082bbe5b3b424ad042a729/demo/load-event/js/libs/detectizr/detectizr-2.2.0.js#L149-L169
40,674
hashchange/jquery.documentsize
spec/helpers/measurement.js
getBoundingClientRectCompat
function getBoundingClientRectCompat ( elem ) { var elemRect = elem.getBoundingClientRect(); if ( elemRect.width === undefined || elemRect.height === undefined ) { // Fix for IE8 elemRect = { top: elemRect.top, left: elemRect.left, bottom: elemRect.bottom, right: elemRect.right, width: elemRect.right - elemRect.left, height: elemRect.bottom - elemRect.top }; } return elemRect; }
javascript
function getBoundingClientRectCompat ( elem ) { var elemRect = elem.getBoundingClientRect(); if ( elemRect.width === undefined || elemRect.height === undefined ) { // Fix for IE8 elemRect = { top: elemRect.top, left: elemRect.left, bottom: elemRect.bottom, right: elemRect.right, width: elemRect.right - elemRect.left, height: elemRect.bottom - elemRect.top }; } return elemRect; }
[ "function", "getBoundingClientRectCompat", "(", "elem", ")", "{", "var", "elemRect", "=", "elem", ".", "getBoundingClientRect", "(", ")", ";", "if", "(", "elemRect", ".", "width", "===", "undefined", "||", "elemRect", ".", "height", "===", "undefined", ")", "{", "// Fix for IE8", "elemRect", "=", "{", "top", ":", "elemRect", ".", "top", ",", "left", ":", "elemRect", ".", "left", ",", "bottom", ":", "elemRect", ".", "bottom", ",", "right", ":", "elemRect", ".", "right", ",", "width", ":", "elemRect", ".", "right", "-", "elemRect", ".", "left", ",", "height", ":", "elemRect", ".", "bottom", "-", "elemRect", ".", "top", "}", ";", "}", "return", "elemRect", ";", "}" ]
Returns the bounding client rect, including width and height properties. For compatibility with IE8, which supports getBoundingClientRect but doesn't calculate width and height. Use only when width and height are actually needed. Will be removed when IE8 support is dropped entirely. @param {HTMLElement} elem @returns {ClientRect}
[ "Returns", "the", "bounding", "client", "rect", "including", "width", "and", "height", "properties", ".", "For", "compatibility", "with", "IE8", "which", "supports", "getBoundingClientRect", "but", "doesn", "t", "calculate", "width", "and", "height", "." ]
4f9c24f054f604b165082bbe5b3b424ad042a729
https://github.com/hashchange/jquery.documentsize/blob/4f9c24f054f604b165082bbe5b3b424ad042a729/spec/helpers/measurement.js#L152-L168
40,675
hashchange/jquery.documentsize
spec/helpers/measurement.js
getAppliedOverflows
function getAppliedOverflows ( props, createBooleans ) { var status = {}; // Establish the applied overflow (e.g. overflowX: "scroll") status.overflowX = props.overflowX || props.overflow || "visible"; status.overflowY = props.overflowY || props.overflow || "visible"; // Create the derived boolean status properties (e.g overflowScrollX: true) if ( createBooleans ) { $.each( [ "Visible", "Auto", "Scroll", "Hidden" ], function ( index, type ) { var lcType = type.toLowerCase(); status["overflow" + type + "X"] = status.overflowX === lcType; status["overflow" + type + "Y"] = status.overflowY === lcType; } ); } return status; }
javascript
function getAppliedOverflows ( props, createBooleans ) { var status = {}; // Establish the applied overflow (e.g. overflowX: "scroll") status.overflowX = props.overflowX || props.overflow || "visible"; status.overflowY = props.overflowY || props.overflow || "visible"; // Create the derived boolean status properties (e.g overflowScrollX: true) if ( createBooleans ) { $.each( [ "Visible", "Auto", "Scroll", "Hidden" ], function ( index, type ) { var lcType = type.toLowerCase(); status["overflow" + type + "X"] = status.overflowX === lcType; status["overflow" + type + "Y"] = status.overflowY === lcType; } ); } return status; }
[ "function", "getAppliedOverflows", "(", "props", ",", "createBooleans", ")", "{", "var", "status", "=", "{", "}", ";", "// Establish the applied overflow (e.g. overflowX: \"scroll\")", "status", ".", "overflowX", "=", "props", ".", "overflowX", "||", "props", ".", "overflow", "||", "\"visible\"", ";", "status", ".", "overflowY", "=", "props", ".", "overflowY", "||", "props", ".", "overflow", "||", "\"visible\"", ";", "// Create the derived boolean status properties (e.g overflowScrollX: true)", "if", "(", "createBooleans", ")", "{", "$", ".", "each", "(", "[", "\"Visible\"", ",", "\"Auto\"", ",", "\"Scroll\"", ",", "\"Hidden\"", "]", ",", "function", "(", "index", ",", "type", ")", "{", "var", "lcType", "=", "type", ".", "toLowerCase", "(", ")", ";", "status", "[", "\"overflow\"", "+", "type", "+", "\"X\"", "]", "=", "status", ".", "overflowX", "===", "lcType", ";", "status", "[", "\"overflow\"", "+", "type", "+", "\"Y\"", "]", "=", "status", ".", "overflowY", "===", "lcType", ";", "}", ")", ";", "}", "return", "status", ";", "}" ]
Determines the effective overflow setting of an element, separately for each axis, based on the `overflow`, `overflowX` and `overflowY` properties of the element which must be passed in as a hash. Returns a hash of the computed results for overflowX, overflowY. Also adds boolean status properties to the hash if the createBooleans flag is set. These are properties for mere convenience. They signal if a particular overflow type applies (e.g. overflowHiddenX = true/false). ATTN The method does not take the special relation of body and documentElement into account. That is handled by the more specific getAppliedViewportOverflows() function. The effective overflow setting is established as follows: - If a computed value for `overflow(X/Y)` exists, it gets applied to the axis. - If not, the computed value of the general `overflow` setting gets applied to the axis. - If there is no computed value at all, the overflow default gets applied to the axis. The default is "visible" in seemingly every browser out there. Falling back to the default should never be necessary, though, because there always is a computed value. @param {Object} props hash of element properties (computed values) @param {string} props.overflow @param {string} props.overflowX @param {string} props.overflowY @param {boolean=false} createBooleans if true, create the full set of boolean status properties, e.g. overflowVisibleX (true/false), overflowHiddenY (true/false) etc @returns {AppliedOverflow} hash of the computed results: overflowX, overflowY, optional boolean status properties
[ "Determines", "the", "effective", "overflow", "setting", "of", "an", "element", "separately", "for", "each", "axis", "based", "on", "the", "overflow", "overflowX", "and", "overflowY", "properties", "of", "the", "element", "which", "must", "be", "passed", "in", "as", "a", "hash", "." ]
4f9c24f054f604b165082bbe5b3b424ad042a729
https://github.com/hashchange/jquery.documentsize/blob/4f9c24f054f604b165082bbe5b3b424ad042a729/spec/helpers/measurement.js#L198-L215
40,676
hashchange/jquery.documentsize
spec/helpers/measurement.js
getAppliedViewportOverflows
function getAppliedViewportOverflows ( documentElementProps, bodyProps ) { var _window = getAppliedOverflows( documentElementProps, false ), body = getAppliedOverflows( bodyProps, false ), consolidated = { window: {}, body: {} }; // Handle the interdependent relation between body and window (documentElement) overflow if ( _window.overflowX === "visible" ) { // If the window overflow is set to "visible", body props get transferred to the window, body changes to // "visible". (Nothing really changes if both are set to "visible".) consolidated.body.overflowX = "visible"; consolidated.window.overflowX = body.overflowX; } else { // No transfer of properties. // - If body overflow is "visible", it remains that way, and the window stays as it is. // - If body and window are set to properties other than "visible", they keep their divergent settings. consolidated.body.overflowX = body.overflowX; consolidated.window.overflowX = _window.overflowX; } // Repeat for overflowY if ( _window.overflowY === "visible" ) { consolidated.body.overflowY = "visible"; consolidated.window.overflowY = body.overflowY; } else { consolidated.body.overflowY = body.overflowY; consolidated.window.overflowY = _window.overflowY; } // window.overflow(X/Y): "visible" actually means "auto" because scroll bars appear as needed; transform if ( consolidated.window.overflowX === "visible" ) consolidated.window.overflowX = "auto"; if ( consolidated.window.overflowY === "visible" ) consolidated.window.overflowY = "auto"; // In iOS, window.overflow(X/Y): "hidden" actually means "auto"; transform if ( isIOS() ) { if ( consolidated.window.overflowX === "hidden" ) consolidated.window.overflowX = "auto"; if ( consolidated.window.overflowY === "hidden" ) consolidated.window.overflowY = "auto"; } // Add the boolean status properties to the result consolidated.window = getAppliedOverflows( consolidated.window, true ); consolidated.body = getAppliedOverflows( consolidated.body, true ); return consolidated; }
javascript
function getAppliedViewportOverflows ( documentElementProps, bodyProps ) { var _window = getAppliedOverflows( documentElementProps, false ), body = getAppliedOverflows( bodyProps, false ), consolidated = { window: {}, body: {} }; // Handle the interdependent relation between body and window (documentElement) overflow if ( _window.overflowX === "visible" ) { // If the window overflow is set to "visible", body props get transferred to the window, body changes to // "visible". (Nothing really changes if both are set to "visible".) consolidated.body.overflowX = "visible"; consolidated.window.overflowX = body.overflowX; } else { // No transfer of properties. // - If body overflow is "visible", it remains that way, and the window stays as it is. // - If body and window are set to properties other than "visible", they keep their divergent settings. consolidated.body.overflowX = body.overflowX; consolidated.window.overflowX = _window.overflowX; } // Repeat for overflowY if ( _window.overflowY === "visible" ) { consolidated.body.overflowY = "visible"; consolidated.window.overflowY = body.overflowY; } else { consolidated.body.overflowY = body.overflowY; consolidated.window.overflowY = _window.overflowY; } // window.overflow(X/Y): "visible" actually means "auto" because scroll bars appear as needed; transform if ( consolidated.window.overflowX === "visible" ) consolidated.window.overflowX = "auto"; if ( consolidated.window.overflowY === "visible" ) consolidated.window.overflowY = "auto"; // In iOS, window.overflow(X/Y): "hidden" actually means "auto"; transform if ( isIOS() ) { if ( consolidated.window.overflowX === "hidden" ) consolidated.window.overflowX = "auto"; if ( consolidated.window.overflowY === "hidden" ) consolidated.window.overflowY = "auto"; } // Add the boolean status properties to the result consolidated.window = getAppliedOverflows( consolidated.window, true ); consolidated.body = getAppliedOverflows( consolidated.body, true ); return consolidated; }
[ "function", "getAppliedViewportOverflows", "(", "documentElementProps", ",", "bodyProps", ")", "{", "var", "_window", "=", "getAppliedOverflows", "(", "documentElementProps", ",", "false", ")", ",", "body", "=", "getAppliedOverflows", "(", "bodyProps", ",", "false", ")", ",", "consolidated", "=", "{", "window", ":", "{", "}", ",", "body", ":", "{", "}", "}", ";", "// Handle the interdependent relation between body and window (documentElement) overflow", "if", "(", "_window", ".", "overflowX", "===", "\"visible\"", ")", "{", "// If the window overflow is set to \"visible\", body props get transferred to the window, body changes to", "// \"visible\". (Nothing really changes if both are set to \"visible\".)", "consolidated", ".", "body", ".", "overflowX", "=", "\"visible\"", ";", "consolidated", ".", "window", ".", "overflowX", "=", "body", ".", "overflowX", ";", "}", "else", "{", "// No transfer of properties.", "// - If body overflow is \"visible\", it remains that way, and the window stays as it is.", "// - If body and window are set to properties other than \"visible\", they keep their divergent settings.", "consolidated", ".", "body", ".", "overflowX", "=", "body", ".", "overflowX", ";", "consolidated", ".", "window", ".", "overflowX", "=", "_window", ".", "overflowX", ";", "}", "// Repeat for overflowY", "if", "(", "_window", ".", "overflowY", "===", "\"visible\"", ")", "{", "consolidated", ".", "body", ".", "overflowY", "=", "\"visible\"", ";", "consolidated", ".", "window", ".", "overflowY", "=", "body", ".", "overflowY", ";", "}", "else", "{", "consolidated", ".", "body", ".", "overflowY", "=", "body", ".", "overflowY", ";", "consolidated", ".", "window", ".", "overflowY", "=", "_window", ".", "overflowY", ";", "}", "// window.overflow(X/Y): \"visible\" actually means \"auto\" because scroll bars appear as needed; transform", "if", "(", "consolidated", ".", "window", ".", "overflowX", "===", "\"visible\"", ")", "consolidated", ".", "window", ".", "overflowX", "=", "\"auto\"", ";", "if", "(", "consolidated", ".", "window", ".", "overflowY", "===", "\"visible\"", ")", "consolidated", ".", "window", ".", "overflowY", "=", "\"auto\"", ";", "// In iOS, window.overflow(X/Y): \"hidden\" actually means \"auto\"; transform", "if", "(", "isIOS", "(", ")", ")", "{", "if", "(", "consolidated", ".", "window", ".", "overflowX", "===", "\"hidden\"", ")", "consolidated", ".", "window", ".", "overflowX", "=", "\"auto\"", ";", "if", "(", "consolidated", ".", "window", ".", "overflowY", "===", "\"hidden\"", ")", "consolidated", ".", "window", ".", "overflowY", "=", "\"auto\"", ";", "}", "// Add the boolean status properties to the result", "consolidated", ".", "window", "=", "getAppliedOverflows", "(", "consolidated", ".", "window", ",", "true", ")", ";", "consolidated", ".", "body", "=", "getAppliedOverflows", "(", "consolidated", ".", "body", ",", "true", ")", ";", "return", "consolidated", ";", "}" ]
Determines the effective overflow setting of the viewport and body, separately for each axis, based on the `overflow`, `overflowX` and `overflowY` properties of the documentElement and body which must be passed in as a hash. Returns the results for viewport and body in an aggregated `{ window: ..., body: ...}` hash. For the basic resolution mechanism, see getAppliedOverflows(). When determining the effective overflow, the peculiarities of viewport and body are taken into account: - Viewport and body overflows are interdependent. If the nominal viewport overflow for a given axis is "visible", the viewport inherits the body overflow for that axis, and the body overflow is set to "visible". Curiously, that transfer is _not_ reflected in the computed values, it just manifests in behaviour. - Once that is done, if the viewport overflow is still "visible" for an axis, it is effectively turned into "auto". Scroll bars appear when the content overflows the viewport (ie, "auto" behaviour). Hence, this function will indeed report "auto". Again, the transformation is only manifest in behaviour, not in the computed values. - In iOS, if the effective overflow setting of the viewport is "hidden", it is ignored and treated as "auto". Content can still overflow the viewport, and scroll bars appear as needed. Now, the catch. This behaviour is impossible to feature-detect. The computed values are not at all affected by it, and the results reported eg. for clientHeight, offsetHeight, scrollHeight of body and documentElement do not differ between Safari on iOS and, say, Chrome. The numbers don't give the behaviour away. So we have to resort to browser sniffing here. It sucks, but there is literally no other option. NB Additional status properties (see getAppliedOverflows) are always generated here. @param {Object} documentElementProps hash of documentElement properties (computed values) @param {string} documentElementProps.overflow @param {string} documentElementProps.overflowX @param {string} documentElementProps.overflowY @param {Object} bodyProps hash of body properties (computed values) @param {string} bodyProps.overflow @param {string} bodyProps.overflowX @param {string} bodyProps.overflowY @returns {{window: AppliedOverflow, body: AppliedOverflow}}
[ "Determines", "the", "effective", "overflow", "setting", "of", "the", "viewport", "and", "body", "separately", "for", "each", "axis", "based", "on", "the", "overflow", "overflowX", "and", "overflowY", "properties", "of", "the", "documentElement", "and", "body", "which", "must", "be", "passed", "in", "as", "a", "hash", "." ]
4f9c24f054f604b165082bbe5b3b424ad042a729
https://github.com/hashchange/jquery.documentsize/blob/4f9c24f054f604b165082bbe5b3b424ad042a729/spec/helpers/measurement.js#L258-L301
40,677
hashchange/jquery.documentsize
demo/amd/amd.js
scaleLog
function scaleLog () { var zoomFactor = $.pinchZoomFactor(), logProps = { top: ( initialLogProps.top / zoomFactor ) + "px", left: ( initialLogProps.left / zoomFactor ) + "px", paddingTop: ( initialLogProps.paddingTop / zoomFactor ) + "px", paddingLeft: ( initialLogProps.paddingLeft / zoomFactor ) + "px", paddingBottom: ( initialLogProps.paddingBottom / zoomFactor ) + "px", paddingRight: ( initialLogProps.paddingRight / zoomFactor ) + "px", minWidth: ( initialLogProps.minWidth / zoomFactor ) + "px", maxWidth: ( initialLogProps.maxWidth / zoomFactor ) + "px" }, dtProps = { fontSize: ( initialLogProps.dtFontSize / zoomFactor ) + "px", lineHeight: ( initialLogProps.dtLineHeight / zoomFactor ) + "px", minWidth: ( initialLogProps.dtMinWidth / zoomFactor ) + "px" }, ddProps = { fontSize: ( initialLogProps.ddFontSize / zoomFactor ) + "px", lineHeight: ( initialLogProps.ddLineHeight / zoomFactor ) + "px" }, dlProps = { fontSize: ( initialLogProps.dlFontSize / zoomFactor ) + "px", lineHeight: ( initialLogProps.dlLineHeight / zoomFactor ) + "px", marginBottom: ( initialLogProps.dlMarginBottom / zoomFactor ) + "px" }, hrProps = { marginTop: ( initialLogProps.hrMarginTop / zoomFactor ) + "px", marginBottom: ( initialLogProps.hrMarginBottom / zoomFactor ) + "px" }; $logPane.css( logProps ); $( "dt", $logPane ).css( dtProps ); $( "dd", $logPane ).css( ddProps ); $( "dl", $logPane ).css( dlProps ); $( "hr", $logPane ).css( hrProps ); }
javascript
function scaleLog () { var zoomFactor = $.pinchZoomFactor(), logProps = { top: ( initialLogProps.top / zoomFactor ) + "px", left: ( initialLogProps.left / zoomFactor ) + "px", paddingTop: ( initialLogProps.paddingTop / zoomFactor ) + "px", paddingLeft: ( initialLogProps.paddingLeft / zoomFactor ) + "px", paddingBottom: ( initialLogProps.paddingBottom / zoomFactor ) + "px", paddingRight: ( initialLogProps.paddingRight / zoomFactor ) + "px", minWidth: ( initialLogProps.minWidth / zoomFactor ) + "px", maxWidth: ( initialLogProps.maxWidth / zoomFactor ) + "px" }, dtProps = { fontSize: ( initialLogProps.dtFontSize / zoomFactor ) + "px", lineHeight: ( initialLogProps.dtLineHeight / zoomFactor ) + "px", minWidth: ( initialLogProps.dtMinWidth / zoomFactor ) + "px" }, ddProps = { fontSize: ( initialLogProps.ddFontSize / zoomFactor ) + "px", lineHeight: ( initialLogProps.ddLineHeight / zoomFactor ) + "px" }, dlProps = { fontSize: ( initialLogProps.dlFontSize / zoomFactor ) + "px", lineHeight: ( initialLogProps.dlLineHeight / zoomFactor ) + "px", marginBottom: ( initialLogProps.dlMarginBottom / zoomFactor ) + "px" }, hrProps = { marginTop: ( initialLogProps.hrMarginTop / zoomFactor ) + "px", marginBottom: ( initialLogProps.hrMarginBottom / zoomFactor ) + "px" }; $logPane.css( logProps ); $( "dt", $logPane ).css( dtProps ); $( "dd", $logPane ).css( ddProps ); $( "dl", $logPane ).css( dlProps ); $( "hr", $logPane ).css( hrProps ); }
[ "function", "scaleLog", "(", ")", "{", "var", "zoomFactor", "=", "$", ".", "pinchZoomFactor", "(", ")", ",", "logProps", "=", "{", "top", ":", "(", "initialLogProps", ".", "top", "/", "zoomFactor", ")", "+", "\"px\"", ",", "left", ":", "(", "initialLogProps", ".", "left", "/", "zoomFactor", ")", "+", "\"px\"", ",", "paddingTop", ":", "(", "initialLogProps", ".", "paddingTop", "/", "zoomFactor", ")", "+", "\"px\"", ",", "paddingLeft", ":", "(", "initialLogProps", ".", "paddingLeft", "/", "zoomFactor", ")", "+", "\"px\"", ",", "paddingBottom", ":", "(", "initialLogProps", ".", "paddingBottom", "/", "zoomFactor", ")", "+", "\"px\"", ",", "paddingRight", ":", "(", "initialLogProps", ".", "paddingRight", "/", "zoomFactor", ")", "+", "\"px\"", ",", "minWidth", ":", "(", "initialLogProps", ".", "minWidth", "/", "zoomFactor", ")", "+", "\"px\"", ",", "maxWidth", ":", "(", "initialLogProps", ".", "maxWidth", "/", "zoomFactor", ")", "+", "\"px\"", "}", ",", "dtProps", "=", "{", "fontSize", ":", "(", "initialLogProps", ".", "dtFontSize", "/", "zoomFactor", ")", "+", "\"px\"", ",", "lineHeight", ":", "(", "initialLogProps", ".", "dtLineHeight", "/", "zoomFactor", ")", "+", "\"px\"", ",", "minWidth", ":", "(", "initialLogProps", ".", "dtMinWidth", "/", "zoomFactor", ")", "+", "\"px\"", "}", ",", "ddProps", "=", "{", "fontSize", ":", "(", "initialLogProps", ".", "ddFontSize", "/", "zoomFactor", ")", "+", "\"px\"", ",", "lineHeight", ":", "(", "initialLogProps", ".", "ddLineHeight", "/", "zoomFactor", ")", "+", "\"px\"", "}", ",", "dlProps", "=", "{", "fontSize", ":", "(", "initialLogProps", ".", "dlFontSize", "/", "zoomFactor", ")", "+", "\"px\"", ",", "lineHeight", ":", "(", "initialLogProps", ".", "dlLineHeight", "/", "zoomFactor", ")", "+", "\"px\"", ",", "marginBottom", ":", "(", "initialLogProps", ".", "dlMarginBottom", "/", "zoomFactor", ")", "+", "\"px\"", "}", ",", "hrProps", "=", "{", "marginTop", ":", "(", "initialLogProps", ".", "hrMarginTop", "/", "zoomFactor", ")", "+", "\"px\"", ",", "marginBottom", ":", "(", "initialLogProps", ".", "hrMarginBottom", "/", "zoomFactor", ")", "+", "\"px\"", "}", ";", "$logPane", ".", "css", "(", "logProps", ")", ";", "$", "(", "\"dt\"", ",", "$logPane", ")", ".", "css", "(", "dtProps", ")", ";", "$", "(", "\"dd\"", ",", "$logPane", ")", ".", "css", "(", "ddProps", ")", ";", "$", "(", "\"dl\"", ",", "$logPane", ")", ".", "css", "(", "dlProps", ")", ";", "$", "(", "\"hr\"", ",", "$logPane", ")", ".", "css", "(", "hrProps", ")", ";", "}" ]
Makes sure the log always keeps the same size, visually, as the user zooms in and out
[ "Makes", "sure", "the", "log", "always", "keeps", "the", "same", "size", "visually", "as", "the", "user", "zooms", "in", "and", "out" ]
4f9c24f054f604b165082bbe5b3b424ad042a729
https://github.com/hashchange/jquery.documentsize/blob/4f9c24f054f604b165082bbe5b3b424ad042a729/demo/amd/amd.js#L106-L145
40,678
hashchange/jquery.documentsize
demo/load-event/js/libs/modernizr/modernizr-custom.js
injectElementWithStyles
function injectElementWithStyles(rule, callback, nodes, testnames) { var mod = 'modernizr'; var style; var ret; var node; var docOverflow; var div = createElement('div'); var body = getBody(); if (parseInt(nodes, 10)) { // In order not to give false positives we create a node for each test // This also allows the method to scale for unspecified uses while (nodes--) { node = createElement('div'); node.id = testnames ? testnames[nodes] : mod + (nodes + 1); div.appendChild(node); } } style = createElement('style'); style.type = 'text/css'; style.id = 's' + mod; // IE6 will false positive on some tests due to the style element inside the test div somehow interfering offsetHeight, so insert it into body or fakebody. // Opera will act all quirky when injecting elements in documentElement when page is served as xml, needs fakebody too. #270 (!body.fake ? div : body).appendChild(style); body.appendChild(div); if (style.styleSheet) { style.styleSheet.cssText = rule; } else { style.appendChild(document.createTextNode(rule)); } div.id = mod; if (body.fake) { //avoid crashing IE8, if background image is used body.style.background = ''; //Safari 5.13/5.1.4 OSX stops loading if ::-webkit-scrollbar is used and scrollbars are visible body.style.overflow = 'hidden'; docOverflow = docElement.style.overflow; docElement.style.overflow = 'hidden'; docElement.appendChild(body); } ret = callback(div, rule); // If this is done after page load we don't want to remove the body so check if body exists if (body.fake) { body.parentNode.removeChild(body); docElement.style.overflow = docOverflow; // Trigger layout so kinetic scrolling isn't disabled in iOS6+ docElement.offsetHeight; } else { div.parentNode.removeChild(div); } return !!ret; }
javascript
function injectElementWithStyles(rule, callback, nodes, testnames) { var mod = 'modernizr'; var style; var ret; var node; var docOverflow; var div = createElement('div'); var body = getBody(); if (parseInt(nodes, 10)) { // In order not to give false positives we create a node for each test // This also allows the method to scale for unspecified uses while (nodes--) { node = createElement('div'); node.id = testnames ? testnames[nodes] : mod + (nodes + 1); div.appendChild(node); } } style = createElement('style'); style.type = 'text/css'; style.id = 's' + mod; // IE6 will false positive on some tests due to the style element inside the test div somehow interfering offsetHeight, so insert it into body or fakebody. // Opera will act all quirky when injecting elements in documentElement when page is served as xml, needs fakebody too. #270 (!body.fake ? div : body).appendChild(style); body.appendChild(div); if (style.styleSheet) { style.styleSheet.cssText = rule; } else { style.appendChild(document.createTextNode(rule)); } div.id = mod; if (body.fake) { //avoid crashing IE8, if background image is used body.style.background = ''; //Safari 5.13/5.1.4 OSX stops loading if ::-webkit-scrollbar is used and scrollbars are visible body.style.overflow = 'hidden'; docOverflow = docElement.style.overflow; docElement.style.overflow = 'hidden'; docElement.appendChild(body); } ret = callback(div, rule); // If this is done after page load we don't want to remove the body so check if body exists if (body.fake) { body.parentNode.removeChild(body); docElement.style.overflow = docOverflow; // Trigger layout so kinetic scrolling isn't disabled in iOS6+ docElement.offsetHeight; } else { div.parentNode.removeChild(div); } return !!ret; }
[ "function", "injectElementWithStyles", "(", "rule", ",", "callback", ",", "nodes", ",", "testnames", ")", "{", "var", "mod", "=", "'modernizr'", ";", "var", "style", ";", "var", "ret", ";", "var", "node", ";", "var", "docOverflow", ";", "var", "div", "=", "createElement", "(", "'div'", ")", ";", "var", "body", "=", "getBody", "(", ")", ";", "if", "(", "parseInt", "(", "nodes", ",", "10", ")", ")", "{", "// In order not to give false positives we create a node for each test", "// This also allows the method to scale for unspecified uses", "while", "(", "nodes", "--", ")", "{", "node", "=", "createElement", "(", "'div'", ")", ";", "node", ".", "id", "=", "testnames", "?", "testnames", "[", "nodes", "]", ":", "mod", "+", "(", "nodes", "+", "1", ")", ";", "div", ".", "appendChild", "(", "node", ")", ";", "}", "}", "style", "=", "createElement", "(", "'style'", ")", ";", "style", ".", "type", "=", "'text/css'", ";", "style", ".", "id", "=", "'s'", "+", "mod", ";", "// IE6 will false positive on some tests due to the style element inside the test div somehow interfering offsetHeight, so insert it into body or fakebody.", "// Opera will act all quirky when injecting elements in documentElement when page is served as xml, needs fakebody too. #270", "(", "!", "body", ".", "fake", "?", "div", ":", "body", ")", ".", "appendChild", "(", "style", ")", ";", "body", ".", "appendChild", "(", "div", ")", ";", "if", "(", "style", ".", "styleSheet", ")", "{", "style", ".", "styleSheet", ".", "cssText", "=", "rule", ";", "}", "else", "{", "style", ".", "appendChild", "(", "document", ".", "createTextNode", "(", "rule", ")", ")", ";", "}", "div", ".", "id", "=", "mod", ";", "if", "(", "body", ".", "fake", ")", "{", "//avoid crashing IE8, if background image is used", "body", ".", "style", ".", "background", "=", "''", ";", "//Safari 5.13/5.1.4 OSX stops loading if ::-webkit-scrollbar is used and scrollbars are visible", "body", ".", "style", ".", "overflow", "=", "'hidden'", ";", "docOverflow", "=", "docElement", ".", "style", ".", "overflow", ";", "docElement", ".", "style", ".", "overflow", "=", "'hidden'", ";", "docElement", ".", "appendChild", "(", "body", ")", ";", "}", "ret", "=", "callback", "(", "div", ",", "rule", ")", ";", "// If this is done after page load we don't want to remove the body so check if body exists", "if", "(", "body", ".", "fake", ")", "{", "body", ".", "parentNode", ".", "removeChild", "(", "body", ")", ";", "docElement", ".", "style", ".", "overflow", "=", "docOverflow", ";", "// Trigger layout so kinetic scrolling isn't disabled in iOS6+", "docElement", ".", "offsetHeight", ";", "}", "else", "{", "div", ".", "parentNode", ".", "removeChild", "(", "div", ")", ";", "}", "return", "!", "!", "ret", ";", "}" ]
injectElementWithStyles injects an element with style element and some CSS rules @access private @function injectElementWithStyles @param {string} rule - String representing a css rule @param {function} callback - A function that is used to test the injected element @param {number} [nodes] - An integer representing the number of additional nodes you want injected @param {string[]} [testnames] - An array of strings that are used as ids for the additional nodes @returns {boolean}
[ "injectElementWithStyles", "injects", "an", "element", "with", "style", "element", "and", "some", "CSS", "rules" ]
4f9c24f054f604b165082bbe5b3b424ad042a729
https://github.com/hashchange/jquery.documentsize/blob/4f9c24f054f604b165082bbe5b3b424ad042a729/demo/load-event/js/libs/modernizr/modernizr-custom.js#L770-L828
40,679
hashchange/jquery.documentsize
demo/load-event/custom.js
htmlAsEntities
function htmlAsEntities(html){ html = html.replace(/&/g, '&amp;'); html = html.replace(/>/g, '&gt;'); html = html.replace(/</g, '&lt;'); html = html.replace(/"/g, '&quot;'); html = html.replace(/'/g, '&#039;'); return html; }
javascript
function htmlAsEntities(html){ html = html.replace(/&/g, '&amp;'); html = html.replace(/>/g, '&gt;'); html = html.replace(/</g, '&lt;'); html = html.replace(/"/g, '&quot;'); html = html.replace(/'/g, '&#039;'); return html; }
[ "function", "htmlAsEntities", "(", "html", ")", "{", "html", "=", "html", ".", "replace", "(", "/", "&", "/", "g", ",", "'&amp;'", ")", ";", "html", "=", "html", ".", "replace", "(", "/", ">", "/", "g", ",", "'&gt;'", ")", ";", "html", "=", "html", ".", "replace", "(", "/", "<", "/", "g", ",", "'&lt;'", ")", ";", "html", "=", "html", ".", "replace", "(", "/", "\"", "/", "g", ",", "'&quot;'", ")", ";", "html", "=", "html", ".", "replace", "(", "/", "'", "/", "g", ",", "'&#039;'", ")", ";", "return", "html", ";", "}" ]
Converts HTML markup to its equivalent representation @param string @return string
[ "Converts", "HTML", "markup", "to", "its", "equivalent", "representation" ]
4f9c24f054f604b165082bbe5b3b424ad042a729
https://github.com/hashchange/jquery.documentsize/blob/4f9c24f054f604b165082bbe5b3b424ad042a729/demo/load-event/custom.js#L50-L57
40,680
hashchange/jquery.documentsize
demo/load-event/custom.js
map
function map(obj, callback){ var result = {}; Object.keys(obj).forEach(function(key){ result[key] = callback.call(obj, obj[key], key, obj); }); return result; }
javascript
function map(obj, callback){ var result = {}; Object.keys(obj).forEach(function(key){ result[key] = callback.call(obj, obj[key], key, obj); }); return result; }
[ "function", "map", "(", "obj", ",", "callback", ")", "{", "var", "result", "=", "{", "}", ";", "Object", ".", "keys", "(", "obj", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "result", "[", "key", "]", "=", "callback", ".", "call", "(", "obj", ",", "obj", "[", "key", "]", ",", "key", ",", "obj", ")", ";", "}", ")", ";", "return", "result", ";", "}" ]
Map for Objects @param Object @return Object
[ "Map", "for", "Objects" ]
4f9c24f054f604b165082bbe5b3b424ad042a729
https://github.com/hashchange/jquery.documentsize/blob/4f9c24f054f604b165082bbe5b3b424ad042a729/demo/load-event/custom.js#L76-L82
40,681
hashchange/jquery.documentsize
demo/load-event/custom.js
sanitizeHtml
function sanitizeHtml(html){ var separator = '/'; if(html.constructor === Object){ return map(html, function(value){ var sanitizedHtml = value.split(separator) .map(sanitizeHtml) .join(separator); return sanitizedHtml; }); } else if(html.constructor === Array){ return html.map(sanitizeHtml); } var div = document.createElement('div'); div.appendChild(document.createTextNode(html)); var sanitizedHtml = div.innerHTML.replace(/&amp;/g, '&'); if(html != sanitizedHtml){ return ''; // Blank it } return sanitizedHtml; }
javascript
function sanitizeHtml(html){ var separator = '/'; if(html.constructor === Object){ return map(html, function(value){ var sanitizedHtml = value.split(separator) .map(sanitizeHtml) .join(separator); return sanitizedHtml; }); } else if(html.constructor === Array){ return html.map(sanitizeHtml); } var div = document.createElement('div'); div.appendChild(document.createTextNode(html)); var sanitizedHtml = div.innerHTML.replace(/&amp;/g, '&'); if(html != sanitizedHtml){ return ''; // Blank it } return sanitizedHtml; }
[ "function", "sanitizeHtml", "(", "html", ")", "{", "var", "separator", "=", "'/'", ";", "if", "(", "html", ".", "constructor", "===", "Object", ")", "{", "return", "map", "(", "html", ",", "function", "(", "value", ")", "{", "var", "sanitizedHtml", "=", "value", ".", "split", "(", "separator", ")", ".", "map", "(", "sanitizeHtml", ")", ".", "join", "(", "separator", ")", ";", "return", "sanitizedHtml", ";", "}", ")", ";", "}", "else", "if", "(", "html", ".", "constructor", "===", "Array", ")", "{", "return", "html", ".", "map", "(", "sanitizeHtml", ")", ";", "}", "var", "div", "=", "document", ".", "createElement", "(", "'div'", ")", ";", "div", ".", "appendChild", "(", "document", ".", "createTextNode", "(", "html", ")", ")", ";", "var", "sanitizedHtml", "=", "div", ".", "innerHTML", ".", "replace", "(", "/", "&amp;", "/", "g", ",", "'&'", ")", ";", "if", "(", "html", "!=", "sanitizedHtml", ")", "{", "return", "''", ";", "// Blank it", "}", "return", "sanitizedHtml", ";", "}" ]
Use the browser's built-in functionality to quickly and safely escape a string @param string|Array|Object @return string|Array|Object
[ "Use", "the", "browser", "s", "built", "-", "in", "functionality", "to", "quickly", "and", "safely", "escape", "a", "string" ]
4f9c24f054f604b165082bbe5b3b424ad042a729
https://github.com/hashchange/jquery.documentsize/blob/4f9c24f054f604b165082bbe5b3b424ad042a729/demo/load-event/custom.js#L91-L114
40,682
hashchange/jquery.documentsize
demo/load-event/js/libs/jquery.isinview/jquery.isinview-1.0.3.js
_isInView
function _isInView ( elem, config ) { var containerWidth, containerHeight, hTolerance, vTolerance, rect, container = config.container, $container = config.$container, cache = config.cache, elemInView = true; if ( elem === container ) throw new Error( "Invalid container: is the same as the element" ); // When hidden elements are ignored, we check if an element consumes space in the document. And we bail out // immediately if it doesn't. // // The test employed for this works in the vast majority of cases, but there is a limitation. We use offsetWidth // and offsetHeight, which considers the content (incl. borders) but ignores margins. Zero-size content with a // margin might actually consume space sometimes, but it won't be detected (see http://jsbin.com/tiwabo/3). // // That said, the definition of visibility and the actual test are the same as in jQuery :visible. if ( config.excludeHidden && !( elem.offsetWidth > 0 && elem.offsetHeight > 0 ) ) return false; if ( config.useHorizontal ) containerWidth = getNetContainerWidth( $container, config.containerIsWindow, cache ); if ( config.useVertical ) containerHeight = getNetContainerHeight( $container, config.containerIsWindow, cache ); // Convert tolerance to a px value (if given as a percentage) hTolerance = cache.hTolerance !== undefined ? cache.hTolerance : ( cache.hTolerance = config.toleranceType === "add" ? config.tolerance : containerWidth * config.tolerance ); vTolerance = cache.vTolerance !== undefined ? cache.vTolerance : ( cache.vTolerance = config.toleranceType === "add" ? config.tolerance : containerHeight * config.tolerance ); // We can safely use getBoundingClientRect without a fallback. Its core properties (top, left, bottom, right) // are supported on the desktop for ages (IE5+). On mobile, too: supported from Blackberry 6+ (2010), iOS 4 // (2010, iPhone 3GS+), according to the jQuery source comment in $.fn.offset. // // In oldIE (up to IE8), the coordinates were 2px off in each dimension because the "viewport" began at (2,2) of // the window. Can be feature-tested by creating an absolutely positioned div at (0,0) and reading the rect // coordinates. Won't be fixed here because the quirk is too minor to justify the overhead, just for oldIE. // // (See http://stackoverflow.com/a/10231202/508355 and Zakas, Professional Javascript (2012), p. 406) rect = config.borderBox ? elem.getBoundingClientRect() : getContentRect( elem ); if ( ! config.containerIsWindow ) rect = getRelativeRect( rect, $container, cache ); if ( config.partially ) { if ( config.useVertical ) elemInView = rect.top < containerHeight + vTolerance && rect.bottom > -vTolerance; if ( config.useHorizontal ) elemInView = elemInView && rect.left < containerWidth + hTolerance && rect.right > -hTolerance; } else { if ( config.useVertical ) elemInView = rect.top >= -vTolerance && rect.top < containerHeight + vTolerance && rect.bottom > -vTolerance && rect.bottom <= containerHeight + vTolerance; if ( config.useHorizontal ) elemInView = elemInView && rect.left >= -hTolerance && rect.left < containerWidth + hTolerance && rect.right > -hTolerance && rect.right <= containerWidth + hTolerance; } return elemInView; }
javascript
function _isInView ( elem, config ) { var containerWidth, containerHeight, hTolerance, vTolerance, rect, container = config.container, $container = config.$container, cache = config.cache, elemInView = true; if ( elem === container ) throw new Error( "Invalid container: is the same as the element" ); // When hidden elements are ignored, we check if an element consumes space in the document. And we bail out // immediately if it doesn't. // // The test employed for this works in the vast majority of cases, but there is a limitation. We use offsetWidth // and offsetHeight, which considers the content (incl. borders) but ignores margins. Zero-size content with a // margin might actually consume space sometimes, but it won't be detected (see http://jsbin.com/tiwabo/3). // // That said, the definition of visibility and the actual test are the same as in jQuery :visible. if ( config.excludeHidden && !( elem.offsetWidth > 0 && elem.offsetHeight > 0 ) ) return false; if ( config.useHorizontal ) containerWidth = getNetContainerWidth( $container, config.containerIsWindow, cache ); if ( config.useVertical ) containerHeight = getNetContainerHeight( $container, config.containerIsWindow, cache ); // Convert tolerance to a px value (if given as a percentage) hTolerance = cache.hTolerance !== undefined ? cache.hTolerance : ( cache.hTolerance = config.toleranceType === "add" ? config.tolerance : containerWidth * config.tolerance ); vTolerance = cache.vTolerance !== undefined ? cache.vTolerance : ( cache.vTolerance = config.toleranceType === "add" ? config.tolerance : containerHeight * config.tolerance ); // We can safely use getBoundingClientRect without a fallback. Its core properties (top, left, bottom, right) // are supported on the desktop for ages (IE5+). On mobile, too: supported from Blackberry 6+ (2010), iOS 4 // (2010, iPhone 3GS+), according to the jQuery source comment in $.fn.offset. // // In oldIE (up to IE8), the coordinates were 2px off in each dimension because the "viewport" began at (2,2) of // the window. Can be feature-tested by creating an absolutely positioned div at (0,0) and reading the rect // coordinates. Won't be fixed here because the quirk is too minor to justify the overhead, just for oldIE. // // (See http://stackoverflow.com/a/10231202/508355 and Zakas, Professional Javascript (2012), p. 406) rect = config.borderBox ? elem.getBoundingClientRect() : getContentRect( elem ); if ( ! config.containerIsWindow ) rect = getRelativeRect( rect, $container, cache ); if ( config.partially ) { if ( config.useVertical ) elemInView = rect.top < containerHeight + vTolerance && rect.bottom > -vTolerance; if ( config.useHorizontal ) elemInView = elemInView && rect.left < containerWidth + hTolerance && rect.right > -hTolerance; } else { if ( config.useVertical ) elemInView = rect.top >= -vTolerance && rect.top < containerHeight + vTolerance && rect.bottom > -vTolerance && rect.bottom <= containerHeight + vTolerance; if ( config.useHorizontal ) elemInView = elemInView && rect.left >= -hTolerance && rect.left < containerWidth + hTolerance && rect.right > -hTolerance && rect.right <= containerWidth + hTolerance; } return elemInView; }
[ "function", "_isInView", "(", "elem", ",", "config", ")", "{", "var", "containerWidth", ",", "containerHeight", ",", "hTolerance", ",", "vTolerance", ",", "rect", ",", "container", "=", "config", ".", "container", ",", "$container", "=", "config", ".", "$container", ",", "cache", "=", "config", ".", "cache", ",", "elemInView", "=", "true", ";", "if", "(", "elem", "===", "container", ")", "throw", "new", "Error", "(", "\"Invalid container: is the same as the element\"", ")", ";", "// When hidden elements are ignored, we check if an element consumes space in the document. And we bail out", "// immediately if it doesn't.", "//", "// The test employed for this works in the vast majority of cases, but there is a limitation. We use offsetWidth", "// and offsetHeight, which considers the content (incl. borders) but ignores margins. Zero-size content with a", "// margin might actually consume space sometimes, but it won't be detected (see http://jsbin.com/tiwabo/3).", "//", "// That said, the definition of visibility and the actual test are the same as in jQuery :visible.", "if", "(", "config", ".", "excludeHidden", "&&", "!", "(", "elem", ".", "offsetWidth", ">", "0", "&&", "elem", ".", "offsetHeight", ">", "0", ")", ")", "return", "false", ";", "if", "(", "config", ".", "useHorizontal", ")", "containerWidth", "=", "getNetContainerWidth", "(", "$container", ",", "config", ".", "containerIsWindow", ",", "cache", ")", ";", "if", "(", "config", ".", "useVertical", ")", "containerHeight", "=", "getNetContainerHeight", "(", "$container", ",", "config", ".", "containerIsWindow", ",", "cache", ")", ";", "// Convert tolerance to a px value (if given as a percentage)", "hTolerance", "=", "cache", ".", "hTolerance", "!==", "undefined", "?", "cache", ".", "hTolerance", ":", "(", "cache", ".", "hTolerance", "=", "config", ".", "toleranceType", "===", "\"add\"", "?", "config", ".", "tolerance", ":", "containerWidth", "*", "config", ".", "tolerance", ")", ";", "vTolerance", "=", "cache", ".", "vTolerance", "!==", "undefined", "?", "cache", ".", "vTolerance", ":", "(", "cache", ".", "vTolerance", "=", "config", ".", "toleranceType", "===", "\"add\"", "?", "config", ".", "tolerance", ":", "containerHeight", "*", "config", ".", "tolerance", ")", ";", "// We can safely use getBoundingClientRect without a fallback. Its core properties (top, left, bottom, right)", "// are supported on the desktop for ages (IE5+). On mobile, too: supported from Blackberry 6+ (2010), iOS 4", "// (2010, iPhone 3GS+), according to the jQuery source comment in $.fn.offset.", "//", "// In oldIE (up to IE8), the coordinates were 2px off in each dimension because the \"viewport\" began at (2,2) of", "// the window. Can be feature-tested by creating an absolutely positioned div at (0,0) and reading the rect", "// coordinates. Won't be fixed here because the quirk is too minor to justify the overhead, just for oldIE.", "//", "// (See http://stackoverflow.com/a/10231202/508355 and Zakas, Professional Javascript (2012), p. 406)", "rect", "=", "config", ".", "borderBox", "?", "elem", ".", "getBoundingClientRect", "(", ")", ":", "getContentRect", "(", "elem", ")", ";", "if", "(", "!", "config", ".", "containerIsWindow", ")", "rect", "=", "getRelativeRect", "(", "rect", ",", "$container", ",", "cache", ")", ";", "if", "(", "config", ".", "partially", ")", "{", "if", "(", "config", ".", "useVertical", ")", "elemInView", "=", "rect", ".", "top", "<", "containerHeight", "+", "vTolerance", "&&", "rect", ".", "bottom", ">", "-", "vTolerance", ";", "if", "(", "config", ".", "useHorizontal", ")", "elemInView", "=", "elemInView", "&&", "rect", ".", "left", "<", "containerWidth", "+", "hTolerance", "&&", "rect", ".", "right", ">", "-", "hTolerance", ";", "}", "else", "{", "if", "(", "config", ".", "useVertical", ")", "elemInView", "=", "rect", ".", "top", ">=", "-", "vTolerance", "&&", "rect", ".", "top", "<", "containerHeight", "+", "vTolerance", "&&", "rect", ".", "bottom", ">", "-", "vTolerance", "&&", "rect", ".", "bottom", "<=", "containerHeight", "+", "vTolerance", ";", "if", "(", "config", ".", "useHorizontal", ")", "elemInView", "=", "elemInView", "&&", "rect", ".", "left", ">=", "-", "hTolerance", "&&", "rect", ".", "left", "<", "containerWidth", "+", "hTolerance", "&&", "rect", ".", "right", ">", "-", "hTolerance", "&&", "rect", ".", "right", "<=", "containerWidth", "+", "hTolerance", ";", "}", "return", "elemInView", ";", "}" ]
Returns if an element is in view, with regard to a given configuration. The configuration is built with _prepareConfig(). @param {HTMLElement} elem @param {Object} config @param {HTMLElement|Window} config.container @param {jQuery} config.$container @param {boolean} config.containerIsWindow @param {Object} config.cache @param {boolean} config.useHorizontal @param {boolean} config.useVertical @param {boolean} config.partially @param {boolean} config.excludeHidden @param {boolean} config.borderBox @param {number} config.tolerance @param {string} config.toleranceType @returns {boolean}
[ "Returns", "if", "an", "element", "is", "in", "view", "with", "regard", "to", "a", "given", "configuration", "." ]
4f9c24f054f604b165082bbe5b3b424ad042a729
https://github.com/hashchange/jquery.documentsize/blob/4f9c24f054f604b165082bbe5b3b424ad042a729/demo/load-event/js/libs/jquery.isinview/jquery.isinview-1.0.3.js#L412-L462
40,683
hashchange/jquery.documentsize
demo/load-event/js/libs/jquery.isinview/jquery.isinview-1.0.3.js
getRelativeRect
function getRelativeRect ( rect, $container, cache ) { var containerPaddingRectRoot; if ( cache && cache.containerPaddingRectRoot ) { containerPaddingRectRoot = cache.containerPaddingRectRoot; } else { // gBCR coordinates enclose padding, and leave out margin. That is perfect for scrolling because // // - padding scrolls (ie,o it is part of the scrollable area, and gBCR puts it inside) // - margin doesn't scroll (ie, it pushes the scrollable area to another position, and gBCR records that) // // Borders, however, don't scroll, so they are not part of the scrollable area, but gBCR puts them inside. // // (See http://jsbin.com/pivata/10 for an extensive test of gBCR behaviour.) containerPaddingRectRoot = getPaddingRectRoot( $container[0] ); // Cache the calculations if ( cache ) cache.containerPaddingRectRoot = containerPaddingRectRoot; } return { top: rect.top - containerPaddingRectRoot.top, bottom: rect.bottom - containerPaddingRectRoot.top, left: rect.left - containerPaddingRectRoot.left, right: rect.right - containerPaddingRectRoot.left }; }
javascript
function getRelativeRect ( rect, $container, cache ) { var containerPaddingRectRoot; if ( cache && cache.containerPaddingRectRoot ) { containerPaddingRectRoot = cache.containerPaddingRectRoot; } else { // gBCR coordinates enclose padding, and leave out margin. That is perfect for scrolling because // // - padding scrolls (ie,o it is part of the scrollable area, and gBCR puts it inside) // - margin doesn't scroll (ie, it pushes the scrollable area to another position, and gBCR records that) // // Borders, however, don't scroll, so they are not part of the scrollable area, but gBCR puts them inside. // // (See http://jsbin.com/pivata/10 for an extensive test of gBCR behaviour.) containerPaddingRectRoot = getPaddingRectRoot( $container[0] ); // Cache the calculations if ( cache ) cache.containerPaddingRectRoot = containerPaddingRectRoot; } return { top: rect.top - containerPaddingRectRoot.top, bottom: rect.bottom - containerPaddingRectRoot.top, left: rect.left - containerPaddingRectRoot.left, right: rect.right - containerPaddingRectRoot.left }; }
[ "function", "getRelativeRect", "(", "rect", ",", "$container", ",", "cache", ")", "{", "var", "containerPaddingRectRoot", ";", "if", "(", "cache", "&&", "cache", ".", "containerPaddingRectRoot", ")", "{", "containerPaddingRectRoot", "=", "cache", ".", "containerPaddingRectRoot", ";", "}", "else", "{", "// gBCR coordinates enclose padding, and leave out margin. That is perfect for scrolling because", "//", "// - padding scrolls (ie,o it is part of the scrollable area, and gBCR puts it inside)", "// - margin doesn't scroll (ie, it pushes the scrollable area to another position, and gBCR records that)", "//", "// Borders, however, don't scroll, so they are not part of the scrollable area, but gBCR puts them inside.", "//", "// (See http://jsbin.com/pivata/10 for an extensive test of gBCR behaviour.)", "containerPaddingRectRoot", "=", "getPaddingRectRoot", "(", "$container", "[", "0", "]", ")", ";", "// Cache the calculations", "if", "(", "cache", ")", "cache", ".", "containerPaddingRectRoot", "=", "containerPaddingRectRoot", ";", "}", "return", "{", "top", ":", "rect", ".", "top", "-", "containerPaddingRectRoot", ".", "top", ",", "bottom", ":", "rect", ".", "bottom", "-", "containerPaddingRectRoot", ".", "top", ",", "left", ":", "rect", ".", "left", "-", "containerPaddingRectRoot", ".", "left", ",", "right", ":", "rect", ".", "right", "-", "containerPaddingRectRoot", ".", "left", "}", ";", "}" ]
Gets the TextRectangle coordinates relative to a container element. Do not call if the container is a window (redundant) or a document. Both calls would fail.
[ "Gets", "the", "TextRectangle", "coordinates", "relative", "to", "a", "container", "element", "." ]
4f9c24f054f604b165082bbe5b3b424ad042a729
https://github.com/hashchange/jquery.documentsize/blob/4f9c24f054f604b165082bbe5b3b424ad042a729/demo/load-event/js/libs/jquery.isinview/jquery.isinview-1.0.3.js#L469-L498
40,684
hashchange/jquery.documentsize
demo/load-event/js/libs/jquery.isinview/jquery.isinview-1.0.3.js
getContentRect
function getContentRect( elem ) { var rect = elem.getBoundingClientRect(), props = getCss( elem, [ "borderTopWidth", "borderRightWidth", "borderBottomWidth", "borderLeftWidth", "paddingTop", "paddingRight", "paddingBottom", "paddingLeft" ], { toFloat: true } ); return { top: rect.top + props.paddingTop + props.borderTopWidth, right: rect.right - ( props.paddingRight + props.borderRightWidth ), bottom: rect.bottom - ( props.paddingBottom + props.borderBottomWidth ), left: rect.left + props.paddingLeft + props.borderLeftWidth }; }
javascript
function getContentRect( elem ) { var rect = elem.getBoundingClientRect(), props = getCss( elem, [ "borderTopWidth", "borderRightWidth", "borderBottomWidth", "borderLeftWidth", "paddingTop", "paddingRight", "paddingBottom", "paddingLeft" ], { toFloat: true } ); return { top: rect.top + props.paddingTop + props.borderTopWidth, right: rect.right - ( props.paddingRight + props.borderRightWidth ), bottom: rect.bottom - ( props.paddingBottom + props.borderBottomWidth ), left: rect.left + props.paddingLeft + props.borderLeftWidth }; }
[ "function", "getContentRect", "(", "elem", ")", "{", "var", "rect", "=", "elem", ".", "getBoundingClientRect", "(", ")", ",", "props", "=", "getCss", "(", "elem", ",", "[", "\"borderTopWidth\"", ",", "\"borderRightWidth\"", ",", "\"borderBottomWidth\"", ",", "\"borderLeftWidth\"", ",", "\"paddingTop\"", ",", "\"paddingRight\"", ",", "\"paddingBottom\"", ",", "\"paddingLeft\"", "]", ",", "{", "toFloat", ":", "true", "}", ")", ";", "return", "{", "top", ":", "rect", ".", "top", "+", "props", ".", "paddingTop", "+", "props", ".", "borderTopWidth", ",", "right", ":", "rect", ".", "right", "-", "(", "props", ".", "paddingRight", "+", "props", ".", "borderRightWidth", ")", ",", "bottom", ":", "rect", ".", "bottom", "-", "(", "props", ".", "paddingBottom", "+", "props", ".", "borderBottomWidth", ")", ",", "left", ":", "rect", ".", "left", "+", "props", ".", "paddingLeft", "+", "props", ".", "borderLeftWidth", "}", ";", "}" ]
Calculates the rect of the content-box. Similar to getBoundingClientRect, but excludes padding and borders - and is much slower. @param {HTMLElement} elem @returns {ClientRect}
[ "Calculates", "the", "rect", "of", "the", "content", "-", "box", ".", "Similar", "to", "getBoundingClientRect", "but", "excludes", "padding", "and", "borders", "-", "and", "is", "much", "slower", "." ]
4f9c24f054f604b165082bbe5b3b424ad042a729
https://github.com/hashchange/jquery.documentsize/blob/4f9c24f054f604b165082bbe5b3b424ad042a729/demo/load-event/js/libs/jquery.isinview/jquery.isinview-1.0.3.js#L507-L521
40,685
hashchange/jquery.documentsize
demo/load-event/js/libs/jquery.isinview/jquery.isinview-1.0.3.js
wrapContainer
function wrapContainer ( container ) { var $container, isJquery = container instanceof $; if ( ! isJquery && ! $.isWindow( container ) && ! container.nodeType && ! isString( container ) ) throw new Error( 'Invalid container: not a window, node, jQuery object or selector string' ); $container = isJquery ? container : container === root ? $root : $( container ); if ( !$container.length ) throw new Error( 'Invalid container: empty jQuery object' ); container = $container[0]; if ( container.nodeType === 9 ) { // Document is passed in, transform to window $container = wrapContainer( container.defaultView || container.parentWindow ); } else if ( container.nodeType === 1 && container.tagName.toLowerCase() === "iframe" ) { // IFrame element is passed in, transform to IFrame content window $container = wrapContainer( container.contentWindow ); } // Check if the container matches the requirements if ( !$.isWindow( $container[0] ) && $container.css( "overflow" ) === "visible" ) throw new Error( 'Invalid container: is set to overflow:visible. Containers must have the ability to obscure some of their content, otherwise the in-view test is pointless. Containers must be set to overflow:scroll/auto/hide, or be a window (or document, or iframe, as proxies for a window)' ); return $container; }
javascript
function wrapContainer ( container ) { var $container, isJquery = container instanceof $; if ( ! isJquery && ! $.isWindow( container ) && ! container.nodeType && ! isString( container ) ) throw new Error( 'Invalid container: not a window, node, jQuery object or selector string' ); $container = isJquery ? container : container === root ? $root : $( container ); if ( !$container.length ) throw new Error( 'Invalid container: empty jQuery object' ); container = $container[0]; if ( container.nodeType === 9 ) { // Document is passed in, transform to window $container = wrapContainer( container.defaultView || container.parentWindow ); } else if ( container.nodeType === 1 && container.tagName.toLowerCase() === "iframe" ) { // IFrame element is passed in, transform to IFrame content window $container = wrapContainer( container.contentWindow ); } // Check if the container matches the requirements if ( !$.isWindow( $container[0] ) && $container.css( "overflow" ) === "visible" ) throw new Error( 'Invalid container: is set to overflow:visible. Containers must have the ability to obscure some of their content, otherwise the in-view test is pointless. Containers must be set to overflow:scroll/auto/hide, or be a window (or document, or iframe, as proxies for a window)' ); return $container; }
[ "function", "wrapContainer", "(", "container", ")", "{", "var", "$container", ",", "isJquery", "=", "container", "instanceof", "$", ";", "if", "(", "!", "isJquery", "&&", "!", "$", ".", "isWindow", "(", "container", ")", "&&", "!", "container", ".", "nodeType", "&&", "!", "isString", "(", "container", ")", ")", "throw", "new", "Error", "(", "'Invalid container: not a window, node, jQuery object or selector string'", ")", ";", "$container", "=", "isJquery", "?", "container", ":", "container", "===", "root", "?", "$root", ":", "$", "(", "container", ")", ";", "if", "(", "!", "$container", ".", "length", ")", "throw", "new", "Error", "(", "'Invalid container: empty jQuery object'", ")", ";", "container", "=", "$container", "[", "0", "]", ";", "if", "(", "container", ".", "nodeType", "===", "9", ")", "{", "// Document is passed in, transform to window", "$container", "=", "wrapContainer", "(", "container", ".", "defaultView", "||", "container", ".", "parentWindow", ")", ";", "}", "else", "if", "(", "container", ".", "nodeType", "===", "1", "&&", "container", ".", "tagName", ".", "toLowerCase", "(", ")", "===", "\"iframe\"", ")", "{", "// IFrame element is passed in, transform to IFrame content window", "$container", "=", "wrapContainer", "(", "container", ".", "contentWindow", ")", ";", "}", "// Check if the container matches the requirements", "if", "(", "!", "$", ".", "isWindow", "(", "$container", "[", "0", "]", ")", "&&", "$container", ".", "css", "(", "\"overflow\"", ")", "===", "\"visible\"", ")", "throw", "new", "Error", "(", "'Invalid container: is set to overflow:visible. Containers must have the ability to obscure some of their content, otherwise the in-view test is pointless. Containers must be set to overflow:scroll/auto/hide, or be a window (or document, or iframe, as proxies for a window)'", ")", ";", "return", "$container", ";", "}" ]
Establishes the container and returns it in a jQuery wrapper. Resolves and normalizes the input, which may be a document, HTMLElement, window, or selector string. Corrects likely mistakes, such as passing in a document or an iframe, rather than the corresponding window. @param {Window|Document|HTMLElement|HTMLIFrameElement|jQuery|string} container @returns {jQuery}
[ "Establishes", "the", "container", "and", "returns", "it", "in", "a", "jQuery", "wrapper", "." ]
4f9c24f054f604b165082bbe5b3b424ad042a729
https://github.com/hashchange/jquery.documentsize/blob/4f9c24f054f604b165082bbe5b3b424ad042a729/demo/load-event/js/libs/jquery.isinview/jquery.isinview-1.0.3.js#L795-L819
40,686
hashchange/jquery.documentsize
demo/load-event/js/libs/jquery.isinview/jquery.isinview-1.0.3.js
checkOptions
function checkOptions ( opts ) { var isNum, isNumWithUnit; if ( opts.direction && !( opts.direction === 'vertical' || opts.direction === 'horizontal' || opts.direction === 'both' ) ) { throw new Error( 'Invalid option value: direction = "' + opts.direction + '"' ); } if ( opts.box && !( opts.box === 'border-box' || opts.box === 'content-box' ) ) { throw new Error( 'Invalid option value: box = "' + opts.box + '"' ); } if ( opts.tolerance !== undefined ) { isNum = isNumber( opts.tolerance ); isNumWithUnit = isString( opts.tolerance ) && ( /^[+-]?\d*\.?\d+(px|%)?$/.test( opts.tolerance ) ); if ( ! ( isNum || isNumWithUnit ) ) throw new Error( 'Invalid option value: tolerance = "' + opts.tolerance + '"' ); } }
javascript
function checkOptions ( opts ) { var isNum, isNumWithUnit; if ( opts.direction && !( opts.direction === 'vertical' || opts.direction === 'horizontal' || opts.direction === 'both' ) ) { throw new Error( 'Invalid option value: direction = "' + opts.direction + '"' ); } if ( opts.box && !( opts.box === 'border-box' || opts.box === 'content-box' ) ) { throw new Error( 'Invalid option value: box = "' + opts.box + '"' ); } if ( opts.tolerance !== undefined ) { isNum = isNumber( opts.tolerance ); isNumWithUnit = isString( opts.tolerance ) && ( /^[+-]?\d*\.?\d+(px|%)?$/.test( opts.tolerance ) ); if ( ! ( isNum || isNumWithUnit ) ) throw new Error( 'Invalid option value: tolerance = "' + opts.tolerance + '"' ); } }
[ "function", "checkOptions", "(", "opts", ")", "{", "var", "isNum", ",", "isNumWithUnit", ";", "if", "(", "opts", ".", "direction", "&&", "!", "(", "opts", ".", "direction", "===", "'vertical'", "||", "opts", ".", "direction", "===", "'horizontal'", "||", "opts", ".", "direction", "===", "'both'", ")", ")", "{", "throw", "new", "Error", "(", "'Invalid option value: direction = \"'", "+", "opts", ".", "direction", "+", "'\"'", ")", ";", "}", "if", "(", "opts", ".", "box", "&&", "!", "(", "opts", ".", "box", "===", "'border-box'", "||", "opts", ".", "box", "===", "'content-box'", ")", ")", "{", "throw", "new", "Error", "(", "'Invalid option value: box = \"'", "+", "opts", ".", "box", "+", "'\"'", ")", ";", "}", "if", "(", "opts", ".", "tolerance", "!==", "undefined", ")", "{", "isNum", "=", "isNumber", "(", "opts", ".", "tolerance", ")", ";", "isNumWithUnit", "=", "isString", "(", "opts", ".", "tolerance", ")", "&&", "(", "/", "^[+-]?\\d*\\.?\\d+(px|%)?$", "/", ".", "test", "(", "opts", ".", "tolerance", ")", ")", ";", "if", "(", "!", "(", "isNum", "||", "isNumWithUnit", ")", ")", "throw", "new", "Error", "(", "'Invalid option value: tolerance = \"'", "+", "opts", ".", "tolerance", "+", "'\"'", ")", ";", "}", "}" ]
Spots likely option mistakes and throws appropriate errors. @param {Object} opts
[ "Spots", "likely", "option", "mistakes", "and", "throws", "appropriate", "errors", "." ]
4f9c24f054f604b165082bbe5b3b424ad042a729
https://github.com/hashchange/jquery.documentsize/blob/4f9c24f054f604b165082bbe5b3b424ad042a729/demo/load-event/js/libs/jquery.isinview/jquery.isinview-1.0.3.js#L854-L871
40,687
hashchange/jquery.documentsize
demo/load-event/js/libs/jquery.isinview/jquery.isinview-1.0.3.js
getContainerScrollbarWidths
function getContainerScrollbarWidths ( $container, cache ) { var containerScrollbarWidths; if ( cache && cache.containerScrollbarWidths ) { containerScrollbarWidths = cache.containerScrollbarWidths; } else { containerScrollbarWidths = effectiveScrollbarWith( $container ); if ( cache ) cache.containerScrollbarWidths = containerScrollbarWidths; } return containerScrollbarWidths; }
javascript
function getContainerScrollbarWidths ( $container, cache ) { var containerScrollbarWidths; if ( cache && cache.containerScrollbarWidths ) { containerScrollbarWidths = cache.containerScrollbarWidths; } else { containerScrollbarWidths = effectiveScrollbarWith( $container ); if ( cache ) cache.containerScrollbarWidths = containerScrollbarWidths; } return containerScrollbarWidths; }
[ "function", "getContainerScrollbarWidths", "(", "$container", ",", "cache", ")", "{", "var", "containerScrollbarWidths", ";", "if", "(", "cache", "&&", "cache", ".", "containerScrollbarWidths", ")", "{", "containerScrollbarWidths", "=", "cache", ".", "containerScrollbarWidths", ";", "}", "else", "{", "containerScrollbarWidths", "=", "effectiveScrollbarWith", "(", "$container", ")", ";", "if", "(", "cache", ")", "cache", ".", "containerScrollbarWidths", "=", "containerScrollbarWidths", ";", "}", "return", "containerScrollbarWidths", ";", "}" ]
Gets the effective scroll bar widths of a given container. Makes use of caching if a cache object is provided. @param {jQuery} $container @param {Object} [cache] @returns {Object}
[ "Gets", "the", "effective", "scroll", "bar", "widths", "of", "a", "given", "container", ".", "Makes", "use", "of", "caching", "if", "a", "cache", "object", "is", "provided", "." ]
4f9c24f054f604b165082bbe5b3b424ad042a729
https://github.com/hashchange/jquery.documentsize/blob/4f9c24f054f604b165082bbe5b3b424ad042a729/demo/load-event/js/libs/jquery.isinview/jquery.isinview-1.0.3.js#L930-L941
40,688
hashchange/jquery.documentsize
demo/load-event/js/libs/jquery.isinview/jquery.isinview-1.0.3.js
getCss
function getCss ( elem, properties, opts ) { var i, length, name, props = {}, _window = ( elem.ownerDocument.defaultView || elem.ownerDocument.parentWindow ), computedStyles = _useGetComputedStyle ? _window.getComputedStyle( elem, null ) : elem.currentStyle; opts || ( opts = {} ); if ( ! $.isArray( properties ) ) properties = [ properties ]; length = properties.length; for ( i = 0; i < length; i++ ) { name = properties[i]; props[name] = $.css( elem, name, false, computedStyles ); if ( opts.toLowerCase && props[name] && props[name].toLowerCase ) props[name] = props[name].toLowerCase(); if ( opts.toFloat ) props[name] = parseFloat( props[name] ); } return props; }
javascript
function getCss ( elem, properties, opts ) { var i, length, name, props = {}, _window = ( elem.ownerDocument.defaultView || elem.ownerDocument.parentWindow ), computedStyles = _useGetComputedStyle ? _window.getComputedStyle( elem, null ) : elem.currentStyle; opts || ( opts = {} ); if ( ! $.isArray( properties ) ) properties = [ properties ]; length = properties.length; for ( i = 0; i < length; i++ ) { name = properties[i]; props[name] = $.css( elem, name, false, computedStyles ); if ( opts.toLowerCase && props[name] && props[name].toLowerCase ) props[name] = props[name].toLowerCase(); if ( opts.toFloat ) props[name] = parseFloat( props[name] ); } return props; }
[ "function", "getCss", "(", "elem", ",", "properties", ",", "opts", ")", "{", "var", "i", ",", "length", ",", "name", ",", "props", "=", "{", "}", ",", "_window", "=", "(", "elem", ".", "ownerDocument", ".", "defaultView", "||", "elem", ".", "ownerDocument", ".", "parentWindow", ")", ",", "computedStyles", "=", "_useGetComputedStyle", "?", "_window", ".", "getComputedStyle", "(", "elem", ",", "null", ")", ":", "elem", ".", "currentStyle", ";", "opts", "||", "(", "opts", "=", "{", "}", ")", ";", "if", "(", "!", "$", ".", "isArray", "(", "properties", ")", ")", "properties", "=", "[", "properties", "]", ";", "length", "=", "properties", ".", "length", ";", "for", "(", "i", "=", "0", ";", "i", "<", "length", ";", "i", "++", ")", "{", "name", "=", "properties", "[", "i", "]", ";", "props", "[", "name", "]", "=", "$", ".", "css", "(", "elem", ",", "name", ",", "false", ",", "computedStyles", ")", ";", "if", "(", "opts", ".", "toLowerCase", "&&", "props", "[", "name", "]", "&&", "props", "[", "name", "]", ".", "toLowerCase", ")", "props", "[", "name", "]", "=", "props", "[", "name", "]", ".", "toLowerCase", "(", ")", ";", "if", "(", "opts", ".", "toFloat", ")", "props", "[", "name", "]", "=", "parseFloat", "(", "props", "[", "name", "]", ")", ";", "}", "return", "props", ";", "}" ]
Returns the computed style for a property, or an array of properties, as a hash. Building a CSS properties hash this way can be significantly faster than the more convenient, conventional jQuery approach, $( elem ).css( propertiesArray ). ATTN ==== We are using an internal jQuery API here: $.css(). The current signature was introduced in jQuery 1.9.0. It may break without warning with any change of the minor version. For that reason, the $.css API is monitored by the tests in api.jquery.css.spec.js which verify that it works as expected. @param {HTMLElement} elem @param {string|string[]} properties @param {Object} [opts] @param {boolean} [opts.toLowerCase=false] ensures return values in lower case @param {boolean} [opts.toFloat=false] converts return values to numbers, using parseFloat @returns {Object} property names and their values
[ "Returns", "the", "computed", "style", "for", "a", "property", "or", "an", "array", "of", "properties", "as", "a", "hash", "." ]
4f9c24f054f604b165082bbe5b3b424ad042a729
https://github.com/hashchange/jquery.documentsize/blob/4f9c24f054f604b165082bbe5b3b424ad042a729/demo/load-event/js/libs/jquery.isinview/jquery.isinview-1.0.3.js#L984-L1003
40,689
hashchange/jquery.documentsize
demo/load-event/js/libs/jquery.isinview/jquery.isinview-1.0.3.js
isIOS
function isIOS () { if ( _isIOS === undefined ) _isIOS = (/iPad|iPhone|iPod/g).test( navigator.userAgent ); return _isIOS; }
javascript
function isIOS () { if ( _isIOS === undefined ) _isIOS = (/iPad|iPhone|iPod/g).test( navigator.userAgent ); return _isIOS; }
[ "function", "isIOS", "(", ")", "{", "if", "(", "_isIOS", "===", "undefined", ")", "_isIOS", "=", "(", "/", "iPad|iPhone|iPod", "/", "g", ")", ".", "test", "(", "navigator", ".", "userAgent", ")", ";", "return", "_isIOS", ";", "}" ]
Detects if the browser is on iOS. Works for Safari as well as other browsers, say, Chrome on iOS. Required for some iOS behaviour which can't be feature-detected in any way. @returns {boolean}
[ "Detects", "if", "the", "browser", "is", "on", "iOS", ".", "Works", "for", "Safari", "as", "well", "as", "other", "browsers", "say", "Chrome", "on", "iOS", "." ]
4f9c24f054f604b165082bbe5b3b424ad042a729
https://github.com/hashchange/jquery.documentsize/blob/4f9c24f054f604b165082bbe5b3b424ad042a729/demo/load-event/js/libs/jquery.isinview/jquery.isinview-1.0.3.js#L1041-L1044
40,690
hashchange/jquery.documentsize
demo/load-event/js/libs/jquery.isinview/jquery.isinview-1.0.3.js
toFloat
function toFloat ( object ) { var transformed = {}; $.map( object, function ( value, key ) { transformed[key] = parseFloat( value ); } ); return transformed; }
javascript
function toFloat ( object ) { var transformed = {}; $.map( object, function ( value, key ) { transformed[key] = parseFloat( value ); } ); return transformed; }
[ "function", "toFloat", "(", "object", ")", "{", "var", "transformed", "=", "{", "}", ";", "$", ".", "map", "(", "object", ",", "function", "(", "value", ",", "key", ")", "{", "transformed", "[", "key", "]", "=", "parseFloat", "(", "value", ")", ";", "}", ")", ";", "return", "transformed", ";", "}" ]
Calls parseFloat on each value. Useful for removing units from numeric values. @param {Object} object @returns {Object}
[ "Calls", "parseFloat", "on", "each", "value", ".", "Useful", "for", "removing", "units", "from", "numeric", "values", "." ]
4f9c24f054f604b165082bbe5b3b424ad042a729
https://github.com/hashchange/jquery.documentsize/blob/4f9c24f054f604b165082bbe5b3b424ad042a729/demo/load-event/js/libs/jquery.isinview/jquery.isinview-1.0.3.js#L1052-L1060
40,691
hashchange/jquery.documentsize
spec/helpers/dom-utils.js
createChildWindow
function createChildWindow ( readyDfd, size ) { var childWindow, width, height, sizedDefaultProps = ",top=0,left=0,location=no,menubar=no,status=no,toolbar=no,resizeable=yes,scrollbars=yes"; if ( size ) { width = size === "parent" ? window.document.documentElement.clientWidth : size.width; height = size === "parent" ? window.document.documentElement.clientHeight : size.height; childWindow = window.open( "", "", "width=" + width + ",height=" + height + sizedDefaultProps ); } else { childWindow = window.open(); } if ( childWindow ) { // Setting the document content (using plain JS - jQuery can't write an entire HTML document, including the // doctype and <head> tags). childWindow.document.open(); childWindow.document.write( '<!DOCTYPE html>\n<html>\n<head>\n<meta charset="UTF-8">\n<title></title>\n</head>\n<body>\n</body>\n</html>' ); childWindow.document.close(); } if ( readyDfd ) { if ( ! varExists( $ ) ) throw new Error( "`$` variable is not available. For using a readyDfd, jQuery (or a compatible library) must be loaded" ); if ( childWindow && childWindow.document ) { $( childWindow.document ).ready ( function () { windowSizeReady( childWindow, readyDfd ); } ); } else { readyDfd.reject(); } } return childWindow; }
javascript
function createChildWindow ( readyDfd, size ) { var childWindow, width, height, sizedDefaultProps = ",top=0,left=0,location=no,menubar=no,status=no,toolbar=no,resizeable=yes,scrollbars=yes"; if ( size ) { width = size === "parent" ? window.document.documentElement.clientWidth : size.width; height = size === "parent" ? window.document.documentElement.clientHeight : size.height; childWindow = window.open( "", "", "width=" + width + ",height=" + height + sizedDefaultProps ); } else { childWindow = window.open(); } if ( childWindow ) { // Setting the document content (using plain JS - jQuery can't write an entire HTML document, including the // doctype and <head> tags). childWindow.document.open(); childWindow.document.write( '<!DOCTYPE html>\n<html>\n<head>\n<meta charset="UTF-8">\n<title></title>\n</head>\n<body>\n</body>\n</html>' ); childWindow.document.close(); } if ( readyDfd ) { if ( ! varExists( $ ) ) throw new Error( "`$` variable is not available. For using a readyDfd, jQuery (or a compatible library) must be loaded" ); if ( childWindow && childWindow.document ) { $( childWindow.document ).ready ( function () { windowSizeReady( childWindow, readyDfd ); } ); } else { readyDfd.reject(); } } return childWindow; }
[ "function", "createChildWindow", "(", "readyDfd", ",", "size", ")", "{", "var", "childWindow", ",", "width", ",", "height", ",", "sizedDefaultProps", "=", "\",top=0,left=0,location=no,menubar=no,status=no,toolbar=no,resizeable=yes,scrollbars=yes\"", ";", "if", "(", "size", ")", "{", "width", "=", "size", "===", "\"parent\"", "?", "window", ".", "document", ".", "documentElement", ".", "clientWidth", ":", "size", ".", "width", ";", "height", "=", "size", "===", "\"parent\"", "?", "window", ".", "document", ".", "documentElement", ".", "clientHeight", ":", "size", ".", "height", ";", "childWindow", "=", "window", ".", "open", "(", "\"\"", ",", "\"\"", ",", "\"width=\"", "+", "width", "+", "\",height=\"", "+", "height", "+", "sizedDefaultProps", ")", ";", "}", "else", "{", "childWindow", "=", "window", ".", "open", "(", ")", ";", "}", "if", "(", "childWindow", ")", "{", "// Setting the document content (using plain JS - jQuery can't write an entire HTML document, including the", "// doctype and <head> tags).", "childWindow", ".", "document", ".", "open", "(", ")", ";", "childWindow", ".", "document", ".", "write", "(", "'<!DOCTYPE html>\\n<html>\\n<head>\\n<meta charset=\"UTF-8\">\\n<title></title>\\n</head>\\n<body>\\n</body>\\n</html>'", ")", ";", "childWindow", ".", "document", ".", "close", "(", ")", ";", "}", "if", "(", "readyDfd", ")", "{", "if", "(", "!", "varExists", "(", "$", ")", ")", "throw", "new", "Error", "(", "\"`$` variable is not available. For using a readyDfd, jQuery (or a compatible library) must be loaded\"", ")", ";", "if", "(", "childWindow", "&&", "childWindow", ".", "document", ")", "{", "$", "(", "childWindow", ".", "document", ")", ".", "ready", "(", "function", "(", ")", "{", "windowSizeReady", "(", "childWindow", ",", "readyDfd", ")", ";", "}", ")", ";", "}", "else", "{", "readyDfd", ".", "reject", "(", ")", ";", "}", "}", "return", "childWindow", ";", "}" ]
Creates a child window, including a document with an HTML 5 doctype, UFT-8 charset, head, title, and body tags. Returns the handle, or undefined if window creation fails. Optionally accepts a jQuery Deferred. The deferred is resolved when the document in the child window is ready and the window has expanded to its intended size. If the child window can't be created, the deferred is rejected. (For this, jQuery needs to be loaded, obviously.) The size can also be specified. If so, the new window is opened with minimal browser chrome (no menu, location, and status bars) and is positioned at the top left of the viewport. By default, the window is opened with the default settings of the browser (usually with browser chrome, and not exactly in the top left corner). If the child window can't be created, a pop-up blocker usually prevents it. Pop-up blockers are active by default in most browsers - Chrome, for instance. @param {jQuery.Deferred} [readyDfd] @param {Object|string} [size] "parent" (same size as parent window), or size object @param {number} [size.width] @param {number} [size.height] @returns {Window|undefined} the window handle
[ "Creates", "a", "child", "window", "including", "a", "document", "with", "an", "HTML", "5", "doctype", "UFT", "-", "8", "charset", "head", "title", "and", "body", "tags", ".", "Returns", "the", "handle", "or", "undefined", "if", "window", "creation", "fails", "." ]
4f9c24f054f604b165082bbe5b3b424ad042a729
https://github.com/hashchange/jquery.documentsize/blob/4f9c24f054f604b165082bbe5b3b424ad042a729/spec/helpers/dom-utils.js#L29-L69
40,692
hashchange/jquery.documentsize
spec/helpers/dom-utils.js
createIframe
function createIframe ( opts ) { var parent = ( opts && opts.parent ) ? ( varExists( $ ) && opts.parent instanceof $ ) ? opts.parent[0] : opts.parent : document.body, _document = parent.ownerDocument, iframe = _document.createElement( "iframe" ); opts || ( opts = {} ); if ( opts.elementStyles ) iframe.style.cssText = ensureTrailingSemicolon( opts.elementStyles ); iframe.frameborder = "0"; if ( opts.prepend ) { parent.insertBefore( iframe, parent.firstChild ); } else { parent.appendChild( iframe ); } iframe.src = 'about:blank'; createIframeDocument( iframe, opts.documentStyles ); return iframe; }
javascript
function createIframe ( opts ) { var parent = ( opts && opts.parent ) ? ( varExists( $ ) && opts.parent instanceof $ ) ? opts.parent[0] : opts.parent : document.body, _document = parent.ownerDocument, iframe = _document.createElement( "iframe" ); opts || ( opts = {} ); if ( opts.elementStyles ) iframe.style.cssText = ensureTrailingSemicolon( opts.elementStyles ); iframe.frameborder = "0"; if ( opts.prepend ) { parent.insertBefore( iframe, parent.firstChild ); } else { parent.appendChild( iframe ); } iframe.src = 'about:blank'; createIframeDocument( iframe, opts.documentStyles ); return iframe; }
[ "function", "createIframe", "(", "opts", ")", "{", "var", "parent", "=", "(", "opts", "&&", "opts", ".", "parent", ")", "?", "(", "varExists", "(", "$", ")", "&&", "opts", ".", "parent", "instanceof", "$", ")", "?", "opts", ".", "parent", "[", "0", "]", ":", "opts", ".", "parent", ":", "document", ".", "body", ",", "_document", "=", "parent", ".", "ownerDocument", ",", "iframe", "=", "_document", ".", "createElement", "(", "\"iframe\"", ")", ";", "opts", "||", "(", "opts", "=", "{", "}", ")", ";", "if", "(", "opts", ".", "elementStyles", ")", "iframe", ".", "style", ".", "cssText", "=", "ensureTrailingSemicolon", "(", "opts", ".", "elementStyles", ")", ";", "iframe", ".", "frameborder", "=", "\"0\"", ";", "if", "(", "opts", ".", "prepend", ")", "{", "parent", ".", "insertBefore", "(", "iframe", ",", "parent", ".", "firstChild", ")", ";", "}", "else", "{", "parent", ".", "appendChild", "(", "iframe", ")", ";", "}", "iframe", ".", "src", "=", "'about:blank'", ";", "createIframeDocument", "(", "iframe", ",", "opts", ".", "documentStyles", ")", ";", "return", "iframe", ";", "}" ]
Creates an iframe with an HTML5 doctype and UTF-8 encoding. Appends it to the body, or to another specified parent element. Alternatively, the iframe can be prepended to the parent. The iframe element can be styled as it is created, before it is added to the DOM, e.g. to keep it out of view. Likewise, styles can be written into the iframe document as it is created, providing it with defaults from the get-go. @param {Object} [opts] @param {HTMLElement|jQuery} [opts.parent=document.body] the parent element to which the iframe is appended @param {boolean} [opts.prepend=false] if true, the iframe gets prepended to the parent, rather than appended @param {string} [opts.elementStyles] cssText string, styles the iframe _element_ @param {string} [opts.documentStyles] cssText string of entire rules, styles the iframe document, e.g. "html, body { overflow: hidden; } div.foo { margin: 2em; }" @returns {HTMLIFrameElement}
[ "Creates", "an", "iframe", "with", "an", "HTML5", "doctype", "and", "UTF", "-", "8", "encoding", ".", "Appends", "it", "to", "the", "body", "or", "to", "another", "specified", "parent", "element", ".", "Alternatively", "the", "iframe", "can", "be", "prepended", "to", "the", "parent", "." ]
4f9c24f054f604b165082bbe5b3b424ad042a729
https://github.com/hashchange/jquery.documentsize/blob/4f9c24f054f604b165082bbe5b3b424ad042a729/spec/helpers/dom-utils.js#L87-L107
40,693
hashchange/jquery.documentsize
spec/helpers/dom-utils.js
createIframeDocument
function createIframeDocument ( iframe, documentStyles ) { if ( varExists( $ ) && iframe instanceof $ ) iframe = iframe[0]; if ( ! iframe.ownerDocument.body.contains( iframe ) ) throw new Error( "The iframe has not been appended to the DOM, or is not a descendant of the body element. Can't create an iframe content document." ); if ( ! iframe.contentDocument ) throw new Error( "Cannot access the iframe content document. Check for cross-domain policy restrictions." ); documentStyles = documentStyles ? '<style type="text/css">\n' + documentStyles + '\n</style>\n' : ""; iframe.contentDocument.write( '<!DOCTYPE html>\n<html>\n<head>\n<meta charset="UTF-8">\n<title></title>\n' + documentStyles + '</head>\n<body>\n</body>\n</html>' ); return iframe.contentDocument; }
javascript
function createIframeDocument ( iframe, documentStyles ) { if ( varExists( $ ) && iframe instanceof $ ) iframe = iframe[0]; if ( ! iframe.ownerDocument.body.contains( iframe ) ) throw new Error( "The iframe has not been appended to the DOM, or is not a descendant of the body element. Can't create an iframe content document." ); if ( ! iframe.contentDocument ) throw new Error( "Cannot access the iframe content document. Check for cross-domain policy restrictions." ); documentStyles = documentStyles ? '<style type="text/css">\n' + documentStyles + '\n</style>\n' : ""; iframe.contentDocument.write( '<!DOCTYPE html>\n<html>\n<head>\n<meta charset="UTF-8">\n<title></title>\n' + documentStyles + '</head>\n<body>\n</body>\n</html>' ); return iframe.contentDocument; }
[ "function", "createIframeDocument", "(", "iframe", ",", "documentStyles", ")", "{", "if", "(", "varExists", "(", "$", ")", "&&", "iframe", "instanceof", "$", ")", "iframe", "=", "iframe", "[", "0", "]", ";", "if", "(", "!", "iframe", ".", "ownerDocument", ".", "body", ".", "contains", "(", "iframe", ")", ")", "throw", "new", "Error", "(", "\"The iframe has not been appended to the DOM, or is not a descendant of the body element. Can't create an iframe content document.\"", ")", ";", "if", "(", "!", "iframe", ".", "contentDocument", ")", "throw", "new", "Error", "(", "\"Cannot access the iframe content document. Check for cross-domain policy restrictions.\"", ")", ";", "documentStyles", "=", "documentStyles", "?", "'<style type=\"text/css\">\\n'", "+", "documentStyles", "+", "'\\n</style>\\n'", ":", "\"\"", ";", "iframe", ".", "contentDocument", ".", "write", "(", "'<!DOCTYPE html>\\n<html>\\n<head>\\n<meta charset=\"UTF-8\">\\n<title></title>\\n'", "+", "documentStyles", "+", "'</head>\\n<body>\\n</body>\\n</html>'", ")", ";", "return", "iframe", ".", "contentDocument", ";", "}" ]
Creates an iframe document with an HTML5 doctype and UTF-8 encoding. The iframe element MUST have been appended to the DOM by the time this function is called, and it must be a descendant of the body element. A document inside an iframe can only be created when these conditions are met. @param {HTMLIFrameElement|jQuery} iframe @param {string} [documentStyles] cssText string of CSS rules, styles the iframe document, e.g. "html, body { overflow: hidden; } div.foo { margin: 2em; }" @returns {Document}
[ "Creates", "an", "iframe", "document", "with", "an", "HTML5", "doctype", "and", "UTF", "-", "8", "encoding", "." ]
4f9c24f054f604b165082bbe5b3b424ad042a729
https://github.com/hashchange/jquery.documentsize/blob/4f9c24f054f604b165082bbe5b3b424ad042a729/spec/helpers/dom-utils.js#L120-L130
40,694
hashchange/jquery.documentsize
spec/helpers/dom-utils.js
windowSizeReady
function windowSizeReady ( queriedWindow, readyDfd, interval ) { if ( !varExists( $ ) ) throw new Error( "This method uses jQuery deferreds, but the $ variable is not available" ); if ( queriedWindow instanceof $ ) queriedWindow = queriedWindow[0]; readyDfd || ( readyDfd = $.Deferred() ); $( queriedWindow.document ).ready( function () { var documentElement = queriedWindow.document.documentElement, lastSize = { width: documentElement.clientWidth, height: documentElement.clientHeight }, repeater = setInterval( function () { var width = documentElement.clientWidth, height = documentElement.clientHeight, isStable = width > 0 && height > 0 && width === lastSize.width && height === lastSize.height; if ( isStable ) { clearInterval( repeater ); readyDfd.resolve(); } else { lastSize = { width: width, height: height }; } }, interval || 100 ); } ); return readyDfd; }
javascript
function windowSizeReady ( queriedWindow, readyDfd, interval ) { if ( !varExists( $ ) ) throw new Error( "This method uses jQuery deferreds, but the $ variable is not available" ); if ( queriedWindow instanceof $ ) queriedWindow = queriedWindow[0]; readyDfd || ( readyDfd = $.Deferred() ); $( queriedWindow.document ).ready( function () { var documentElement = queriedWindow.document.documentElement, lastSize = { width: documentElement.clientWidth, height: documentElement.clientHeight }, repeater = setInterval( function () { var width = documentElement.clientWidth, height = documentElement.clientHeight, isStable = width > 0 && height > 0 && width === lastSize.width && height === lastSize.height; if ( isStable ) { clearInterval( repeater ); readyDfd.resolve(); } else { lastSize = { width: width, height: height }; } }, interval || 100 ); } ); return readyDfd; }
[ "function", "windowSizeReady", "(", "queriedWindow", ",", "readyDfd", ",", "interval", ")", "{", "if", "(", "!", "varExists", "(", "$", ")", ")", "throw", "new", "Error", "(", "\"This method uses jQuery deferreds, but the $ variable is not available\"", ")", ";", "if", "(", "queriedWindow", "instanceof", "$", ")", "queriedWindow", "=", "queriedWindow", "[", "0", "]", ";", "readyDfd", "||", "(", "readyDfd", "=", "$", ".", "Deferred", "(", ")", ")", ";", "$", "(", "queriedWindow", ".", "document", ")", ".", "ready", "(", "function", "(", ")", "{", "var", "documentElement", "=", "queriedWindow", ".", "document", ".", "documentElement", ",", "lastSize", "=", "{", "width", ":", "documentElement", ".", "clientWidth", ",", "height", ":", "documentElement", ".", "clientHeight", "}", ",", "repeater", "=", "setInterval", "(", "function", "(", ")", "{", "var", "width", "=", "documentElement", ".", "clientWidth", ",", "height", "=", "documentElement", ".", "clientHeight", ",", "isStable", "=", "width", ">", "0", "&&", "height", ">", "0", "&&", "width", "===", "lastSize", ".", "width", "&&", "height", "===", "lastSize", ".", "height", ";", "if", "(", "isStable", ")", "{", "clearInterval", "(", "repeater", ")", ";", "readyDfd", ".", "resolve", "(", ")", ";", "}", "else", "{", "lastSize", "=", "{", "width", ":", "width", ",", "height", ":", "height", "}", ";", "}", "}", ",", "interval", "||", "100", ")", ";", "}", ")", ";", "return", "readyDfd", ";", "}" ]
Waits for the size of a window to become stable, in case it is undergoing a change. Returns a deferred which resolves when the window size is stable. Optionally accepts an external jQuery deferred to act on, which is then returned instead. This check can be used to determine when the process of resizing a window has ended. It should also be used when a new window is created. Technique --------- In most cases, it would be enough to set a timeout of 0 and then resolve the deferred. The timeout frees the UI and allows the window to assume its eventual size before the deferred is resolved. Unfortunately, the success rate of this approach is close to, but not quite, 100%. So instead, we check the reported window size in regular intervals, so we know for sure when it is stable. @param {Window|jQuery} queriedWindow the window to observe, also accepted inside a jQuery `$( window )` wrapper @param {jQuery.Deferred} [readyDfd] @param {number} [interval=100] the interval for checking the window size, in ms @returns {jQuery.Deferred}
[ "Waits", "for", "the", "size", "of", "a", "window", "to", "become", "stable", "in", "case", "it", "is", "undergoing", "a", "change", ".", "Returns", "a", "deferred", "which", "resolves", "when", "the", "window", "size", "is", "stable", "." ]
4f9c24f054f604b165082bbe5b3b424ad042a729
https://github.com/hashchange/jquery.documentsize/blob/4f9c24f054f604b165082bbe5b3b424ad042a729/spec/helpers/dom-utils.js#L156-L188
40,695
hashchange/jquery.documentsize
spec/helpers/dom-utils.js
validateWindowSize
function validateWindowSize ( expected, opts ) { var msg = "", documentElement = ( opts && opts.window || window ).document.documentElement, width = documentElement.clientWidth, height = documentElement.clientHeight; if ( opts && opts.exactly ) { if ( width !== expected.width ) msg = " Window width is " + width + "px (expected: " + expected.width + "px)."; if ( height !== expected.height ) msg += " Window height is " + height + "px (expected: " + expected.height + "px)."; } else { if ( width < expected.width ) msg = " Window width is " + width + "px (expected minimum: " + expected.width + "px)."; if ( height < expected.height ) msg += " Window height is " + height + "px (expected minimum: " + expected.height + "px)."; } if ( msg !== "" ) throw new Error( "The browser window does not match the expected size." + msg ); }
javascript
function validateWindowSize ( expected, opts ) { var msg = "", documentElement = ( opts && opts.window || window ).document.documentElement, width = documentElement.clientWidth, height = documentElement.clientHeight; if ( opts && opts.exactly ) { if ( width !== expected.width ) msg = " Window width is " + width + "px (expected: " + expected.width + "px)."; if ( height !== expected.height ) msg += " Window height is " + height + "px (expected: " + expected.height + "px)."; } else { if ( width < expected.width ) msg = " Window width is " + width + "px (expected minimum: " + expected.width + "px)."; if ( height < expected.height ) msg += " Window height is " + height + "px (expected minimum: " + expected.height + "px)."; } if ( msg !== "" ) throw new Error( "The browser window does not match the expected size." + msg ); }
[ "function", "validateWindowSize", "(", "expected", ",", "opts", ")", "{", "var", "msg", "=", "\"\"", ",", "documentElement", "=", "(", "opts", "&&", "opts", ".", "window", "||", "window", ")", ".", "document", ".", "documentElement", ",", "width", "=", "documentElement", ".", "clientWidth", ",", "height", "=", "documentElement", ".", "clientHeight", ";", "if", "(", "opts", "&&", "opts", ".", "exactly", ")", "{", "if", "(", "width", "!==", "expected", ".", "width", ")", "msg", "=", "\" Window width is \"", "+", "width", "+", "\"px (expected: \"", "+", "expected", ".", "width", "+", "\"px).\"", ";", "if", "(", "height", "!==", "expected", ".", "height", ")", "msg", "+=", "\" Window height is \"", "+", "height", "+", "\"px (expected: \"", "+", "expected", ".", "height", "+", "\"px).\"", ";", "}", "else", "{", "if", "(", "width", "<", "expected", ".", "width", ")", "msg", "=", "\" Window width is \"", "+", "width", "+", "\"px (expected minimum: \"", "+", "expected", ".", "width", "+", "\"px).\"", ";", "if", "(", "height", "<", "expected", ".", "height", ")", "msg", "+=", "\" Window height is \"", "+", "height", "+", "\"px (expected minimum: \"", "+", "expected", ".", "height", "+", "\"px).\"", ";", "}", "if", "(", "msg", "!==", "\"\"", ")", "throw", "new", "Error", "(", "\"The browser window does not match the expected size.\"", "+", "msg", ")", ";", "}" ]
Makes sure a window is as at least as large as the specified minimum. If the window is too small, an error is thrown. Optionally, it can be validated that the window matches the expected size exactly. @param {Object} expected @param {number} expected.width @param {number} expected.height @param {Object} [opts] @param {Object} [opts.window=window] a window handle, defaults to the global `window` @param {boolean} [opts.exactly=false]
[ "Makes", "sure", "a", "window", "is", "as", "at", "least", "as", "large", "as", "the", "specified", "minimum", ".", "If", "the", "window", "is", "too", "small", "an", "error", "is", "thrown", "." ]
4f9c24f054f604b165082bbe5b3b424ad042a729
https://github.com/hashchange/jquery.documentsize/blob/4f9c24f054f604b165082bbe5b3b424ad042a729/spec/helpers/dom-utils.js#L203-L218
40,696
hashchange/jquery.documentsize
spec/helpers/dom-utils.js
forceReflow
function forceReflow ( element ) { if ( !varExists( $ ) ) throw new Error( "This method uses jQuery, but the $ variable is not available" ); var $element = element instanceof $ ? element : $( element ); $element.css( { display: "none" } ).height(); $element.css( { display: "block" } ); }
javascript
function forceReflow ( element ) { if ( !varExists( $ ) ) throw new Error( "This method uses jQuery, but the $ variable is not available" ); var $element = element instanceof $ ? element : $( element ); $element.css( { display: "none" } ).height(); $element.css( { display: "block" } ); }
[ "function", "forceReflow", "(", "element", ")", "{", "if", "(", "!", "varExists", "(", "$", ")", ")", "throw", "new", "Error", "(", "\"This method uses jQuery, but the $ variable is not available\"", ")", ";", "var", "$element", "=", "element", "instanceof", "$", "?", "element", ":", "$", "(", "element", ")", ";", "$element", ".", "css", "(", "{", "display", ":", "\"none\"", "}", ")", ".", "height", "(", ")", ";", "$element", ".", "css", "(", "{", "display", ":", "\"block\"", "}", ")", ";", "}" ]
Forces a reflow for a given element, in case it doesn't happen automatically. For the technique, see http://stackoverflow.com/a/14382251/508355 For some background, see e.g. http://apmblog.dynatrace.com/2009/12/12/understanding-internet-explorer-rendering-behaviour/ @param {HTMLElement|jQuery} element
[ "Forces", "a", "reflow", "for", "a", "given", "element", "in", "case", "it", "doesn", "t", "happen", "automatically", "." ]
4f9c24f054f604b165082bbe5b3b424ad042a729
https://github.com/hashchange/jquery.documentsize/blob/4f9c24f054f604b165082bbe5b3b424ad042a729/spec/helpers/dom-utils.js#L256-L263
40,697
hashchange/jquery.documentsize
spec/helpers/dom-utils.js
isIE
function isIE ( opts ) { var ver = getIEVersion(), isMatch = ver !== 0; opts || ( opts = {} ); if ( isMatch && opts.eq ) isMatch = ver === opts.eq; if ( isMatch && opts.lt ) isMatch = ver < opts.lt; if ( isMatch && opts.lte ) isMatch = ver <= opts.lte; if ( isMatch && opts.gt ) isMatch = ver > opts.gt; if ( isMatch && opts.gte ) isMatch = ver >= opts.gte; return isMatch; }
javascript
function isIE ( opts ) { var ver = getIEVersion(), isMatch = ver !== 0; opts || ( opts = {} ); if ( isMatch && opts.eq ) isMatch = ver === opts.eq; if ( isMatch && opts.lt ) isMatch = ver < opts.lt; if ( isMatch && opts.lte ) isMatch = ver <= opts.lte; if ( isMatch && opts.gt ) isMatch = ver > opts.gt; if ( isMatch && opts.gte ) isMatch = ver >= opts.gte; return isMatch; }
[ "function", "isIE", "(", "opts", ")", "{", "var", "ver", "=", "getIEVersion", "(", ")", ",", "isMatch", "=", "ver", "!==", "0", ";", "opts", "||", "(", "opts", "=", "{", "}", ")", ";", "if", "(", "isMatch", "&&", "opts", ".", "eq", ")", "isMatch", "=", "ver", "===", "opts", ".", "eq", ";", "if", "(", "isMatch", "&&", "opts", ".", "lt", ")", "isMatch", "=", "ver", "<", "opts", ".", "lt", ";", "if", "(", "isMatch", "&&", "opts", ".", "lte", ")", "isMatch", "=", "ver", "<=", "opts", ".", "lte", ";", "if", "(", "isMatch", "&&", "opts", ".", "gt", ")", "isMatch", "=", "ver", ">", "opts", ".", "gt", ";", "if", "(", "isMatch", "&&", "opts", ".", "gte", ")", "isMatch", "=", "ver", ">=", "opts", ".", "gte", ";", "return", "isMatch", ";", "}" ]
Detects IE. Can use a version requirement. A range can also be specified, e.g. with an option like { gte: 8, lt: 11 }. @param {Object} [opts] @param {number} [opts.eq] the IE version must be as specified @param {number} [opts.lt] the IE version must be less than the one specified @param {number} [opts.lte] the IE version must be less than or equal to the one specified @param {number} [opts.gt] the IE version must be greater than the one specified @param {number} [opts.gte] the IE version must be greater than or equal to the one specified
[ "Detects", "IE", "." ]
4f9c24f054f604b165082bbe5b3b424ad042a729
https://github.com/hashchange/jquery.documentsize/blob/4f9c24f054f604b165082bbe5b3b424ad042a729/spec/helpers/dom-utils.js#L416-L429
40,698
hashchange/jquery.documentsize
spec/helpers/dom-utils.js
getIEVersion
function getIEVersion () { var ieMatch = /MSIE (\d+)/.exec( navigator.userAgent ) || /Trident\/.+? rv:(\d+)/.exec( navigator.userAgent ); return ( ieMatch && ieMatch.length ) ? parseFloat( ieMatch[1] ) : 0; }
javascript
function getIEVersion () { var ieMatch = /MSIE (\d+)/.exec( navigator.userAgent ) || /Trident\/.+? rv:(\d+)/.exec( navigator.userAgent ); return ( ieMatch && ieMatch.length ) ? parseFloat( ieMatch[1] ) : 0; }
[ "function", "getIEVersion", "(", ")", "{", "var", "ieMatch", "=", "/", "MSIE (\\d+)", "/", ".", "exec", "(", "navigator", ".", "userAgent", ")", "||", "/", "Trident\\/.+? rv:(\\d+)", "/", ".", "exec", "(", "navigator", ".", "userAgent", ")", ";", "return", "(", "ieMatch", "&&", "ieMatch", ".", "length", ")", "?", "parseFloat", "(", "ieMatch", "[", "1", "]", ")", ":", "0", ";", "}" ]
Detects the IE version. Returns the major version number, or 0 if the browser is not IE. Simple solution, solely based on UA sniffing. In a better implementation, conditional comments would be used to detect IE6 to IE9 - see https://gist.github.com/cowboy/542301 for an example. UA sniffing would only serve as a fallback to detect IE > 9. There are also other solutions to infer the version of IE > 9. For inspiration, see http://stackoverflow.com/q/17907445/508355.
[ "Detects", "the", "IE", "version", ".", "Returns", "the", "major", "version", "number", "or", "0", "if", "the", "browser", "is", "not", "IE", "." ]
4f9c24f054f604b165082bbe5b3b424ad042a729
https://github.com/hashchange/jquery.documentsize/blob/4f9c24f054f604b165082bbe5b3b424ad042a729/spec/helpers/dom-utils.js#L439-L442
40,699
klei/grunt-injector
tasks/injector.js
removeEmptySources
function removeEmptySources (sources) { return _.reject(sources, function (obj) { return _.isEmpty(obj.transformed); }); }
javascript
function removeEmptySources (sources) { return _.reject(sources, function (obj) { return _.isEmpty(obj.transformed); }); }
[ "function", "removeEmptySources", "(", "sources", ")", "{", "return", "_", ".", "reject", "(", "sources", ",", "function", "(", "obj", ")", "{", "return", "_", ".", "isEmpty", "(", "obj", ".", "transformed", ")", ";", "}", ")", ";", "}" ]
Remove the entry whose transformed string is empty since we don't want to inject empty string.
[ "Remove", "the", "entry", "whose", "transformed", "string", "is", "empty", "since", "we", "don", "t", "want", "to", "inject", "empty", "string", "." ]
6387c056f74f35a65a462a6e07f2247a11da5a46
https://github.com/klei/grunt-injector/blob/6387c056f74f35a65a462a6e07f2247a11da5a46/tasks/injector.js#L292-L296