_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3
values | text stringlengths 52 373k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q16500 | cleanNode | train | function cleanNode(node)
{
var child = node.firstChild;
while (child != null)
{
var next = child.nextSibling;
cleanNode(child);
child = next;
}
if ((node.nodeType != 1 || (node.nodeName !== 'BR' && node.firstChild == null)) &&
(node.nodeType != 3 || mxUtils.trim(mxUtils.getTextContent(node)).length == 0))
{
node.parentNode.removeChild(node);
}
else
{
// Removes linefeeds
if (node.nodeType == 3)
{
mxUtils.setTextContent(node, mxUtils.getTextContent(node).replace(/\n|\r/g, ''));
}
// Removes CSS classes and styles (for Word and Excel)
if (node.nodeType == 1)
{
node.removeAttribute('style');
node.removeAttribute('class');
node.removeAttribute('width');
node.removeAttribute('cellpadding');
node.removeAttribute('cellspacing');
node.removeAttribute('border');
}
}
} | javascript | {
"resource": ""
} |
q16501 | createHint | train | function createHint()
{
var hint = document.createElement('div');
hint.className = 'geHint';
hint.style.whiteSpace = 'nowrap';
hint.style.position = 'absolute';
return hint;
} | javascript | {
"resource": ""
} |
q16502 | train | function(evt)
{
if (evt != null)
{
var source = mxEvent.getSource(evt);
if (source.nodeName == 'A')
{
while (source != null)
{
if (source.className == 'geHint')
{
return true;
}
source = source.parentNode;
}
}
}
return textEditing(evt);
} | javascript | {
"resource": ""
} | |
q16503 | isOrContains | train | function isOrContains(container, node)
{
while (node != null)
{
if (node === container)
{
return true;
}
node = node.parentNode;
}
return false;
} | javascript | {
"resource": ""
} |
q16504 | Menu | train | function Menu(funct, enabled)
{
mxEventSource.call(this);
this.funct = funct;
this.enabled = (enabled != null) ? enabled : true;
} | javascript | {
"resource": ""
} |
q16505 | preview | train | function preview(print)
{
var autoOrigin = onePageCheckBox.checked || pageCountCheckBox.checked;
var printScale = parseInt(pageScaleInput.value) / 100;
if (isNaN(printScale))
{
printScale = 1;
pageScaleInput.value = '100%';
}
// Workaround to match available paper size in actual print output
printScale *= 0.75;
var pf = graph.pageFormat || mxConstants.PAGE_FORMAT_A4_PORTRAIT;
var scale = 1 / graph.pageScale;
if (autoOrigin)
{
var pageCount = (onePageCheckBox.checked) ? 1 : parseInt(pageCountInput.value);
if (!isNaN(pageCount))
{
scale = mxUtils.getScaleForPageCount(pageCount, graph, pf);
}
}
// Negative coordinates are cropped or shifted if page visible
var gb = graph.getGraphBounds();
var border = 0;
var x0 = 0;
var y0 = 0;
// Applies print scale
pf = mxRectangle.fromRectangle(pf);
pf.width = Math.ceil(pf.width * printScale);
pf.height = Math.ceil(pf.height * printScale);
scale *= printScale;
// Starts at first visible page
if (!autoOrigin && graph.pageVisible)
{
var layout = graph.getPageLayout();
x0 -= layout.x * pf.width;
y0 -= layout.y * pf.height;
}
else
{
autoOrigin = true;
}
var preview = PrintDialog.createPrintPreview(graph, scale, pf, border, x0, y0, autoOrigin);
preview.open();
if (print)
{
PrintDialog.printPreview(preview);
}
} | javascript | {
"resource": ""
} |
q16506 | snapX | train | function snapX(x, state)
{
x += this.graph.panDx;
var override = false;
if (Math.abs(x - center) < ttX)
{
dx = x - bounds.getCenterX();
ttX = Math.abs(x - center);
override = true;
}
else if (Math.abs(x - left) < ttX)
{
dx = x - bounds.x;
ttX = Math.abs(x - left);
override = true;
}
else if (Math.abs(x - right) < ttX)
{
dx = x - bounds.x - bounds.width;
ttX = Math.abs(x - right);
override = true;
}
if (override)
{
stateX = state;
valueX = Math.round(x - this.graph.panDx);
if (this.guideX == null)
{
this.guideX = this.createGuideShape(true);
// Makes sure to use either VML or SVG shapes in order to implement
// event-transparency on the background area of the rectangle since
// HTML shapes do not let mouseevents through even when transparent
this.guideX.dialect = (this.graph.dialect != mxConstants.DIALECT_SVG) ?
mxConstants.DIALECT_VML : mxConstants.DIALECT_SVG;
this.guideX.pointerEvents = false;
this.guideX.init(this.graph.getView().getOverlayPane());
}
}
overrideX = overrideX || override;
} | javascript | {
"resource": ""
} |
q16507 | snapY | train | function snapY(y, state)
{
y += this.graph.panDy;
var override = false;
if (Math.abs(y - middle) < ttY)
{
dy = y - bounds.getCenterY();
ttY = Math.abs(y - middle);
override = true;
}
else if (Math.abs(y - top) < ttY)
{
dy = y - bounds.y;
ttY = Math.abs(y - top);
override = true;
}
else if (Math.abs(y - bottom) < ttY)
{
dy = y - bounds.y - bounds.height;
ttY = Math.abs(y - bottom);
override = true;
}
if (override)
{
stateY = state;
valueY = Math.round(y - this.graph.panDy);
if (this.guideY == null)
{
this.guideY = this.createGuideShape(false);
// Makes sure to use either VML or SVG shapes in order to implement
// event-transparency on the background area of the rectangle since
// HTML shapes do not let mouseevents through even when transparent
this.guideY.dialect = (this.graph.dialect != mxConstants.DIALECT_SVG) ?
mxConstants.DIALECT_VML : mxConstants.DIALECT_SVG;
this.guideY.pointerEvents = false;
this.guideY.init(this.graph.getView().getOverlayPane());
}
}
overrideY = overrideY || override;
} | javascript | {
"resource": ""
} |
q16508 | pushPoint | train | function pushPoint(pt)
{
if (lastPushed == null || Math.abs(lastPushed.x - pt.x) >= tol || Math.abs(lastPushed.y - pt.y) >= tol)
{
result.push(pt);
lastPushed = pt;
}
return lastPushed;
} | javascript | {
"resource": ""
} |
q16509 | train | function(state, source, target, points, isSource)
{
var value = mxUtils.getValue(state.style, (isSource) ? mxConstants.STYLE_SOURCE_JETTY_SIZE :
mxConstants.STYLE_TARGET_JETTY_SIZE, mxUtils.getValue(state.style,
mxConstants.STYLE_JETTY_SIZE, mxEdgeStyle.orthBuffer));
if (value == 'auto')
{
// Computes the automatic jetty size
var type = mxUtils.getValue(state.style, (isSource) ? mxConstants.STYLE_STARTARROW : mxConstants.STYLE_ENDARROW, mxConstants.NONE);
if (type != mxConstants.NONE)
{
var size = mxUtils.getNumber(state.style, (isSource) ? mxConstants.STYLE_STARTSIZE : mxConstants.STYLE_ENDSIZE, mxConstants.DEFAULT_MARKERSIZE);
value = Math.max(2, Math.ceil((size + mxEdgeStyle.orthBuffer) / mxEdgeStyle.orthBuffer)) * mxEdgeStyle.orthBuffer;
}
else
{
value = 2 * mxEdgeStyle.orthBuffer;
}
}
return value;
} | javascript | {
"resource": ""
} | |
q16510 | train | function(evt)
{
var state = null;
// Workaround for touch events which started on some DOM node
// on top of the container, in which case the cells under the
// mouse for the move and up events are not detected.
if (mxClient.IS_TOUCH)
{
var x = mxEvent.getClientX(evt);
var y = mxEvent.getClientY(evt);
// Dispatches the drop event to the graph which
// consumes and executes the source function
var pt = mxUtils.convertPoint(container, x, y);
state = graph.view.getState(graph.getCellAt(pt.x, pt.y));
}
return state;
} | javascript | {
"resource": ""
} | |
q16511 | train | function(sender, evt)
{
var changes = evt.getProperty('edit').changes;
graph.setSelectionCells(graph.getSelectionCellsForChanges(changes));
} | javascript | {
"resource": ""
} | |
q16512 | makeDiscordjsError | train | function makeDiscordjsError(Base) {
return class DiscordjsError extends Base {
constructor(key, ...args) {
super(message(key, args));
this[kCode] = key;
if (Error.captureStackTrace) Error.captureStackTrace(this, DiscordjsError);
}
get name() {
return `${super.name} [${this[kCode]}]`;
}
get code() {
return this[kCode];
}
};
} | javascript | {
"resource": ""
} |
q16513 | message | train | function message(key, args) {
if (typeof key !== 'string') throw new Error('Error message key must be a string');
const msg = messages.get(key);
if (!msg) throw new Error(`An invalid error message key was used: ${key}.`);
if (typeof msg === 'function') return msg(...args);
if (args === undefined || args.length === 0) return msg;
args.unshift(msg);
return String(...args);
} | javascript | {
"resource": ""
} |
q16514 | register | train | function register(sym, val) {
messages.set(sym, typeof val === 'function' ? val : String(val));
} | javascript | {
"resource": ""
} |
q16515 | train | function (fn, repeatTest = 0, args = []) {
/**
* if a new hook gets executed we can assume that all commands should have finised
* with exception of timeouts where `commandIsRunning` will never be reset but here
*/
// commandIsRunning = false
return new Promise((resolve, reject) => {
try {
const res = fn.apply(this, args)
resolve(res)
} catch (e) {
if (repeatTest) {
return resolve(executeSync(fn, --repeatTest, args))
}
/**
* no need to modify stack if no stack available
*/
if (!e.stack) {
return reject(e)
}
e.stack = e.stack.split('\n').filter(STACKTRACE_FILTER_FN).join('\n')
reject(e)
}
})
} | javascript | {
"resource": ""
} | |
q16516 | train | function (fn, repeatTest = 0, args = []) {
let result, error
/**
* if a new hook gets executed we can assume that all commands should have finised
* with exception of timeouts where `commandIsRunning` will never be reset but here
*/
// commandIsRunning = false
try {
result = fn.apply(this, args)
} catch (e) {
error = e
}
/**
* handle errors that get thrown directly and are not cause by
* rejected promises
*/
if (error) {
if (repeatTest) {
return executeAsync(fn, --repeatTest, args)
}
return new Promise((resolve, reject) => reject(error))
}
/**
* if we don't retry just return result
*/
if (repeatTest === 0 || !result || typeof result.catch !== 'function') {
return new Promise(resolve => resolve(result))
}
/**
* handle promise response
*/
return result.catch((e) => {
if (repeatTest) {
return executeAsync(fn, --repeatTest, args)
}
e.stack = e.stack.split('\n').filter(STACKTRACE_FILTER_FN).join('\n')
return Promise.reject(e)
})
} | javascript | {
"resource": ""
} | |
q16517 | runSync | train | function runSync (fn, repeatTest = 0, args = []) {
return (resolve, reject) =>
Fiber(() => executeSync.call(this, fn, repeatTest, args).then(() => resolve(), reject)).run()
} | javascript | {
"resource": ""
} |
q16518 | train | function (testInterfaceFnNames, before, after, fnName, scope = global) {
const origFn = scope[fnName]
scope[fnName] = wrapTestFunction(fnName, origFn, testInterfaceFnNames, before, after)
/**
* support it.skip for the Mocha framework
*/
if (typeof origFn.skip === 'function') {
scope[fnName].skip = origFn.skip
}
/**
* wrap it.only for the Mocha framework
*/
if (typeof origFn.only === 'function') {
const origOnlyFn = origFn.only
scope[fnName].only = wrapTestFunction(fnName + '.only', origOnlyFn, testInterfaceFnNames, before, after)
}
} | javascript | {
"resource": ""
} | |
q16519 | getStyleComputedProperty | train | function getStyleComputedProperty(element, property) {
if (element.nodeType !== 1) {
return [];
}
// NOTE: 1 DOM access here
var css = getComputedStyle(element, null);
return property ? css[property] : css;
} | javascript | {
"resource": ""
} |
q16520 | getClientRect | train | function getClientRect(offsets) {
return _extends({}, offsets, {
right: offsets.left + offsets.width,
bottom: offsets.top + offsets.height
});
} | javascript | {
"resource": ""
} |
q16521 | getFixedPositionOffsetParent | train | function getFixedPositionOffsetParent(element) {
// This check is needed to avoid errors in case one of the elements isn't defined for any reason
if (!element || !element.parentElement || isIE()) {
return document.documentElement;
}
var el = element.parentElement;
while (el && getStyleComputedProperty(el, 'transform') === 'none') {
el = el.parentElement;
}
return el || document.documentElement;
} | javascript | {
"resource": ""
} |
q16522 | find | train | function find(arr, check) {
// use native find if supported
if (Array.prototype.find) {
return arr.find(check);
}
// use `filter` to obtain the same behavior of `find`
return arr.filter(check)[0];
} | javascript | {
"resource": ""
} |
q16523 | findIndex | train | function findIndex(arr, prop, value) {
// use native findIndex if supported
if (Array.prototype.findIndex) {
return arr.findIndex(function (cur) {
return cur[prop] === value;
});
}
// use `find` + `indexOf` if `findIndex` isn't supported
var match = find(arr, function (obj) {
return obj[prop] === value;
});
return arr.indexOf(match);
} | javascript | {
"resource": ""
} |
q16524 | runModifiers | train | function runModifiers(modifiers, data, ends) {
var modifiersToRun = ends === undefined ? modifiers : modifiers.slice(0, findIndex(modifiers, 'name', ends));
modifiersToRun.forEach(function (modifier) {
if (modifier['function']) {
// eslint-disable-line dot-notation
console.warn('`modifier.function` is deprecated, use `modifier.fn`!');
}
var fn = modifier['function'] || modifier.fn; // eslint-disable-line dot-notation
if (modifier.enabled && isFunction(fn)) {
// Add properties to offsets to make them a complete clientRect object
// we do this before each modifier to make sure the previous one doesn't
// mess with these values
data.offsets.popper = getClientRect(data.offsets.popper);
data.offsets.reference = getClientRect(data.offsets.reference);
data = fn(data, modifier);
}
});
return data;
} | javascript | {
"resource": ""
} |
q16525 | updateModifiers | train | function updateModifiers() {
if (this.state.isDestroyed) {
return;
}
// Deep merge modifiers options
let options = this.defaultOptions;
this.options.modifiers = {};
const _this = this;
Object.keys(_extends({}, Popper.Defaults.modifiers, options.modifiers)).forEach(function (name) {
_this.options.modifiers[name] = _extends({}, Popper.Defaults.modifiers[name] || {}, options.modifiers ? options.modifiers[name] : {});
});
// Refactoring modifiers' list (Object => Array)
this.modifiers = Object.keys(this.options.modifiers).map(function (name) {
return _extends({
name: name
}, _this.options.modifiers[name]);
})
// sort the modifiers by order
.sort(function (a, b) {
return a.order - b.order;
});
// modifiers have the ability to execute arbitrary code when Popper.js get inited
// such code is executed in the same order of its modifier
// they could add new properties to their options configuration
// BE AWARE: don't add options to `options.modifiers.name` but to `modifierOptions`!
this.modifiers.forEach(function (modifierOptions) {
if (modifierOptions.enabled && isFunction(modifierOptions.onLoad)) {
modifierOptions.onLoad(_this.reference, _this.popper, _this.options, modifierOptions, _this.state);
}
});
} | javascript | {
"resource": ""
} |
q16526 | setupEventListeners | train | function setupEventListeners(reference, options, state, updateBound) {
// Resize event listener on window
state.updateBound = updateBound;
getWindow(reference).addEventListener('resize', state.updateBound, { passive: true });
// Scroll event listener on scroll parents
var scrollElement = getScrollParent(reference);
attachToScrollParents(scrollElement, 'scroll', state.updateBound, state.scrollParents);
state.scrollElement = scrollElement;
state.eventsEnabled = true;
return state;
} | javascript | {
"resource": ""
} |
q16527 | removeEventListeners | train | function removeEventListeners(reference, state) {
// Remove resize event listener on window
getWindow(reference).removeEventListener('resize', state.updateBound);
// Remove scroll event listener on scroll parents
state.scrollParents.forEach(function (target) {
target.removeEventListener('scroll', state.updateBound);
});
// Reset state
state.updateBound = null;
state.scrollParents = [];
state.scrollElement = null;
state.eventsEnabled = false;
return state;
} | javascript | {
"resource": ""
} |
q16528 | setStyles | train | function setStyles(element, styles) {
Object.keys(styles).forEach(function (prop) {
var unit = '';
// add unit if the value is numeric and is one of the following
if (['width', 'height', 'top', 'right', 'bottom', 'left'].indexOf(prop) !== -1 && isNumeric(styles[prop])) {
unit = 'px';
}
element.style[prop] = styles[prop] + unit;
});
} | javascript | {
"resource": ""
} |
q16529 | setAttributes | train | function setAttributes(element, attributes) {
Object.keys(attributes).forEach(function (prop) {
var value = attributes[prop];
if (value !== false) {
element.setAttribute(prop, attributes[prop]);
} else {
element.removeAttribute(prop);
}
});
} | javascript | {
"resource": ""
} |
q16530 | toValue | train | function toValue(str, measurement, popperOffsets, referenceOffsets) {
// separate value from unit
var split = str.match(/((?:\-|\+)?\d*\.?\d*)(.*)/);
var value = +split[1];
var unit = split[2];
// If it's not a number it's an operator, I guess
if (!value) {
return str;
}
if (unit.indexOf('%') === 0) {
var element = void 0;
switch (unit) {
case '%p':
element = popperOffsets;
break;
case '%':
case '%r':
default:
element = referenceOffsets;
}
var rect = getClientRect(element);
return rect[measurement] / 100 * value;
} else if (unit === 'vh' || unit === 'vw') {
// if is a vh or vw, we calculate the size based on the viewport
var size = void 0;
if (unit === 'vh') {
size = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
} else {
size = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
}
return size / 100 * value;
} else {
// if is an explicit pixel unit, we get rid of the unit and keep the value
// if is an implicit unit, it's px, and we return just the value
return value;
}
} | javascript | {
"resource": ""
} |
q16531 | Popper | train | function Popper(reference, popper) {
var _this = this;
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
classCallCheck(this, Popper);
this.scheduleUpdate = function () {
return requestAnimation(_this.update);
};
// make update() debounced, so that it only runs at most once-per-tick
this.update = debounce(this.update.bind(this));
// with {} we create a new object with the options inside it
this.defaultOptions = options;
this.options = _extends({}, Popper.Defaults, options);
// init state
this.state = {
isDestroyed: false,
isCreated: false,
scrollParents: []
};
// get reference and popper elements (allow jQuery wrappers)
this.reference = reference && reference.jquery ? reference[0] : reference;
this.popper = popper && popper.jquery ? popper[0] : popper;
this.updateModifiers();
// fire the first update to position the popper in the right place
this.update();
var eventsEnabled = this.options.eventsEnabled;
if (eventsEnabled) {
// setup event listeners, they will take care of update the position in specific situations
this.enableEventListeners();
}
this.state.eventsEnabled = eventsEnabled;
} | javascript | {
"resource": ""
} |
q16532 | queryIndex | train | function queryIndex(query) {
try {
if (query.length) {
var results = index.search(query);
if (results.length === 0) {
// Add a relaxed search in the title for the first word in the query
// E.g. if the search is "ngCont guide" then we search for "ngCont guide titleWords:ngCont*"
var titleQuery = 'titleWords:*' + query.split(' ', 1)[0] + '*';
results = index.search(query + ' ' + titleQuery);
}
// Map the hits into info about each page to be returned as results
return results.map(function(hit) { return pages[hit.ref]; });
}
} catch(e) {
// If the search query cannot be parsed the index throws an error
// Log it and recover
console.log(e);
}
return [];
} | javascript | {
"resource": ""
} |
q16533 | runE2e | train | function runE2e() {
if (argv.setup) {
// Run setup.
console.log('runE2e: setup boilerplate');
const installPackagesCommand = `example-use-${argv.local ? 'local' : 'npm'}`;
const addBoilerplateCommand = 'boilerplate:add';
shelljs.exec(`yarn ${installPackagesCommand}`, { cwd: AIO_PATH });
shelljs.exec(`yarn ${addBoilerplateCommand}`, { cwd: AIO_PATH });
}
const outputFile = path.join(AIO_PATH, './protractor-results.txt');
return Promise.resolve()
.then(() => findAndRunE2eTests(argv.filter, outputFile, argv.shard))
.then((status) => {
reportStatus(status, outputFile);
if (status.failed.length > 0) {
return Promise.reject('Some test suites failed');
}
}).catch(function (e) {
console.log(e);
process.exitCode = 1;
});
} | javascript | {
"resource": ""
} |
q16534 | getE2eSpecsFor | train | function getE2eSpecsFor(basePath, specFile, filter) {
// Only get spec file at the example root.
const e2eSpecGlob = `${filter ? `*${filter}*` : '*'}/${specFile}`;
return globby(e2eSpecGlob, { cwd: basePath, nodir: true })
.then(paths => paths
.filter(file => !IGNORED_EXAMPLES.some(ignored => file.startsWith(ignored)))
.map(file => path.join(basePath, file))
);
} | javascript | {
"resource": ""
} |
q16535 | watch | train | function watch() {
gulp.watch(['src/**/*.js', '!src/**/README.md'],
['scripts', 'demos', 'components', reload]);
gulp.watch(['src/**/*.{scss,css}'],
['styles', 'styles-grid', 'styletemplates', reload]);
gulp.watch(['src/**/*.html'], ['pages', reload]);
gulp.watch(['src/**/*.{svg,png,jpg}'], ['images', reload]);
gulp.watch(['src/**/README.md'], ['pages', reload]);
gulp.watch(['templates/**/*'], ['templates', reload]);
gulp.watch(['docs/**/*'], ['pages', 'assets', reload]);
gulp.watch(['package.json', 'bower.json', 'LICENSE'], ['metadata']);
} | javascript | {
"resource": ""
} |
q16536 | mdlPublish | train | function mdlPublish(pubScope) {
let cacheTtl = null;
let src = null;
let dest = null;
if (pubScope === 'staging') {
// Set staging specific vars here.
cacheTtl = 0;
src = 'dist/*';
dest = bucketStaging;
} else if (pubScope === 'prod') {
// Set prod specific vars here.
cacheTtl = 60;
src = 'dist/*';
dest = bucketProd;
} else if (pubScope === 'promote') {
// Set promote (essentially prod) specific vars here.
cacheTtl = 60;
src = `${bucketStaging}/*`;
dest = bucketProd;
}
let infoMsg = `Publishing ${pubScope}/${pkg.version} to GCS (${dest})`;
if (src) {
infoMsg += ` from ${src}`;
}
console.log(infoMsg);
// Build gsutil commands:
// The gsutil -h option is used to set metadata headers.
// The gsutil -m option requests parallel copies.
// The gsutil -R option is used for recursive file copy.
const cacheControl = `-h "Cache-Control:public,max-age=${cacheTtl}"`;
const gsutilCacheCmd = `gsutil -m setmeta ${cacheControl} ${dest}/**`;
const gsutilCpCmd = `gsutil -m cp -r -z html,css,js,svg ${src} ${dest}`;
gulp.src('').pipe($.shell([gsutilCpCmd, gsutilCacheCmd]));
} | javascript | {
"resource": ""
} |
q16537 | findRegisteredClass_ | train | function findRegisteredClass_(name, optReplace) {
for (var i = 0; i < registeredComponents_.length; i++) {
if (registeredComponents_[i].className === name) {
if (typeof optReplace !== 'undefined') {
registeredComponents_[i] = optReplace;
}
return registeredComponents_[i];
}
}
return false;
} | javascript | {
"resource": ""
} |
q16538 | createEvent_ | train | function createEvent_(eventType, bubbles, cancelable) {
if ('CustomEvent' in window && typeof window.CustomEvent === 'function') {
return new CustomEvent(eventType, {
bubbles: bubbles,
cancelable: cancelable
});
} else {
var ev = document.createEvent('Events');
ev.initEvent(eventType, bubbles, cancelable);
return ev;
}
} | javascript | {
"resource": ""
} |
q16539 | upgradeDomInternal | train | function upgradeDomInternal(optJsClass, optCssClass) {
if (typeof optJsClass === 'undefined' &&
typeof optCssClass === 'undefined') {
for (var i = 0; i < registeredComponents_.length; i++) {
upgradeDomInternal(registeredComponents_[i].className,
registeredComponents_[i].cssClass);
}
} else {
var jsClass = /** @type {string} */ (optJsClass);
if (typeof optCssClass === 'undefined') {
var registeredClass = findRegisteredClass_(jsClass);
if (registeredClass) {
optCssClass = registeredClass.cssClass;
}
}
var elements = document.querySelectorAll('.' + optCssClass);
for (var n = 0; n < elements.length; n++) {
upgradeElementInternal(elements[n], jsClass);
}
}
} | javascript | {
"resource": ""
} |
q16540 | upgradeElementsInternal | train | function upgradeElementsInternal(elements) {
if (!Array.isArray(elements)) {
if (elements instanceof Element) {
elements = [elements];
} else {
elements = Array.prototype.slice.call(elements);
}
}
for (var i = 0, n = elements.length, element; i < n; i++) {
element = elements[i];
if (element instanceof HTMLElement) {
upgradeElementInternal(element);
if (element.children.length > 0) {
upgradeElementsInternal(element.children);
}
}
}
} | javascript | {
"resource": ""
} |
q16541 | registerInternal | train | function registerInternal(config) {
// In order to support both Closure-compiled and uncompiled code accessing
// this method, we need to allow for both the dot and array syntax for
// property access. You'll therefore see the `foo.bar || foo['bar']`
// pattern repeated across this method.
var widgetMissing = (typeof config.widget === 'undefined' &&
typeof config['widget'] === 'undefined');
var widget = true;
if (!widgetMissing) {
widget = config.widget || config['widget'];
}
var newConfig = /** @type {componentHandler.ComponentConfig} */ ({
classConstructor: config.constructor || config['constructor'],
className: config.classAsString || config['classAsString'],
cssClass: config.cssClass || config['cssClass'],
widget: widget,
callbacks: []
});
registeredComponents_.forEach(function(item) {
if (item.cssClass === newConfig.cssClass) {
throw new Error('The provided cssClass has already been registered: ' + item.cssClass);
}
if (item.className === newConfig.className) {
throw new Error('The provided className has already been registered');
}
});
if (config.constructor.prototype
.hasOwnProperty(componentConfigProperty_)) {
throw new Error(
'MDL component classes must not have ' + componentConfigProperty_ +
' defined as a property.');
}
var found = findRegisteredClass_(config.classAsString, newConfig);
if (!found) {
registeredComponents_.push(newConfig);
}
} | javascript | {
"resource": ""
} |
q16542 | registerUpgradedCallbackInternal | train | function registerUpgradedCallbackInternal(jsClass, callback) {
var regClass = findRegisteredClass_(jsClass);
if (regClass) {
regClass.callbacks.push(callback);
}
} | javascript | {
"resource": ""
} |
q16543 | upgradeAllRegisteredInternal | train | function upgradeAllRegisteredInternal() {
for (var n = 0; n < registeredComponents_.length; n++) {
upgradeDomInternal(registeredComponents_[n].className);
}
} | javascript | {
"resource": ""
} |
q16544 | downgradeNodesInternal | train | function downgradeNodesInternal(nodes) {
/**
* Auxiliary function to downgrade a single node.
* @param {!Node} node the node to be downgraded
*/
var downgradeNode = function(node) {
createdComponents_.filter(function(item) {
return item.element_ === node;
}).forEach(deconstructComponentInternal);
};
if (nodes instanceof Array || nodes instanceof NodeList) {
for (var n = 0; n < nodes.length; n++) {
downgradeNode(nodes[n]);
}
} else if (nodes instanceof Node) {
downgradeNode(nodes);
} else {
throw new Error('Invalid argument provided to downgrade MDL nodes.');
}
} | javascript | {
"resource": ""
} |
q16545 | MaterialComponentsNav | train | function MaterialComponentsNav() {
'use strict';
this.element_ = document.querySelector('.mdl-js-components');
if (this.element_) {
this.componentLinks = this.element_.querySelectorAll('.mdl-components__link');
this.activeLink = null;
this.activePage = null;
this.init();
}
} | javascript | {
"resource": ""
} |
q16546 | train | function () {
var el;
el = document.createElement('a-entity');
el.play = this.wrapPlay(el.play);
el.setAttribute('mixin', this.data.mixin);
el.object3D.visible = false;
el.pause();
this.container.appendChild(el);
this.availableEls.push(el);
} | javascript | {
"resource": ""
} | |
q16547 | train | function () {
var el;
if (this.availableEls.length === 0) {
if (this.data.dynamic === false) {
warn('Requested entity from empty pool: ' + this.attrName);
return;
} else {
warn('Requested entity from empty pool. This pool is dynamic and will resize ' +
'automatically. You might want to increase its initial size: ' + this.attrName);
}
this.createEntity();
}
el = this.availableEls.shift();
this.usedEls.push(el);
el.object3D.visible = true;
return el;
} | javascript | {
"resource": ""
} | |
q16548 | train | function (el) {
var index = this.usedEls.indexOf(el);
if (index === -1) {
warn('The returned entity was not previously pooled from ' + this.attrName);
return;
}
this.usedEls.splice(index, 1);
this.availableEls.push(el);
el.object3D.visible = false;
el.pause();
return el;
} | javascript | {
"resource": ""
} | |
q16549 | isComponentMixedIn | train | function isComponentMixedIn (name, mixinEls) {
var i;
var inMixin = false;
for (i = 0; i < mixinEls.length; ++i) {
inMixin = mixinEls[i].hasAttribute(name);
if (inMixin) { break; }
}
return inMixin;
} | javascript | {
"resource": ""
} |
q16550 | mergeComponentData | train | function mergeComponentData (attrValue, extraData) {
// Extra data not defined, just return attrValue.
if (!extraData) { return attrValue; }
// Merge multi-property data.
if (extraData.constructor === Object) {
return utils.extend(extraData, utils.styleParser.parse(attrValue || {}));
}
// Return data, precendence to the defined value.
return attrValue || extraData;
} | javascript | {
"resource": ""
} |
q16551 | train | function (value, silent) {
var schema = this.schema;
if (this.isSingleProperty) { return parseProperty(value, schema); }
return parseProperties(styleParser.parse(value), schema, true, this.name, silent);
} | javascript | {
"resource": ""
} | |
q16552 | train | function (data) {
var schema = this.schema;
if (typeof data === 'string') { return data; }
if (this.isSingleProperty) { return stringifyProperty(data, schema); }
data = stringifyProperties(data, schema);
return styleParser.stringify(data);
} | javascript | {
"resource": ""
} | |
q16553 | train | function (value, clobber) {
var newAttrValue;
var tempObject;
var property;
if (value === undefined) { return; }
// If null value is the new attribute value, make the attribute value falsy.
if (value === null) {
if (this.isObjectBased && this.attrValue) {
this.objectPool.recycle(this.attrValue);
}
this.attrValue = undefined;
return;
}
if (value instanceof Object && !(value instanceof window.HTMLElement)) {
// If value is an object, copy it to our pooled newAttrValue object to use to update
// the attrValue.
tempObject = this.objectPool.use();
newAttrValue = utils.extend(tempObject, value);
} else {
newAttrValue = this.parseAttrValueForCache(value);
}
// Merge new data with previous `attrValue` if updating and not clobbering.
if (this.isObjectBased && !clobber && this.attrValue) {
for (property in this.attrValue) {
if (newAttrValue[property] === undefined) {
newAttrValue[property] = this.attrValue[property];
}
}
}
// Update attrValue.
if (this.isObjectBased && !this.attrValue) {
this.attrValue = this.objectPool.use();
}
utils.objectPool.clearObject(this.attrValue);
this.attrValue = extendProperties(this.attrValue, newAttrValue, this.isObjectBased);
utils.objectPool.clearObject(tempObject);
} | javascript | {
"resource": ""
} | |
q16554 | train | function (value) {
var parsedValue;
if (typeof value !== 'string') { return value; }
if (this.isSingleProperty) {
parsedValue = this.schema.parse(value);
/**
* To avoid bogus double parsings. Cached values will be parsed when building
* component data. For instance when parsing a src id to its url, we want to cache
* original string and not the parsed one (#monster -> models/monster.dae)
* so when building data we parse the expected value.
*/
if (typeof parsedValue === 'string') { parsedValue = value; }
} else {
// Parse using the style parser to avoid double parsing of individual properties.
utils.objectPool.clearObject(this.parsingAttrValue);
parsedValue = styleParser.parse(value, this.parsingAttrValue);
}
return parsedValue;
} | javascript | {
"resource": ""
} | |
q16555 | train | function (isDefault) {
var attrValue = isDefault ? this.data : this.attrValue;
if (attrValue === null || attrValue === undefined) { return; }
window.HTMLElement.prototype.setAttribute.call(this.el, this.attrName,
this.stringify(attrValue));
} | javascript | {
"resource": ""
} | |
q16556 | train | function () {
var hasComponentChanged;
// Store the previous old data before we calculate the new oldData.
if (this.previousOldData instanceof Object) {
utils.objectPool.clearObject(this.previousOldData);
}
if (this.isObjectBased) {
copyData(this.previousOldData, this.oldData);
} else {
this.previousOldData = this.oldData;
}
hasComponentChanged = !utils.deepEqual(this.oldData, this.data);
// Don't update if properties haven't changed.
// Always update rotation, position, scale.
if (!this.isPositionRotationScale && !hasComponentChanged) { return; }
// Store current data as previous data for future updates.
// Reuse `this.oldData` object to try not to allocate another one.
if (this.oldData instanceof Object) { utils.objectPool.clearObject(this.oldData); }
this.oldData = extendProperties(this.oldData, this.data, this.isObjectBased);
// Update component with the previous old data.
this.update(this.previousOldData);
this.throttledEmitComponentChanged();
} | javascript | {
"resource": ""
} | |
q16557 | train | function (propertyName) {
if (this.isObjectBased) {
if (!(propertyName in this.attrValue)) { return; }
delete this.attrValue[propertyName];
this.data[propertyName] = this.schema[propertyName].default;
} else {
this.attrValue = this.schema.default;
this.data = this.schema.default;
}
this.updateProperties(this.attrValue);
} | javascript | {
"resource": ""
} | |
q16558 | train | function (schemaAddon) {
var extendedSchema;
// Clone base schema.
extendedSchema = utils.extend({}, components[this.name].schema);
// Extend base schema with new schema chunk.
utils.extend(extendedSchema, schemaAddon);
this.schema = processSchema(extendedSchema);
this.el.emit('schemachanged', this.evtDetail);
} | javascript | {
"resource": ""
} | |
q16559 | train | function (newData, clobber, silent) {
var componentDefined;
var data;
var defaultValue;
var key;
var mixinData;
var nextData = this.nextData;
var schema = this.schema;
var i;
var mixinEls = this.el.mixinEls;
var previousData;
// Whether component has a defined value. For arrays, treat empty as not defined.
componentDefined = newData && newData.constructor === Array
? newData.length
: newData !== undefined && newData !== null;
if (this.isObjectBased) { utils.objectPool.clearObject(nextData); }
// 1. Gather default values (lowest precendence).
if (this.isSingleProperty) {
if (this.isObjectBased) {
// If object-based single-prop, then copy over the data to our pooled object.
data = copyData(nextData, schema.default);
} else {
// If is plain single-prop, copy by value the default.
data = isObjectOrArray(schema.default)
? utils.clone(schema.default)
: schema.default;
}
} else {
// Preserve previously set properties if clobber not enabled.
previousData = !clobber && this.attrValue;
// Clone default value if object so components don't share object
data = previousData instanceof Object
? copyData(nextData, previousData)
: nextData;
// Apply defaults.
for (key in schema) {
defaultValue = schema[key].default;
if (data[key] !== undefined) { continue; }
// Clone default value if object so components don't share object
data[key] = isObjectOrArray(defaultValue)
? utils.clone(defaultValue)
: defaultValue;
}
}
// 2. Gather mixin values.
for (i = 0; i < mixinEls.length; i++) {
mixinData = mixinEls[i].getAttribute(this.attrName);
if (!mixinData) { continue; }
data = extendProperties(data, mixinData, this.isObjectBased);
}
// 3. Gather attribute values (highest precendence).
if (componentDefined) {
if (this.isSingleProperty) {
// If object-based, copy the value to not modify the original.
if (isObject(newData)) {
copyData(this.parsingAttrValue, newData);
return parseProperty(this.parsingAttrValue, schema);
}
return parseProperty(newData, schema);
}
data = extendProperties(data, newData, this.isObjectBased);
} else {
// Parse and coerce using the schema.
if (this.isSingleProperty) { return parseProperty(data, schema); }
}
return parseProperties(data, schema, undefined, this.name, silent);
} | javascript | {
"resource": ""
} | |
q16560 | train | function () {
this.objectPool.recycle(this.attrValue);
this.objectPool.recycle(this.oldData);
this.objectPool.recycle(this.parsingAttrValue);
this.attrValue = this.oldData = this.parsingAttrValue = undefined;
} | javascript | {
"resource": ""
} | |
q16561 | copyData | train | function copyData (dest, sourceData) {
var parsedProperty;
var key;
for (key in sourceData) {
if (sourceData[key] === undefined) { continue; }
parsedProperty = sourceData[key];
dest[key] = isObjectOrArray(parsedProperty)
? utils.clone(parsedProperty)
: parsedProperty;
}
return dest;
} | javascript | {
"resource": ""
} |
q16562 | extendProperties | train | function extendProperties (dest, source, isObjectBased) {
var key;
if (isObjectBased && source.constructor === Object) {
for (key in source) {
if (source[key] === undefined) { continue; }
if (source[key] && source[key].constructor === Object) {
dest[key] = utils.clone(source[key]);
} else {
dest[key] = source[key];
}
}
return dest;
}
return source;
} | javascript | {
"resource": ""
} |
q16563 | wrapPause | train | function wrapPause (pauseMethod) {
return function pause () {
var sceneEl = this.el.sceneEl;
if (!this.isPlaying) { return; }
pauseMethod.call(this);
this.isPlaying = false;
this.eventsDetach();
// Remove tick behavior.
if (!hasBehavior(this)) { return; }
sceneEl.removeBehavior(this);
};
} | javascript | {
"resource": ""
} |
q16564 | wrapPlay | train | function wrapPlay (playMethod) {
return function play () {
var sceneEl = this.el.sceneEl;
var shouldPlay = this.el.isPlaying && !this.isPlaying;
if (!this.initialized || !shouldPlay) { return; }
playMethod.call(this);
this.isPlaying = true;
this.eventsAttach();
// Add tick behavior.
if (!hasBehavior(this)) { return; }
sceneEl.addBehavior(this);
};
} | javascript | {
"resource": ""
} |
q16565 | train | function (data) {
var cache = this.cache;
var cachedGeometry;
var hash;
// Skip all caching logic.
if (data.skipCache) { return createGeometry(data); }
// Try to retrieve from cache first.
hash = this.hash(data);
cachedGeometry = cache[hash];
incrementCacheCount(this.cacheCount, hash);
if (cachedGeometry) { return cachedGeometry; }
// Create geometry.
cachedGeometry = createGeometry(data);
// Cache and return geometry.
cache[hash] = cachedGeometry;
return cachedGeometry;
} | javascript | {
"resource": ""
} | |
q16566 | train | function (data) {
var cache = this.cache;
var cacheCount = this.cacheCount;
var geometry;
var hash;
if (data.skipCache) { return; }
hash = this.hash(data);
if (!cache[hash]) { return; }
decrementCacheCount(cacheCount, hash);
// Another entity is still using this geometry. No need to do anything.
if (cacheCount[hash] > 0) { return; }
// No more entities are using this geometry. Dispose.
geometry = cache[hash];
geometry.dispose();
delete cache[hash];
delete cacheCount[hash];
} | javascript | {
"resource": ""
} | |
q16567 | createGeometry | train | function createGeometry (data) {
var geometryType = data.primitive;
var GeometryClass = geometries[geometryType] && geometries[geometryType].Geometry;
var geometryInstance = new GeometryClass();
if (!GeometryClass) { throw new Error('Unknown geometry `' + geometryType + '`'); }
geometryInstance.init(data);
return toBufferGeometry(geometryInstance.geometry, data.buffer);
} | javascript | {
"resource": ""
} |
q16568 | incrementCacheCount | train | function incrementCacheCount (cacheCount, hash) {
cacheCount[hash] = cacheCount[hash] === undefined ? 1 : cacheCount[hash] + 1;
} | javascript | {
"resource": ""
} |
q16569 | toBufferGeometry | train | function toBufferGeometry (geometry, doBuffer) {
var bufferGeometry;
if (!doBuffer) { return geometry; }
bufferGeometry = new THREE.BufferGeometry().fromGeometry(geometry);
bufferGeometry.metadata = {type: geometry.type, parameters: geometry.parameters || {}};
geometry.dispose(); // Dispose no longer needed non-buffer geometry.
return bufferGeometry;
} | javascript | {
"resource": ""
} |
q16570 | handleTextureEvents | train | function handleTextureEvents (el, texture) {
if (!texture) { return; }
el.emit('materialtextureloaded', {src: texture.image, texture: texture});
// Video events.
if (!texture.image || texture.image.tagName !== 'VIDEO') { return; }
texture.image.addEventListener('loadeddata', function emitVideoTextureLoadedDataAll () {
// Check to see if we need to use iOS 10 HLS shader.
// Only override the shader if it is stock shader that we know doesn't correct.
if (!el.components || !el.components.material) { return; }
if (texture.needsCorrectionBGRA && texture.needsCorrectionFlipY &&
['standard', 'flat'].indexOf(el.components.material.data.shader) !== -1) {
el.setAttribute('material', 'shader', 'ios10hls');
}
el.emit('materialvideoloadeddata', {src: texture.image, texture: texture});
});
texture.image.addEventListener('ended', function emitVideoTextureEndedAll () {
// Works for non-looping videos only.
el.emit('materialvideoended', {src: texture.image, texture: texture});
});
} | javascript | {
"resource": ""
} |
q16571 | isTablet | train | function isTablet (mockUserAgent) {
var userAgent = mockUserAgent || window.navigator.userAgent;
return /ipad|Nexus (7|9)|xoom|sch-i800|playbook|tablet|kindle/i.test(userAgent);
} | javascript | {
"resource": ""
} |
q16572 | train | function (data) {
var self = this;
var material = this.material;
var envMap = data.envMap;
var sphericalEnvMap = data.sphericalEnvMap;
// No envMap defined or already loading.
if ((!envMap && !sphericalEnvMap) || this.isLoadingEnvMap) {
material.envMap = null;
material.needsUpdate = true;
return;
}
this.isLoadingEnvMap = true;
// if a spherical env map is defined then use it.
if (sphericalEnvMap) {
this.el.sceneEl.systems.material.loadTexture(sphericalEnvMap, {src: sphericalEnvMap}, function textureLoaded (texture) {
self.isLoadingEnvMap = false;
texture.mapping = THREE.SphericalReflectionMapping;
material.envMap = texture;
utils.material.handleTextureEvents(self.el, texture);
material.needsUpdate = true;
});
return;
}
// Another material is already loading this texture. Wait on promise.
if (texturePromises[envMap]) {
texturePromises[envMap].then(function (cube) {
self.isLoadingEnvMap = false;
material.envMap = cube;
utils.material.handleTextureEvents(self.el, cube);
material.needsUpdate = true;
});
return;
}
// Material is first to load this texture. Load and resolve texture.
texturePromises[envMap] = new Promise(function (resolve) {
utils.srcLoader.validateCubemapSrc(envMap, function loadEnvMap (urls) {
CubeLoader.load(urls, function (cube) {
// Texture loaded.
self.isLoadingEnvMap = false;
material.envMap = cube;
utils.material.handleTextureEvents(self.el, cube);
resolve(cube);
});
});
});
} | javascript | {
"resource": ""
} | |
q16573 | train | function () {
var el = this.el;
var data = this.data;
var light = this.light;
light.castShadow = data.castShadow;
// Shadow camera helper.
var cameraHelper = el.getObject3D('cameraHelper');
if (data.shadowCameraVisible && !cameraHelper) {
el.setObject3D('cameraHelper', new THREE.CameraHelper(light.shadow.camera));
} else if (!data.shadowCameraVisible && cameraHelper) {
el.removeObject3D('cameraHelper');
}
if (!data.castShadow) { return light; }
// Shadow appearance.
light.shadow.bias = data.shadowBias;
light.shadow.radius = data.shadowRadius;
light.shadow.mapSize.height = data.shadowMapHeight;
light.shadow.mapSize.width = data.shadowMapWidth;
// Shadow camera.
light.shadow.camera.near = data.shadowCameraNear;
light.shadow.camera.far = data.shadowCameraFar;
if (light.shadow.camera instanceof THREE.OrthographicCamera) {
light.shadow.camera.top = data.shadowCameraTop;
light.shadow.camera.right = data.shadowCameraRight;
light.shadow.camera.bottom = data.shadowCameraBottom;
light.shadow.camera.left = data.shadowCameraLeft;
} else {
light.shadow.camera.fov = data.shadowCameraFov;
}
light.shadow.camera.updateProjectionMatrix();
if (cameraHelper) { cameraHelper.update(); }
} | javascript | {
"resource": ""
} | |
q16574 | train | function (data) {
var angle = data.angle;
var color = new THREE.Color(data.color);
this.rendererSystem.applyColorCorrection(color);
color = color.getHex();
var decay = data.decay;
var distance = data.distance;
var groundColor = new THREE.Color(data.groundColor);
this.rendererSystem.applyColorCorrection(groundColor);
groundColor = groundColor.getHex();
var intensity = data.intensity;
var type = data.type;
var target = data.target;
var light = null;
switch (type.toLowerCase()) {
case 'ambient': {
return new THREE.AmbientLight(color, intensity);
}
case 'directional': {
light = new THREE.DirectionalLight(color, intensity);
this.defaultTarget = light.target;
if (target) {
if (target.hasLoaded) {
this.onSetTarget(target, light);
} else {
target.addEventListener('loaded', bind(this.onSetTarget, this, target, light));
}
}
return light;
}
case 'hemisphere': {
return new THREE.HemisphereLight(color, groundColor, intensity);
}
case 'point': {
return new THREE.PointLight(color, intensity, distance, decay);
}
case 'spot': {
light = new THREE.SpotLight(color, intensity, distance, degToRad(angle), data.penumbra, decay);
this.defaultTarget = light.target;
if (target) {
if (target.hasLoaded) {
this.onSetTarget(target, light);
} else {
target.addEventListener('loaded', bind(this.onSetTarget, this, target, light));
}
}
return light;
}
default: {
warn('%s is not a valid light type. ' +
'Choose from ambient, directional, hemisphere, point, spot.', type);
}
}
} | javascript | {
"resource": ""
} | |
q16575 | train | function (rawData) {
var oldData = this.data;
if (!Object.keys(schema).length) { return; }
this.buildData(rawData);
this.update(oldData);
} | javascript | {
"resource": ""
} | |
q16576 | train | function () {
var data = this.data;
var object3D = this.el.object3D;
object3D.rotation.set(degToRad(data.x), degToRad(data.y), degToRad(data.z));
object3D.rotation.order = 'YXZ';
} | javascript | {
"resource": ""
} | |
q16577 | train | function (oldData) {
var data = this.data;
if (!this.shader || data.shader !== oldData.shader) {
this.updateShader(data.shader);
}
this.shader.update(this.data);
this.updateMaterial(oldData);
} | javascript | {
"resource": ""
} | |
q16578 | train | function (oldData) {
var data = this.data;
var material = this.material;
var oldDataHasKeys;
// Base material properties.
material.alphaTest = data.alphaTest;
material.depthTest = data.depthTest !== false;
material.depthWrite = data.depthWrite !== false;
material.opacity = data.opacity;
material.flatShading = data.flatShading;
material.side = parseSide(data.side);
material.transparent = data.transparent !== false || data.opacity < 1.0;
material.vertexColors = parseVertexColors(data.vertexColors);
material.visible = data.visible;
material.blending = parseBlending(data.blending);
// Check if material needs update.
for (oldDataHasKeys in oldData) { break; }
if (oldDataHasKeys &&
(oldData.alphaTest !== data.alphaTest ||
oldData.side !== data.side ||
oldData.vertexColors !== data.vertexColors)) {
material.needsUpdate = true;
}
} | javascript | {
"resource": ""
} | |
q16579 | parseBlending | train | function parseBlending (blending) {
switch (blending) {
case 'none': {
return THREE.NoBlending;
}
case 'additive': {
return THREE.AdditiveBlending;
}
case 'subtractive': {
return THREE.SubtractiveBlending;
}
case 'multiply': {
return THREE.MultiplyBlending;
}
default: {
return THREE.NormalBlending;
}
}
} | javascript | {
"resource": ""
} |
q16580 | train | function () {
var camera;
var el = this.el;
// Create camera.
camera = this.camera = new THREE.PerspectiveCamera();
el.setObject3D('camera', camera);
} | javascript | {
"resource": ""
} | |
q16581 | train | function (oldData) {
var data = this.data;
var camera = this.camera;
// Update properties.
camera.aspect = data.aspect || (window.innerWidth / window.innerHeight);
camera.far = data.far;
camera.fov = data.fov;
camera.near = data.near;
camera.zoom = data.zoom;
camera.updateProjectionMatrix();
this.updateActiveCamera(oldData);
this.updateSpectatorCamera(oldData);
} | javascript | {
"resource": ""
} | |
q16582 | train | function () {
var data = this.data;
this.updateConfig();
this.animationIsPlaying = false;
this.animation = anime(this.config);
this.animation.began = true;
this.removeEventListeners();
this.addEventListeners();
// Wait for start events for animation.
if (!data.autoplay || data.startEvents && data.startEvents.length) { return; }
// Delay animation.
if (data.delay) {
setTimeout(this.beginAnimation, data.delay);
return;
}
// Play animation.
this.beginAnimation();
} | javascript | {
"resource": ""
} | |
q16583 | train | function () {
var config = this.config;
var data = this.data;
var el = this.el;
var from;
var isBoolean;
var isNumber;
var to;
if (this.waitComponentInitRawProperty(this.updateConfigForDefault)) {
return;
}
if (data.from === '') {
// Infer from.
from = isRawProperty(data)
? getRawProperty(el, data.property)
: getComponentProperty(el, data.property);
} else {
// Explicit from.
from = data.from;
}
to = data.to;
isNumber = !isNaN(from || to);
if (isNumber) {
from = parseFloat(from);
to = parseFloat(to);
} else {
from = from ? from.toString() : from;
to = to ? to.toString() : to;
}
// Convert booleans to integer to allow boolean flipping.
isBoolean = data.to === 'true' || data.to === 'false' ||
data.to === true || data.to === false;
if (isBoolean) {
from = data.from === 'true' || data.from === true ? 1 : 0;
to = data.to === 'true' || data.to === true ? 1 : 0;
}
this.targets.aframeProperty = from;
config.targets = this.targets;
config.aframeProperty = to;
config.update = (function () {
var lastValue;
return function (anim) {
var value;
value = anim.animatables[0].target.aframeProperty;
// Need to do a last value check for animation timeline since all the tweening
// begins simultaenously even if the value has not changed. Also better for perf
// anyways.
if (value === lastValue) { return; }
lastValue = value;
if (isBoolean) { value = value >= 1; }
if (isRawProperty(data)) {
setRawProperty(el, data.property, value, data.type);
} else {
setComponentProperty(el, data.property, value);
}
};
})();
} | javascript | {
"resource": ""
} | |
q16584 | train | function () {
var propType;
// Route config type.
propType = getPropertyType(this.el, this.data.property);
if (isRawProperty(this.data) && this.data.type === TYPE_COLOR) {
this.updateConfigForRawColor();
} else if (propType === 'vec2' || propType === 'vec3' || propType === 'vec4') {
this.updateConfigForVector();
} else {
this.updateConfigForDefault();
}
} | javascript | {
"resource": ""
} | |
q16585 | train | function (cb) {
var componentName;
var data = this.data;
var el = this.el;
var self = this;
if (data.from !== '') { return false; }
if (!data.property.startsWith(STRING_COMPONENTS)) { return false; }
componentName = splitDot(data.property)[1];
if (el.components[componentName]) { return false; }
el.addEventListener('componentinitialized', function wait (evt) {
if (evt.detail.name !== componentName) { return; }
cb();
// Since the config was created async, create the animation now since we missed it
// earlier.
self.animation = anime(self.config);
el.removeEventListener('componentinitialized', wait);
});
return true;
} | javascript | {
"resource": ""
} | |
q16586 | getPropertyType | train | function getPropertyType (el, property) {
var component;
var componentName;
var split;
var propertyName;
split = property.split('.');
componentName = split[0];
propertyName = split[1];
component = el.components[componentName] || components[componentName];
// Primitives.
if (!component) { return null; }
// Dynamic schema. We only care about vectors anyways.
if (propertyName && !component.schema[propertyName]) { return null; }
// Multi-prop.
if (propertyName) { return component.schema[propertyName].type; }
// Single-prop.
return component.schema.type;
} | javascript | {
"resource": ""
} |
q16587 | toRadians | train | function toRadians (obj) {
obj.x = THREE.Math.degToRad(obj.x);
obj.y = THREE.Math.degToRad(obj.y);
obj.z = THREE.Math.degToRad(obj.z);
} | javascript | {
"resource": ""
} |
q16588 | train | function () {
var material = this.el.components.material;
if (!material) { return; }
this.model.traverse(function (child) {
if (child instanceof THREE.Mesh) {
child.material = material.material;
}
});
} | javascript | {
"resource": ""
} | |
q16589 | AndroidWakeLock | train | function AndroidWakeLock() {
var video = document.createElement('video');
video.addEventListener('ended', function() {
video.play();
});
this.request = function() {
if (video.paused) {
// Base64 version of videos_src/no-sleep-60s.webm.
video.src = Util.base64('video/webm', 'GkXfowEAAAAAAAAfQoaBAUL3gQFC8oEEQvOBCEKChHdlYm1Ch4ECQoWBAhhTgGcBAAAAAAAH4xFNm3RALE27i1OrhBVJqWZTrIHfTbuMU6uEFlSua1OsggEwTbuMU6uEHFO7a1OsggfG7AEAAAAAAACkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAVSalmAQAAAAAAAEUq17GDD0JATYCNTGF2ZjU2LjQwLjEwMVdBjUxhdmY1Ni40MC4xMDFzpJAGSJTMbsLpDt/ySkipgX1fRImIQO1MAAAAAAAWVK5rAQAAAAAAADuuAQAAAAAAADLXgQFzxYEBnIEAIrWcg3VuZIaFVl9WUDmDgQEj44OEO5rKAOABAAAAAAAABrCBsLqBkB9DtnUBAAAAAAAAo+eBAKOmgQAAgKJJg0IAAV4BHsAHBIODCoAACmH2MAAAZxgz4dPSTFi5JACjloED6ACmAECSnABMQAADYAAAWi0quoCjloEH0ACmAECSnABNwAADYAAAWi0quoCjloELuACmAECSnABNgAADYAAAWi0quoCjloEPoACmAECSnABNYAADYAAAWi0quoCjloETiACmAECSnABNIAADYAAAWi0quoAfQ7Z1AQAAAAAAAJTnghdwo5aBAAAApgBAkpwATOAAA2AAAFotKrqAo5aBA+gApgBAkpwATMAAA2AAAFotKrqAo5aBB9AApgBAkpwATIAAA2AAAFotKrqAo5aBC7gApgBAkpwATEAAA2AAAFotKrqAo5aBD6AApgDAkpwAQ2AAA2AAAFotKrqAo5aBE4gApgBAkpwATCAAA2AAAFotKrqAH0O2dQEAAAAAAACU54Iu4KOWgQAAAKYAQJKcAEvAAANgAABaLSq6gKOWgQPoAKYAQJKcAEtgAANgAABaLSq6gKOWgQfQAKYAQJKcAEsAAANgAABaLSq6gKOWgQu4AKYAQJKcAEqAAANgAABaLSq6gKOWgQ+gAKYAQJKcAEogAANgAABaLSq6gKOWgROIAKYAQJKcAEnAAANgAABaLSq6gB9DtnUBAAAAAAAAlOeCRlCjloEAAACmAECSnABJgAADYAAAWi0quoCjloED6ACmAECSnABJIAADYAAAWi0quoCjloEH0ACmAMCSnABDYAADYAAAWi0quoCjloELuACmAECSnABI4AADYAAAWi0quoCjloEPoACmAECSnABIoAADYAAAWi0quoCjloETiACmAECSnABIYAADYAAAWi0quoAfQ7Z1AQAAAAAAAJTngl3Ao5aBAAAApgBAkpwASCAAA2AAAFotKrqAo5aBA+gApgBAkpwASAAAA2AAAFotKrqAo5aBB9AApgBAkpwAR8AAA2AAAFotKrqAo5aBC7gApgBAkpwAR4AAA2AAAFotKrqAo5aBD6AApgBAkpwAR2AAA2AAAFotKrqAo5aBE4gApgBAkpwARyAAA2AAAFotKrqAH0O2dQEAAAAAAACU54J1MKOWgQAAAKYAwJKcAENgAANgAABaLSq6gKOWgQPoAKYAQJKcAEbgAANgAABaLSq6gKOWgQfQAKYAQJKcAEagAANgAABaLSq6gKOWgQu4AKYAQJKcAEaAAANgAABaLSq6gKOWgQ+gAKYAQJKcAEZAAANgAABaLSq6gKOWgROIAKYAQJKcAEYAAANgAABaLSq6gB9DtnUBAAAAAAAAlOeCjKCjloEAAACmAECSnABF4AADYAAAWi0quoCjloED6ACmAECSnABFwAADYAAAWi0quoCjloEH0ACmAECSnABFoAADYAAAWi0quoCjloELuACmAECSnABFgAADYAAAWi0quoCjloEPoACmAMCSnABDYAADYAAAWi0quoCjloETiACmAECSnABFYAADYAAAWi0quoAfQ7Z1AQAAAAAAAJTngqQQo5aBAAAApgBAkpwARUAAA2AAAFotKrqAo5aBA+gApgBAkpwARSAAA2AAAFotKrqAo5aBB9AApgBAkpwARQAAA2AAAFotKrqAo5aBC7gApgBAkpwARQAAA2AAAFotKrqAo5aBD6AApgBAkpwAROAAA2AAAFotKrqAo5aBE4gApgBAkpwARMAAA2AAAFotKrqAH0O2dQEAAAAAAACU54K7gKOWgQAAAKYAQJKcAESgAANgAABaLSq6gKOWgQPoAKYAQJKcAESAAANgAABaLSq6gKOWgQfQAKYAwJKcAENgAANgAABaLSq6gKOWgQu4AKYAQJKcAERgAANgAABaLSq6gKOWgQ+gAKYAQJKcAERAAANgAABaLSq6gKOWgROIAKYAQJKcAEQgAANgAABaLSq6gB9DtnUBAAAAAAAAlOeC0vCjloEAAACmAECSnABEIAADYAAAWi0quoCjloED6ACmAECSnABEAAADYAAAWi0quoCjloEH0ACmAECSnABD4AADYAAAWi0quoCjloELuACmAECSnABDwAADYAAAWi0quoCjloEPoACmAECSnABDoAADYAAAWi0quoCjloETiACmAECSnABDgAADYAAAWi0quoAcU7trAQAAAAAAABG7j7OBALeK94EB8YIBd/CBAw==');
video.play();
}
};
this.release = function() {
video.pause();
video.src = '';
};
} | javascript | {
"resource": ""
} |
q16590 | train | function (previousHand) {
var controlConfiguration;
var el = this.el;
var hand = this.data;
var self = this;
// Get common configuration to abstract different vendor controls.
controlConfiguration = {
hand: hand,
model: false,
orientationOffset: {x: 0, y: 0, z: hand === 'left' ? 90 : -90}
};
// Set model.
if (hand !== previousHand) {
this.loader.load(MODEL_URLS[hand], function (gltf) {
var mesh = gltf.scene.children[0];
mesh.mixer = new THREE.AnimationMixer(mesh);
self.clips = gltf.animations;
el.setObject3D('mesh', mesh);
mesh.position.set(0, 0, 0);
mesh.rotation.set(0, 0, 0);
el.setAttribute('vive-controls', controlConfiguration);
el.setAttribute('oculus-touch-controls', controlConfiguration);
el.setAttribute('windows-motion-controls', controlConfiguration);
});
}
} | javascript | {
"resource": ""
} | |
q16591 | train | function (button, evt) {
var lastGesture;
var isPressed = evt === 'down';
var isTouched = evt === 'touchstart';
// Update objects.
if (evt.indexOf('touch') === 0) {
// Update touch object.
if (isTouched === this.touchedButtons[button]) { return; }
this.touchedButtons[button] = isTouched;
} else {
// Update button object.
if (isPressed === this.pressedButtons[button]) { return; }
this.pressedButtons[button] = isPressed;
}
// Determine the gesture.
lastGesture = this.gesture;
this.gesture = this.determineGesture();
// Same gesture.
if (this.gesture === lastGesture) { return; }
// Animate gesture.
this.animateGesture(this.gesture, lastGesture);
// Emit events.
this.emitGestureEvents(this.gesture, lastGesture);
} | javascript | {
"resource": ""
} | |
q16592 | train | function () {
var gesture;
var isGripActive = this.pressedButtons['grip'];
var isSurfaceActive = this.pressedButtons['surface'] || this.touchedButtons['surface'];
var isTrackpadActive = this.pressedButtons['trackpad'] || this.touchedButtons['trackpad'];
var isTriggerActive = this.pressedButtons['trigger'] || this.touchedButtons['trigger'];
var isABXYActive = this.touchedButtons['AorX'] || this.touchedButtons['BorY'];
var isVive = isViveController(this.el.components['tracked-controls']);
// Works well with Oculus Touch and Windows Motion Controls, but Vive needs tweaks.
if (isVive) {
if (isGripActive || isTriggerActive) {
gesture = ANIMATIONS.fist;
} else if (isTrackpadActive) {
gesture = ANIMATIONS.point;
}
} else {
if (isGripActive) {
if (isSurfaceActive || isABXYActive || isTrackpadActive) {
gesture = isTriggerActive ? ANIMATIONS.fist : ANIMATIONS.point;
} else {
gesture = isTriggerActive ? ANIMATIONS.thumbUp : ANIMATIONS.pointThumb;
}
} else if (isTriggerActive) {
gesture = ANIMATIONS.hold;
}
}
return gesture;
} | javascript | {
"resource": ""
} | |
q16593 | train | function (gesture) {
var clip;
var i;
for (i = 0; i < this.clips.length; i++) {
clip = this.clips[i];
if (clip.name !== gesture) { continue; }
return clip;
}
} | javascript | {
"resource": ""
} | |
q16594 | train | function (gesture, lastGesture) {
if (gesture) {
this.playAnimation(gesture || ANIMATIONS.open, lastGesture, false);
return;
}
// If no gesture, then reverse the current gesture back to open pose.
this.playAnimation(lastGesture, lastGesture, true);
} | javascript | {
"resource": ""
} | |
q16595 | train | function (gesture, lastGesture) {
var el = this.el;
var eventName;
if (lastGesture === gesture) { return; }
// Emit event for lastGesture not inactive.
eventName = getGestureEventName(lastGesture, false);
if (eventName) { el.emit(eventName); }
// Emit event for current gesture now active.
eventName = getGestureEventName(gesture, true);
if (eventName) { el.emit(eventName); }
} | javascript | {
"resource": ""
} | |
q16596 | train | function (gesture, lastGesture, reverse) {
var clip;
var fromAction;
var mesh = this.el.getObject3D('mesh');
var toAction;
if (!mesh) { return; }
// Stop all current animations.
mesh.mixer.stopAllAction();
// Grab clip action.
clip = this.getClip(gesture);
toAction = mesh.mixer.clipAction(clip);
toAction.clampWhenFinished = true;
toAction.loop = THREE.LoopRepeat;
toAction.repetitions = 0;
toAction.timeScale = reverse ? -1 : 1;
toAction.time = reverse ? clip.duration : 0;
toAction.weight = 1;
// No gesture to gesture or gesture to no gesture.
if (!lastGesture || gesture === lastGesture) {
// Stop all current animations.
mesh.mixer.stopAllAction();
// Play animation.
toAction.play();
return;
}
// Animate or crossfade from gesture to gesture.
clip = this.getClip(lastGesture);
fromAction = mesh.mixer.clipAction(clip);
fromAction.weight = 0.15;
fromAction.play();
toAction.play();
fromAction.crossFadeTo(toAction, 0.15, true);
} | javascript | {
"resource": ""
} | |
q16597 | getFog | train | function getFog (data) {
var fog;
if (data.type === 'exponential') {
fog = new THREE.FogExp2(data.color, data.density);
} else {
fog = new THREE.Fog(data.color, data.near, data.far);
}
fog.name = data.type;
return fog;
} | javascript | {
"resource": ""
} |
q16598 | train | function () {
var clearedIntersectedEls = this.clearedIntersectedEls;
var el = this.el;
var data = this.data;
var i;
var intersectedEls = this.intersectedEls;
var intersection;
var intersections = this.intersections;
var newIntersectedEls = this.newIntersectedEls;
var newIntersections = this.newIntersections;
var prevIntersectedEls = this.prevIntersectedEls;
var rawIntersections = this.rawIntersections;
// Refresh the object whitelist if needed.
if (this.dirty) { this.refreshObjects(); }
// Store old previously intersected entities.
copyArray(this.prevIntersectedEls, this.intersectedEls);
// Raycast.
this.updateOriginDirection();
rawIntersections.length = 0;
this.raycaster.intersectObjects(this.objects, true, rawIntersections);
// Only keep intersections against objects that have a reference to an entity.
intersections.length = 0;
intersectedEls.length = 0;
for (i = 0; i < rawIntersections.length; i++) {
intersection = rawIntersections[i];
// Don't intersect with own line.
if (data.showLine && intersection.object === el.getObject3D('line')) {
continue;
}
if (intersection.object.el) {
intersections.push(intersection);
intersectedEls.push(intersection.object.el);
}
}
// Get newly intersected entities.
newIntersections.length = 0;
newIntersectedEls.length = 0;
for (i = 0; i < intersections.length; i++) {
if (prevIntersectedEls.indexOf(intersections[i].object.el) === -1) {
newIntersections.push(intersections[i]);
newIntersectedEls.push(intersections[i].object.el);
}
}
// Emit intersection cleared on both entities per formerly intersected entity.
clearedIntersectedEls.length = 0;
for (i = 0; i < prevIntersectedEls.length; i++) {
if (intersectedEls.indexOf(prevIntersectedEls[i]) !== -1) { continue; }
prevIntersectedEls[i].emit(EVENTS.INTERSECT_CLEAR,
this.intersectedClearedDetail);
clearedIntersectedEls.push(prevIntersectedEls[i]);
}
if (clearedIntersectedEls.length) {
el.emit(EVENTS.INTERSECTION_CLEAR, this.intersectionClearedDetail);
}
// Emit intersected on intersected entity per intersected entity.
for (i = 0; i < newIntersectedEls.length; i++) {
newIntersectedEls[i].emit(EVENTS.INTERSECT, this.intersectedDetail);
}
// Emit all intersections at once on raycasting entity.
if (newIntersections.length) {
this.intersectionDetail.els = newIntersectedEls;
this.intersectionDetail.intersections = newIntersections;
el.emit(EVENTS.INTERSECTION, this.intersectionDetail);
}
// Update line length.
setTimeout(this.updateLine);
} | javascript | {
"resource": ""
} | |
q16599 | train | function (el) {
var i;
var intersection;
for (i = 0; i < this.intersections.length; i++) {
intersection = this.intersections[i];
if (intersection.object.el === el) { return intersection; }
}
return null;
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.