_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q20100
|
train
|
function(ev) {
if (sourceElem === target[0] && ev.target === target[0]) {
ev.stopPropagation();
ev.preventDefault();
smartClose();
}
}
|
javascript
|
{
"resource": ""
}
|
|
q20101
|
configureAria
|
train
|
function configureAria(element, options) {
var role = (options.$type === 'alert') ? 'alertdialog' : 'dialog';
var dialogContent = element.find('md-dialog-content');
var existingDialogId = element.attr('id');
var dialogContentId = 'dialogContent_' + (existingDialogId || $mdUtil.nextUid());
element.attr({
'role': role,
'tabIndex': '-1'
});
if (dialogContent.length === 0) {
dialogContent = element;
// If the dialog element already had an ID, don't clobber it.
if (existingDialogId) {
dialogContentId = existingDialogId;
}
}
dialogContent.attr('id', dialogContentId);
element.attr('aria-describedby', dialogContentId);
if (options.ariaLabel) {
$mdAria.expect(element, 'aria-label', options.ariaLabel);
}
else {
$mdAria.expectAsync(element, 'aria-label', function() {
// If dialog title is specified, set aria-label with it
// See https://github.com/angular/material/issues/10582
if (options.title) {
return options.title;
} else {
var words = dialogContent.text().split(/\s+/);
if (words.length > 3) words = words.slice(0, 3).concat('...');
return words.join(' ');
}
});
}
// Set up elements before and after the dialog content to capture focus and
// redirect back into the dialog.
topFocusTrap = document.createElement('div');
topFocusTrap.classList.add('md-dialog-focus-trap');
topFocusTrap.tabIndex = 0;
bottomFocusTrap = topFocusTrap.cloneNode(false);
// When focus is about to move out of the dialog, we want to intercept it and redirect it
// back to the dialog element.
var focusHandler = function() {
element.focus();
};
topFocusTrap.addEventListener('focus', focusHandler);
bottomFocusTrap.addEventListener('focus', focusHandler);
// The top focus trap inserted immeidately before the md-dialog element (as a sibling).
// The bottom focus trap is inserted at the very end of the md-dialog element (as a child).
element[0].parentNode.insertBefore(topFocusTrap, element[0]);
element.after(bottomFocusTrap);
}
|
javascript
|
{
"resource": ""
}
|
q20102
|
lockScreenReader
|
train
|
function lockScreenReader(element, options) {
var isHidden = true;
// get raw DOM node
walkDOM(element[0]);
options.unlockScreenReader = function () {
isHidden = false;
walkDOM(element[0]);
options.unlockScreenReader = null;
};
/**
* Get all of an element's parent elements up the DOM tree
* @return {Array} The parent elements
*/
function getParents(element) {
var parents = [];
while (element.parentNode) {
if (element === document.body) {
return parents;
}
var children = element.parentNode.children;
for (var i = 0; i < children.length; i++) {
// skip over child if it is an ascendant of the dialog
// a script or style tag, or a live region.
if (element !== children[i] &&
!isNodeOneOf(children[i], ['SCRIPT', 'STYLE']) &&
!children[i].hasAttribute('aria-live')) {
parents.push(children[i]);
}
}
element = element.parentNode;
}
return parents;
}
/**
* Walk DOM to apply or remove aria-hidden on sibling nodes
* and parent sibling nodes
*/
function walkDOM(element) {
var elements = getParents(element);
for (var i = 0; i < elements.length; i++) {
elements[i].setAttribute('aria-hidden', isHidden);
}
}
}
|
javascript
|
{
"resource": ""
}
|
q20103
|
getParents
|
train
|
function getParents(element) {
var parents = [];
while (element.parentNode) {
if (element === document.body) {
return parents;
}
var children = element.parentNode.children;
for (var i = 0; i < children.length; i++) {
// skip over child if it is an ascendant of the dialog
// a script or style tag, or a live region.
if (element !== children[i] &&
!isNodeOneOf(children[i], ['SCRIPT', 'STYLE']) &&
!children[i].hasAttribute('aria-live')) {
parents.push(children[i]);
}
}
element = element.parentNode;
}
return parents;
}
|
javascript
|
{
"resource": ""
}
|
q20104
|
walkDOM
|
train
|
function walkDOM(element) {
var elements = getParents(element);
for (var i = 0; i < elements.length; i++) {
elements[i].setAttribute('aria-hidden', isHidden);
}
}
|
javascript
|
{
"resource": ""
}
|
q20105
|
stretchDialogContainerToViewport
|
train
|
function stretchDialogContainerToViewport(container, options) {
var isFixed = $window.getComputedStyle($document[0].body).position == 'fixed';
var backdrop = options.backdrop ? $window.getComputedStyle(options.backdrop[0]) : null;
var height = backdrop ? Math.min($document[0].body.clientHeight, Math.ceil(Math.abs(parseInt(backdrop.height, 10)))) : 0;
var previousStyles = {
top: container.css('top'),
height: container.css('height')
};
// If the body is fixed, determine the distance to the viewport in relative from the parent.
var parentTop = Math.abs(options.parent[0].getBoundingClientRect().top);
container.css({
top: (isFixed ? parentTop : 0) + 'px',
height: height ? height + 'px' : '100%'
});
return function() {
// Reverts the modified styles back to the previous values.
// This is needed for contentElements, which should have the same styles after close
// as before.
container.css(previousStyles);
};
}
|
javascript
|
{
"resource": ""
}
|
q20106
|
dialogPopIn
|
train
|
function dialogPopIn(container, options) {
// Add the `md-dialog-container` to the DOM
options.parent.append(container);
options.reverseContainerStretch = stretchDialogContainerToViewport(container, options);
var dialogEl = container.find('md-dialog');
var animator = $mdUtil.dom.animator;
var buildTranslateToOrigin = animator.calculateZoomToOrigin;
var translateOptions = {transitionInClass: 'md-transition-in', transitionOutClass: 'md-transition-out'};
var from = animator.toTransformCss(buildTranslateToOrigin(dialogEl, options.openFrom || options.origin));
var to = animator.toTransformCss(""); // defaults to center display (or parent or $rootElement)
dialogEl.toggleClass('md-dialog-fullscreen', !!options.fullscreen);
return animator
.translate3d(dialogEl, from, to, translateOptions)
.then(function(animateReversal) {
// Build a reversal translate function synced to this translation...
options.reverseAnimate = function() {
delete options.reverseAnimate;
if (options.closeTo) {
// Using the opposite classes to create a close animation to the closeTo element
translateOptions = {transitionInClass: 'md-transition-out', transitionOutClass: 'md-transition-in'};
from = to;
to = animator.toTransformCss(buildTranslateToOrigin(dialogEl, options.closeTo));
return animator
.translate3d(dialogEl, from, to,translateOptions);
}
return animateReversal(
to = animator.toTransformCss(
// in case the origin element has moved or is hidden,
// let's recalculate the translateCSS
buildTranslateToOrigin(dialogEl, options.origin)
)
);
};
// Function to revert the generated animation styles on the dialog element.
// Useful when using a contentElement instead of a template.
options.clearAnimate = function() {
delete options.clearAnimate;
// Remove the transition classes, added from $animateCSS, since those can't be removed
// by reversely running the animator.
dialogEl.removeClass([
translateOptions.transitionOutClass,
translateOptions.transitionInClass
].join(' '));
// Run the animation reversely to remove the previous added animation styles.
return animator.translate3d(dialogEl, to, animator.toTransformCss(''), {});
};
return true;
});
}
|
javascript
|
{
"resource": ""
}
|
q20107
|
dialogPopOut
|
train
|
function dialogPopOut(container, options) {
return options.reverseAnimate().then(function() {
if (options.contentElement) {
// When we use a contentElement, we want the element to be the same as before.
// That means, that we have to clear all the animation properties, like transform.
options.clearAnimate();
}
});
}
|
javascript
|
{
"resource": ""
}
|
q20108
|
watchAttributes
|
train
|
function watchAttributes() {
attr.$observe('value', function(value) {
var percentValue = clamp(value);
element.attr('aria-valuenow', percentValue);
if (mode() != MODE_QUERY) animateIndicator(bar2, percentValue);
});
attr.$observe('mdBufferValue', function(value) {
animateIndicator(bar1, clamp(value));
});
attr.$observe('disabled', function(value) {
if (value === true || value === false) {
isDisabled = !!value;
} else {
isDisabled = angular.isDefined(value);
}
element.toggleClass(DISABLED_CLASS, isDisabled);
container.toggleClass(lastMode, !isDisabled);
});
attr.$observe('mdMode', function(mode) {
if (lastMode) container.removeClass(lastMode);
switch (mode) {
case MODE_QUERY:
case MODE_BUFFER:
case MODE_DETERMINATE:
case MODE_INDETERMINATE:
container.addClass(lastMode = "md-mode-" + mode);
break;
default:
container.addClass(lastMode = "md-mode-" + MODE_INDETERMINATE);
break;
}
});
}
|
javascript
|
{
"resource": ""
}
|
q20109
|
validateMode
|
train
|
function validateMode() {
if (angular.isUndefined(attr.mdMode)) {
var hasValue = angular.isDefined(attr.value);
var mode = hasValue ? MODE_DETERMINATE : MODE_INDETERMINATE;
var info = "Auto-adding the missing md-mode='{0}' to the ProgressLinear element";
element.attr("md-mode", mode);
attr.mdMode = mode;
}
}
|
javascript
|
{
"resource": ""
}
|
q20110
|
mode
|
train
|
function mode() {
var value = (attr.mdMode || "").trim();
if (value) {
switch (value) {
case MODE_DETERMINATE:
case MODE_INDETERMINATE:
case MODE_BUFFER:
case MODE_QUERY:
break;
default:
value = MODE_INDETERMINATE;
break;
}
}
return value;
}
|
javascript
|
{
"resource": ""
}
|
q20111
|
updateInputCursor
|
train
|
function updateInputCursor() {
if (isValidInput) {
var inputLength = input[0].value.length;
try {
input[0].selectionStart = input[0].selectionEnd = inputLength;
} catch (e) {
// Chrome does not allow setting a selection for number inputs and just throws
// a DOMException as soon as something tries to set a selection programmatically.
// Faking the selection properties for the ChipsController works for our tests.
var selectionDescriptor = { writable: true, value: inputLength };
Object.defineProperty(input[0], 'selectionStart', selectionDescriptor);
Object.defineProperty(input[0], 'selectionEnd', selectionDescriptor);
}
}
}
|
javascript
|
{
"resource": ""
}
|
q20112
|
getBoundingRect
|
train
|
function getBoundingRect(el) {
const clientRect = el.getBoundingClientRect();
const bound = {
left: clientRect.left,
top: clientRect.top,
width: clientRect.width,
height: clientRect.height
};
let frame = el.ownerDocument.defaultView.frameElement;
while (frame) {
const frameBound = frame.getBoundingClientRect();
// This computation doesn't account for more complex CSS transforms on the
// frame (e.g. scaling or rotations).
bound.left += frameBound.left;
bound.top += frameBound.top;
frame = frame.ownerDocument.frameElement;
}
return bound;
}
|
javascript
|
{
"resource": ""
}
|
q20113
|
getPageScaleFactor
|
train
|
function getPageScaleFactor() {
const pageScaleFactor = chrome.gpuBenchmarking.pageScaleFactor;
return pageScaleFactor ? pageScaleFactor.apply(chrome.gpuBenchmarking) : 1;
}
|
javascript
|
{
"resource": ""
}
|
q20114
|
getBoundingVisibleRect
|
train
|
function getBoundingVisibleRect(el) {
// Get the element bounding rect in the layout viewport.
const rect = getBoundingRect(el);
// Apply the visual viewport transform (i.e. pinch-zoom) to the bounding
// rect. The viewportX|Y values are in CSS pixels so they don't change
// with page scale. We first translate so that the viewport offset is
// at the origin and then we apply the scaling factor.
const scale = getPageScaleFactor();
const visualViewportX = chrome.gpuBenchmarking.visualViewportX();
const visualViewportY = chrome.gpuBenchmarking.visualViewportY();
rect.top = (rect.top - visualViewportY) * scale;
rect.left = (rect.left - visualViewportX) * scale;
rect.width *= scale;
rect.height *= scale;
// Get the window dimensions.
const windowHeight = getWindowHeight();
const windowWidth = getWindowWidth();
// Then clip the rect to the screen size.
rect.top = clamp(0, rect.top, windowHeight);
rect.left = clamp(0, rect.left, windowWidth);
rect.height = clamp(0, rect.height, windowHeight - rect.top);
rect.width = clamp(0, rect.width, windowWidth - rect.left);
return rect;
}
|
javascript
|
{
"resource": ""
}
|
q20115
|
mutablePropertyChange
|
train
|
function mutablePropertyChange(inst, property, value, old, mutableData) {
let isObject;
if (mutableData) {
isObject = (typeof value === 'object' && value !== null);
// Pull `old` for Objects from temp cache, but treat `null` as a primitive
if (isObject) {
old = inst.__dataTemp[property];
}
}
// Strict equality check, but return false for NaN===NaN
let shouldChange = (old !== value && (old === old || value === value));
// Objects are stored in temporary cache (cleared at end of
// turn), which is used for dirty-checking
if (isObject && shouldChange) {
inst.__dataTemp[property] = value;
}
return shouldChange;
}
|
javascript
|
{
"resource": ""
}
|
q20116
|
wire
|
train
|
function wire (httpMethodName, contentSource, body, headers, withCredentials){
var oboeBus = pubSub();
// Wire the input stream in if we are given a content source.
// This will usually be the case. If not, the instance created
// will have to be passed content from an external source.
if( contentSource ) {
streamingHttp( oboeBus,
httpTransport(),
httpMethodName,
contentSource,
body,
headers,
withCredentials
);
}
clarinet(oboeBus);
ascentManager(oboeBus, incrementalContentBuilder(oboeBus));
patternAdapter(oboeBus, jsonPathCompiler);
return instanceApi(oboeBus, contentSource);
}
|
javascript
|
{
"resource": ""
}
|
q20117
|
oboe
|
train
|
function oboe(arg1) {
// We use duck-typing to detect if the parameter given is a stream, with the
// below list of parameters.
// Unpipe and unshift would normally be present on a stream but this breaks
// compatibility with Request streams.
// See https://github.com/jimhigson/oboe.js/issues/65
var nodeStreamMethodNames = list('resume', 'pause', 'pipe'),
isStream = partialComplete(
hasAllProperties
, nodeStreamMethodNames
);
if( arg1 ) {
if (isStream(arg1) || isString(arg1)) {
// simple version for GETs. Signature is:
// oboe( url )
// or, under node:
// oboe( readableStream )
return applyDefaults(
wire,
arg1 // url
);
} else {
// method signature is:
// oboe({method:m, url:u, body:b, headers:{...}})
return applyDefaults(
wire,
arg1.url,
arg1.method,
arg1.body,
arg1.headers,
arg1.withCredentials,
arg1.cached
);
}
} else {
// wire up a no-AJAX, no-stream Oboe. Will have to have content
// fed in externally and using .emit.
return wire();
}
}
|
javascript
|
{
"resource": ""
}
|
q20118
|
announceAccessibleMessage
|
train
|
function announceAccessibleMessage(msg) {
var element = document.createElement('div');
element.setAttribute('aria-live', 'polite');
element.style.position = 'relative';
element.style.left = '-9999px';
element.style.height = '0px';
element.innerText = msg;
document.body.appendChild(element);
window.setTimeout(function() {
document.body.removeChild(element);
}, 0);
}
|
javascript
|
{
"resource": ""
}
|
q20119
|
url
|
train
|
function url(s) {
// http://www.w3.org/TR/css3-values/#uris
// Parentheses, commas, whitespace characters, single quotes (') and double
// quotes (") appearing in a URI must be escaped with a backslash
var s2 = s.replace(/(\(|\)|\,|\s|\'|\"|\\)/g, '\\$1');
// WebKit has a bug when it comes to URLs that end with \
// https://bugs.webkit.org/show_bug.cgi?id=28885
if (/\\\\$/.test(s2)) {
// Add a space to work around the WebKit bug.
s2 += ' ';
}
return 'url("' + s2 + '")';
}
|
javascript
|
{
"resource": ""
}
|
q20120
|
parseQueryParams
|
train
|
function parseQueryParams(location) {
var params = {};
var query = unescape(location.search.substring(1));
var vars = query.split('&');
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
params[pair[0]] = pair[1];
}
return params;
}
|
javascript
|
{
"resource": ""
}
|
q20121
|
setQueryParam
|
train
|
function setQueryParam(location, key, value) {
var query = parseQueryParams(location);
query[encodeURIComponent(key)] = encodeURIComponent(value);
var newQuery = '';
for (var q in query) {
newQuery += (newQuery ? '&' : '?') + q + '=' + query[q];
}
return location.origin + location.pathname + newQuery + location.hash;
}
|
javascript
|
{
"resource": ""
}
|
q20122
|
disableTextSelectAndDrag
|
train
|
function disableTextSelectAndDrag(opt_allowSelectStart, opt_allowDragStart) {
// Disable text selection.
document.onselectstart = function(e) {
if (!(opt_allowSelectStart && opt_allowSelectStart.call(this, e)))
e.preventDefault();
};
// Disable dragging.
document.ondragstart = function(e) {
if (!(opt_allowDragStart && opt_allowDragStart.call(this, e)))
e.preventDefault();
};
}
|
javascript
|
{
"resource": ""
}
|
q20123
|
queryRequiredElement
|
train
|
function queryRequiredElement(selectors, opt_context) {
var element = (opt_context || document).querySelector(selectors);
return assertInstanceof(element, HTMLElement,
'Missing required element: ' + selectors);
}
|
javascript
|
{
"resource": ""
}
|
q20124
|
appendParam
|
train
|
function appendParam(url, key, value) {
var param = encodeURIComponent(key) + '=' + encodeURIComponent(value);
if (url.indexOf('?') == -1)
return url + '?' + param;
return url + '&' + param;
}
|
javascript
|
{
"resource": ""
}
|
q20125
|
createElementWithClassName
|
train
|
function createElementWithClassName(type, className) {
var elm = document.createElement(type);
elm.className = className;
return elm;
}
|
javascript
|
{
"resource": ""
}
|
q20126
|
setScrollTopForDocument
|
train
|
function setScrollTopForDocument(doc, value) {
doc.documentElement.scrollTop = doc.body.scrollTop = value;
}
|
javascript
|
{
"resource": ""
}
|
q20127
|
setScrollLeftForDocument
|
train
|
function setScrollLeftForDocument(doc, value) {
doc.documentElement.scrollLeft = doc.body.scrollLeft = value;
}
|
javascript
|
{
"resource": ""
}
|
q20128
|
varArgs
|
train
|
function varArgs(fn){
var numberOfFixedArguments = fn.length -1,
slice = Array.prototype.slice;
if( numberOfFixedArguments == 0 ) {
// an optimised case for when there are no fixed args:
return function(){
return fn.call(this, slice.call(arguments));
}
} else if( numberOfFixedArguments == 1 ) {
// an optimised case for when there are is one fixed args:
return function(){
return fn.call(this, arguments[0], slice.call(arguments, 1));
}
}
// general case
// we know how many arguments fn will always take. Create a
// fixed-size array to hold that many, to be re-used on
// every call to the returned function
var argsHolder = Array(fn.length);
return function(){
for (var i = 0; i < numberOfFixedArguments; i++) {
argsHolder[i] = arguments[i];
}
argsHolder[numberOfFixedArguments] =
slice.call(arguments, numberOfFixedArguments);
return fn.apply( this, argsHolder);
}
}
|
javascript
|
{
"resource": ""
}
|
q20129
|
ascentManager
|
train
|
function ascentManager(oboeBus, handlers){
"use strict";
var listenerId = {},
ascent;
function stateAfter(handler) {
return function(param){
ascent = handler( ascent, param);
}
}
for( var eventName in handlers ) {
oboeBus(eventName).on(stateAfter(handlers[eventName]), listenerId);
}
oboeBus(NODE_SWAP).on(function(newNode) {
var oldHead = head(ascent),
key = keyOf(oldHead),
ancestors = tail(ascent),
parentNode;
if( ancestors ) {
parentNode = nodeOf(head(ancestors));
parentNode[key] = newNode;
}
});
oboeBus(NODE_DROP).on(function() {
var oldHead = head(ascent),
key = keyOf(oldHead),
ancestors = tail(ascent),
parentNode;
if( ancestors ) {
parentNode = nodeOf(head(ancestors));
delete parentNode[key];
}
});
oboeBus(ABORTING).on(function(){
for( var eventName in handlers ) {
oboeBus(eventName).un(listenerId);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q20130
|
PASSIVE_TOUCH
|
train
|
function PASSIVE_TOUCH(eventName) {
if (isMouseEvent(eventName) || eventName === 'touchend') {
return;
}
if (HAS_NATIVE_TA && SUPPORTS_PASSIVE && passiveTouchGestures) {
return {passive: true};
} else {
return;
}
}
|
javascript
|
{
"resource": ""
}
|
q20131
|
_add
|
train
|
function _add(node, evType, handler) {
let recognizer = gestures[evType];
let deps = recognizer.deps;
let name = recognizer.name;
let gobj = node[GESTURE_KEY];
if (!gobj) {
node[GESTURE_KEY] = gobj = {};
}
for (let i = 0, dep, gd; i < deps.length; i++) {
dep = deps[i];
// don't add mouse handlers on iOS because they cause gray selection overlays
if (IS_TOUCH_ONLY && isMouseEvent(dep) && dep !== 'click') {
continue;
}
gd = gobj[dep];
if (!gd) {
gobj[dep] = gd = {_count: 0};
}
if (gd._count === 0) {
node.addEventListener(dep, _handleNative, PASSIVE_TOUCH(dep));
}
gd[name] = (gd[name] || 0) + 1;
gd._count = (gd._count || 0) + 1;
}
node.addEventListener(evType, handler);
if (recognizer.touchAction) {
setTouchAction(node, recognizer.touchAction);
}
}
|
javascript
|
{
"resource": ""
}
|
q20132
|
_remove
|
train
|
function _remove(node, evType, handler) {
let recognizer = gestures[evType];
let deps = recognizer.deps;
let name = recognizer.name;
let gobj = node[GESTURE_KEY];
if (gobj) {
for (let i = 0, dep, gd; i < deps.length; i++) {
dep = deps[i];
gd = gobj[dep];
if (gd && gd[name]) {
gd[name] = (gd[name] || 1) - 1;
gd._count = (gd._count || 1) - 1;
if (gd._count === 0) {
node.removeEventListener(dep, _handleNative, PASSIVE_TOUCH(dep));
}
}
}
}
node.removeEventListener(evType, handler);
}
|
javascript
|
{
"resource": ""
}
|
q20133
|
_fire
|
train
|
function _fire(target, type, detail) {
let ev = new Event(type, { bubbles: true, cancelable: true, composed: true });
ev.detail = detail;
target.dispatchEvent(ev);
// forward `preventDefault` in a clean way
if (ev.defaultPrevented) {
let preventer = detail.preventer || detail.sourceEvent;
if (preventer && preventer.preventDefault) {
preventer.preventDefault();
}
}
}
|
javascript
|
{
"resource": ""
}
|
q20134
|
pubSub
|
train
|
function pubSub(){
var singles = {},
newListener = newSingle('newListener'),
removeListener = newSingle('removeListener');
function newSingle(eventName) {
return singles[eventName] = singleEventPubSub(
eventName,
newListener,
removeListener
);
}
/** pubSub instances are functions */
function pubSubInstance( eventName ){
return singles[eventName] || newSingle( eventName );
}
// add convenience EventEmitter-style uncurried form of 'emit' and 'on'
['emit', 'on', 'un'].forEach(function(methodName){
pubSubInstance[methodName] = varArgs(function(eventName, parameters){
apply( parameters, pubSubInstance( eventName )[methodName]);
});
});
return pubSubInstance;
}
|
javascript
|
{
"resource": ""
}
|
q20135
|
listAsArray
|
train
|
function listAsArray(list){
return foldR( function(arraySoFar, listItem){
arraySoFar.unshift(listItem);
return arraySoFar;
}, [], list );
}
|
javascript
|
{
"resource": ""
}
|
q20136
|
map
|
train
|
function map(fn, list) {
return list
? cons(fn(head(list)), map(fn,tail(list)))
: emptyList
;
}
|
javascript
|
{
"resource": ""
}
|
q20137
|
without
|
train
|
function without(list, test, removedFn) {
return withoutInner(list, removedFn || noop);
function withoutInner(subList, removedFn) {
return subList
? ( test(head(subList))
? (removedFn(head(subList)), tail(subList))
: cons(head(subList), withoutInner(tail(subList), removedFn))
)
: emptyList
;
}
}
|
javascript
|
{
"resource": ""
}
|
q20138
|
all
|
train
|
function all(fn, list) {
return !list ||
( fn(head(list)) && all(fn, tail(list)) );
}
|
javascript
|
{
"resource": ""
}
|
q20139
|
applyEach
|
train
|
function applyEach(fnList, args) {
if( fnList ) {
head(fnList).apply(null, args);
applyEach(tail(fnList), args);
}
}
|
javascript
|
{
"resource": ""
}
|
q20140
|
reverseList
|
train
|
function reverseList(list){
// js re-implementation of 3rd solution from:
// http://www.haskell.org/haskellwiki/99_questions/Solutions/5
function reverseInner( list, reversedAlready ) {
if( !list ) {
return reversedAlready;
}
return reverseInner(tail(list), cons(head(list), reversedAlready))
}
return reverseInner(list, emptyList);
}
|
javascript
|
{
"resource": ""
}
|
q20141
|
handleBatch
|
train
|
function handleBatch(results, showingTriaged) {
const alerts = [];
const nextRequests = [];
const triagedRequests = [];
let totalCount = 0;
for (const {body, response} of results) {
alerts.push.apply(alerts, response.anomalies);
if (body.count_limit) totalCount += response.count;
const cursor = response.next_cursor;
if (cursor) {
const request = {...body, cursor};
delete request.count_limit;
nextRequests.push(request);
}
if (!showingTriaged && body.bug_id === '') {
// Prepare to fetch triaged alerts for the untriaged alerts that
// were just received.
const request = {...body, bug_id: '*'};
delete request.recovered;
delete request.count_limit;
delete request.cursor;
delete request.is_improvement;
triagedRequests.push(request);
}
}
return {alerts, nextRequests, triagedRequests, totalCount};
}
|
javascript
|
{
"resource": ""
}
|
q20142
|
loadMore
|
train
|
function loadMore(batches, alertGroups, nextRequests, triagedRequests,
triagedMaxStartRevision, started) {
const minStartRevision = tr.b.math.Statistics.min(
alertGroups, group => tr.b.math.Statistics.min(
group.alerts, a => a.startRevision));
if (!triagedMaxStartRevision ||
(minStartRevision < triagedMaxStartRevision)) {
for (const request of triagedRequests) {
request.min_start_revision = minStartRevision;
if (triagedMaxStartRevision) {
request.max_start_revision = triagedMaxStartRevision;
}
batches.add(wrapRequest(request));
}
}
for (const next of nextRequests) {
// Always chase down cursors for triaged alerts.
// Limit the number of alertGroups displayed to prevent OOM.
if (next.bug_id === '*' ||
(alertGroups.length < ENOUGH_GROUPS &&
((performance.now() - started) < ENOUGH_LOADING_MS))) {
batches.add(wrapRequest(next));
}
}
return minStartRevision;
}
|
javascript
|
{
"resource": ""
}
|
q20143
|
patternAdapter
|
train
|
function patternAdapter(oboeBus, jsonPathCompiler) {
var predicateEventMap = {
node:oboeBus(NODE_CLOSED)
, path:oboeBus(NODE_OPENED)
};
function emitMatchingNode(emitMatch, node, ascent) {
/*
We're now calling to the outside world where Lisp-style
lists will not be familiar. Convert to standard arrays.
Also, reverse the order because it is more common to
list paths "root to leaf" than "leaf to root" */
var descent = reverseList(ascent);
emitMatch(
node,
// To make a path, strip off the last item which is the special
// ROOT_PATH token for the 'path' to the root node
listAsArray(tail(map(keyOf,descent))), // path
listAsArray(map(nodeOf, descent)) // ancestors
);
}
/*
* Set up the catching of events such as NODE_CLOSED and NODE_OPENED and, if
* matching the specified pattern, propagate to pattern-match events such as
* oboeBus('node:!')
*
*
*
* @param {Function} predicateEvent
* either oboeBus(NODE_CLOSED) or oboeBus(NODE_OPENED).
* @param {Function} compiledJsonPath
*/
function addUnderlyingListener( fullEventName, predicateEvent, compiledJsonPath ){
var emitMatch = oboeBus(fullEventName).emit;
predicateEvent.on( function (ascent) {
var maybeMatchingMapping = compiledJsonPath(ascent);
/* Possible values for maybeMatchingMapping are now:
false:
we did not match
an object/array/string/number/null:
we matched and have the node that matched.
Because nulls are valid json values this can be null.
undefined:
we matched but don't have the matching node yet.
ie, we know there is an upcoming node that matches but we
can't say anything else about it.
*/
if (maybeMatchingMapping !== false) {
emitMatchingNode(
emitMatch,
nodeOf(maybeMatchingMapping),
ascent
);
}
}, fullEventName);
oboeBus('removeListener').on( function(removedEventName){
// if the fully qualified match event listener is later removed, clean up
// by removing the underlying listener if it was the last using that pattern:
if( removedEventName == fullEventName ) {
if( !oboeBus(removedEventName).listeners( )) {
predicateEvent.un( fullEventName );
}
}
});
}
oboeBus('newListener').on( function(fullEventName){
var match = /(node|path):(.*)/.exec(fullEventName);
if( match ) {
var predicateEvent = predicateEventMap[match[1]];
if( !predicateEvent.hasListener( fullEventName) ) {
addUnderlyingListener(
fullEventName,
predicateEvent,
jsonPathCompiler( match[2] )
);
}
}
})
}
|
javascript
|
{
"resource": ""
}
|
q20144
|
protectedCallback
|
train
|
function protectedCallback( callback ) {
return function() {
try{
return callback.apply(oboeApi, arguments);
}catch(e) {
setTimeout(function() {
throw new Error(e.message);
});
}
}
}
|
javascript
|
{
"resource": ""
}
|
q20145
|
addMultipleNodeOrPathListeners
|
train
|
function addMultipleNodeOrPathListeners(eventId, listenerMap) {
for( var pattern in listenerMap ) {
addSingleNodeOrPathListener(eventId, pattern, listenerMap[pattern]);
}
}
|
javascript
|
{
"resource": ""
}
|
q20146
|
consumeParenthesised
|
train
|
function consumeParenthesised(parser, string) {
var nesting = 0;
for (var n = 0; n < string.length; n++) {
if (/\s|,/.test(string[n]) && nesting == 0) {
break;
} else if (string[n] == '(') {
nesting++;
} else if (string[n] == ')') {
nesting--;
if (nesting == 0)
n++;
if (nesting <= 0)
break;
}
}
var parsed = parser(string.substr(0, n));
return parsed == undefined ? undefined : [parsed, string.substr(n)];
}
|
javascript
|
{
"resource": ""
}
|
q20147
|
doScrollCheck
|
train
|
function doScrollCheck() {
if ( jQuery.isReady ) {
return;
}
try {
// If IE is used, use the trick by Diego Perini
// http://javascript.nwbox.com/IEContentLoaded/
document.documentElement.doScroll("left");
} catch(e) {
setTimeout( doScrollCheck, 1 );
return;
}
// and execute any waiting functions
jQuery.ready();
}
|
javascript
|
{
"resource": ""
}
|
q20148
|
createFlags
|
train
|
function createFlags( flags ) {
var object = flagsCache[ flags ] = {},
i, length;
flags = flags.split( /\s+/ );
for ( i = 0, length = flags.length; i < length; i++ ) {
object[ flags[i] ] = true;
}
return object;
}
|
javascript
|
{
"resource": ""
}
|
q20149
|
train
|
function( obj ) {
if ( obj == null ) {
obj = promise;
} else {
for ( var key in promise ) {
obj[ key ] = promise[ key ];
}
}
return obj;
}
|
javascript
|
{
"resource": ""
}
|
|
q20150
|
isEmptyDataObject
|
train
|
function isEmptyDataObject( obj ) {
for ( var name in obj ) {
// if the public data object is empty, the private is still empty
if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) {
continue;
}
if ( name !== "toJSON" ) {
return false;
}
}
return true;
}
|
javascript
|
{
"resource": ""
}
|
q20151
|
fixDefaultChecked
|
train
|
function fixDefaultChecked( elem ) {
if ( elem.type === "checkbox" || elem.type === "radio" ) {
elem.defaultChecked = elem.checked;
}
}
|
javascript
|
{
"resource": ""
}
|
q20152
|
findInputs
|
train
|
function findInputs( elem ) {
var nodeName = ( elem.nodeName || "" ).toLowerCase();
if ( nodeName === "input" ) {
fixDefaultChecked( elem );
// Skip scripts, get other children
} else if ( nodeName !== "script" && typeof elem.getElementsByTagName !== "undefined" ) {
jQuery.grep( elem.getElementsByTagName("input"), fixDefaultChecked );
}
}
|
javascript
|
{
"resource": ""
}
|
q20153
|
ajaxConvert
|
train
|
function ajaxConvert( s, response ) {
// Apply the dataFilter if provided
if ( s.dataFilter ) {
response = s.dataFilter( response, s.dataType );
}
var dataTypes = s.dataTypes,
converters = {},
i,
key,
length = dataTypes.length,
tmp,
// Current and previous dataTypes
current = dataTypes[ 0 ],
prev,
// Conversion expression
conversion,
// Conversion function
conv,
// Conversion functions (transitive conversion)
conv1,
conv2;
// For each dataType in the chain
for ( i = 1; i < length; i++ ) {
// Create converters map
// with lowercased keys
if ( i === 1 ) {
for ( key in s.converters ) {
if ( typeof key === "string" ) {
converters[ key.toLowerCase() ] = s.converters[ key ];
}
}
}
// Get the dataTypes
prev = current;
current = dataTypes[ i ];
// If current is auto dataType, update it to prev
if ( current === "*" ) {
current = prev;
// If no auto and dataTypes are actually different
} else if ( prev !== "*" && prev !== current ) {
// Get the converter
conversion = prev + " " + current;
conv = converters[ conversion ] || converters[ "* " + current ];
// If there is no direct converter, search transitively
if ( !conv ) {
conv2 = undefined;
for ( conv1 in converters ) {
tmp = conv1.split( " " );
if ( tmp[ 0 ] === prev || tmp[ 0 ] === "*" ) {
conv2 = converters[ tmp[1] + " " + current ];
if ( conv2 ) {
conv1 = converters[ conv1 ];
if ( conv1 === true ) {
conv = conv2;
} else if ( conv2 === true ) {
conv = conv1;
}
break;
}
}
}
}
// If we found no converter, dispatch an error
if ( !( conv || conv2 ) ) {
jQuery.error( "No conversion from " + conversion.replace(" "," to ") );
}
// If found converter is not an equivalence
if ( conv !== true ) {
// Convert with 1 or 2 converters accordingly
response = conv ? conv( response ) : conv2( conv1(response) );
}
}
}
return response;
}
|
javascript
|
{
"resource": ""
}
|
q20154
|
onError
|
train
|
function onError(e) {
window.__error = 'Media error: ' + e.type + ', code:' + e.target.error.code;
throw new Error(window.__error);
}
|
javascript
|
{
"resource": ""
}
|
q20155
|
GridBounds
|
train
|
function GridBounds(bounds) {
// [sw, ne]
this.minX = Math.min(bounds[0].x, bounds[1].x);
this.maxX = Math.max(bounds[0].x, bounds[1].x);
this.minY = Math.min(bounds[0].y, bounds[1].y);
this.maxY = Math.max(bounds[0].y, bounds[1].y);
}
|
javascript
|
{
"resource": ""
}
|
q20156
|
ProjectionHelperOverlay
|
train
|
function ProjectionHelperOverlay(map) {
this.setMap(map);
var TILEFACTOR = 8;
var TILESIDE = 1 << TILEFACTOR;
var RADIUS = 7;
this._map = map;
this._zoom = -1;
this._X0 =
this._Y0 =
this._X1 =
this._Y1 = -1;
}
|
javascript
|
{
"resource": ""
}
|
q20157
|
hasAllProperties
|
train
|
function hasAllProperties(fieldList, o) {
return (o instanceof Object)
&&
all(function (field) {
return (field in o);
}, fieldList);
}
|
javascript
|
{
"resource": ""
}
|
q20158
|
incrementalContentBuilder
|
train
|
function incrementalContentBuilder( oboeBus ) {
var emitNodeOpened = oboeBus(NODE_OPENED).emit,
emitNodeClosed = oboeBus(NODE_CLOSED).emit,
emitRootOpened = oboeBus(ROOT_PATH_FOUND).emit,
emitRootClosed = oboeBus(ROOT_NODE_FOUND).emit;
function arrayIndicesAreKeys( possiblyInconsistentAscent, newDeepestNode) {
/* for values in arrays we aren't pre-warned of the coming paths
(Clarinet gives no call to onkey like it does for values in objects)
so if we are in an array we need to create this path ourselves. The
key will be len(parentNode) because array keys are always sequential
numbers. */
var parentNode = nodeOf( head( possiblyInconsistentAscent));
return isOfType( Array, parentNode)
?
keyFound( possiblyInconsistentAscent,
len(parentNode),
newDeepestNode
)
:
// nothing needed, return unchanged
possiblyInconsistentAscent
;
}
function nodeOpened( ascent, newDeepestNode ) {
if( !ascent ) {
// we discovered the root node,
emitRootOpened( newDeepestNode);
return keyFound( ascent, ROOT_PATH, newDeepestNode);
}
// we discovered a non-root node
var arrayConsistentAscent = arrayIndicesAreKeys( ascent, newDeepestNode),
ancestorBranches = tail( arrayConsistentAscent),
previouslyUnmappedName = keyOf( head( arrayConsistentAscent));
appendBuiltContent(
ancestorBranches,
previouslyUnmappedName,
newDeepestNode
);
return cons(
namedNode( previouslyUnmappedName, newDeepestNode ),
ancestorBranches
);
}
/**
* Add a new value to the object we are building up to represent the
* parsed JSON
*/
function appendBuiltContent( ancestorBranches, key, node ){
nodeOf( head( ancestorBranches))[key] = node;
}
/**
* For when we find a new key in the json.
*
* @param {String|Number|Object} newDeepestName the key. If we are in an
* array will be a number, otherwise a string. May take the special
* value ROOT_PATH if the root node has just been found
*
* @param {String|Number|Object|Array|Null|undefined} [maybeNewDeepestNode]
* usually this won't be known so can be undefined. Can't use null
* to represent unknown because null is a valid value in JSON
**/
function keyFound(ascent, newDeepestName, maybeNewDeepestNode) {
if( ascent ) { // if not root
// If we have the key but (unless adding to an array) no known value
// yet. Put that key in the output but against no defined value:
appendBuiltContent( ascent, newDeepestName, maybeNewDeepestNode );
}
var ascentWithNewPath = cons(
namedNode( newDeepestName,
maybeNewDeepestNode),
ascent
);
emitNodeOpened( ascentWithNewPath);
return ascentWithNewPath;
}
/**
* For when the current node ends.
*/
function nodeClosed( ascent ) {
emitNodeClosed( ascent);
return tail( ascent) ||
// If there are no nodes left in the ascent the root node
// just closed. Emit a special event for this:
emitRootClosed(nodeOf(head(ascent)));
}
var contentBuilderHandlers = {};
contentBuilderHandlers[SAX_VALUE_OPEN] = nodeOpened;
contentBuilderHandlers[SAX_VALUE_CLOSE] = nodeClosed;
contentBuilderHandlers[SAX_KEY] = keyFound;
return contentBuilderHandlers;
}
|
javascript
|
{
"resource": ""
}
|
q20159
|
keyFound
|
train
|
function keyFound(ascent, newDeepestName, maybeNewDeepestNode) {
if( ascent ) { // if not root
// If we have the key but (unless adding to an array) no known value
// yet. Put that key in the output but against no defined value:
appendBuiltContent( ascent, newDeepestName, maybeNewDeepestNode );
}
var ascentWithNewPath = cons(
namedNode( newDeepestName,
maybeNewDeepestNode),
ascent
);
emitNodeOpened( ascentWithNewPath);
return ascentWithNewPath;
}
|
javascript
|
{
"resource": ""
}
|
q20160
|
nodeClosed
|
train
|
function nodeClosed( ascent ) {
emitNodeClosed( ascent);
return tail( ascent) ||
// If there are no nodes left in the ascent the root node
// just closed. Emit a special event for this:
emitRootClosed(nodeOf(head(ascent)));
}
|
javascript
|
{
"resource": ""
}
|
q20161
|
skip1
|
train
|
function skip1(previousExpr) {
if( previousExpr == always ) {
/* If there is no previous expression this consume command
is at the start of the jsonPath.
Since JSONPath specifies what we'd like to find but not
necessarily everything leading down to it, when running
out of JSONPath to check against we default to true */
return always;
}
/** return true if the ascent we have contains only the JSON root,
* false otherwise
*/
function notAtRoot(ascent){
return headKey(ascent) != ROOT_PATH;
}
return lazyIntersection(
/* If we're already at the root but there are more
expressions to satisfy, can't consume any more. No match.
This check is why none of the other exprs have to be able
to handle empty lists; skip1 is the only evaluator that
moves onto the next token and it refuses to do so once it
reaches the last item in the list. */
notAtRoot,
/* We are not at the root of the ascent yet.
Move to the next level of the ascent by handing only
the tail to the previous expression */
compose2(previousExpr, tail)
);
}
|
javascript
|
{
"resource": ""
}
|
q20162
|
statementExpr
|
train
|
function statementExpr(lastClause) {
return function(ascent) {
// kick off the evaluation by passing through to the last clause
var exprMatch = lastClause(ascent);
return exprMatch === true ? head(ascent) : exprMatch;
};
}
|
javascript
|
{
"resource": ""
}
|
q20163
|
expressionsReader
|
train
|
function expressionsReader( exprs, parserGeneratedSoFar, detection ) {
// if exprs is zero-length foldR will pass back the
// parserGeneratedSoFar as-is so we don't need to treat
// this as a special case
return foldR(
function( parserGeneratedSoFar, expr ){
return expr(parserGeneratedSoFar, detection);
},
parserGeneratedSoFar,
exprs
);
}
|
javascript
|
{
"resource": ""
}
|
q20164
|
generateClauseReaderIfTokenFound
|
train
|
function generateClauseReaderIfTokenFound (
tokenDetector, clauseEvaluatorGenerators,
jsonPath, parserGeneratedSoFar, onSuccess) {
var detected = tokenDetector(jsonPath);
if(detected) {
var compiledParser = expressionsReader(
clauseEvaluatorGenerators,
parserGeneratedSoFar,
detected
),
remainingUnparsedJsonPath = jsonPath.substr(len(detected[0]));
return onSuccess(remainingUnparsedJsonPath, compiledParser);
}
}
|
javascript
|
{
"resource": ""
}
|
q20165
|
compileJsonPathToFunction
|
train
|
function compileJsonPathToFunction( uncompiledJsonPath,
parserGeneratedSoFar ) {
/**
* On finding a match, if there is remaining text to be compiled
* we want to either continue parsing using a recursive call to
* compileJsonPathToFunction. Otherwise, we want to stop and return
* the parser that we have found so far.
*/
var onFind = uncompiledJsonPath
? compileJsonPathToFunction
: returnFoundParser;
return clauseForJsonPath(
uncompiledJsonPath,
parserGeneratedSoFar,
onFind
);
}
|
javascript
|
{
"resource": ""
}
|
q20166
|
callAdoptionAgency
|
train
|
function callAdoptionAgency(p, token) {
for (var i = 0; i < AA_OUTER_LOOP_ITER; i++) {
var formattingElementEntry = aaObtainFormattingElementEntry(p, token, formattingElementEntry);
if (!formattingElementEntry)
break;
var furthestBlock = aaObtainFurthestBlock(p, formattingElementEntry);
if (!furthestBlock)
break;
p.activeFormattingElements.bookmark = formattingElementEntry;
var lastElement = aaInnerLoop(p, furthestBlock, formattingElementEntry.element),
commonAncestor = p.openElements.getCommonAncestor(formattingElementEntry.element);
p.treeAdapter.detachNode(lastElement);
aaInsertLastNodeInCommonAncestor(p, commonAncestor, lastElement);
aaReplaceFormattingElement(p, furthestBlock, formattingElementEntry);
}
}
|
javascript
|
{
"resource": ""
}
|
q20167
|
readSingleFile
|
train
|
function readSingleFile(e) {
const file = e.target.files[0];
if (!file) {
return;
}
// Extract data from file and distribute it in some relevant structures:
// results for all guid-related( for now they are not
// divided in 3 parts depending on the type ) and
// all results with sample-value-related and
// map guid to value within the same structure
const reader = new FileReader();
reader.onload = function(e) {
const contents = extractData(e.target.result);
const sampleArr = contents.sampleValueArray;
const guidValueInfo = contents.guidValueInfo;
const metricAverage = new Map();
const allLabels = new Set();
for (const e of sampleArr) {
// This version of the tool focuses on analysing memory
// metrics, which contain a slightly different structure
// to the non-memory metrics.
if (e.name.startsWith('memory')) {
const { name, sampleValues, diagnostics } = e;
const { labels, stories } = diagnostics;
const label = guidValueInfo.get(labels)[0];
allLabels.add(label);
const story = guidValueInfo.get(stories)[0];
menu.significanceTester.add(name, label, story, sampleValues);
}
}
menu.allLabels = Array.from(allLabels);
let metricNames = [];
sampleArr.map(e => metricNames.push(e.name));
metricNames = _.uniq(metricNames);
// The content for the default table: with name
// of the metric, the average value of the sample values
// plus an id. The latest is used to expand the row.
// It may disappear later.
const tableElems = [];
let id = 1;
for (const name of metricNames) {
tableElems.push({
id: id++,
metric: name
});
}
const labelsResult = getMetricStoriesLabelsToValuesMap(
sampleArr, guidValueInfo);
const columnsForChosenDiagnostic = labelsResult.labelNames;
const metricToDiagnosticValuesMap = labelsResult.mapLabelToValues;
for (const elem of tableElems) {
if (metricToDiagnosticValuesMap.get(elem.metric) === undefined) {
continue;
}
for (const diagnostic of columnsForChosenDiagnostic) {
if (!metricToDiagnosticValuesMap.get(elem.metric).has(diagnostic)) {
continue;
}
elem[diagnostic] = fromBytesToMiB(average(metricToDiagnosticValuesMap
.get(elem.metric).get(diagnostic)));
}
}
app.state.gridData = tableElems;
app.defaultGridData = tableElems;
app.sampleArr = sampleArr;
app.guidValue = guidValueInfo;
app.columnsForChosenDiagnostic = columnsForChosenDiagnostic;
const result = parseAllMetrics(metricNames);
menu.sampelArr = sampleArr;
menu.guidValueInfo = guidValueInfo;
menu.browserOptions = result.browsers;
menu.subprocessOptions = result.subprocesses;
menu.componentMap = result.components;
menu.sizeMap = result.sizes;
menu.metricNames = result.names;
};
reader.readAsText(file);
}
|
javascript
|
{
"resource": ""
}
|
q20168
|
applyTemplateContent
|
train
|
function applyTemplateContent(inst, node, nodeInfo) {
if (nodeInfo.templateInfo) {
node._templateInfo = nodeInfo.templateInfo;
}
}
|
javascript
|
{
"resource": ""
}
|
q20169
|
isCrossOrigin
|
train
|
function isCrossOrigin(pageLocation, ajaxHost) {
/*
* NB: defaultPort only knows http and https.
* Returns undefined otherwise.
*/
function defaultPort(protocol) {
return {'http:':80, 'https:':443}[protocol];
}
function portOf(location) {
// pageLocation should always have a protocol. ajaxHost if no port or
// protocol is specified, should use the port of the containing page
return location.port || defaultPort(location.protocol||pageLocation.protocol);
}
// if ajaxHost doesn't give a domain, port is the same as pageLocation
// it can't give a protocol but not a domain
// it can't give a port but not a domain
return !!( (ajaxHost.protocol && (ajaxHost.protocol != pageLocation.protocol)) ||
(ajaxHost.host && (ajaxHost.host != pageLocation.host)) ||
(ajaxHost.host && (portOf(ajaxHost) != portOf(pageLocation)))
);
}
|
javascript
|
{
"resource": ""
}
|
q20170
|
ensureOwnEffectMap
|
train
|
function ensureOwnEffectMap(model, type) {
let effects = model[type];
if (!effects) {
effects = model[type] = {};
} else if (!model.hasOwnProperty(type)) {
effects = model[type] = Object.create(model[type]);
for (let p in effects) {
let protoFx = effects[p];
let instFx = effects[p] = Array(protoFx.length);
for (let i=0; i<protoFx.length; i++) {
instFx[i] = protoFx[i];
}
}
}
return effects;
}
|
javascript
|
{
"resource": ""
}
|
q20171
|
runEffectsForProperty
|
train
|
function runEffectsForProperty(inst, effects, dedupeId, prop, props, oldProps, hasPaths, extraArgs) {
let ran = false;
let rootProperty = hasPaths ? root$0(prop) : prop;
let fxs = effects[rootProperty];
if (fxs) {
for (let i=0, l=fxs.length, fx; (i<l) && (fx=fxs[i]); i++) {
if ((!fx.info || fx.info.lastRun !== dedupeId) &&
(!hasPaths || pathMatchesTrigger(prop, fx.trigger))) {
if (fx.info) {
fx.info.lastRun = dedupeId;
}
fx.fn(inst, prop, props, oldProps, fx.info, hasPaths, extraArgs);
ran = true;
}
}
}
return ran;
}
|
javascript
|
{
"resource": ""
}
|
q20172
|
runObserverEffect
|
train
|
function runObserverEffect(inst, property, props, oldProps, info) {
let fn = typeof info.method === "string" ? inst[info.method] : info.method;
let changedProp = info.property;
if (fn) {
fn.call(inst, inst.__data[changedProp], oldProps[changedProp]);
} else if (!info.dynamicFn) {
console.warn('observer method `' + info.method + '` not defined');
}
}
|
javascript
|
{
"resource": ""
}
|
q20173
|
runNotifyEffects
|
train
|
function runNotifyEffects(inst, notifyProps, props, oldProps, hasPaths) {
// Notify
let fxs = inst[TYPES.NOTIFY];
let notified;
let id = dedupeId++;
// Try normal notify effects; if none, fall back to try path notification
for (let prop in notifyProps) {
if (notifyProps[prop]) {
if (fxs && runEffectsForProperty(inst, fxs, id, prop, props, oldProps, hasPaths)) {
notified = true;
} else if (hasPaths && notifyPath(inst, prop, props)) {
notified = true;
}
}
}
// Flush host if we actually notified and host was batching
// And the host has already initialized clients; this prevents
// an issue with a host observing data changes before clients are ready.
let host;
if (notified && (host = inst.__dataHost) && host._invalidateProperties) {
host._invalidateProperties();
}
}
|
javascript
|
{
"resource": ""
}
|
q20174
|
runNotifyEffect
|
train
|
function runNotifyEffect(inst, property, props, oldProps, info, hasPaths) {
let rootProperty = hasPaths ? root$0(property) : property;
let path = rootProperty != property ? property : null;
let value = path ? get$0(inst, path) : inst.__data[property];
if (path && value === undefined) {
value = props[property]; // specifically for .splices
}
dispatchNotifyEvent(inst, info.eventName, value, path);
}
|
javascript
|
{
"resource": ""
}
|
q20175
|
runReflectEffect
|
train
|
function runReflectEffect(inst, property, props, oldProps, info) {
let value = inst.__data[property];
if (sanitizeDOMValue) {
value = sanitizeDOMValue(value, info.attrName, 'attribute', /** @type {Node} */(inst));
}
inst._propertyToAttribute(property, info.attrName, value);
}
|
javascript
|
{
"resource": ""
}
|
q20176
|
runComputedEffects
|
train
|
function runComputedEffects(inst, changedProps, oldProps, hasPaths) {
let computeEffects = inst[TYPES.COMPUTE];
if (computeEffects) {
let inputProps = changedProps;
while (runEffects(inst, computeEffects, inputProps, oldProps, hasPaths)) {
Object.assign(oldProps, inst.__dataOld);
Object.assign(changedProps, inst.__dataPending);
inputProps = inst.__dataPending;
inst.__dataPending = null;
}
}
}
|
javascript
|
{
"resource": ""
}
|
q20177
|
runComputedEffect
|
train
|
function runComputedEffect(inst, property, props, oldProps, info) {
let result = runMethodEffect(inst, property, props, oldProps, info);
let computedProp = info.methodInfo;
if (inst.__dataHasAccessor && inst.__dataHasAccessor[computedProp]) {
inst._setPendingProperty(computedProp, result, true);
} else {
inst[computedProp] = result;
}
}
|
javascript
|
{
"resource": ""
}
|
q20178
|
computeLinkedPaths
|
train
|
function computeLinkedPaths(inst, path, value) {
let links = inst.__dataLinkedPaths;
if (links) {
let link;
for (let a in links) {
let b = links[a];
if (isDescendant(a, path)) {
link = translate(a, b, path);
inst._setPendingPropertyOrPath(link, value, true, true);
} else if (isDescendant(b, path)) {
link = translate(b, a, path);
inst._setPendingPropertyOrPath(link, value, true, true);
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
q20179
|
addEffectForBindingPart
|
train
|
function addEffectForBindingPart(constructor, templateInfo, binding, part, index) {
if (!part.literal) {
if (binding.kind === 'attribute' && binding.target[0] === '-') {
console.warn('Cannot set attribute ' + binding.target +
' because "-" is not a valid attribute starting character');
} else {
let dependencies = part.dependencies;
let info = { index, binding, part, evaluator: constructor };
for (let j=0; j<dependencies.length; j++) {
let trigger = dependencies[j];
if (typeof trigger == 'string') {
trigger = parseArg(trigger);
trigger.wildcard = true;
}
constructor._addTemplatePropertyEffect(templateInfo, trigger.rootProperty, {
fn: runBindingEffect,
info, trigger
});
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
q20180
|
computeBindingValue
|
train
|
function computeBindingValue(node, value, binding, part) {
if (binding.isCompound) {
let storage = node.__dataCompoundStorage[binding.target];
storage[part.compoundIndex] = value;
value = storage.join('');
}
if (binding.kind !== 'attribute') {
// Some browsers serialize `undefined` to `"undefined"`
if (binding.target === 'textContent' ||
(binding.target === 'value' &&
(node.localName === 'input' || node.localName === 'textarea'))) {
value = value == undefined ? '' : value;
}
}
return value;
}
|
javascript
|
{
"resource": ""
}
|
q20181
|
setupBindings
|
train
|
function setupBindings(inst, templateInfo) {
// Setup compound storage, dataHost, and notify listeners
let {nodeList, nodeInfoList} = templateInfo;
if (nodeInfoList.length) {
for (let i=0; i < nodeInfoList.length; i++) {
let info = nodeInfoList[i];
let node = nodeList[i];
let bindings = info.bindings;
if (bindings) {
for (let i=0; i<bindings.length; i++) {
let binding = bindings[i];
setupCompoundStorage(node, binding);
addNotifyListener(node, inst, binding);
}
}
node.__dataHost = inst;
}
}
}
|
javascript
|
{
"resource": ""
}
|
q20182
|
addNotifyListener
|
train
|
function addNotifyListener(node, inst, binding) {
if (binding.listenerEvent) {
let part = binding.parts[0];
node.addEventListener(binding.listenerEvent, function(e) {
handleNotification(e, inst, binding.target, part.source, part.negate);
});
}
}
|
javascript
|
{
"resource": ""
}
|
q20183
|
runMethodEffect
|
train
|
function runMethodEffect(inst, property, props, oldProps, info) {
// Instances can optionally have a _methodHost which allows redirecting where
// to find methods. Currently used by `templatize`.
let context = inst._methodHost || inst;
let fn = context[info.methodName];
if (fn) {
let args = marshalArgs(inst.__data, info.args, property, props);
return fn.apply(context, args);
} else if (!info.dynamicFn) {
console.warn('method `' + info.methodName + '` not defined');
}
}
|
javascript
|
{
"resource": ""
}
|
q20184
|
literalFromParts
|
train
|
function literalFromParts(parts) {
let s = '';
for (let i=0; i<parts.length; i++) {
let literal = parts[i].literal;
s += literal || '';
}
return s;
}
|
javascript
|
{
"resource": ""
}
|
q20185
|
parseArgs
|
train
|
function parseArgs(argList, sig) {
sig.args = argList.map(function(rawArg) {
let arg = parseArg(rawArg);
if (!arg.literal) {
sig.static = false;
}
return arg;
}, this);
return sig;
}
|
javascript
|
{
"resource": ""
}
|
q20186
|
marshalArgs
|
train
|
function marshalArgs(data, args, path, props) {
let values = [];
for (let i=0, l=args.length; i<l; i++) {
let arg = args[i];
let name = arg.name;
let v;
if (arg.literal) {
v = arg.value;
} else {
if (arg.structured) {
v = get$0(data, name);
// when data is not stored e.g. `splices`
if (v === undefined) {
v = props[name];
}
} else {
v = data[name];
}
}
if (arg.wildcard) {
// Only send the actual path changed info if the change that
// caused the observer to run matched the wildcard
let baseChanged = (name.indexOf(path + '.') === 0);
let matches = (path.indexOf(name) === 0 && !baseChanged);
values[i] = {
path: matches ? path : name,
value: matches ? props[path] : v,
base: v
};
} else {
values[i] = v;
}
}
return values;
}
|
javascript
|
{
"resource": ""
}
|
q20187
|
notifySplice
|
train
|
function notifySplice(inst, array, path, index, addedCount, removed) {
notifySplices(inst, array, path, [{
index: index,
addedCount: addedCount,
removed: removed,
object: array,
type: 'splice'
}]);
}
|
javascript
|
{
"resource": ""
}
|
q20188
|
getService
|
train
|
function getService(privateKeyDetails) {
return OAuth2.createService('PerfDash:' + Session.getActiveUser().getEmail())
// Set the endpoint URL.
.setTokenUrl('https://accounts.google.com/o/oauth2/token')
// Set the private key and issuer.
.setPrivateKey(privateKeyDetails['private_key'])
.setIssuer(privateKeyDetails['client_email'])
// Set the property store where authorized tokens should be persisted.
.setPropertyStore(PropertiesService.getScriptProperties())
// Set the scope. This must match one of the scopes configured during the
// setup of domain-wide delegation.
.setScope('https://www.googleapis.com/auth/userinfo.email');
}
|
javascript
|
{
"resource": ""
}
|
q20189
|
getPrivateKeyDetailsFromDriveFile
|
train
|
function getPrivateKeyDetailsFromDriveFile(driveFileId) {
var file = DriveApp.getFileById(driveFileId);
return JSON.parse(file.getAs('application/json').getDataAsString());
}
|
javascript
|
{
"resource": ""
}
|
q20190
|
writeHexString
|
train
|
function writeHexString(bytes, out) {
function byteToPaddedHex(b) {
let str = b.toString(16).toUpperCase();
if (str.length < 2) {
str = '0' + str;
}
return str;
}
const kBytesPerLine = 16;
// Returns pretty printed kBytesPerLine bytes starting from
// bytes[startIndex], in hexdump style format.
function formatLine(startIndex) {
let result = ' ';
// Append a hex formatting of |bytes|.
for (let i = 0; i < kBytesPerLine; ++i) {
result += ' ';
// Add a separator every 8 bytes.
if ((i % 8) === 0) {
result += ' ';
}
// Output hex for the byte, or space if no bytes remain.
const byteIndex = startIndex + i;
if (byteIndex < bytes.length) {
result += byteToPaddedHex(bytes[byteIndex]);
} else {
result += ' ';
}
}
result += ' ';
// Append an ASCII formatting of the bytes, where ASCII codes 32
// though 126 display the corresponding characters, nulls are
// represented by spaces, and any other character is represented
// by a period.
for (let i = 0; i < kBytesPerLine; ++i) {
const byteIndex = startIndex + i;
if (byteIndex >= bytes.length) {
break;
}
const curByte = bytes[byteIndex];
if (curByte >= 0x20 && curByte <= 0x7E) {
result += String.fromCharCode(curByte);
} else if (curByte === 0x00) {
result += ' ';
} else {
result += '.';
}
}
return result;
}
// Output lines for each group of kBytesPerLine bytes.
for (let i = 0; i < bytes.length; i += kBytesPerLine) {
out.writeLine(formatLine(i));
}
}
|
javascript
|
{
"resource": ""
}
|
q20191
|
writeParameters
|
train
|
function writeParameters(entry, out) {
// If headers are in an object, convert them to an array for better
// display.
entry = reformatHeaders(entry);
// Use any parameter writer available for this event type.
const paramsWriter = getParameterWriterForEventType(entry.type);
const consumedParams = {};
if (paramsWriter) {
paramsWriter(entry, out, consumedParams);
}
// Write any un-consumed parameters.
for (const k in entry.params) {
if (consumedParams[k]) {
continue;
}
defaultWriteParameter(k, entry.params[k], out);
}
}
|
javascript
|
{
"resource": ""
}
|
q20192
|
getParameterWriterForEventType
|
train
|
function getParameterWriterForEventType(eventType) {
switch (eventType) {
case EventType.HTTP_TRANSACTION_SEND_REQUEST_HEADERS:
case EventType.HTTP_TRANSACTION_SEND_TUNNEL_HEADERS:
case EventType.TYPE_HTTP_CACHE_CALLER_REQUEST_HEADERS:
return writeParamsForRequestHeaders;
case EventType.PROXY_CONFIG_CHANGED:
return writeParamsForProxyConfigChanged;
case EventType.CERT_VERIFIER_JOB:
case EventType.SSL_CERTIFICATES_RECEIVED:
return writeParamsForCertificates;
case EventType.CERT_CT_COMPLIANCE_CHECKED:
case EventType.EV_CERT_CT_COMPLIANCE_CHECKED:
return writeParamsForCheckedCertificates;
}
return null;
}
|
javascript
|
{
"resource": ""
}
|
q20193
|
tryParseHexToBytes
|
train
|
function tryParseHexToBytes(hexStr) {
if ((hexStr.length % 2) !== 0) {
return null;
}
const result = [];
for (let i = 0; i < hexStr.length; i += 2) {
const value = parseInt(hexStr.substr(i, 2), 16);
if (isNaN(value)) {
return null;
}
result.push(value);
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q20194
|
tryParseBase64ToBytes
|
train
|
function tryParseBase64ToBytes(b64Str) {
let decodedStr;
try {
decodedStr = atob(b64Str);
} catch (e) {
return null;
}
return Uint8Array.from(decodedStr, c => c.charCodeAt(0));
}
|
javascript
|
{
"resource": ""
}
|
q20195
|
defaultWriteParameter
|
train
|
function defaultWriteParameter(key, value, out) {
if (key === 'headers' && value instanceof Array) {
out.writeArrowIndentedLines(value);
return;
}
// For transferred bytes, display the bytes in hex and ASCII.
// TODO(eroman): 'hex_encoded_bytes' was removed in M73, and
// support for it can be removed in the future.
if (key === 'hex_encoded_bytes' && typeof value === 'string') {
const bytes = tryParseHexToBytes(value);
if (bytes) {
out.writeArrowKey(key);
writeHexString(bytes, out);
return;
}
}
if (key === 'bytes' && typeof value === 'string') {
const bytes = tryParseBase64ToBytes(value);
if (bytes) {
out.writeArrowKey(key);
writeHexString(bytes, out);
return;
}
}
// Handle source_dependency entries - add link and map source type to
// string.
if (key === 'source_dependency' && typeof value === 'object') {
const link = '#events&s=' + value.id;
const valueStr = value.id + ' (' + EventSourceTypeNames[value.type] + ')';
out.writeArrowKeyValue(key, valueStr, link);
return;
}
if (key === 'net_error' && typeof value === 'number') {
const valueStr = value + ' (' + netErrorToString(value) + ')';
out.writeArrowKeyValue(key, valueStr);
return;
}
if (key === 'quic_error' && typeof value === 'number') {
const valueStr = value + ' (' + quicErrorToString(value) + ')';
out.writeArrowKeyValue(key, valueStr);
return;
}
if (key === 'quic_crypto_handshake_message' && typeof value === 'string') {
const lines = value.split('\n');
out.writeArrowIndentedLines(lines);
return;
}
if (key === 'quic_rst_stream_error' && typeof value === 'number') {
const valueStr = value + ' (' + quicRstStreamErrorToString(value) + ')';
out.writeArrowKeyValue(key, valueStr);
return;
}
if (key === 'load_flags' && typeof value === 'number') {
const valueStr = value + ' (' + getLoadFlagSymbolicString(value) + ')';
out.writeArrowKeyValue(key, valueStr);
return;
}
if (key === 'load_state' && typeof value === 'number') {
const valueStr = value + ' (' + getKeyWithValue(LoadState, value) + ')';
out.writeArrowKeyValue(key, valueStr);
return;
}
// Otherwise just default to JSON formatting of the value.
out.writeArrowKeyValue(key, JSON.stringify(value));
}
|
javascript
|
{
"resource": ""
}
|
q20196
|
getSymbolicString
|
train
|
function getSymbolicString(bitmask, valueToName, zeroName) {
const matchingFlagNames = [];
for (const k in valueToName) {
if (bitmask & valueToName[k]) {
matchingFlagNames.push(k);
}
}
// If no flags were matched, returns a special value.
if (matchingFlagNames.length === 0) {
return zeroName;
}
return matchingFlagNames.join(' | ');
}
|
javascript
|
{
"resource": ""
}
|
q20197
|
reformatHeaders
|
train
|
function reformatHeaders(entry) {
// If there are no headers, or it is not an object other than an array,
// return |entry| without modification.
if (!entry.params || entry.params.headers === undefined ||
typeof entry.params.headers !== 'object' ||
entry.params.headers instanceof Array) {
return entry;
}
// Duplicate the top level object, and |entry.params|, so the original
// object
// will not be modified.
entry = shallowCloneObject(entry);
entry.params = shallowCloneObject(entry.params);
// Convert headers to an array.
const headers = [];
for (const key in entry.params.headers) {
headers.push(key + ': ' + entry.params.headers[key]);
}
entry.params.headers = headers;
return entry;
}
|
javascript
|
{
"resource": ""
}
|
q20198
|
writeParamsForRequestHeaders
|
train
|
function writeParamsForRequestHeaders(entry, out, consumedParams) {
const params = entry.params;
if (!(typeof params.line === 'string') ||
!(params.headers instanceof Array)) {
// Unrecognized params.
return;
}
// Strip the trailing CRLF that params.line contains.
const lineWithoutCRLF = params.line.replace(/\r\n$/g, '');
out.writeArrowIndentedLines([lineWithoutCRLF].concat(params.headers));
consumedParams.line = true;
consumedParams.headers = true;
}
|
javascript
|
{
"resource": ""
}
|
q20199
|
writeParamsForCertificates
|
train
|
function writeParamsForCertificates(entry, out, consumedParams) {
writeCertificateParam(entry.params, out, consumedParams, 'certificates');
if (typeof(entry.params.verified_cert) === 'object') {
writeCertificateParam(
entry.params.verified_cert, out, consumedParams, 'verified_cert');
}
if (typeof(entry.params.cert_status) === 'number') {
const valueStr = entry.params.cert_status + ' (' +
getCertStatusFlagSymbolicString(entry.params.cert_status) + ')';
out.writeArrowKeyValue('cert_status', valueStr);
consumedParams.cert_status = true;
}
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.