_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q22800
|
train
|
function($el) {
var el = joint.util.isString($el)
? this.viewport.querySelector($el)
: $el instanceof $ ? $el[0] : $el;
var id = this.findAttribute('model-id', el);
if (id) return this._views[id];
return undefined;
}
|
javascript
|
{
"resource": ""
}
|
|
q22801
|
train
|
function(cell) {
var id = (joint.util.isString(cell) || joint.util.isNumber(cell)) ? cell : (cell && cell.id);
return this._views[id];
}
|
javascript
|
{
"resource": ""
}
|
|
q22802
|
train
|
function(p) {
p = new g.Point(p);
var views = this.model.getElements().map(this.findViewByModel, this);
return views.filter(function(view) {
return view && view.vel.getBBox({ target: this.viewport }).containsPoint(p);
}, this);
}
|
javascript
|
{
"resource": ""
}
|
|
q22803
|
train
|
function(rect, opt) {
opt = joint.util.defaults(opt || {}, { strict: false });
rect = new g.Rect(rect);
var views = this.model.getElements().map(this.findViewByModel, this);
var method = opt.strict ? 'containsRect' : 'intersect';
return views.filter(function(view) {
return view && rect[method](view.vel.getBBox({ target: this.viewport }));
}, this);
}
|
javascript
|
{
"resource": ""
}
|
|
q22804
|
train
|
function(evt, view) {
if (evt.type === 'mousedown' && evt.button === 2) {
// handled as `contextmenu` type
return true;
}
if (this.options.guard && this.options.guard(evt, view)) {
return true;
}
if (evt.data && evt.data.guarded !== undefined) {
return evt.data.guarded;
}
if (view && view.model && (view.model instanceof joint.dia.Cell)) {
return false;
}
if (this.svg === evt.target || this.el === evt.target || $.contains(this.svg, evt.target)) {
return false;
}
return true; // Event guarded. Paper should not react on it in any way.
}
|
javascript
|
{
"resource": ""
}
|
|
q22805
|
train
|
function() {
var current = this.get('ports') || {};
var currentItemsMap = {};
util.toArray(current.items).forEach(function(item) {
currentItemsMap[item.id] = true;
});
var previous = this.previous('ports') || {};
var removed = {};
util.toArray(previous.items).forEach(function(item) {
if (!currentItemsMap[item.id]) {
removed[item.id] = true;
}
});
var graph = this.graph;
if (graph && !util.isEmpty(removed)) {
var inboundLinks = graph.getConnectedLinks(this, { inbound: true });
inboundLinks.forEach(function(link) {
if (removed[link.get('target').port]) link.remove();
});
var outboundLinks = graph.getConnectedLinks(this, { outbound: true });
outboundLinks.forEach(function(link) {
if (removed[link.get('source').port]) link.remove();
});
}
}
|
javascript
|
{
"resource": ""
}
|
|
q22806
|
train
|
function(port) {
if (this._portElementsCache[port.id]) {
return this._portElementsCache[port.id].portElement;
}
return this._createPortElement(port);
}
|
javascript
|
{
"resource": ""
}
|
|
q22807
|
freeJoin
|
train
|
function freeJoin(p1, p2, bbox) {
var p = new g.Point(p1.x, p2.y);
if (bbox.containsPoint(p)) p = new g.Point(p2.x, p1.y);
// kept for reference
// if (bbox.containsPoint(p)) p = null;
return p;
}
|
javascript
|
{
"resource": ""
}
|
q22808
|
insideElement
|
train
|
function insideElement(from, to, fromBBox, toBBox, bearing) {
var route = {};
var boundary = fromBBox.union(toBBox).inflate(1);
// start from the point which is closer to the boundary
var reversed = boundary.center().distance(to) > boundary.center().distance(from);
var start = reversed ? to : from;
var end = reversed ? from : to;
var p1, p2, p3;
if (bearing) {
// Points on circle with radius equals 'W + H` are always outside the rectangle
// with width W and height H if the center of that circle is the center of that rectangle.
p1 = g.Point.fromPolar(boundary.width + boundary.height, radians[bearing], start);
p1 = boundary.pointNearestToPoint(p1).move(p1, -1);
} else {
p1 = boundary.pointNearestToPoint(start).move(start, 1);
}
p2 = freeJoin(p1, end, boundary);
if (p1.round().equals(p2.round())) {
p2 = g.Point.fromPolar(boundary.width + boundary.height, g.toRad(p1.theta(start)) + Math.PI / 2, end);
p2 = boundary.pointNearestToPoint(p2).move(end, 1).round();
p3 = freeJoin(p1, p2, boundary);
route.points = reversed ? [p2, p3, p1] : [p1, p3, p2];
} else {
route.points = reversed ? [p2, p1] : [p1, p2];
}
route.direction = reversed ? getBearing(p1, to) : getBearing(p2, to);
return route;
}
|
javascript
|
{
"resource": ""
}
|
q22809
|
router
|
train
|
function router(vertices, opt, linkView) {
var sourceBBox = getSourceBBox(linkView, opt);
var targetBBox = getTargetBBox(linkView, opt);
var sourceAnchor = getSourceAnchor(linkView, opt);
var targetAnchor = getTargetAnchor(linkView, opt);
// if anchor lies outside of bbox, the bbox expands to include it
sourceBBox = sourceBBox.union(getPointBox(sourceAnchor));
targetBBox = targetBBox.union(getPointBox(targetAnchor));
vertices = util.toArray(vertices).map(g.Point);
vertices.unshift(sourceAnchor);
vertices.push(targetAnchor);
var bearing; // bearing of previous route segment
var orthogonalVertices = []; // the array of found orthogonal vertices to be returned
for (var i = 0, max = vertices.length - 1; i < max; i++) {
var route = null;
var from = vertices[i];
var to = vertices[i + 1];
var isOrthogonal = !!getBearing(from, to);
if (i === 0) { // source
if (i + 1 === max) { // route source -> target
// Expand one of the elements by 1px to detect situations when the two
// elements are positioned next to each other with no gap in between.
if (sourceBBox.intersect(targetBBox.clone().inflate(1))) {
route = insideElement(from, to, sourceBBox, targetBBox);
} else if (!isOrthogonal) {
route = elementElement(from, to, sourceBBox, targetBBox);
}
} else { // route source -> vertex
if (sourceBBox.containsPoint(to)) {
route = insideElement(from, to, sourceBBox, getPointBox(to).moveAndExpand(getPaddingBox(opt)));
} else if (!isOrthogonal) {
route = elementVertex(from, to, sourceBBox);
}
}
} else if (i + 1 === max) { // route vertex -> target
// prevent overlaps with previous line segment
var isOrthogonalLoop = isOrthogonal && getBearing(to, from) === bearing;
if (targetBBox.containsPoint(from) || isOrthogonalLoop) {
route = insideElement(from, to, getPointBox(from).moveAndExpand(getPaddingBox(opt)), targetBBox, bearing);
} else if (!isOrthogonal) {
route = vertexElement(from, to, targetBBox, bearing);
}
} else if (!isOrthogonal) { // route vertex -> vertex
route = vertexVertex(from, to, bearing);
}
// applicable to all routes:
// set bearing for next iteration
if (route) {
Array.prototype.push.apply(orthogonalVertices, route.points);
bearing = route.direction;
} else {
// orthogonal route and not looped
bearing = getBearing(from, to);
}
// push `to` point to identified orthogonal vertices array
if (i + 1 < max) {
orthogonalVertices.push(to);
}
}
return orthogonalVertices;
}
|
javascript
|
{
"resource": ""
}
|
q22810
|
modelCenter
|
train
|
function modelCenter(view, magnet) {
var model = view.model;
var bbox = model.getBBox();
var center = bbox.center();
var angle = model.angle();
var portId = view.findAttribute('port', magnet);
if (portId) {
var portGroup = model.portProp(portId, 'group');
var portsPositions = model.getPortsPositions(portGroup);
var anchor = new g.Point(portsPositions[portId]).offset(bbox.origin());
anchor.rotate(center, -angle);
return anchor;
}
return center;
}
|
javascript
|
{
"resource": ""
}
|
q22811
|
train
|
function(ctx, from, to, width, gradient) {
var innerWidth = width - 4;
var outerWidth = width;
var buttFrom = g.point(from).move(to, -outerWidth / 2);
var buttTo = g.point(to).move(from, -outerWidth / 2);
ctx.beginPath();
ctx.lineWidth = outerWidth;
ctx.strokeStyle = 'rgba(0,0,0,0.6)';
ctx.moveTo(from.x, from.y);
ctx.lineTo(to.x, to.y);
ctx.stroke();
ctx.closePath();
gradient.addColorStop(0.000, 'rgba(86, 170, 255, 1)');
gradient.addColorStop(0.500, 'rgba(255, 255, 255, 1)');
gradient.addColorStop(1.000, 'rgba(86, 170, 255, 1)');
ctx.beginPath();
ctx.lineWidth = innerWidth;
ctx.strokeStyle = gradient;
ctx.moveTo(from.x, from.y);
ctx.lineTo(to.x, to.y);
ctx.stroke();
ctx.closePath();
ctx.lineCap = "square";
ctx.beginPath();
ctx.lineWidth = innerWidth;
ctx.strokeStyle = 'rgba(0,0,0,0.5)';
ctx.moveTo(from.x, from.y);
ctx.lineTo(buttFrom.x, buttFrom.y);
ctx.stroke();
ctx.closePath();
ctx.beginPath();
ctx.lineWidth = innerWidth;
ctx.strokeStyle = 'rgba(0,0,0,0.5)';
ctx.moveTo(to.x, to.y);
ctx.lineTo(buttTo.x, buttTo.y);
ctx.stroke();
ctx.closePath();
}
|
javascript
|
{
"resource": ""
}
|
|
q22812
|
SeeAddKnightAttacks
|
train
|
function SeeAddKnightAttacks(target, us, attacks) {
var pieceIdx = (us | pieceKnight) << 4;
var attackerSq = g_pieceList[pieceIdx++];
while (attackerSq != 0) {
if (IsSquareOnPieceLine(target, attackerSq)) {
attacks[attacks.length] = attackerSq;
}
attackerSq = g_pieceList[pieceIdx++];
}
}
|
javascript
|
{
"resource": ""
}
|
q22813
|
train
|
function(p, opt) {
opt = opt || {};
var precision = (opt.precision === undefined) ? this.PRECISION : opt.precision;
var subdivisions = (opt.subdivisions === undefined) ? this.getSubdivisions({ precision: precision }) : opt.subdivisions;
// does not use localOpt
// identify the subdivision that contains the point:
var investigatedSubdivision;
var investigatedSubdivisionStartT; // assume that subdivisions are evenly spaced
var investigatedSubdivisionEndT;
var distFromStart; // distance of point from start of baseline
var distFromEnd; // distance of point from end of baseline
var chordLength; // distance between start and end of the subdivision
var minSumDist; // lowest observed sum of the two distances
var n = subdivisions.length;
var subdivisionSize = (n ? (1 / n) : 0);
for (var i = 0; i < n; i++) {
var currentSubdivision = subdivisions[i];
var startDist = currentSubdivision.start.distance(p);
var endDist = currentSubdivision.end.distance(p);
var sumDist = startDist + endDist;
// check that the point is closest to current subdivision and not any other
if (!minSumDist || (sumDist < minSumDist)) {
investigatedSubdivision = currentSubdivision;
investigatedSubdivisionStartT = i * subdivisionSize;
investigatedSubdivisionEndT = (i + 1) * subdivisionSize;
distFromStart = startDist;
distFromEnd = endDist;
chordLength = currentSubdivision.start.distance(currentSubdivision.end);
minSumDist = sumDist;
}
}
var precisionRatio = pow(10, -precision);
// recursively divide investigated subdivision:
// until distance between baselinePoint and closest path endpoint is within 10^(-precision)
// then return the closest endpoint of that final subdivision
while (true) {
// check if we have reached at least one required observed precision
// - calculated as: the difference in distances from point to start and end divided by the distance
// - note that this function is not monotonic = it doesn't converge stably but has "teeth"
// - the function decreases while one of the endpoints is fixed but "jumps" whenever we switch
// - this criterion works well for points lying far away from the curve
var startPrecisionRatio = (distFromStart ? (abs(distFromStart - distFromEnd) / distFromStart) : 0);
var endPrecisionRatio = (distFromEnd ? (abs(distFromStart - distFromEnd) / distFromEnd) : 0);
var hasRequiredPrecision = ((startPrecisionRatio < precisionRatio) || (endPrecisionRatio < precisionRatio));
// check if we have reached at least one required minimal distance
// - calculated as: the subdivision chord length multiplied by precisionRatio
// - calculation is relative so it will work for arbitrarily large/small curves and their subdivisions
// - this is a backup criterion that works well for points lying "almost at" the curve
var hasMinimalStartDistance = (distFromStart ? (distFromStart < (chordLength * precisionRatio)) : true);
var hasMinimalEndDistance = (distFromEnd ? (distFromEnd < (chordLength * precisionRatio)) : true);
var hasMinimalDistance = (hasMinimalStartDistance || hasMinimalEndDistance);
// do we stop now?
if (hasRequiredPrecision || hasMinimalDistance) {
return ((distFromStart <= distFromEnd) ? investigatedSubdivisionStartT : investigatedSubdivisionEndT);
}
// otherwise, set up for next iteration
var divided = investigatedSubdivision.divide(0.5);
subdivisionSize /= 2;
var startDist1 = divided[0].start.distance(p);
var endDist1 = divided[0].end.distance(p);
var sumDist1 = startDist1 + endDist1;
var startDist2 = divided[1].start.distance(p);
var endDist2 = divided[1].end.distance(p);
var sumDist2 = startDist2 + endDist2;
if (sumDist1 <= sumDist2) {
investigatedSubdivision = divided[0];
investigatedSubdivisionEndT -= subdivisionSize; // subdivisionSize was already halved
distFromStart = startDist1;
distFromEnd = endDist1;
} else {
investigatedSubdivision = divided[1];
investigatedSubdivisionStartT += subdivisionSize; // subdivisionSize was already halved
distFromStart = startDist2;
distFromEnd = endDist2;
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q22814
|
train
|
function(p) {
var start = this.start;
var end = this.end;
if (start.cross(p, end) !== 0) return false;
// else: cross product of 0 indicates that this line and the vector to `p` are collinear
var length = this.length();
if ((new g.Line(start, p)).length() > length) return false;
if ((new g.Line(p, end)).length() > length) return false;
// else: `p` lies between start and end of the line
return true;
}
|
javascript
|
{
"resource": ""
}
|
|
q22815
|
train
|
function(ratio) {
var dividerPoint = this.pointAt(ratio);
// return array with two new lines
return [
new Line(this.start, dividerPoint),
new Line(dividerPoint, this.end)
];
}
|
javascript
|
{
"resource": ""
}
|
|
q22816
|
train
|
function(length) {
var dividerPoint = this.pointAtLength(length);
// return array with two new lines
return [
new Line(this.start, dividerPoint),
new Line(dividerPoint, this.end)
];
}
|
javascript
|
{
"resource": ""
}
|
|
q22817
|
train
|
function(ratio, opt) {
var segments = this.segments;
var numSegments = segments.length;
if (numSegments === 0) return null; // if segments is an empty array
if (ratio < 0) ratio = 0;
if (ratio > 1) ratio = 1;
opt = opt || {};
var precision = (opt.precision === undefined) ? this.PRECISION : opt.precision;
var segmentSubdivisions = (opt.segmentSubdivisions === undefined) ? this.getSegmentSubdivisions({ precision: precision }) : opt.segmentSubdivisions;
var localOpt = { precision: precision, segmentSubdivisions: segmentSubdivisions };
var pathLength = this.length(localOpt);
var length = pathLength * ratio;
return this.divideAtLength(length, localOpt);
}
|
javascript
|
{
"resource": ""
}
|
|
q22818
|
train
|
function(index, arg) {
var segments = this.segments;
var numSegments = segments.length;
if (numSegments === 0) throw new Error('Path has no segments.');
if (index < 0) index = numSegments + index; // convert negative indices to positive
if (index >= numSegments || index < 0) throw new Error('Index out of range.');
var currentSegment;
var replacedSegment = segments[index];
var previousSegment = replacedSegment.previousSegment;
var nextSegment = replacedSegment.nextSegment;
var updateSubpathStart = replacedSegment.isSubpathStart; // boolean: is an update of subpath starts necessary?
if (!Array.isArray(arg)) {
if (!arg || !arg.isSegment) throw new Error('Segment required.');
currentSegment = this.prepareSegment(arg, previousSegment, nextSegment);
segments.splice(index, 1, currentSegment); // directly replace
if (updateSubpathStart && currentSegment.isSubpathStart) updateSubpathStart = false; // already updated by `prepareSegment`
} else {
// flatten one level deep
// so we can chain arbitrary Path.createSegment results
arg = arg.reduce(function(acc, val) {
return acc.concat(val);
}, []);
if (!arg[0].isSegment) throw new Error('Segments required.');
segments.splice(index, 1);
var n = arg.length;
for (var i = 0; i < n; i++) {
var currentArg = arg[i];
currentSegment = this.prepareSegment(currentArg, previousSegment, nextSegment);
segments.splice((index + i), 0, currentSegment); // incrementing index to insert subsequent segments after inserted segments
previousSegment = currentSegment;
if (updateSubpathStart && currentSegment.isSubpathStart) updateSubpathStart = false; // already updated by `prepareSegment`
}
}
// if replaced segment used to start a subpath and no new subpath start was added, update all subsequent segments until another subpath start segment is reached
if (updateSubpathStart && nextSegment) this.updateSubpathStartSegment(nextSegment);
}
|
javascript
|
{
"resource": ""
}
|
|
q22819
|
train
|
function(cell, portId) {
console.assert(cell.isVisible());
console.assert(!cell.portProp(portId, 'collapsed'), 'port ' + portId + ' on ' + cell.id + ' should be expanded');
}
|
javascript
|
{
"resource": ""
}
|
|
q22820
|
displayValue
|
train
|
function displayValue(gauge) {
if (gauge.options.animatedValue) {
return gauge.options.value;
}
return gauge.value;
}
|
javascript
|
{
"resource": ""
}
|
q22821
|
drawLinearBar
|
train
|
function drawLinearBar(context, options, x, y, w, h) {
drawLinearBarShape(context, options, '', x, y, w, h);
}
|
javascript
|
{
"resource": ""
}
|
q22822
|
replaceVersionPlaceholders
|
train
|
function replaceVersionPlaceholders(packageDir, projectVersion) {
// Resolve files that contain version placeholders using Grep or Findstr since those are
// extremely fast and also have a very simple usage.
const files = findFilesWithPlaceholders(packageDir);
// Walk through every file that contains version placeholders and replace those with the current
// version of the root package.json file.
files.forEach(filePath => {
const fileContent = readFileSync(filePath, 'utf-8')
.replace(ngVersionPlaceholderRegex, buildConfig.angularVersion)
.replace(materialVersionPlaceholderRegex, buildConfig.materialVersion)
.replace(versionPlaceholderRegex, projectVersion);
writeFileSync(filePath, fileContent);
});
}
|
javascript
|
{
"resource": ""
}
|
q22823
|
findFilesWithPlaceholders
|
train
|
function findFilesWithPlaceholders(packageDir) {
const findCommand = buildPlaceholderFindCommand(packageDir);
return spawnSync(findCommand.binary, findCommand.args).stdout
.toString()
.split(/[\n\r]/)
.filter(String);
}
|
javascript
|
{
"resource": ""
}
|
q22824
|
buildPlaceholderFindCommand
|
train
|
function buildPlaceholderFindCommand(packageDir) {
if (platform() === 'win32') {
return {
binary: 'findstr',
args: ['/msi', `${materialVersionPlaceholderText} ${ngVersionPlaceholderText} ${versionPlaceholderText}`, `${packageDir}\\*`]
};
} else {
return {
binary: 'grep',
args: ['-ril', `${materialVersionPlaceholderText}\\|${ngVersionPlaceholderText}\\|${versionPlaceholderText}`, packageDir]
};
}
}
|
javascript
|
{
"resource": ""
}
|
q22825
|
_cloneNode
|
train
|
function _cloneNode(deep, sourceNode, parentNode) {
const clone = new sourceNode.constructor(sourceNode[symbols.windowSymbol]);
clone.attrs = sourceNode.attrs;
clone.tagName = sourceNode.tagName;
clone.value = sourceNode.value;
// Link the parent.
if (parentNode) { clone.parentNode = parentNode; }
// Copy children.
if (deep) {
clone.childNodes = new NodeList(
sourceNode.childNodes.map(childNode =>
_cloneNode(true, childNode, clone)
)
);
}
return clone;
}
|
javascript
|
{
"resource": ""
}
|
q22826
|
train
|
function () {
var images = {};
var blobs = {};
if ( 'Video' in fbxTree.Objects ) {
var videoNodes = fbxTree.Objects.Video;
for ( var nodeID in videoNodes ) {
var videoNode = videoNodes[ nodeID ];
var id = parseInt( nodeID );
images[ id ] = videoNode.RelativeFilename || videoNode.Filename;
// raw image data is in videoNode.Content
if ( 'Content' in videoNode ) {
var arrayBufferContent = ( videoNode.Content instanceof ArrayBuffer ) && ( videoNode.Content.byteLength > 0 );
var base64Content = ( typeof videoNode.Content === 'string' ) && ( videoNode.Content !== '' );
if ( arrayBufferContent || base64Content ) {
var image = this.parseImage( videoNodes[ nodeID ] );
blobs[ videoNode.RelativeFilename || videoNode.Filename ] = image;
}
}
}
}
for ( var id in images ) {
var filename = images[ id ];
if ( blobs[ filename ] !== undefined ) images[ id ] = blobs[ filename ];
else images[ id ] = images[ id ].split( '\\' ).pop();
}
return images;
}
|
javascript
|
{
"resource": ""
}
|
|
q22827
|
train
|
function ( videoNode ) {
var content = videoNode.Content;
var fileName = videoNode.RelativeFilename || videoNode.Filename;
var extension = fileName.slice( fileName.lastIndexOf( '.' ) + 1 ).toLowerCase();
var type;
switch ( extension ) {
case 'bmp':
type = 'image/bmp';
break;
case 'jpg':
case 'jpeg':
type = 'image/jpeg';
break;
case 'png':
type = 'image/png';
break;
case 'tif':
type = 'image/tiff';
break;
case 'tga':
if ( typeof THREE.TGALoader !== 'function' ) {
console.warn( 'FBXLoader: THREE.TGALoader is required to load TGA textures' );
return;
} else {
if ( THREE.Loader.Handlers.get( '.tga' ) === null ) {
THREE.Loader.Handlers.add( /\.tga$/i, new THREE.TGALoader() );
}
type = 'image/tga';
break;
}
default:
console.warn( 'FBXLoader: Image type "' + extension + '" is not supported.' );
return;
}
if ( typeof content === 'string' ) { // ASCII format
return 'data:' + type + ';base64,' + content;
} else { // Binary Format
var array = new Uint8Array( content );
return window.URL.createObjectURL( new Blob( [ array ], { type: type } ) );
}
}
|
javascript
|
{
"resource": ""
}
|
|
q22828
|
train
|
function ( images ) {
var textureMap = new Map();
if ( 'Texture' in fbxTree.Objects ) {
var textureNodes = fbxTree.Objects.Texture;
for ( var nodeID in textureNodes ) {
var texture = this.parseTexture( textureNodes[ nodeID ], images );
textureMap.set( parseInt( nodeID ), texture );
}
}
return textureMap;
}
|
javascript
|
{
"resource": ""
}
|
|
q22829
|
train
|
function ( textureNode, images ) {
var texture = this.loadTexture( textureNode, images );
texture.ID = textureNode.id;
texture.name = textureNode.attrName;
var wrapModeU = textureNode.WrapModeU;
var wrapModeV = textureNode.WrapModeV;
var valueU = wrapModeU !== undefined ? wrapModeU.value : 0;
var valueV = wrapModeV !== undefined ? wrapModeV.value : 0;
// http://download.autodesk.com/us/fbx/SDKdocs/FBX_SDK_Help/files/fbxsdkref/class_k_fbx_texture.html#889640e63e2e681259ea81061b85143a
// 0: repeat(default), 1: clamp
texture.wrapS = valueU === 0 ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
texture.wrapT = valueV === 0 ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
if ( 'Scaling' in textureNode ) {
var values = textureNode.Scaling.value;
texture.repeat.x = values[ 0 ];
texture.repeat.y = values[ 1 ];
}
return texture;
}
|
javascript
|
{
"resource": ""
}
|
|
q22830
|
train
|
function ( textureNode, images ) {
var fileName;
var currentPath = this.textureLoader.path;
var children = connections.get( textureNode.id ).children;
if ( children !== undefined && children.length > 0 && images[ children[ 0 ].ID ] !== undefined ) {
fileName = images[ children[ 0 ].ID ];
if ( fileName.indexOf( 'blob:' ) === 0 || fileName.indexOf( 'data:' ) === 0 ) {
this.textureLoader.setPath( undefined );
}
}
var texture;
var extension = textureNode.FileName.slice( - 3 ).toLowerCase();
if ( extension === 'tga' ) {
var loader = THREE.Loader.Handlers.get( '.tga' );
if ( loader === null ) {
console.warn( 'FBXLoader: TGALoader not found, creating empty placeholder texture for', fileName );
texture = new THREE.Texture();
} else {
texture = loader.load( fileName );
}
} else if ( extension === 'psd' ) {
console.warn( 'FBXLoader: PSD textures are not supported, creating empty placeholder texture for', fileName );
texture = new THREE.Texture();
} else {
texture = this.textureLoader.load( fileName );
}
this.textureLoader.setPath( currentPath );
return texture;
}
|
javascript
|
{
"resource": ""
}
|
|
q22831
|
train
|
function ( textureMap ) {
var materialMap = new Map();
if ( 'Material' in fbxTree.Objects ) {
var materialNodes = fbxTree.Objects.Material;
for ( var nodeID in materialNodes ) {
var material = this.parseMaterial( materialNodes[ nodeID ], textureMap );
if ( material !== null ) materialMap.set( parseInt( nodeID ), material );
}
}
return materialMap;
}
|
javascript
|
{
"resource": ""
}
|
|
q22832
|
train
|
function ( materialNode, textureMap ) {
var ID = materialNode.id;
var name = materialNode.attrName;
var type = materialNode.ShadingModel;
// Case where FBX wraps shading model in property object.
if ( typeof type === 'object' ) {
type = type.value;
}
// Ignore unused materials which don't have any connections.
if ( ! connections.has( ID ) ) return null;
var parameters = this.parseParameters( materialNode, textureMap, ID );
var material;
switch ( type.toLowerCase() ) {
case 'phong':
material = new THREE.MeshPhongMaterial();
break;
case 'lambert':
material = new THREE.MeshLambertMaterial();
break;
default:
console.warn( 'THREE.FBXLoader: unknown material type "%s". Defaulting to MeshPhongMaterial.', type );
material = new THREE.MeshPhongMaterial( { color: 0x3300ff } );
break;
}
material.setValues( parameters );
material.name = name;
return material;
}
|
javascript
|
{
"resource": ""
}
|
|
q22833
|
train
|
function ( textureMap, id ) {
// if the texture is a layered texture, just use the first layer and issue a warning
if ( 'LayeredTexture' in fbxTree.Objects && id in fbxTree.Objects.LayeredTexture ) {
console.warn( 'THREE.FBXLoader: layered textures are not supported in three.js. Discarding all but first layer.' );
id = connections.get( id ).children[ 0 ].ID;
}
return textureMap.get( id );
}
|
javascript
|
{
"resource": ""
}
|
|
q22834
|
train
|
function () {
var skeletons = {};
var morphTargets = {};
if ( 'Deformer' in fbxTree.Objects ) {
var DeformerNodes = fbxTree.Objects.Deformer;
for ( var nodeID in DeformerNodes ) {
var deformerNode = DeformerNodes[ nodeID ];
var relationships = connections.get( parseInt( nodeID ) );
if ( deformerNode.attrType === 'Skin' ) {
var skeleton = this.parseSkeleton( relationships, DeformerNodes );
skeleton.ID = nodeID;
if ( relationships.parents.length > 1 ) console.warn( 'THREE.FBXLoader: skeleton attached to more than one geometry is not supported.' );
skeleton.geometryID = relationships.parents[ 0 ].ID;
skeletons[ nodeID ] = skeleton;
} else if ( deformerNode.attrType === 'BlendShape' ) {
var morphTarget = {
id: nodeID,
};
morphTarget.rawTargets = this.parseMorphTargets( relationships, DeformerNodes );
morphTarget.id = nodeID;
if ( relationships.parents.length > 1 ) console.warn( 'THREE.FBXLoader: morph target attached to more than one geometry is not supported.' );
morphTargets[ nodeID ] = morphTarget;
}
}
}
return {
skeletons: skeletons,
morphTargets: morphTargets,
};
}
|
javascript
|
{
"resource": ""
}
|
|
q22835
|
train
|
function ( relationships, deformerNodes ) {
var rawBones = [];
relationships.children.forEach( function ( child ) {
var boneNode = deformerNodes[ child.ID ];
if ( boneNode.attrType !== 'Cluster' ) return;
var rawBone = {
ID: child.ID,
indices: [],
weights: [],
transform: new THREE.Matrix4().fromArray( boneNode.Transform.a ),
transformLink: new THREE.Matrix4().fromArray( boneNode.TransformLink.a ),
linkMode: boneNode.Mode,
};
if ( 'Indexes' in boneNode ) {
rawBone.indices = boneNode.Indexes.a;
rawBone.weights = boneNode.Weights.a;
}
rawBones.push( rawBone );
} );
return {
rawBones: rawBones,
bones: []
};
}
|
javascript
|
{
"resource": ""
}
|
|
q22836
|
train
|
function ( relationships, deformerNodes ) {
var rawMorphTargets = [];
for ( var i = 0; i < relationships.children.length; i ++ ) {
if ( i === 8 ) {
console.warn( 'FBXLoader: maximum of 8 morph targets supported. Ignoring additional targets.' );
break;
}
var child = relationships.children[ i ];
var morphTargetNode = deformerNodes[ child.ID ];
var rawMorphTarget = {
name: morphTargetNode.attrName,
initialWeight: morphTargetNode.DeformPercent,
id: morphTargetNode.id,
fullWeights: morphTargetNode.FullWeights.a
};
if ( morphTargetNode.attrType !== 'BlendShapeChannel' ) return;
var targetRelationships = connections.get( parseInt( child.ID ) );
targetRelationships.children.forEach( function ( child ) {
if ( child.relationship === undefined ) rawMorphTarget.geoID = child.ID;
} );
rawMorphTargets.push( rawMorphTarget );
}
return rawMorphTargets;
}
|
javascript
|
{
"resource": ""
}
|
|
q22837
|
train
|
function ( skeletons, geometryMap, materialMap ) {
var modelMap = new Map();
var modelNodes = fbxTree.Objects.Model;
for ( var nodeID in modelNodes ) {
var id = parseInt( nodeID );
var node = modelNodes[ nodeID ];
var relationships = connections.get( id );
var model = this.buildSkeleton( relationships, skeletons, id, node.attrName );
if ( ! model ) {
switch ( node.attrType ) {
case 'Camera':
model = this.createCamera( relationships );
break;
case 'Light':
model = this.createLight( relationships );
break;
case 'Mesh':
model = this.createMesh( relationships, geometryMap, materialMap );
break;
case 'NurbsCurve':
model = this.createCurve( relationships, geometryMap );
break;
case 'LimbNode': // usually associated with a Bone, however if a Bone was not created we'll make a Group instead
case 'Null':
default:
model = new THREE.Group();
break;
}
model.name = THREE.PropertyBinding.sanitizeNodeName( node.attrName );
model.ID = id;
}
this.setModelTransforms( model, node );
modelMap.set( id, model );
}
return modelMap;
}
|
javascript
|
{
"resource": ""
}
|
|
q22838
|
train
|
function ( relationships ) {
var model;
var cameraAttribute;
relationships.children.forEach( function ( child ) {
var attr = fbxTree.Objects.NodeAttribute[ child.ID ];
if ( attr !== undefined ) {
cameraAttribute = attr;
}
} );
if ( cameraAttribute === undefined ) {
model = new THREE.Object3D();
} else {
var type = 0;
if ( cameraAttribute.CameraProjectionType !== undefined && cameraAttribute.CameraProjectionType.value === 1 ) {
type = 1;
}
var nearClippingPlane = 1;
if ( cameraAttribute.NearPlane !== undefined ) {
nearClippingPlane = cameraAttribute.NearPlane.value / 1000;
}
var farClippingPlane = 1000;
if ( cameraAttribute.FarPlane !== undefined ) {
farClippingPlane = cameraAttribute.FarPlane.value / 1000;
}
var width = window.innerWidth;
var height = window.innerHeight;
if ( cameraAttribute.AspectWidth !== undefined && cameraAttribute.AspectHeight !== undefined ) {
width = cameraAttribute.AspectWidth.value;
height = cameraAttribute.AspectHeight.value;
}
var aspect = width / height;
var fov = 45;
if ( cameraAttribute.FieldOfView !== undefined ) {
fov = cameraAttribute.FieldOfView.value;
}
var focalLength = cameraAttribute.FocalLength ? cameraAttribute.FocalLength.value : null;
switch ( type ) {
case 0: // Perspective
model = new THREE.PerspectiveCamera( fov, aspect, nearClippingPlane, farClippingPlane );
if ( focalLength !== null ) model.setFocalLength( focalLength );
break;
case 1: // Orthographic
model = new THREE.OrthographicCamera( - width / 2, width / 2, height / 2, - height / 2, nearClippingPlane, farClippingPlane );
break;
default:
console.warn( 'THREE.FBXLoader: Unknown camera type ' + type + '.' );
model = new THREE.Object3D();
break;
}
}
return model;
}
|
javascript
|
{
"resource": ""
}
|
|
q22839
|
train
|
function ( relationships ) {
var model;
var lightAttribute;
relationships.children.forEach( function ( child ) {
var attr = fbxTree.Objects.NodeAttribute[ child.ID ];
if ( attr !== undefined ) {
lightAttribute = attr;
}
} );
if ( lightAttribute === undefined ) {
model = new THREE.Object3D();
} else {
var type;
// LightType can be undefined for Point lights
if ( lightAttribute.LightType === undefined ) {
type = 0;
} else {
type = lightAttribute.LightType.value;
}
var color = 0xffffff;
if ( lightAttribute.Color !== undefined ) {
color = new THREE.Color().fromArray( lightAttribute.Color.value );
}
var intensity = ( lightAttribute.Intensity === undefined ) ? 1 : lightAttribute.Intensity.value / 100;
// light disabled
if ( lightAttribute.CastLightOnObject !== undefined && lightAttribute.CastLightOnObject.value === 0 ) {
intensity = 0;
}
var distance = 0;
if ( lightAttribute.FarAttenuationEnd !== undefined ) {
if ( lightAttribute.EnableFarAttenuation !== undefined && lightAttribute.EnableFarAttenuation.value === 0 ) {
distance = 0;
} else {
distance = lightAttribute.FarAttenuationEnd.value;
}
}
// TODO: could this be calculated linearly from FarAttenuationStart to FarAttenuationEnd?
var decay = 1;
switch ( type ) {
case 0: // Point
model = new THREE.PointLight( color, intensity, distance, decay );
break;
case 1: // Directional
model = new THREE.DirectionalLight( color, intensity );
break;
case 2: // Spot
var angle = Math.PI / 3;
if ( lightAttribute.InnerAngle !== undefined ) {
angle = THREE.Math.degToRad( lightAttribute.InnerAngle.value );
}
var penumbra = 0;
if ( lightAttribute.OuterAngle !== undefined ) {
// TODO: this is not correct - FBX calculates outer and inner angle in degrees
// with OuterAngle > InnerAngle && OuterAngle <= Math.PI
// while three.js uses a penumbra between (0, 1) to attenuate the inner angle
penumbra = THREE.Math.degToRad( lightAttribute.OuterAngle.value );
penumbra = Math.max( penumbra, 1 );
}
model = new THREE.SpotLight( color, intensity, distance, angle, penumbra, decay );
break;
default:
console.warn( 'THREE.FBXLoader: Unknown light type ' + lightAttribute.LightType.value + ', defaulting to a THREE.PointLight.' );
model = new THREE.PointLight( color, intensity );
break;
}
if ( lightAttribute.CastShadows !== undefined && lightAttribute.CastShadows.value === 1 ) {
model.castShadow = true;
}
}
return model;
}
|
javascript
|
{
"resource": ""
}
|
|
q22840
|
train
|
function ( deformers ) {
var geometryMap = new Map();
if ( 'Geometry' in fbxTree.Objects ) {
var geoNodes = fbxTree.Objects.Geometry;
for ( var nodeID in geoNodes ) {
var relationships = connections.get( parseInt( nodeID ) );
var geo = this.parseGeometry( relationships, geoNodes[ nodeID ], deformers );
geometryMap.set( parseInt( nodeID ), geo );
}
}
return geometryMap;
}
|
javascript
|
{
"resource": ""
}
|
|
q22841
|
train
|
function ( relationships, geoNode, deformers ) {
switch ( geoNode.attrType ) {
case 'Mesh':
return this.parseMeshGeometry( relationships, geoNode, deformers );
break;
case 'NurbsCurve':
return this.parseNurbsGeometry( geoNode );
break;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q22842
|
train
|
function ( relationships, geoNode, deformers ) {
var skeletons = deformers.skeletons;
var morphTargets = deformers.morphTargets;
var modelNodes = relationships.parents.map( function ( parent ) {
return fbxTree.Objects.Model[ parent.ID ];
} );
// don't create geometry if it is not associated with any models
if ( modelNodes.length === 0 ) return;
var skeleton = relationships.children.reduce( function ( skeleton, child ) {
if ( skeletons[ child.ID ] !== undefined ) skeleton = skeletons[ child.ID ];
return skeleton;
}, null );
var morphTarget = relationships.children.reduce( function ( morphTarget, child ) {
if ( morphTargets[ child.ID ] !== undefined ) morphTarget = morphTargets[ child.ID ];
return morphTarget;
}, null );
// TODO: if there is more than one model associated with the geometry, AND the models have
// different geometric transforms, then this will cause problems
// if ( modelNodes.length > 1 ) { }
// For now just assume one model and get the preRotations from that
var modelNode = modelNodes[ 0 ];
var transformData = {};
if ( 'RotationOrder' in modelNode ) transformData.eulerOrder = modelNode.RotationOrder.value;
if ( 'GeometricTranslation' in modelNode ) transformData.translation = modelNode.GeometricTranslation.value;
if ( 'GeometricRotation' in modelNode ) transformData.rotation = modelNode.GeometricRotation.value;
if ( 'GeometricScaling' in modelNode ) transformData.scale = modelNode.GeometricScaling.value;
var transform = generateTransform( transformData );
return this.genGeometry( geoNode, skeleton, morphTarget, transform );
}
|
javascript
|
{
"resource": ""
}
|
|
q22843
|
train
|
function ( geoNode, skeleton, morphTarget, preTransform ) {
var geo = new THREE.BufferGeometry();
if ( geoNode.attrName ) geo.name = geoNode.attrName;
var geoInfo = this.parseGeoNode( geoNode, skeleton );
var buffers = this.genBuffers( geoInfo );
var positionAttribute = new THREE.Float32BufferAttribute( buffers.vertex, 3 );
preTransform.applyToBufferAttribute( positionAttribute );
geo.addAttribute( 'position', positionAttribute );
if ( buffers.colors.length > 0 ) {
geo.addAttribute( 'color', new THREE.Float32BufferAttribute( buffers.colors, 3 ) );
}
if ( skeleton ) {
geo.addAttribute( 'skinIndex', new THREE.Uint16BufferAttribute( buffers.weightsIndices, 4 ) );
geo.addAttribute( 'skinWeight', new THREE.Float32BufferAttribute( buffers.vertexWeights, 4 ) );
// used later to bind the skeleton to the model
geo.FBX_Deformer = skeleton;
}
if ( buffers.normal.length > 0 ) {
var normalAttribute = new THREE.Float32BufferAttribute( buffers.normal, 3 );
var normalMatrix = new THREE.Matrix3().getNormalMatrix( preTransform );
normalMatrix.applyToBufferAttribute( normalAttribute );
geo.addAttribute( 'normal', normalAttribute );
}
buffers.uvs.forEach( function ( uvBuffer, i ) {
// subsequent uv buffers are called 'uv1', 'uv2', ...
var name = 'uv' + ( i + 1 ).toString();
// the first uv buffer is just called 'uv'
if ( i === 0 ) {
name = 'uv';
}
geo.addAttribute( name, new THREE.Float32BufferAttribute( buffers.uvs[ i ], 2 ) );
} );
if ( geoInfo.material && geoInfo.material.mappingType !== 'AllSame' ) {
// Convert the material indices of each vertex into rendering groups on the geometry.
var prevMaterialIndex = buffers.materialIndex[ 0 ];
var startIndex = 0;
buffers.materialIndex.forEach( function ( currentIndex, i ) {
if ( currentIndex !== prevMaterialIndex ) {
geo.addGroup( startIndex, i - startIndex, prevMaterialIndex );
prevMaterialIndex = currentIndex;
startIndex = i;
}
} );
// the loop above doesn't add the last group, do that here.
if ( geo.groups.length > 0 ) {
var lastGroup = geo.groups[ geo.groups.length - 1 ];
var lastIndex = lastGroup.start + lastGroup.count;
if ( lastIndex !== buffers.materialIndex.length ) {
geo.addGroup( lastIndex, buffers.materialIndex.length - lastIndex, prevMaterialIndex );
}
}
// case where there are multiple materials but the whole geometry is only
// using one of them
if ( geo.groups.length === 0 ) {
geo.addGroup( 0, buffers.materialIndex.length, buffers.materialIndex[ 0 ] );
}
}
this.addMorphTargets( geo, geoNode, morphTarget, preTransform );
return geo;
}
|
javascript
|
{
"resource": ""
}
|
|
q22844
|
train
|
function ( parentGeo, parentGeoNode, morphGeoNode, preTransform ) {
var morphGeo = new THREE.BufferGeometry();
if ( morphGeoNode.attrName ) morphGeo.name = morphGeoNode.attrName;
var vertexIndices = ( parentGeoNode.PolygonVertexIndex !== undefined ) ? parentGeoNode.PolygonVertexIndex.a : [];
// make a copy of the parent's vertex positions
var vertexPositions = ( parentGeoNode.Vertices !== undefined ) ? parentGeoNode.Vertices.a.slice() : [];
var morphPositions = ( morphGeoNode.Vertices !== undefined ) ? morphGeoNode.Vertices.a : [];
var indices = ( morphGeoNode.Indexes !== undefined ) ? morphGeoNode.Indexes.a : [];
for ( var i = 0; i < indices.length; i ++ ) {
var morphIndex = indices[ i ] * 3;
// FBX format uses blend shapes rather than morph targets. This can be converted
// by additively combining the blend shape positions with the original geometry's positions
vertexPositions[ morphIndex ] += morphPositions[ i * 3 ];
vertexPositions[ morphIndex + 1 ] += morphPositions[ i * 3 + 1 ];
vertexPositions[ morphIndex + 2 ] += morphPositions[ i * 3 + 2 ];
}
// TODO: add morph normal support
var morphGeoInfo = {
vertexIndices: vertexIndices,
vertexPositions: vertexPositions,
};
var morphBuffers = this.genBuffers( morphGeoInfo );
var positionAttribute = new THREE.Float32BufferAttribute( morphBuffers.vertex, 3 );
positionAttribute.name = morphGeoNode.attrName;
preTransform.applyToBufferAttribute( positionAttribute );
parentGeo.morphAttributes.position.push( positionAttribute );
}
|
javascript
|
{
"resource": ""
}
|
|
q22845
|
train
|
function ( NormalNode ) {
var mappingType = NormalNode.MappingInformationType;
var referenceType = NormalNode.ReferenceInformationType;
var buffer = NormalNode.Normals.a;
var indexBuffer = [];
if ( referenceType === 'IndexToDirect' ) {
if ( 'NormalIndex' in NormalNode ) {
indexBuffer = NormalNode.NormalIndex.a;
} else if ( 'NormalsIndex' in NormalNode ) {
indexBuffer = NormalNode.NormalsIndex.a;
}
}
return {
dataSize: 3,
buffer: buffer,
indices: indexBuffer,
mappingType: mappingType,
referenceType: referenceType
};
}
|
javascript
|
{
"resource": ""
}
|
|
q22846
|
train
|
function ( UVNode ) {
var mappingType = UVNode.MappingInformationType;
var referenceType = UVNode.ReferenceInformationType;
var buffer = UVNode.UV.a;
var indexBuffer = [];
if ( referenceType === 'IndexToDirect' ) {
indexBuffer = UVNode.UVIndex.a;
}
return {
dataSize: 2,
buffer: buffer,
indices: indexBuffer,
mappingType: mappingType,
referenceType: referenceType
};
}
|
javascript
|
{
"resource": ""
}
|
|
q22847
|
train
|
function ( ColorNode ) {
var mappingType = ColorNode.MappingInformationType;
var referenceType = ColorNode.ReferenceInformationType;
var buffer = ColorNode.Colors.a;
var indexBuffer = [];
if ( referenceType === 'IndexToDirect' ) {
indexBuffer = ColorNode.ColorIndex.a;
}
return {
dataSize: 4,
buffer: buffer,
indices: indexBuffer,
mappingType: mappingType,
referenceType: referenceType
};
}
|
javascript
|
{
"resource": ""
}
|
|
q22848
|
train
|
function ( MaterialNode ) {
var mappingType = MaterialNode.MappingInformationType;
var referenceType = MaterialNode.ReferenceInformationType;
if ( mappingType === 'NoMappingInformation' ) {
return {
dataSize: 1,
buffer: [ 0 ],
indices: [ 0 ],
mappingType: 'AllSame',
referenceType: referenceType
};
}
var materialIndexBuffer = MaterialNode.Materials.a;
// Since materials are stored as indices, there's a bit of a mismatch between FBX and what
// we expect.So we create an intermediate buffer that points to the index in the buffer,
// for conforming with the other functions we've written for other data.
var materialIndices = [];
for ( var i = 0; i < materialIndexBuffer.length; ++ i ) {
materialIndices.push( i );
}
return {
dataSize: 1,
buffer: materialIndexBuffer,
indices: materialIndices,
mappingType: mappingType,
referenceType: referenceType
};
}
|
javascript
|
{
"resource": ""
}
|
|
q22849
|
train
|
function ( geoNode ) {
if ( THREE.NURBSCurve === undefined ) {
console.error( 'THREE.FBXLoader: The loader relies on THREE.NURBSCurve for any nurbs present in the model. Nurbs will show up as empty geometry.' );
return new THREE.BufferGeometry();
}
var order = parseInt( geoNode.Order );
if ( isNaN( order ) ) {
console.error( 'THREE.FBXLoader: Invalid Order %s given for geometry ID: %s', geoNode.Order, geoNode.id );
return new THREE.BufferGeometry();
}
var degree = order - 1;
var knots = geoNode.KnotVector.a;
var controlPoints = [];
var pointsValues = geoNode.Points.a;
for ( var i = 0, l = pointsValues.length; i < l; i += 4 ) {
controlPoints.push( new THREE.Vector4().fromArray( pointsValues, i ) );
}
var startKnot, endKnot;
if ( geoNode.Form === 'Closed' ) {
controlPoints.push( controlPoints[ 0 ] );
} else if ( geoNode.Form === 'Periodic' ) {
startKnot = degree;
endKnot = knots.length - 1 - startKnot;
for ( var i = 0; i < degree; ++ i ) {
controlPoints.push( controlPoints[ i ] );
}
}
var curve = new THREE.NURBSCurve( degree, knots, controlPoints, startKnot, endKnot );
var vertices = curve.getPoints( controlPoints.length * 7 );
var positions = new Float32Array( vertices.length * 3 );
vertices.forEach( function ( vertex, i ) {
vertex.toArray( positions, i * 3 );
} );
var geometry = new THREE.BufferGeometry();
geometry.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) );
return geometry;
}
|
javascript
|
{
"resource": ""
}
|
|
q22850
|
train
|
function () {
var animationClips = [];
var rawClips = this.parseClips();
if ( rawClips === undefined ) return;
for ( var key in rawClips ) {
var rawClip = rawClips[ key ];
var clip = this.addClip( rawClip );
animationClips.push( clip );
}
return animationClips;
}
|
javascript
|
{
"resource": ""
}
|
|
q22851
|
train
|
function ( layersMap ) {
var rawStacks = fbxTree.Objects.AnimationStack;
// connect the stacks (clips) up to the layers
var rawClips = {};
for ( var nodeID in rawStacks ) {
var children = connections.get( parseInt( nodeID ) ).children;
if ( children.length > 1 ) {
// it seems like stacks will always be associated with a single layer. But just in case there are files
// where there are multiple layers per stack, we'll display a warning
console.warn( 'THREE.FBXLoader: Encountered an animation stack with multiple layers, this is currently not supported. Ignoring subsequent layers.' );
}
var layer = layersMap.get( children[ 0 ].ID );
rawClips[ nodeID ] = {
name: rawStacks[ nodeID ].attrName,
layer: layer,
};
}
return rawClips;
}
|
javascript
|
{
"resource": ""
}
|
|
q22852
|
train
|
function ( curves ) {
var times = [];
// first join together the times for each axis, if defined
if ( curves.x !== undefined ) times = times.concat( curves.x.times );
if ( curves.y !== undefined ) times = times.concat( curves.y.times );
if ( curves.z !== undefined ) times = times.concat( curves.z.times );
// then sort them and remove duplicates
times = times.sort( function ( a, b ) {
return a - b;
} ).filter( function ( elem, index, array ) {
return array.indexOf( elem ) == index;
} );
return times;
}
|
javascript
|
{
"resource": ""
}
|
|
q22853
|
train
|
function ( curve ) {
for ( var i = 1; i < curve.values.length; i ++ ) {
var initialValue = curve.values[ i - 1 ];
var valuesSpan = curve.values[ i ] - initialValue;
var absoluteSpan = Math.abs( valuesSpan );
if ( absoluteSpan >= 180 ) {
var numSubIntervals = absoluteSpan / 180;
var step = valuesSpan / numSubIntervals;
var nextValue = initialValue + step;
var initialTime = curve.times[ i - 1 ];
var timeSpan = curve.times[ i ] - initialTime;
var interval = timeSpan / numSubIntervals;
var nextTime = initialTime + interval;
var interpolatedTimes = [];
var interpolatedValues = [];
while ( nextTime < curve.times[ i ] ) {
interpolatedTimes.push( nextTime );
nextTime += interval;
interpolatedValues.push( nextValue );
nextValue += step;
}
curve.times = inject( curve.times, i, interpolatedTimes );
curve.values = inject( curve.values, i, interpolatedValues );
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q22854
|
train
|
function ( reader ) {
// footer size: 160bytes + 16-byte alignment padding
// - 16bytes: magic
// - padding til 16-byte alignment (at least 1byte?)
// (seems like some exporters embed fixed 15 or 16bytes?)
// - 4bytes: magic
// - 4bytes: version
// - 120bytes: zero
// - 16bytes: magic
if ( reader.size() % 16 === 0 ) {
return ( ( reader.getOffset() + 160 + 16 ) & ~ 0xf ) >= reader.size();
} else {
return reader.getOffset() + 160 + 16 >= reader.size();
}
}
|
javascript
|
{
"resource": ""
}
|
|
q22855
|
train
|
function ( reader, version ) {
var node = {};
// The first three data sizes depends on version.
var endOffset = ( version >= 7500 ) ? reader.getUint64() : reader.getUint32();
var numProperties = ( version >= 7500 ) ? reader.getUint64() : reader.getUint32();
// note: do not remove this even if you get a linter warning as it moves the buffer forward
var propertyListLen = ( version >= 7500 ) ? reader.getUint64() : reader.getUint32();
var nameLen = reader.getUint8();
var name = reader.getString( nameLen );
// Regards this node as NULL-record if endOffset is zero
if ( endOffset === 0 ) return null;
var propertyList = [];
for ( var i = 0; i < numProperties; i ++ ) {
propertyList.push( this.parseProperty( reader ) );
}
// Regards the first three elements in propertyList as id, attrName, and attrType
var id = propertyList.length > 0 ? propertyList[ 0 ] : '';
var attrName = propertyList.length > 1 ? propertyList[ 1 ] : '';
var attrType = propertyList.length > 2 ? propertyList[ 2 ] : '';
// check if this node represents just a single property
// like (name, 0) set or (name2, [0, 1, 2]) set of {name: 0, name2: [0, 1, 2]}
node.singleProperty = ( numProperties === 1 && reader.getOffset() === endOffset ) ? true : false;
while ( endOffset > reader.getOffset() ) {
var subNode = this.parseNode( reader, version );
if ( subNode !== null ) this.parseSubNode( name, node, subNode );
}
node.propertyList = propertyList; // raw property list used by parent
if ( typeof id === 'number' ) node.id = id;
if ( attrName !== '' ) node.attrName = attrName;
if ( attrType !== '' ) node.attrType = attrType;
if ( name !== '' ) node.name = name;
return node;
}
|
javascript
|
{
"resource": ""
}
|
|
q22856
|
getData
|
train
|
function getData( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) {
var index;
switch ( infoObject.mappingType ) {
case 'ByPolygonVertex' :
index = polygonVertexIndex;
break;
case 'ByPolygon' :
index = polygonIndex;
break;
case 'ByVertice' :
index = vertexIndex;
break;
case 'AllSame' :
index = infoObject.indices[ 0 ];
break;
default :
console.warn( 'THREE.FBXLoader: unknown attribute mapping type ' + infoObject.mappingType );
}
if ( infoObject.referenceType === 'IndexToDirect' ) index = infoObject.indices[ index ];
var from = index * infoObject.dataSize;
var to = from + infoObject.dataSize;
return slice( dataArray, infoObject.buffer, from, to );
}
|
javascript
|
{
"resource": ""
}
|
q22857
|
parseNumberArray
|
train
|
function parseNumberArray( value ) {
var array = value.split( ',' ).map( function ( val ) {
return parseFloat( val );
} );
return array;
}
|
javascript
|
{
"resource": ""
}
|
q22858
|
inject
|
train
|
function inject( a1, index, a2 ) {
return a1.slice( 0, index ).concat( a2 ).concat( a1.slice( index ) );
}
|
javascript
|
{
"resource": ""
}
|
q22859
|
expandXBounds
|
train
|
function expandXBounds(bounds, value) {
if (bounds[MIN_X] > value) bounds[MIN_X] = value;else if (bounds[MAX_X] < value) bounds[MAX_X] = value;
}
|
javascript
|
{
"resource": ""
}
|
q22860
|
expandYBounds
|
train
|
function expandYBounds(bounds, value) {
if (bounds[MIN_Y] > value) bounds[MIN_Y] = value;else if (bounds[MAX_Y] < value) bounds[MAX_Y] = value;
}
|
javascript
|
{
"resource": ""
}
|
q22861
|
calculateBezier
|
train
|
function calculateBezier(t, p0, p1, p2, p3) {
var mt = 1 - t;
return mt * mt * mt * p0 + 3 * mt * mt * t * p1 + 3 * mt * t * t * p2 + t * t * t * p3;
}
|
javascript
|
{
"resource": ""
}
|
q22862
|
train
|
function (str) {
var output = [];
var idx = 0;
var c, num;
var nextNumber = function () {
var chars = [];
while (/[^-\d\.]/.test(str.charAt(idx))) {
// skip the non-digit characters
idx++;
}
if ('-' === str.charAt(idx)) {
chars.push('-');
idx++;
}
while ((c = str.charAt(idx)) && /[\d\.Ee]/.test(c)) {
chars.push(c);
idx++;
}
return parseFloat(chars.join(''));
};
while (!isNaN(num = nextNumber())) output.push(num);
return output;
}
|
javascript
|
{
"resource": ""
}
|
|
q22863
|
train
|
function (res, path) {
let defaultSrc = "default-src 'self';";
let styleSrc = "style-src 'self' fonts.googleapis.com;";
let fontSrc = "font-src 'self' fonts.gstatic.com;";
let imgSrc = "img-src 'self' www.gravatar.com;";
res.setHeader('Content-Security-Policy', `${defaultSrc} ${styleSrc} ${fontSrc} ${imgSrc}`);
}
|
javascript
|
{
"resource": ""
}
|
|
q22864
|
prompt
|
train
|
async function prompt(questions=[], { onSubmit=noop, onCancel=noop }={}) {
const answers = {};
const override = prompt._override || {};
questions = [].concat(questions);
let answer, question, quit, name, type;
const getFormattedAnswer = async (question, answer, skipValidation = false) => {
if (!skipValidation && question.validate && question.validate(answer) !== true) {
return;
}
return question.format ? await question.format(answer, answers) : answer
};
for (question of questions) {
({ name, type } = question);
// if property is a function, invoke it unless it's a special function
for (let key in question) {
if (passOn.includes(key)) continue;
let value = question[key];
question[key] = typeof value === 'function' ? await value(answer, { ...answers }, question) : value;
}
if (typeof question.message !== 'string') {
throw new Error('prompt message is required');
}
// update vars in case they changed
({ name, type } = question);
// skip if type is a falsy value
if (!type) continue;
if (prompts[type] === void 0) {
throw new Error(`prompt type (${type}) is not defined`);
}
if (override[question.name] !== undefined) {
answer = await getFormattedAnswer(question, override[question.name]);
if (answer !== undefined) {
answers[name] = answer;
continue;
}
}
try {
// Get the injected answer if there is one or prompt the user
answer = prompt._injected ? getInjectedAnswer(prompt._injected) : await prompts[type](question);
answers[name] = answer = await getFormattedAnswer(question, answer, true);
quit = await onSubmit(question, answer, answers);
} catch (err) {
quit = !(await onCancel(question, answers));
}
if (quit) return answers;
}
return answers;
}
|
javascript
|
{
"resource": ""
}
|
q22865
|
destroyTextures
|
train
|
function destroyTextures () {
for (var i = 0; i < numTexUnits; ++i) {
gl.activeTexture(GL_TEXTURE0 + i)
gl.bindTexture(GL_TEXTURE_2D, null)
textureUnits[i] = null
}
values(textureSet).forEach(destroy)
stats.cubeCount = 0
stats.textureCount = 0
}
|
javascript
|
{
"resource": ""
}
|
q22866
|
createDrawCall
|
train
|
function createDrawCall (props) {
return regl({
attributes: {
position: props.position
},
uniforms: {
color: props.color,
scale: props.scale,
offset: props.offset,
phase: props.phase,
freq: props.freq
},
lineWidth: lineWidth,
count: props.position.length,
primitive: props.primitive
})
}
|
javascript
|
{
"resource": ""
}
|
q22867
|
centerMesh
|
train
|
function centerMesh (mesh) {
var bb = boundingBox(mesh.positions)
var _translate = [
-0.5 * (bb[0][0] + bb[1][0]),
-0.5 * (bb[0][1] + bb[1][1]),
-0.5 * (bb[0][2] + bb[1][2])
]
var translate = mat4.create()
mat4.translate(translate, translate, _translate)
mesh.positions = tform(mesh.positions, translate)
}
|
javascript
|
{
"resource": ""
}
|
q22868
|
Constraint
|
train
|
function Constraint (i0, i1) {
this.i0 = i0
this.i1 = i1
this.restLength = vec3.distance(position[i0], position[i1])
}
|
javascript
|
{
"resource": ""
}
|
q22869
|
step
|
train
|
function step ({tick}) {
setFBO({ framebuffer: FIELDS[0] }, () => {
regl.clear({ color: [0, 0, 0, 1] })
splatMouse()
splatVerts({
vertexState: VERTEX_STATE[(tick + 1) % 2]
})
})
for (let i = 0; i < 2 * BLUR_PASSES; ++i) {
blurPass({
dest: FIELDS[(i + 1) % 2],
src: FIELDS[i % 2],
axis: (i % 2)
})
}
gradPass({
dest: FIELDS[1],
src: FIELDS[0]
})
applySpringForces({
dest: VERTEX_STATE[(tick + 1) % 2],
src: VERTEX_STATE[tick % 2]
})
integrateVerts({
dest: VERTEX_STATE[tick % 2],
src: VERTEX_STATE[(tick + 1) % 2],
field: FIELDS[1]
})
}
|
javascript
|
{
"resource": ""
}
|
q22870
|
getModelMatrix
|
train
|
function getModelMatrix (rb) {
var ms = rb.getMotionState()
if (ms) {
ms.getWorldTransform(transformTemp)
var p = transformTemp.getOrigin()
var q = transformTemp.getRotation()
return mat4.fromRotationTranslation(
[], [q.x(), q.y(), q.z(), q.w()], [p.x(), p.y(), p.z()])
}
}
|
javascript
|
{
"resource": ""
}
|
q22871
|
createAudioBuffer
|
train
|
function createAudioBuffer (length, createAudioDataCallback) {
var channels = 2
var frameCount = context.sampleRate * length
var audioBuffer = context.createBuffer(channels, frameCount, context.sampleRate)
for (var channel = 0; channel < channels; channel++) {
var channelData = audioBuffer.getChannelData(channel)
createAudioDataCallback(channelData, frameCount)
}
return audioBuffer
}
|
javascript
|
{
"resource": ""
}
|
q22872
|
block
|
train
|
function block () {
var code = []
function push () {
code.push.apply(code, slice(arguments))
}
var vars = []
function def () {
var name = 'v' + (varCounter++)
vars.push(name)
if (arguments.length > 0) {
code.push(name, '=')
code.push.apply(code, slice(arguments))
code.push(';')
}
return name
}
return extend(push, {
def: def,
toString: function () {
return join([
(vars.length > 0 ? 'var ' + vars + ';' : ''),
join(code)
])
}
})
}
|
javascript
|
{
"resource": ""
}
|
q22873
|
sortState
|
train
|
function sortState (state) {
return state.sort(function (a, b) {
if (a === S_VIEWPORT) {
return -1
} else if (b === S_VIEWPORT) {
return 1
}
return (a < b) ? -1 : 1
})
}
|
javascript
|
{
"resource": ""
}
|
q22874
|
_unwrapStorageSnapshot
|
train
|
function _unwrapStorageSnapshot(storageSnapshot) {
return {
bytesTransferred: storageSnapshot.bytesTransferred,
downloadURL: storageSnapshot.downloadURL,
metadata: storageSnapshot.metadata,
ref: storageSnapshot.ref,
state: storageSnapshot.state,
task: storageSnapshot.task,
totalBytes: storageSnapshot.totalBytes
};
}
|
javascript
|
{
"resource": ""
}
|
q22875
|
FirebaseObject
|
train
|
function FirebaseObject(ref) {
if( !(this instanceof FirebaseObject) ) {
return new FirebaseObject(ref);
}
var self = this;
// These are private config props and functions used internally
// they are collected here to reduce clutter in console.log and forEach
this.$$conf = {
// synchronizes data to Firebase
sync: new ObjectSyncManager(this, ref),
// stores the Firebase ref
ref: ref,
// synchronizes $scope variables with this object
binding: new ThreeWayBinding(this),
// stores observers registered with $watch
listeners: []
};
// this bit of magic makes $$conf non-enumerable and non-configurable
// and non-writable (its properties are still writable but the ref cannot be replaced)
// we redundantly assign it above so the IDE can relax
Object.defineProperty(this, '$$conf', {
value: this.$$conf
});
this.$id = ref.ref.key;
this.$priority = null;
$firebaseUtils.applyDefaults(this, this.$$defaults);
// start synchronizing data with Firebase
this.$$conf.sync.init();
// $resolved provides quick access to the current state of the $loaded() promise.
// This is useful in data-binding when needing to delay the rendering or visibilty
// of the data until is has been loaded from firebase.
this.$resolved = false;
this.$loaded().finally(function() {
self.$resolved = true;
});
}
|
javascript
|
{
"resource": ""
}
|
q22876
|
train
|
function () {
var self = this;
var ref = self.$ref();
var def = $q.defer();
var dataJSON;
try {
dataJSON = $firebaseUtils.toJSON(self);
} catch (e) {
def.reject(e);
}
if (typeof dataJSON !== 'undefined') {
$firebaseUtils.doSet(ref, dataJSON).then(function() {
self.$$notify();
def.resolve(self.$ref());
}).catch(def.reject);
}
return def.promise;
}
|
javascript
|
{
"resource": ""
}
|
|
q22877
|
train
|
function() {
var self = this;
$firebaseUtils.trimKeys(self, {});
self.$value = null;
return $firebaseUtils.doRemove(self.$ref()).then(function() {
self.$$notify();
return self.$ref();
});
}
|
javascript
|
{
"resource": ""
}
|
|
q22878
|
train
|
function (scope, varName) {
var self = this;
return self.$loaded().then(function () {
return self.$$conf.binding.bindTo(scope, varName);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q22879
|
train
|
function (stringOrProvider) {
var provider;
if (typeof stringOrProvider == "string") {
var providerID = stringOrProvider.slice(0, 1).toUpperCase() + stringOrProvider.slice(1);
provider = new firebase.auth[providerID+"AuthProvider"]();
} else {
provider = stringOrProvider;
}
return provider;
}
|
javascript
|
{
"resource": ""
}
|
|
q22880
|
train
|
function() {
var auth = this._auth;
return this._q(function(resolve) {
var off;
function callback() {
// Turn off this onAuthStateChanged() callback since we just needed to get the authentication data once.
off();
resolve();
}
off = auth.onAuthStateChanged(callback);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q22881
|
train
|
function(indexOrItem) {
this._assertNotDestroyed('$save');
var self = this;
var item = self._resolveItem(indexOrItem);
var key = self.$keyAt(item);
var def = $q.defer();
if( key !== null ) {
var ref = self.$ref().ref.child(key);
var dataJSON;
try {
dataJSON = $firebaseUtils.toJSON(item);
} catch (err) {
def.reject(err);
}
if (typeof dataJSON !== 'undefined') {
$firebaseUtils.doSet(ref, dataJSON).then(function() {
self.$$notify('child_changed', key);
def.resolve(ref);
}).catch(def.reject);
}
}
else {
def.reject('Invalid record; could not determine key for '+indexOrItem);
}
return def.promise;
}
|
javascript
|
{
"resource": ""
}
|
|
q22882
|
train
|
function(rec, prevChild) {
var i;
if( prevChild === null ) {
i = 0;
}
else {
i = this.$indexFor(prevChild)+1;
if( i === 0 ) { i = this.$list.length; }
}
this.$list.splice(i, 0, rec);
this._indexCache[this.$$getKey(rec)] = i;
return i;
}
|
javascript
|
{
"resource": ""
}
|
|
q22883
|
train
|
function(indexOrItem) {
var list = this.$list;
if( angular.isNumber(indexOrItem) && indexOrItem >= 0 && list.length >= indexOrItem ) {
return list[indexOrItem];
}
else if( angular.isObject(indexOrItem) ) {
// it must be an item in this array; it's not sufficient for it just to have
// a $id or even a $id that is in the array, it must be an actual record
// the fastest way to determine this is to use $getRecord (to avoid iterating all recs)
// and compare the two
var key = this.$$getKey(indexOrItem);
var rec = this.$getRecord(key);
return rec === indexOrItem? rec : null;
}
return null;
}
|
javascript
|
{
"resource": ""
}
|
|
q22884
|
getBox
|
train
|
function getBox(o) {
return {
xMin: o.position.x,
xMax: o.position.x + o.width,
yMin: o.position.y,
yMax: o.position.y + o.height
};
}
|
javascript
|
{
"resource": ""
}
|
q22885
|
clfdate
|
train
|
function clfdate (dateTime) {
var date = dateTime.getUTCDate()
var hour = dateTime.getUTCHours()
var mins = dateTime.getUTCMinutes()
var secs = dateTime.getUTCSeconds()
var year = dateTime.getUTCFullYear()
var month = CLF_MONTH[dateTime.getUTCMonth()]
return pad2(date) + '/' + month + '/' + year +
':' + pad2(hour) + ':' + pad2(mins) + ':' + pad2(secs) +
' +0000'
}
|
javascript
|
{
"resource": ""
}
|
q22886
|
createBufferStream
|
train
|
function createBufferStream (stream, interval) {
var buf = []
var timer = null
// flush function
function flush () {
timer = null
stream.write(buf.join(''))
buf.length = 0
}
// write function
function write (str) {
if (timer === null) {
timer = setTimeout(flush, interval)
}
buf.push(str)
}
// return a minimal "stream"
return { write: write }
}
|
javascript
|
{
"resource": ""
}
|
q22887
|
getFormatFunction
|
train
|
function getFormatFunction (name) {
// lookup format
var fmt = morgan[name] || name || morgan.default
// return compiled format
return typeof fmt !== 'function'
? compile(fmt)
: fmt
}
|
javascript
|
{
"resource": ""
}
|
q22888
|
injectHook
|
train
|
function injectHook(options, name, hook) {
const existing = options[name]
options[name] = existing
? Array.isArray(existing) ? existing.concat(hook) : [existing, hook]
: [hook]
}
|
javascript
|
{
"resource": ""
}
|
q22889
|
patchScopedSlots
|
train
|
function patchScopedSlots (instance) {
if (!instance._u) return
// https://github.com/vuejs/vue/blob/dev/src/core/instance/render-helpers/resolve-scoped-slots.js
const original = instance._u
instance._u = slots => {
try {
// 2.6.4 ~ 2.6.6
return original(slots, true)
} catch (e) {
// 2.5 / >= 2.6.7
return original(slots, null, true)
}
}
return () => {
instance._u = original
}
}
|
javascript
|
{
"resource": ""
}
|
q22890
|
getNodeInfo
|
train
|
function getNodeInfo(x, y){
var nodeInfo = {};
var bestNodeInfo = {
node: null,
boundSize: 0
};
getBestNode(appTree, x, y, bestNodeInfo);
var bestNode = bestNodeInfo.node;
if(bestNode){
var text = bestNode.text || bestNode.label;
if(text){
text = text.replace(/\s*\r?\n\s*/g,' ');
text = text.replace(/^\s+|\s+$/g, '');
var textLen = byteLen(text);
text = textLen > 20 ? leftstr(text, 20) + '...' : text;
nodeInfo.text = text;
}
nodeInfo.path = getNodeXPath(bestNode);
}
else{
nodeInfo.x = x;
nodeInfo.y = y;
}
return nodeInfo;
}
|
javascript
|
{
"resource": ""
}
|
q22891
|
getRootPath
|
train
|
function getRootPath(){
var rootPath = path.resolve('.');
while(rootPath){
if(fs.existsSync(rootPath + '/config.json')){
break;
}
rootPath = rootPath.substring(0, rootPath.lastIndexOf(path.sep));
}
return rootPath;
}
|
javascript
|
{
"resource": ""
}
|
q22892
|
startRecorderServer
|
train
|
function startRecorderServer(config, onReady, onCommand, onEnd){
var server = http.createServer(function(req, res){
if(req.url === '/proxy.pac'){
var wdproxy = config.wdproxy;
if(wdproxy){
res.writeHead(200, { 'Content-Type': 'text/plain' });
var pacContent = 'function FindProxyForURL(url, host){if(!/^(127.0.0.1|localhost)$/.test(host))return "PROXY '+config.wdproxy+'";\r\nreturn "DIRECT"}';
res.end(pacContent);
}
else{
res.end('No wdproxy finded!');
}
}
});
server.listen(0, function(){
var serverPort = server.address().port;
console.log('');
console.log(__('recorder_server_listen_on').green, serverPort);
onReady(serverPort);
});
wsServer = new WebSocketServer({
httpServer: server,
autoAcceptConnections: true
});
wsServer.on('connect', function(connection) {
wsConnection = connection;
sendWsMessage('config', config);
connection.on('message', function(message) {
var message = message.utf8Data;
try{
message = JSON.parse(message);
}
catch(e){};
var type = message.type;
switch(type){
case 'saveCmd':
onCommand(message.data);
break;
case 'save':
onCommand({
cmd: 'end'
});
setTimeout(function(){
wsConnection && wsConnection.close();
server.close(function(){
onEnd(true);
});
}, 500);
break;
case 'end':
onCommand({
cmd: 'end'
});
setTimeout(function(){
wsConnection && wsConnection.close();
server.close(function(){
onEnd(false);
});
}, 500);
break;
}
});
connection.on('close', function(reasonCode, description) {
wsConnection = null;
});
});
}
|
javascript
|
{
"resource": ""
}
|
q22893
|
getDomPath
|
train
|
function getDomPath(target, isAllDom){
var arrAllPaths = [];
var node = target, path;
while(node){
var nodeName = node.nodeName.toLowerCase();
if(/^#document/.test(nodeName)){
path = getRelativeDomPath(node, target, isAllDom);
if(path){
arrAllPaths.push(path);
}
node = node.parentNode || node.host;
target = node;
}
else{
node = node.parentNode || node.host;
}
}
return arrAllPaths.length > 0 ? arrAllPaths.reverse().join(' /deep/ ') : null;
}
|
javascript
|
{
"resource": ""
}
|
q22894
|
getFrameId
|
train
|
function getFrameId(){
var frame = -1;
if(isIframe){
try{
var frameElement = window.frameElement;
if(frameElement !== null){
frame = getDomPath(frameElement) || -1;
}
else{
frame = '!'+location.href.replace(/^https?:/,'');
var parentFrames = parent.frames;
for(var i=0,len=parentFrames.length;i<len;i++){
if(parentFrames[i] === window){
frame = '!'+i;
break;
}
}
}
}
catch(e){}
}
else{
frame = null;
}
return frame;
}
|
javascript
|
{
"resource": ""
}
|
q22895
|
unsafeEval
|
train
|
function unsafeEval(str){
var head = document.getElementsByTagName("head")[0];
var script = document.createElement("script");
script.innerHTML = '('+str+')();';
head.appendChild(script);
head.removeChild(script);
}
|
javascript
|
{
"resource": ""
}
|
q22896
|
hookAlertFunction
|
train
|
function hookAlertFunction(){
var rawAlert = window.alert;
function sendAlertCmd(cmd, data){
var cmdInfo = {
cmd: cmd,
data: data || {}
};
window.postMessage({
'type': 'uiRecorderAlertCommand',
'cmdInfo': cmdInfo
}, '*');
}
window.alert = function(str){
var ret = rawAlert.call(this, str);
sendAlertCmd('acceptAlert');
return ret;
}
var rawConfirm = window.confirm;
window.confirm = function(str){
var ret = rawConfirm.call(this, str);
sendAlertCmd(ret?'acceptAlert':'dismissAlert');
return ret;
}
var rawPrompt = window.prompt;
window.prompt = function(str){
var ret = rawPrompt.call(this, str);
if(ret === null){
sendAlertCmd('dismissAlert');
}
else{
sendAlertCmd('setAlert', {
text: ret
});
sendAlertCmd('acceptAlert');
}
return ret;
}
function wrapBeforeUnloadListener(oldListener){
var newListener = function(e){
var returnValue = oldListener(e);
if(returnValue){
sendAlertCmd('acceptAlert');
}
return returnValue;
}
return newListener;
}
var rawAddEventListener = window.addEventListener;
window.addEventListener = function(type, listener, useCapture){
if(type === 'beforeunload'){
listener = wrapBeforeUnloadListener(listener);
}
return rawAddEventListener.call(window, type, listener, useCapture);
};
setTimeout(function(){
var oldBeforeunload = window.onbeforeunload;
if(oldBeforeunload){
window.onbeforeunload = wrapBeforeUnloadListener(oldBeforeunload)
}
}, 1000);
}
|
javascript
|
{
"resource": ""
}
|
q22897
|
getFixedParent
|
train
|
function getFixedParent(target){
var documentElement = document.documentElement;
var node = target;
var nodeName, path, offset, left, top, savedParent;
var notFirstNode = false; // 当前点击控件以可见范围内进行定位,其它以全局定位(很多局部控件是不可见的)
while(node !== null){
nodeName = node.nodeName.toLowerCase();
if(nodeName !== '#document-fragment'){
path = getDomPath(node, notFirstNode);
if(path === null){
break;
}
offset = node.getBoundingClientRect();
left = parseInt(offset.left, 10);
top = parseInt(offset.top, 10);
savedParent = mapParentsOffset[path];
if(savedParent && left === savedParent.left && top === savedParent.top){
return {
path: path,
left: left,
top: top
};
}
}
if(nodeName === 'html'){
node = null;
}
else{
node = node.parentNode;
}
notFirstNode = true;
}
path = getDomPath(target);
if(path !== null){
offset = target.getBoundingClientRect();
return {
path: path,
left: offset.left,
top: offset.top
};
}
else{
return null;
}
}
|
javascript
|
{
"resource": ""
}
|
q22898
|
setRecorderWork
|
train
|
function setRecorderWork(enable){
isWorking = enable;
if(isWorking){
chrome.browserAction.setTitle({title: __('icon_record_tip')});
chrome.browserAction.setIcon({path: workIcon===1?ENABLE_ICON1:ENABLE_ICON2});
workIcon *= -1;
workIconTimer = setTimeout(function(){
setRecorderWork(true);
}, 1000);
}
else{
clearTimeout(workIconTimer);
chrome.browserAction.setTitle({title: __('icon_end_tip')});
chrome.browserAction.setIcon({path: DISABLE_ICON});
}
}
|
javascript
|
{
"resource": ""
}
|
q22899
|
saveCommand
|
train
|
function saveCommand(windowId, frame, cmd, data){
if(isModuleLoading){
return;
}
var cmdInfo = {
window: windowId,
frame: frame,
cmd: cmd,
data: data,
fix: false
};
checkLostKey(windowId);
switch(cmd){
case 'keyDown':
allKeyMap[data.character] = cmdInfo;
break;
case 'keyUp':
delete allKeyMap[data.character];
break;
case 'mouseDown':
allMouseMap[data.button] = cmdInfo;
break;
case 'mouseUp':
delete allMouseMap[data.button];
break;
}
execNextCommand(cmdInfo);
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.