_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q23800
|
setSamplerParameters
|
train
|
function setSamplerParameters(gl, sampler, options) {
setTextureSamplerParameters(gl, sampler, gl.samplerParameteri, options);
}
|
javascript
|
{
"resource": ""
}
|
q23801
|
createSampler
|
train
|
function createSampler(gl, options) {
const sampler = gl.createSampler();
setSamplerParameters(gl, sampler, options);
return sampler;
}
|
javascript
|
{
"resource": ""
}
|
q23802
|
createSamplers
|
train
|
function createSamplers(gl, samplerOptions) {
const samplers = {};
Object.keys(samplerOptions).forEach(function(name) {
samplers[name] = createSampler(gl, samplerOptions[name]);
});
return samplers;
}
|
javascript
|
{
"resource": ""
}
|
q23803
|
make1Pixel
|
train
|
function make1Pixel(color) {
color = color || defaults.textureColor;
if (isArrayBuffer(color)) {
return color;
}
return new Uint8Array([color[0] * 255, color[1] * 255, color[2] * 255, color[3] * 255]);
}
|
javascript
|
{
"resource": ""
}
|
q23804
|
getCubeFaceOrder
|
train
|
function getCubeFaceOrder(gl, options) {
options = options || {};
return options.cubeFaceOrder || [
gl.TEXTURE_CUBE_MAP_POSITIVE_X,
gl.TEXTURE_CUBE_MAP_NEGATIVE_X,
gl.TEXTURE_CUBE_MAP_POSITIVE_Y,
gl.TEXTURE_CUBE_MAP_NEGATIVE_Y,
gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
gl.TEXTURE_CUBE_MAP_NEGATIVE_Z,
];
}
|
javascript
|
{
"resource": ""
}
|
q23805
|
urlIsSameOrigin
|
train
|
function urlIsSameOrigin(url) {
if (typeof document !== 'undefined') {
// for IE really
const a = document.createElement('a');
a.href = url;
return a.hostname === location.hostname &&
a.port === location.port &&
a.protocol === location.protocol;
} else {
const localOrigin = (new URL(location.href)).origin;
const urlOrigin = (new URL(url, location.href)).origin;
return urlOrigin === localOrigin;
}
}
|
javascript
|
{
"resource": ""
}
|
q23806
|
loadImage
|
train
|
function loadImage(url, crossOrigin, callback) {
callback = callback || noop;
let img;
crossOrigin = crossOrigin !== undefined ? crossOrigin : defaults.crossOrigin;
crossOrigin = setToAnonymousIfUndefinedAndURLIsNotSameOrigin(url, crossOrigin);
if (typeof Image !== 'undefined') {
img = new Image();
if (crossOrigin !== undefined) {
img.crossOrigin = crossOrigin;
}
const clearEventHandlers = function clearEventHandlers() {
img.removeEventListener('error', onError); // eslint-disable-line
img.removeEventListener('load', onLoad); // eslint-disable-line
img = null;
};
const onError = function onError() {
const msg = "couldn't load image: " + url;
helper.error(msg);
callback(msg, img);
clearEventHandlers();
};
const onLoad = function onLoad() {
callback(null, img);
clearEventHandlers();
};
img.addEventListener('error', onError);
img.addEventListener('load', onLoad);
img.src = url;
return img;
} else if (typeof ImageBitmap !== 'undefined') {
let err;
let bm;
const cb = function cb() {
callback(err, bm);
};
const options = {};
if (crossOrigin) {
options.mode = 'cors'; // TODO: not sure how to translate image.crossOrigin
}
fetch(url, options).then(function(response) {
if (!response.ok) {
throw response;
}
return response.blob();
}).then(function(blob) {
return createImageBitmap(blob, {
premultiplyAlpha: 'none',
colorSpaceConversion: 'none',
});
}).then(function(bitmap) {
// not sure if this works. We don't want
// to catch the user's error. So, call
// the callback in a timeout so we're
// not in this scope inside the promise.
bm = bitmap;
setTimeout(cb);
}).catch(function(e) {
err = e;
setTimeout(cb);
});
img = null;
}
return img;
}
|
javascript
|
{
"resource": ""
}
|
q23807
|
isTexImageSource
|
train
|
function isTexImageSource(obj) {
return (typeof ImageBitmap !== 'undefined' && obj instanceof ImageBitmap) ||
(typeof ImageData !== 'undefined' && obj instanceof ImageData) ||
(typeof HTMLElement !== 'undefined' && obj instanceof HTMLElement);
}
|
javascript
|
{
"resource": ""
}
|
q23808
|
loadAndUseImage
|
train
|
function loadAndUseImage(obj, crossOrigin, callback) {
if (isTexImageSource(obj)) {
setTimeout(function() {
callback(null, obj);
});
return obj;
}
return loadImage(obj, crossOrigin, callback);
}
|
javascript
|
{
"resource": ""
}
|
q23809
|
loadTextureFromUrl
|
train
|
function loadTextureFromUrl(gl, tex, options, callback) {
callback = callback || noop;
options = options || defaults.textureOptions;
setTextureTo1PixelColor(gl, tex, options);
// Because it's async we need to copy the options.
options = Object.assign({}, options);
const img = loadAndUseImage(options.src, options.crossOrigin, function(err, img) {
if (err) {
callback(err, tex, img);
} else {
setTextureFromElement(gl, tex, img, options);
callback(null, tex, img);
}
});
return img;
}
|
javascript
|
{
"resource": ""
}
|
q23810
|
setEmptyTexture
|
train
|
function setEmptyTexture(gl, tex, options) {
const target = options.target || gl.TEXTURE_2D;
gl.bindTexture(target, tex);
const level = options.level || 0;
const internalFormat = options.internalFormat || options.format || gl.RGBA;
const formatType = getFormatAndTypeForInternalFormat(internalFormat);
const format = options.format || formatType.format;
const type = options.type || formatType.type;
savePackState(gl, options);
if (target === gl.TEXTURE_CUBE_MAP) {
for (let ii = 0; ii < 6; ++ii) {
gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + ii, level, internalFormat, options.width, options.height, 0, format, type, null);
}
} else if (target === gl.TEXTURE_3D) {
gl.texImage3D(target, level, internalFormat, options.width, options.height, options.depth, 0, format, type, null);
} else {
gl.texImage2D(target, level, internalFormat, options.width, options.height, 0, format, type, null);
}
restorePackState(gl, options);
}
|
javascript
|
{
"resource": ""
}
|
q23811
|
createTexture
|
train
|
function createTexture(gl, options, callback) {
callback = callback || noop;
options = options || defaults.textureOptions;
const tex = gl.createTexture();
const target = options.target || gl.TEXTURE_2D;
let width = options.width || 1;
let height = options.height || 1;
const internalFormat = options.internalFormat || gl.RGBA;
const formatType = getFormatAndTypeForInternalFormat(internalFormat);
let type = options.type || formatType.type;
gl.bindTexture(target, tex);
if (target === gl.TEXTURE_CUBE_MAP) {
// this should have been the default for CUBEMAPS :(
gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
}
let src = options.src;
if (src) {
if (typeof src === "function") {
src = src(gl, options);
}
if (typeof (src) === "string") {
loadTextureFromUrl(gl, tex, options, callback);
} else if (isArrayBuffer(src) ||
(Array.isArray(src) && (
typeof src[0] === 'number' ||
Array.isArray(src[0]) ||
isArrayBuffer(src[0]))
)
) {
const dimensions = setTextureFromArray(gl, tex, src, options);
width = dimensions.width;
height = dimensions.height;
type = dimensions.type;
} else if (Array.isArray(src) && (typeof (src[0]) === 'string' || isTexImageSource(src[0]))) {
if (target === gl.TEXTURE_CUBE_MAP) {
loadCubemapFromUrls(gl, tex, options, callback);
} else {
loadSlicesFromUrls(gl, tex, options, callback);
}
} else if (isTexImageSource(src)) {
setTextureFromElement(gl, tex, src, options);
width = src.width;
height = src.height;
} else {
throw "unsupported src type";
}
} else {
setEmptyTexture(gl, tex, options);
}
if (shouldAutomaticallySetTextureFilteringForSize(options)) {
setTextureFilteringForSize(gl, tex, options, width, height, internalFormat, type);
}
setTextureParameters(gl, tex, options);
return tex;
}
|
javascript
|
{
"resource": ""
}
|
q23812
|
resizeTexture
|
train
|
function resizeTexture(gl, tex, options, width, height) {
width = width || options.width;
height = height || options.height;
const target = options.target || gl.TEXTURE_2D;
gl.bindTexture(target, tex);
const level = options.level || 0;
const internalFormat = options.internalFormat || options.format || gl.RGBA;
const formatType = getFormatAndTypeForInternalFormat(internalFormat);
const format = options.format || formatType.format;
let type;
const src = options.src;
if (!src) {
type = options.type || formatType.type;
} else if (isArrayBuffer(src) || (Array.isArray(src) && typeof (src[0]) === 'number')) {
type = options.type || getTextureTypeForArrayType(gl, src, formatType.type);
} else {
type = options.type || formatType.type;
}
if (target === gl.TEXTURE_CUBE_MAP) {
for (let ii = 0; ii < 6; ++ii) {
gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + ii, level, internalFormat, width, height, 0, format, type, null);
}
} else {
gl.texImage2D(target, level, internalFormat, width, height, 0, format, type, null);
}
}
|
javascript
|
{
"resource": ""
}
|
q23813
|
createTextures
|
train
|
function createTextures(gl, textureOptions, callback) {
callback = callback || noop;
let numDownloading = 0;
const errors = [];
const textures = {};
const images = {};
function callCallbackIfReady() {
if (numDownloading === 0) {
setTimeout(function() {
callback(errors.length ? errors : undefined, textures, images);
}, 0);
}
}
Object.keys(textureOptions).forEach(function(name) {
const options = textureOptions[name];
let onLoadFn;
if (isAsyncSrc(options.src)) {
onLoadFn = function(err, tex, img) {
images[name] = img;
--numDownloading;
if (err) {
errors.push(err);
}
callCallbackIfReady();
};
++numDownloading;
}
textures[name] = createTexture(gl, options, onLoadFn);
});
// queue the callback if there are no images to download.
// We do this because if your code is structured to wait for
// images to download but then you comment out all the async
// images your code would break.
callCallbackIfReady();
return textures;
}
|
javascript
|
{
"resource": ""
}
|
q23814
|
resizeFramebufferInfo
|
train
|
function resizeFramebufferInfo(gl, framebufferInfo, attachments, width, height) {
width = width || gl.drawingBufferWidth;
height = height || gl.drawingBufferHeight;
framebufferInfo.width = width;
framebufferInfo.height = height;
attachments = attachments || defaultAttachments;
attachments.forEach(function(attachmentOptions, ndx) {
const attachment = framebufferInfo.attachments[ndx];
const format = attachmentOptions.format;
if (helper.isRenderbuffer(gl, attachment)) {
gl.bindRenderbuffer(gl.RENDERBUFFER, attachment);
gl.renderbufferStorage(gl.RENDERBUFFER, format, width, height);
} else if (helper.isTexture(gl, attachment)) {
textures.resizeTexture(gl, attachment, attachmentOptions, width, height);
} else {
throw "unknown attachment type";
}
});
}
|
javascript
|
{
"resource": ""
}
|
q23815
|
bindFramebufferInfo
|
train
|
function bindFramebufferInfo(gl, framebufferInfo, target) {
target = target || gl.FRAMEBUFFER;
if (framebufferInfo) {
gl.bindFramebuffer(target, framebufferInfo.framebuffer);
gl.viewport(0, 0, framebufferInfo.width, framebufferInfo.height);
} else {
gl.bindFramebuffer(target, null);
gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
}
}
|
javascript
|
{
"resource": ""
}
|
q23816
|
create
|
train
|
function create(x, y, z) {
const dst = new VecType(3);
if (x) {
dst[0] = x;
}
if (y) {
dst[1] = y;
}
if (z) {
dst[2] = z;
}
return dst;
}
|
javascript
|
{
"resource": ""
}
|
q23817
|
add
|
train
|
function add(a, b, dst) {
dst = dst || new VecType(3);
dst[0] = a[0] + b[0];
dst[1] = a[1] + b[1];
dst[2] = a[2] + b[2];
return dst;
}
|
javascript
|
{
"resource": ""
}
|
q23818
|
subtract
|
train
|
function subtract(a, b, dst) {
dst = dst || new VecType(3);
dst[0] = a[0] - b[0];
dst[1] = a[1] - b[1];
dst[2] = a[2] - b[2];
return dst;
}
|
javascript
|
{
"resource": ""
}
|
q23819
|
mulScalar
|
train
|
function mulScalar(v, k, dst) {
dst = dst || new VecType(3);
dst[0] = v[0] * k;
dst[1] = v[1] * k;
dst[2] = v[2] * k;
return dst;
}
|
javascript
|
{
"resource": ""
}
|
q23820
|
divScalar
|
train
|
function divScalar(v, k, dst) {
dst = dst || new VecType(3);
dst[0] = v[0] / k;
dst[1] = v[1] / k;
dst[2] = v[2] / k;
return dst;
}
|
javascript
|
{
"resource": ""
}
|
q23821
|
cross
|
train
|
function cross(a, b, dst) {
dst = dst || new VecType(3);
const t1 = a[2] * b[0] - a[0] * b[2];
const t2 = a[0] * b[1] - a[1] * b[0];
dst[0] = a[1] * b[2] - a[2] * b[1];
dst[1] = t1;
dst[2] = t2;
return dst;
}
|
javascript
|
{
"resource": ""
}
|
q23822
|
normalize
|
train
|
function normalize(a, dst) {
dst = dst || new VecType(3);
const lenSq = a[0] * a[0] + a[1] * a[1] + a[2] * a[2];
const len = Math.sqrt(lenSq);
if (len > 0.00001) {
dst[0] = a[0] / len;
dst[1] = a[1] / len;
dst[2] = a[2] / len;
} else {
dst[0] = 0;
dst[1] = 0;
dst[2] = 0;
}
return dst;
}
|
javascript
|
{
"resource": ""
}
|
q23823
|
negate
|
train
|
function negate(v, dst) {
dst = dst || new VecType(3);
dst[0] = -v[0];
dst[1] = -v[1];
dst[2] = -v[2];
return dst;
}
|
javascript
|
{
"resource": ""
}
|
q23824
|
copy
|
train
|
function copy(v, dst) {
dst = dst || new VecType(3);
dst[0] = v[0];
dst[1] = v[1];
dst[2] = v[2];
return dst;
}
|
javascript
|
{
"resource": ""
}
|
q23825
|
deindexVertices
|
train
|
function deindexVertices(vertices) {
const indices = vertices.indices;
const newVertices = {};
const numElements = indices.length;
function expandToUnindexed(channel) {
const srcBuffer = vertices[channel];
const numComponents = srcBuffer.numComponents;
const dstBuffer = createAugmentedTypedArray(numComponents, numElements, srcBuffer.constructor);
for (let ii = 0; ii < numElements; ++ii) {
const ndx = indices[ii];
const offset = ndx * numComponents;
for (let jj = 0; jj < numComponents; ++jj) {
dstBuffer.push(srcBuffer[offset + jj]);
}
}
newVertices[channel] = dstBuffer;
}
Object.keys(vertices).filter(allButIndices).forEach(expandToUnindexed);
return newVertices;
}
|
javascript
|
{
"resource": ""
}
|
q23826
|
flattenNormals
|
train
|
function flattenNormals(vertices) {
if (vertices.indices) {
throw "can't flatten normals of indexed vertices. deindex them first";
}
const normals = vertices.normal;
const numNormals = normals.length;
for (let ii = 0; ii < numNormals; ii += 9) {
// pull out the 3 normals for this triangle
const nax = normals[ii + 0];
const nay = normals[ii + 1];
const naz = normals[ii + 2];
const nbx = normals[ii + 3];
const nby = normals[ii + 4];
const nbz = normals[ii + 5];
const ncx = normals[ii + 6];
const ncy = normals[ii + 7];
const ncz = normals[ii + 8];
// add them
let nx = nax + nbx + ncx;
let ny = nay + nby + ncy;
let nz = naz + nbz + ncz;
// normalize them
const length = Math.sqrt(nx * nx + ny * ny + nz * nz);
nx /= length;
ny /= length;
nz /= length;
// copy them back in
normals[ii + 0] = nx;
normals[ii + 1] = ny;
normals[ii + 2] = nz;
normals[ii + 3] = nx;
normals[ii + 4] = ny;
normals[ii + 5] = nz;
normals[ii + 6] = nx;
normals[ii + 7] = ny;
normals[ii + 8] = nz;
}
return vertices;
}
|
javascript
|
{
"resource": ""
}
|
q23827
|
reorientNormals
|
train
|
function reorientNormals(array, matrix) {
applyFuncToV3Array(array, m4.inverse(matrix), transformNormal);
return array;
}
|
javascript
|
{
"resource": ""
}
|
q23828
|
createXYQuadVertices
|
train
|
function createXYQuadVertices(size, xOffset, yOffset) {
size = size || 2;
xOffset = xOffset || 0;
yOffset = yOffset || 0;
size *= 0.5;
return {
position: {
numComponents: 2,
data: [
xOffset + -1 * size, yOffset + -1 * size,
xOffset + 1 * size, yOffset + -1 * size,
xOffset + -1 * size, yOffset + 1 * size,
xOffset + 1 * size, yOffset + 1 * size,
],
},
normal: [
0, 0, 1,
0, 0, 1,
0, 0, 1,
0, 0, 1,
],
texcoord: [
0, 0,
1, 0,
0, 1,
1, 1,
],
indices: [ 0, 1, 2, 2, 1, 3 ],
};
}
|
javascript
|
{
"resource": ""
}
|
q23829
|
createPlaneVertices
|
train
|
function createPlaneVertices(
width,
depth,
subdivisionsWidth,
subdivisionsDepth,
matrix) {
width = width || 1;
depth = depth || 1;
subdivisionsWidth = subdivisionsWidth || 1;
subdivisionsDepth = subdivisionsDepth || 1;
matrix = matrix || m4.identity();
const numVertices = (subdivisionsWidth + 1) * (subdivisionsDepth + 1);
const positions = createAugmentedTypedArray(3, numVertices);
const normals = createAugmentedTypedArray(3, numVertices);
const texcoords = createAugmentedTypedArray(2, numVertices);
for (let z = 0; z <= subdivisionsDepth; z++) {
for (let x = 0; x <= subdivisionsWidth; x++) {
const u = x / subdivisionsWidth;
const v = z / subdivisionsDepth;
positions.push(
width * u - width * 0.5,
0,
depth * v - depth * 0.5);
normals.push(0, 1, 0);
texcoords.push(u, v);
}
}
const numVertsAcross = subdivisionsWidth + 1;
const indices = createAugmentedTypedArray(
3, subdivisionsWidth * subdivisionsDepth * 2, Uint16Array);
for (let z = 0; z < subdivisionsDepth; z++) { // eslint-disable-line
for (let x = 0; x < subdivisionsWidth; x++) { // eslint-disable-line
// Make triangle 1 of quad.
indices.push(
(z + 0) * numVertsAcross + x,
(z + 1) * numVertsAcross + x,
(z + 0) * numVertsAcross + x + 1);
// Make triangle 2 of quad.
indices.push(
(z + 1) * numVertsAcross + x,
(z + 1) * numVertsAcross + x + 1,
(z + 0) * numVertsAcross + x + 1);
}
}
const arrays = reorientVertices({
position: positions,
normal: normals,
texcoord: texcoords,
indices: indices,
}, matrix);
return arrays;
}
|
javascript
|
{
"resource": ""
}
|
q23830
|
createSphereVertices
|
train
|
function createSphereVertices(
radius,
subdivisionsAxis,
subdivisionsHeight,
opt_startLatitudeInRadians,
opt_endLatitudeInRadians,
opt_startLongitudeInRadians,
opt_endLongitudeInRadians) {
if (subdivisionsAxis <= 0 || subdivisionsHeight <= 0) {
throw Error('subdivisionAxis and subdivisionHeight must be > 0');
}
opt_startLatitudeInRadians = opt_startLatitudeInRadians || 0;
opt_endLatitudeInRadians = opt_endLatitudeInRadians || Math.PI;
opt_startLongitudeInRadians = opt_startLongitudeInRadians || 0;
opt_endLongitudeInRadians = opt_endLongitudeInRadians || (Math.PI * 2);
const latRange = opt_endLatitudeInRadians - opt_startLatitudeInRadians;
const longRange = opt_endLongitudeInRadians - opt_startLongitudeInRadians;
// We are going to generate our sphere by iterating through its
// spherical coordinates and generating 2 triangles for each quad on a
// ring of the sphere.
const numVertices = (subdivisionsAxis + 1) * (subdivisionsHeight + 1);
const positions = createAugmentedTypedArray(3, numVertices);
const normals = createAugmentedTypedArray(3, numVertices);
const texcoords = createAugmentedTypedArray(2 , numVertices);
// Generate the individual vertices in our vertex buffer.
for (let y = 0; y <= subdivisionsHeight; y++) {
for (let x = 0; x <= subdivisionsAxis; x++) {
// Generate a vertex based on its spherical coordinates
const u = x / subdivisionsAxis;
const v = y / subdivisionsHeight;
const theta = longRange * u + opt_startLongitudeInRadians;
const phi = latRange * v + opt_startLatitudeInRadians;
const sinTheta = Math.sin(theta);
const cosTheta = Math.cos(theta);
const sinPhi = Math.sin(phi);
const cosPhi = Math.cos(phi);
const ux = cosTheta * sinPhi;
const uy = cosPhi;
const uz = sinTheta * sinPhi;
positions.push(radius * ux, radius * uy, radius * uz);
normals.push(ux, uy, uz);
texcoords.push(1 - u, v);
}
}
const numVertsAround = subdivisionsAxis + 1;
const indices = createAugmentedTypedArray(3, subdivisionsAxis * subdivisionsHeight * 2, Uint16Array);
for (let x = 0; x < subdivisionsAxis; x++) { // eslint-disable-line
for (let y = 0; y < subdivisionsHeight; y++) { // eslint-disable-line
// Make triangle 1 of quad.
indices.push(
(y + 0) * numVertsAround + x,
(y + 0) * numVertsAround + x + 1,
(y + 1) * numVertsAround + x);
// Make triangle 2 of quad.
indices.push(
(y + 1) * numVertsAround + x,
(y + 0) * numVertsAround + x + 1,
(y + 1) * numVertsAround + x + 1);
}
}
return {
position: positions,
normal: normals,
texcoord: texcoords,
indices: indices,
};
}
|
javascript
|
{
"resource": ""
}
|
q23831
|
createCubeVertices
|
train
|
function createCubeVertices(size) {
size = size || 1;
const k = size / 2;
const cornerVertices = [
[-k, -k, -k],
[+k, -k, -k],
[-k, +k, -k],
[+k, +k, -k],
[-k, -k, +k],
[+k, -k, +k],
[-k, +k, +k],
[+k, +k, +k],
];
const faceNormals = [
[+1, +0, +0],
[-1, +0, +0],
[+0, +1, +0],
[+0, -1, +0],
[+0, +0, +1],
[+0, +0, -1],
];
const uvCoords = [
[1, 0],
[0, 0],
[0, 1],
[1, 1],
];
const numVertices = 6 * 4;
const positions = createAugmentedTypedArray(3, numVertices);
const normals = createAugmentedTypedArray(3, numVertices);
const texcoords = createAugmentedTypedArray(2 , numVertices);
const indices = createAugmentedTypedArray(3, 6 * 2, Uint16Array);
for (let f = 0; f < 6; ++f) {
const faceIndices = CUBE_FACE_INDICES[f];
for (let v = 0; v < 4; ++v) {
const position = cornerVertices[faceIndices[v]];
const normal = faceNormals[f];
const uv = uvCoords[v];
// Each face needs all four vertices because the normals and texture
// coordinates are not all the same.
positions.push(position);
normals.push(normal);
texcoords.push(uv);
}
// Two triangles make a square face.
const offset = 4 * f;
indices.push(offset + 0, offset + 1, offset + 2);
indices.push(offset + 0, offset + 2, offset + 3);
}
return {
position: positions,
normal: normals,
texcoord: texcoords,
indices: indices,
};
}
|
javascript
|
{
"resource": ""
}
|
q23832
|
expandRLEData
|
train
|
function expandRLEData(rleData, padding) {
padding = padding || [];
const data = [];
for (let ii = 0; ii < rleData.length; ii += 4) {
const runLength = rleData[ii];
const element = rleData.slice(ii + 1, ii + 4);
element.push.apply(element, padding);
for (let jj = 0; jj < runLength; ++jj) {
data.push.apply(data, element);
}
}
return data;
}
|
javascript
|
{
"resource": ""
}
|
q23833
|
createCylinderVertices
|
train
|
function createCylinderVertices(
radius,
height,
radialSubdivisions,
verticalSubdivisions,
topCap,
bottomCap) {
return createTruncatedConeVertices(
radius,
radius,
height,
radialSubdivisions,
verticalSubdivisions,
topCap,
bottomCap);
}
|
javascript
|
{
"resource": ""
}
|
q23834
|
createTorusVertices
|
train
|
function createTorusVertices(
radius,
thickness,
radialSubdivisions,
bodySubdivisions,
startAngle,
endAngle) {
if (radialSubdivisions < 3) {
throw Error('radialSubdivisions must be 3 or greater');
}
if (bodySubdivisions < 3) {
throw Error('verticalSubdivisions must be 3 or greater');
}
startAngle = startAngle || 0;
endAngle = endAngle || Math.PI * 2;
const range = endAngle - startAngle;
const radialParts = radialSubdivisions + 1;
const bodyParts = bodySubdivisions + 1;
const numVertices = radialParts * bodyParts;
const positions = createAugmentedTypedArray(3, numVertices);
const normals = createAugmentedTypedArray(3, numVertices);
const texcoords = createAugmentedTypedArray(2, numVertices);
const indices = createAugmentedTypedArray(3, (radialSubdivisions) * (bodySubdivisions) * 2, Uint16Array);
for (let slice = 0; slice < bodyParts; ++slice) {
const v = slice / bodySubdivisions;
const sliceAngle = v * Math.PI * 2;
const sliceSin = Math.sin(sliceAngle);
const ringRadius = radius + sliceSin * thickness;
const ny = Math.cos(sliceAngle);
const y = ny * thickness;
for (let ring = 0; ring < radialParts; ++ring) {
const u = ring / radialSubdivisions;
const ringAngle = startAngle + u * range;
const xSin = Math.sin(ringAngle);
const zCos = Math.cos(ringAngle);
const x = xSin * ringRadius;
const z = zCos * ringRadius;
const nx = xSin * sliceSin;
const nz = zCos * sliceSin;
positions.push(x, y, z);
normals.push(nx, ny, nz);
texcoords.push(u, 1 - v);
}
}
for (let slice = 0; slice < bodySubdivisions; ++slice) { // eslint-disable-line
for (let ring = 0; ring < radialSubdivisions; ++ring) { // eslint-disable-line
const nextRingIndex = 1 + ring;
const nextSliceIndex = 1 + slice;
indices.push(radialParts * slice + ring,
radialParts * nextSliceIndex + ring,
radialParts * slice + nextRingIndex);
indices.push(radialParts * nextSliceIndex + ring,
radialParts * nextSliceIndex + nextRingIndex,
radialParts * slice + nextRingIndex);
}
}
return {
position: positions,
normal: normals,
texcoord: texcoords,
indices: indices,
};
}
|
javascript
|
{
"resource": ""
}
|
q23835
|
createDiscVertices
|
train
|
function createDiscVertices(
radius,
divisions,
stacks,
innerRadius,
stackPower) {
if (divisions < 3) {
throw Error('divisions must be at least 3');
}
stacks = stacks ? stacks : 1;
stackPower = stackPower ? stackPower : 1;
innerRadius = innerRadius ? innerRadius : 0;
// Note: We don't share the center vertex because that would
// mess up texture coordinates.
const numVertices = (divisions + 1) * (stacks + 1);
const positions = createAugmentedTypedArray(3, numVertices);
const normals = createAugmentedTypedArray(3, numVertices);
const texcoords = createAugmentedTypedArray(2, numVertices);
const indices = createAugmentedTypedArray(3, stacks * divisions * 2, Uint16Array);
let firstIndex = 0;
const radiusSpan = radius - innerRadius;
const pointsPerStack = divisions + 1;
// Build the disk one stack at a time.
for (let stack = 0; stack <= stacks; ++stack) {
const stackRadius = innerRadius + radiusSpan * Math.pow(stack / stacks, stackPower);
for (let i = 0; i <= divisions; ++i) {
const theta = 2.0 * Math.PI * i / divisions;
const x = stackRadius * Math.cos(theta);
const z = stackRadius * Math.sin(theta);
positions.push(x, 0, z);
normals.push(0, 1, 0);
texcoords.push(1 - (i / divisions), stack / stacks);
if (stack > 0 && i !== divisions) {
// a, b, c and d are the indices of the vertices of a quad. unless
// the current stack is the one closest to the center, in which case
// the vertices a and b connect to the center vertex.
const a = firstIndex + (i + 1);
const b = firstIndex + i;
const c = firstIndex + i - pointsPerStack;
const d = firstIndex + (i + 1) - pointsPerStack;
// Make a quad of the vertices a, b, c, d.
indices.push(a, b, c);
indices.push(a, c, d);
}
}
firstIndex += divisions + 1;
}
return {
position: positions,
normal: normals,
texcoord: texcoords,
indices: indices,
};
}
|
javascript
|
{
"resource": ""
}
|
q23836
|
createBufferFunc
|
train
|
function createBufferFunc(fn) {
return function(gl) {
const arrays = fn.apply(this, Array.prototype.slice.call(arguments, 1));
return attributes.createBuffersFromArrays(gl, arrays);
};
}
|
javascript
|
{
"resource": ""
}
|
q23837
|
createBufferInfoFunc
|
train
|
function createBufferInfoFunc(fn) {
return function(gl) {
const arrays = fn.apply(null, Array.prototype.slice.call(arguments, 1));
return attributes.createBufferInfoFromArrays(gl, arrays);
};
}
|
javascript
|
{
"resource": ""
}
|
q23838
|
copyElements
|
train
|
function copyElements(src, dst, dstNdx, offset) {
offset = offset || 0;
const length = src.length;
for (let ii = 0; ii < length; ++ii) {
dst[dstNdx + ii] = src[ii] + offset;
}
}
|
javascript
|
{
"resource": ""
}
|
q23839
|
createArrayOfSameType
|
train
|
function createArrayOfSameType(srcArray, length) {
const arraySrc = getArray(srcArray);
const newArray = new arraySrc.constructor(length);
let newArraySpec = newArray;
// If it appears to have been augmented make new one augemented
if (arraySrc.numComponents && arraySrc.numElements) {
augmentTypedArray(newArray, arraySrc.numComponents);
}
// If it was a fullspec make new one a fullspec
if (srcArray.data) {
newArraySpec = {
data: newArray,
};
helper.copyNamedProperties(arraySpecPropertyNames, srcArray, newArraySpec);
}
return newArraySpec;
}
|
javascript
|
{
"resource": ""
}
|
q23840
|
concatVertices
|
train
|
function concatVertices(arrayOfArrays) {
const names = {};
let baseName;
// get names of all arrays.
// and numElements for each set of vertices
for (let ii = 0; ii < arrayOfArrays.length; ++ii) {
const arrays = arrayOfArrays[ii];
Object.keys(arrays).forEach(function(name) { // eslint-disable-line
if (!names[name]) {
names[name] = [];
}
if (!baseName && name !== 'indices') {
baseName = name;
}
const arrayInfo = arrays[name];
const numComponents = getNumComponents(arrayInfo, name);
const array = getArray(arrayInfo);
const numElements = array.length / numComponents;
names[name].push(numElements);
});
}
// compute length of combined array
// and return one for reference
function getLengthOfCombinedArrays(name) {
let length = 0;
let arraySpec;
for (let ii = 0; ii < arrayOfArrays.length; ++ii) {
const arrays = arrayOfArrays[ii];
const arrayInfo = arrays[name];
const array = getArray(arrayInfo);
length += array.length;
if (!arraySpec || arrayInfo.data) {
arraySpec = arrayInfo;
}
}
return {
length: length,
spec: arraySpec,
};
}
function copyArraysToNewArray(name, base, newArray) {
let baseIndex = 0;
let offset = 0;
for (let ii = 0; ii < arrayOfArrays.length; ++ii) {
const arrays = arrayOfArrays[ii];
const arrayInfo = arrays[name];
const array = getArray(arrayInfo);
if (name === 'indices') {
copyElements(array, newArray, offset, baseIndex);
baseIndex += base[ii];
} else {
copyElements(array, newArray, offset);
}
offset += array.length;
}
}
const base = names[baseName];
const newArrays = {};
Object.keys(names).forEach(function(name) {
const info = getLengthOfCombinedArrays(name);
const newArraySpec = createArrayOfSameType(info.spec, info.length);
copyArraysToNewArray(name, base, getArray(newArraySpec));
newArrays[name] = newArraySpec;
});
return newArrays;
}
|
javascript
|
{
"resource": ""
}
|
q23841
|
getLengthOfCombinedArrays
|
train
|
function getLengthOfCombinedArrays(name) {
let length = 0;
let arraySpec;
for (let ii = 0; ii < arrayOfArrays.length; ++ii) {
const arrays = arrayOfArrays[ii];
const arrayInfo = arrays[name];
const array = getArray(arrayInfo);
length += array.length;
if (!arraySpec || arrayInfo.data) {
arraySpec = arrayInfo;
}
}
return {
length: length,
spec: arraySpec,
};
}
|
javascript
|
{
"resource": ""
}
|
q23842
|
duplicateVertices
|
train
|
function duplicateVertices(arrays) {
const newArrays = {};
Object.keys(arrays).forEach(function(name) {
const arraySpec = arrays[name];
const srcArray = getArray(arraySpec);
const newArraySpec = createArrayOfSameType(arraySpec, srcArray.length);
copyElements(srcArray, getArray(newArraySpec), 0);
newArrays[name] = newArraySpec;
});
return newArrays;
}
|
javascript
|
{
"resource": ""
}
|
q23843
|
printKey
|
train
|
function printKey () {
let keyid = printKeyid(this.primaryKey.getKeyId())
let userid = printUser(this.getPrimaryUser().user)
return keyid + ' ' + userid
}
|
javascript
|
{
"resource": ""
}
|
q23844
|
otherVarIntDecode
|
train
|
function otherVarIntDecode (reader, startWith) {
let result = startWith
let shift = 4
let byte = null
do {
byte = reader.readUInt8()
result |= (byte & 0b01111111) << shift
shift += 7
} while (byte & 0b10000000)
return result
}
|
javascript
|
{
"resource": ""
}
|
q23845
|
parseCacheEntryFlags
|
train
|
function parseCacheEntryFlags (bits) {
return {
assumeValid: Boolean(bits & 0b1000000000000000),
extended: Boolean(bits & 0b0100000000000000),
stage: (bits & 0b0011000000000000) >> 12,
nameLength: bits & 0b0000111111111111
}
}
|
javascript
|
{
"resource": ""
}
|
q23846
|
fillInit
|
train
|
function fillInit() {
console.log('\nThis utility will generate a resume.json file in your current working directory.');
console.log('Fill out your name and email to get started, or leave the fields blank.');
console.log('All fields are optional.\n');
console.log('Press ^C at any time to quit.');
read({
prompt: 'name: '
}, function(er, name) {
if (er) {
console.log();
process.exit();
}
read({
prompt: 'email: '
}, function(er, email) {
if (er) {
console.log();
process.exit();
}
resumeJson.basics.name = name;
resumeJson.basics.email = email;
fs.writeFileSync(process.cwd() + '/resume.json', JSON.stringify(resumeJson, undefined, 2));
console.log('\nYour resume.json has been created!'.green);
console.log('');
console.log('To generate a formatted .html .md .txt or .pdf resume from your resume.json');
console.log('type: `resume export [someFileName]` including file extension eg: `resume export myresume.html`');
console.log('\nYou can optionally specify an available theme for html and pdf resumes using the --theme flag.');
console.log('Example: `resume export myresume.pdf --theme flat`');
console.log('Or simply type: `resume export` and follow the prompts.');
console.log('');
process.exit();
callback(true);
});
});
}
|
javascript
|
{
"resource": ""
}
|
q23847
|
ToonAnimationMaterial
|
train
|
function ToonAnimationMaterial(parameters) {
if (!parameters.defines) {
parameters.defines = {};
}
parameters.defines['TOON'] = '';
PhongAnimationMaterial.call(this, parameters);
}
|
javascript
|
{
"resource": ""
}
|
q23848
|
MultiPrefabBufferGeometry
|
train
|
function MultiPrefabBufferGeometry(prefabs, repeatCount) {
BufferGeometry.call(this);
if (Array.isArray(prefabs)) {
this.prefabGeometries = prefabs;
} else {
this.prefabGeometries = [prefabs];
}
this.prefabGeometriesCount = this.prefabGeometries.length;
/**
* Number of prefabs.
* @type {Number}
*/
this.prefabCount = repeatCount * this.prefabGeometriesCount;
/**
* How often the prefab array is repeated.
* @type {Number}
*/
this.repeatCount = repeatCount;
/**
* Array of vertex counts per prefab.
* @type {Array}
*/
this.prefabVertexCounts = this.prefabGeometries.map(function (p) {
return p.isBufferGeometry ? p.attributes.position.count : p.vertices.length;
});
/**
* Total number of vertices for one repetition of the prefabs
* @type {number}
*/
this.repeatVertexCount = this.prefabVertexCounts.reduce(function (r, v) {
return r + v;
}, 0);
this.bufferIndices();
this.bufferPositions();
}
|
javascript
|
{
"resource": ""
}
|
q23849
|
InstancedPrefabBufferGeometry
|
train
|
function InstancedPrefabBufferGeometry(prefab, count) {
if (prefab.isGeometry === true) {
console.error('InstancedPrefabBufferGeometry prefab must be a BufferGeometry.');
}
InstancedBufferGeometry.call(this);
this.prefabGeometry = prefab;
this.copy(prefab);
this.maxInstancedCount = count;
this.prefabCount = count;
}
|
javascript
|
{
"resource": ""
}
|
q23850
|
separateFaces
|
train
|
function separateFaces(geometry) {
var vertices = [];
for (var i = 0, il = geometry.faces.length; i < il; i++) {
var n = vertices.length;
var face = geometry.faces[i];
var a = face.a;
var b = face.b;
var c = face.c;
var va = geometry.vertices[a];
var vb = geometry.vertices[b];
var vc = geometry.vertices[c];
vertices.push(va.clone());
vertices.push(vb.clone());
vertices.push(vc.clone());
face.a = n;
face.b = n + 1;
face.c = n + 2;
}
geometry.vertices = vertices;
}
|
javascript
|
{
"resource": ""
}
|
q23851
|
createDepthAnimationMaterial
|
train
|
function createDepthAnimationMaterial(sourceMaterial) {
return new DepthAnimationMaterial({
uniforms: sourceMaterial.uniforms,
defines: sourceMaterial.defines,
vertexFunctions: sourceMaterial.vertexFunctions,
vertexParameters: sourceMaterial.vertexParameters,
vertexInit: sourceMaterial.vertexInit,
vertexPosition: sourceMaterial.vertexPosition
});
}
|
javascript
|
{
"resource": ""
}
|
q23852
|
createDistanceAnimationMaterial
|
train
|
function createDistanceAnimationMaterial(sourceMaterial) {
return new DistanceAnimationMaterial({
uniforms: sourceMaterial.uniforms,
defines: sourceMaterial.defines,
vertexFunctions: sourceMaterial.vertexFunctions,
vertexParameters: sourceMaterial.vertexParameters,
vertexInit: sourceMaterial.vertexInit,
vertexPosition: sourceMaterial.vertexPosition
});
}
|
javascript
|
{
"resource": ""
}
|
q23853
|
ModelBufferGeometry
|
train
|
function ModelBufferGeometry(model, options) {
BufferGeometry.call(this);
/**
* A reference to the geometry used to create this instance.
* @type {THREE.Geometry}
*/
this.modelGeometry = model;
/**
* Number of faces of the model.
* @type {Number}
*/
this.faceCount = this.modelGeometry.faces.length;
/**
* Number of vertices of the model.
* @type {Number}
*/
this.vertexCount = this.modelGeometry.vertices.length;
options = options || {};
options.computeCentroids && this.computeCentroids();
this.bufferIndices();
this.bufferPositions(options.localizeFaces);
}
|
javascript
|
{
"resource": ""
}
|
q23854
|
train
|
function (start, end) {
var total = 0;
start = start || 0;
end = end || this.binCount;
for (var i = start; i < end; i++) {
total += this.frequencyByteData[i];
}
return total / (end - start);
}
|
javascript
|
{
"resource": ""
}
|
|
q23855
|
getRandomPointOnSphere
|
train
|
function getRandomPointOnSphere(r) {
var u = THREE.Math.randFloat(0, 1);
var v = THREE.Math.randFloat(0, 1);
var theta = 2 * Math.PI * u;
var phi = Math.acos(2 * v - 1);
var x = r * Math.sin(theta) * Math.sin(phi);
var y = r * Math.cos(theta) * Math.sin(phi);
var z = r * Math.cos(phi);
return {
x,
y,
z,
};
}
|
javascript
|
{
"resource": ""
}
|
q23856
|
getPointsOnPicture
|
train
|
function getPointsOnPicture(selector) {
var img = document.querySelector(selector);
var width = img.width;
var height = img.height;
var canvas = document.createElement('canvas');
document.body.appendChild(canvas);
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0, width, height);
var imgData = ctx.getImageData(0, 0, width, height);
var points = [];
var xStep = 8;
var yStep = 8;
for (var x = 0; x < width; x += xStep) {
for (var y = 0; y < height; y += yStep) {
var i = (y * width + x) * 4;
// not collect the points for alpha is zero
if (imgData.data[i + 4] <= 0) {
continue;
}
points.push({
x: x - width / 2,
y: -(y - height / 2),
z: 0,
r: imgData.data[i] / 255,
g: imgData.data[i + 1] / 255,
b: imgData.data[i + 2] / 255,
a: imgData.data[i + 3] / 255,
});
}
}
return points;
}
|
javascript
|
{
"resource": ""
}
|
q23857
|
BasicAnimationMaterial
|
train
|
function BasicAnimationMaterial(parameters) {
this.varyingParameters = [];
this.vertexParameters = [];
this.vertexFunctions = [];
this.vertexInit = [];
this.vertexNormal = [];
this.vertexPosition = [];
this.vertexColor = [];
this.vertexPostMorph = [];
this.vertexPostSkinning = [];
this.fragmentFunctions = [];
this.fragmentParameters = [];
this.fragmentInit = [];
this.fragmentMap = [];
this.fragmentDiffuse = [];
BaseAnimationMaterial.call(this, parameters, three.ShaderLib['basic'].uniforms);
this.lights = false;
this.vertexShader = this.concatVertexShader();
this.fragmentShader = this.concatFragmentShader();
}
|
javascript
|
{
"resource": ""
}
|
q23858
|
PointsAnimationMaterial
|
train
|
function PointsAnimationMaterial(parameters) {
this.varyingParameters = [];
this.vertexFunctions = [];
this.vertexParameters = [];
this.vertexInit = [];
this.vertexPosition = [];
this.vertexColor = [];
this.fragmentFunctions = [];
this.fragmentParameters = [];
this.fragmentInit = [];
this.fragmentMap = [];
this.fragmentDiffuse = [];
// use fragment shader to shape to point, reference: https://thebookofshaders.com/07/
this.fragmentShape = [];
BaseAnimationMaterial.call(this, parameters, three.ShaderLib['points'].uniforms);
this.vertexShader = this.concatVertexShader();
this.fragmentShader = this.concatFragmentShader();
}
|
javascript
|
{
"resource": ""
}
|
q23859
|
PrefabBufferGeometry
|
train
|
function PrefabBufferGeometry(prefab, count) {
three.BufferGeometry.call(this);
/**
* A reference to the prefab geometry used to create this instance.
* @type {Geometry|BufferGeometry}
*/
this.prefabGeometry = prefab;
this.isPrefabBufferGeometry = prefab.isBufferGeometry;
/**
* Number of prefabs.
* @type {Number}
*/
this.prefabCount = count;
/**
* Number of vertices of the prefab.
* @type {Number}
*/
if (this.isPrefabBufferGeometry) {
this.prefabVertexCount = prefab.attributes.position.count;
} else {
this.prefabVertexCount = prefab.vertices.length;
}
this.bufferIndices();
this.bufferPositions();
}
|
javascript
|
{
"resource": ""
}
|
q23860
|
RpcNotification
|
train
|
function RpcNotification(method, params)
{
if(defineProperty_IE8)
{
this.method = method
this.params = params
}
else
{
Object.defineProperty(this, 'method', {value: method, enumerable: true});
Object.defineProperty(this, 'params', {value: params, enumerable: true});
}
}
|
javascript
|
{
"resource": ""
}
|
q23861
|
storeResponse
|
train
|
function storeResponse(message, id, dest)
{
var response =
{
message: message,
/** Timeout to auto-clean old responses */
timeout: setTimeout(function()
{
responses.remove(id, dest);
},
response_timeout)
};
responses.set(response, id, dest);
}
|
javascript
|
{
"resource": ""
}
|
q23862
|
storeProcessedResponse
|
train
|
function storeProcessedResponse(ack, from)
{
var timeout = setTimeout(function()
{
processedResponses.remove(ack, from);
},
duplicates_timeout);
processedResponses.set(timeout, ack, from);
}
|
javascript
|
{
"resource": ""
}
|
q23863
|
formatter
|
train
|
function formatter(data, parentAuthority, parentName) {
if (!data) {
return undefined;
}
return data
.map(item => {
if (!item.name || !item.path) {
return null;
}
let locale = 'menu';
if (parentName && parentName !== '/') {
locale = `${parentName}.${item.name}`;
} else {
locale = `menu.${item.name}`;
}
const result = {
...item,
title:locale
};
if (item.routes) {
const children = formatter(item.routes, item.authority, locale);
// Reduce memory usage
result.children = children;
}
delete result.routes;
return result;
})
.filter(item => item);
}
|
javascript
|
{
"resource": ""
}
|
q23864
|
getByte
|
train
|
function getByte(array, position, length) {
const d = position % 8;
const a = Math.floor(position / 8);
const de = 8 - d;
const ef = (position + length) - ((a + 1) * 8);
let fg = (8 * (a + 2)) - (position + length);
const dg = ((a + 2) * 8) - position;
fg = Math.max(0, fg);
if (a >= array.length) {
console.warn('ran off the end of the buffer before finding EOI_CODE (end on input code)');
return EOI_CODE;
}
let chunk1 = array[a] & ((2 ** (8 - d)) - 1);
chunk1 <<= (length - de);
let chunks = chunk1;
if (a + 1 < array.length) {
let chunk2 = array[a + 1] >>> fg;
chunk2 <<= Math.max(0, (length - dg));
chunks += chunk2;
}
if (ef > 8 && a + 2 < array.length) {
const hi = ((a + 3) * 8) - (position + length);
const chunk3 = array[a + 2] >>> hi;
chunks += chunk3;
}
return chunks;
}
|
javascript
|
{
"resource": ""
}
|
q23865
|
train
|
function(element, options) {
var that = this;
that.name = NAME;
that.$ = $(element);
options = that.options = $.extend({}, Pager.DEFAULTS, this.$.data(), options);
var lang = options.lang || $.zui.clientLang();
that.lang = $.isPlainObject(lang) ? ($.extend(true, {}, LANG[lang.lang || $.zui.clientLang()], lang)) : LANG[lang];
that.state = {};
that.set(options.page, options.recTotal, options.recPerPage, true);
that.$.on('click', '.pager-goto-btn', function() {
var $goto = $(this).closest('.pager-goto');
var page = parseInt($goto.find('.pager-goto-input').val());
if (page !== NaN) {
that.set(page);
}
}).on('click', '.pager-item', function() {
var page = $(this).data('page');
if (typeof page === 'number' && page > 0) {
that.set(page);
}
}).on('click', '.pager-size-menu [data-size]', function() {
var size = $(this).data('size');
if (typeof size === 'number' && size > 0) {
that.set(-1, -1, size);
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q23866
|
train
|
function () {
var ie = this.isIE() || this.isIE10() || false;
if (ie) {
for (var i = 10; i > 5; i--) {
if (this.isIE(i)) {
ie = i;
break;
}
}
}
this.ie = ie;
this.cssHelper();
}
|
javascript
|
{
"resource": ""
}
|
|
q23867
|
train
|
function() {
// Since window has its own native 'resize' event, return false so that
// jQuery will bind the event using DOM methods. Since only 'window'
// objects have a .setTimeout method, this should be a sufficient test.
// Unless, of course, we're throttling the 'resize' event for window.
if(!jq_resize[str_throttle] && this[str_setTimeout]) {
return false;
}
var elem = $(this);
// Add this element to the list of internal elements to monitor.
elems = elems.add(elem);
// Initialize data store on the element.
$.data(this, str_data, {
w: elem.width(),
h: elem.height()
});
// If this is the first element added, start the polling loop.
if(elems.length === 1) {
loopy();
}
}
|
javascript
|
{
"resource": ""
}
|
|
q23868
|
train
|
function() {
// Since window has its own native 'resize' event, return false so that
// jQuery will unbind the event using DOM methods. Since only 'window'
// objects have a .setTimeout method, this should be a sufficient test.
// Unless, of course, we're throttling the 'resize' event for window.
if(!jq_resize[str_throttle] && this[str_setTimeout]) {
return false;
}
var elem = $(this);
// Remove this element from the list of internal elements to monitor.
elems = elems.not(elem);
// Remove any data stored on the element.
elem.removeData(str_data);
// If this is the last element removed, stop the polling loop.
if(!elems.length) {
clearTimeout(timeout_id);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q23869
|
new_handler
|
train
|
function new_handler(e, w, h) {
var elem = $(this),
data = $.data(this, str_data) || {};
// If called from the polling loop, w and h will be passed in as
// arguments. If called manually, via .trigger( 'resize' ) or .resize(),
// those values will need to be computed.
data.w = w !== undefined ? w : elem.width();
data.h = h !== undefined ? h : elem.height();
old_handler.apply(this, arguments);
}
|
javascript
|
{
"resource": ""
}
|
q23870
|
train
|
function(modal, callback, redirect) {
var originModal = modal;
if($.isFunction(modal)) {
var oldModal = redirect;
redirect = callback;
callback = modal;
modal = oldModal;
}
modal = getModal(modal);
if(modal && modal.length) {
modal.each(function() {
$(this).data(NAME).close(callback, redirect);
});
} else if(!$('body').hasClass('modal-open') && !$('.modal.in').length) {
// check if current page is as modal iframe
if ($('body').hasClass('body-modal')) {
window.parent.$.zui.closeModal(originModal, callback, redirect);
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q23871
|
train
|
function(element, options) {
var that = this;
that.name = NAME;
that.$ = $(element);
options = that.options = $.extend({trigger: 'contextmenu'}, ContextMenu.DEFAULTS, this.$.data(), options);
var trigger = options.trigger;
that.id = $.zui.uuid();
var eventHandler = function(e) {
if (e.type === 'mousedown' && e.button !== 2) {
return;
}
var config = {
x: e.clientX,
y: e.clientY,
event: e
};
if (options.itemsCreator) {
config.items = options.itemsCreator.call(this, e);
}
that.show(config);
e.preventDefault();
e.returnValue = false; // 解决IE8右键弹出
return false;
};
var eventName = trigger + '.' + NAME;
if (options.selector) {
that.$.on(eventName, options.selector, eventHandler);
} else {
that.$.on(eventName, eventHandler);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q23872
|
train
|
function () {
if (document.body) {
// make sure all resources are loaded on first activation
if (!loaded) Live.loadresources();
Live.checkForChanges();
}
setTimeout(Live.heartbeat, interval);
}
|
javascript
|
{
"resource": ""
}
|
|
q23873
|
train
|
function () {
// helper method to assert if a given url is local
function isLocal(url) {
var loc = document.location,
reg = new RegExp("^\\.|^\/(?!\/)|^[\\w]((?!://).)*$|" + loc.protocol + "//" + loc.host);
return url.match(reg);
}
// gather all resources
var scripts = document.getElementsByTagName("script"),
links = document.getElementsByTagName("link"),
uris = [];
// track local js urls
for (var i = 0; i < scripts.length; i++) {
var script = scripts[i], src = script.getAttribute("src");
if (src && isLocal(src))
uris.push(src);
if (src && src.match(/\blive.js#/)) {
for (var type in active)
active[type] = src.match("[#,|]" + type) != null
if (src.match("notify"))
alert("Live.js is loaded.");
}
}
if (!active.js) uris = [];
if (active.html) uris.push(document.location.href);
// track local css urls
for (var i = 0; i < links.length && active.css; i++) {
var link = links[i], rel = link.getAttribute("rel"), href = link.getAttribute("href", 2);
if (href && rel && rel.match(new RegExp("stylesheet", "i")) && isLocal(href)) {
uris.push(href);
currentLinkElements[href] = link;
}
}
// initialize the resources info
for (var i = 0; i < uris.length; i++) {
var url = uris[i];
Live.getHead(url, function (url, info) {
resources[url] = info;
});
}
// add rule for morphing between old and new css files
var head = document.getElementsByTagName("head")[0],
style = document.createElement("style"),
rule = "transition: all .3s ease-out;"
css = [".livejs-loading * { ", rule, " -webkit-", rule, "-moz-", rule, "-o-", rule, "}"].join('');
style.setAttribute("type", "text/css");
head.appendChild(style);
style.styleSheet ? style.styleSheet.cssText = css : style.appendChild(document.createTextNode(css));
// yep
loaded = true;
}
|
javascript
|
{
"resource": ""
}
|
|
q23874
|
isLocal
|
train
|
function isLocal(url) {
var loc = document.location,
reg = new RegExp("^\\.|^\/(?!\/)|^[\\w]((?!://).)*$|" + loc.protocol + "//" + loc.host);
return url.match(reg);
}
|
javascript
|
{
"resource": ""
}
|
q23875
|
train
|
function () {
for (var url in resources) {
if (pendingRequests[url])
continue;
Live.getHead(url, function (url, newInfo) {
var oldInfo = resources[url],
hasChanged = false;
resources[url] = newInfo;
for (var header in oldInfo) {
// do verification based on the header type
var oldValue = oldInfo[header],
newValue = newInfo[header],
contentType = newInfo["Content-Type"];
switch (header.toLowerCase()) {
case "etag":
if (!newValue) break;
// fall through to default
default:
hasChanged = oldValue != newValue;
break;
}
// if changed, act
if (hasChanged) {
Live.refreshResource(url, contentType);
break;
}
}
});
}
}
|
javascript
|
{
"resource": ""
}
|
|
q23876
|
train
|
function (url, type) {
switch (type.toLowerCase()) {
// css files can be reloaded dynamically by replacing the link element
case "text/css":
var link = currentLinkElements[url],
html = document.body.parentNode,
head = link.parentNode,
next = link.nextSibling,
newLink = document.createElement("link");
html.className = html.className.replace(/\s*livejs\-loading/gi, '') + ' livejs-loading';
newLink.setAttribute("type", "text/css");
newLink.setAttribute("rel", "stylesheet");
newLink.setAttribute("href", url + "?now=" + new Date() * 1);
next ? head.insertBefore(newLink, next) : head.appendChild(newLink);
currentLinkElements[url] = newLink;
oldLinkElements[url] = link;
// schedule removal of the old link
Live.removeoldLinkElements();
break;
// check if an html resource is our current url, then reload
case "text/html":
if (url != document.location.href)
return;
// local javascript changes cause a reload as well
case "text/javascript":
case "application/javascript":
case "application/x-javascript":
document.location.reload();
}
}
|
javascript
|
{
"resource": ""
}
|
|
q23877
|
train
|
function () {
var pending = 0;
for (var url in oldLinkElements) {
// if this sheet has any cssRules, delete the old link
try {
var link = currentLinkElements[url],
oldLink = oldLinkElements[url],
html = document.body.parentNode,
sheet = link.sheet || link.styleSheet,
rules = sheet.rules || sheet.cssRules;
if (rules.length >= 0) {
oldLink.parentNode.removeChild(oldLink);
delete oldLinkElements[url];
setTimeout(function () {
html.className = html.className.replace(/\s*livejs\-loading/gi, '');
}, 100);
}
} catch (e) {
pending++;
}
if (pending) setTimeout(Live.removeoldLinkElements, 50);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q23878
|
train
|
function (url, callback) {
pendingRequests[url] = true;
var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XmlHttp");
xhr.open("HEAD", url, true);
xhr.onreadystatechange = function () {
delete pendingRequests[url];
if (xhr.readyState == 4 && xhr.status != 304) {
xhr.getAllResponseHeaders();
var info = {};
for (var h in headers) {
var value = xhr.getResponseHeader(h);
// adjust the simple Etag variant to match on its significant part
if (h.toLowerCase() == "etag" && value) value = value.replace(/^W\//, '');
if (h.toLowerCase() == "content-type" && value) value = value.replace(/^(.*?);.*?$/i, "$1");
info[h] = value;
}
callback(url, info);
}
}
xhr.send();
}
|
javascript
|
{
"resource": ""
}
|
|
q23879
|
train
|
function(element, options) {
var that = this;
that.name = NAME;
that.$ = $(element);
that.options = $.extend({}, MarkDoc.DEFAULTS, this.$.data(), options);
that.$.data('originContent', that.$.text());
that.render();
}
|
javascript
|
{
"resource": ""
}
|
|
q23880
|
train
|
function(easeDecimal) {
var animDecimal = (easeDecimal) ? easeDecimal : 1;
this.clear();
// ZUI change begin
var labelPositionMap;
// ZUI change end
helpers.each(this.segments, function(segment, index) {
segment.transition({
circumference: this.calculateCircumference(segment.value),
outerRadius: this.outerRadius,
innerRadius: (this.outerRadius / 100) * this.options.percentageInnerCutout
}, animDecimal);
segment.endAngle = segment.startAngle + segment.circumference;
// ZUI change begin
if (!this.options.reverseDrawOrder) {
// ZUI change end
// ZUI change begin
segment.draw();
// ZUI change end
}
// ZUI change end
if(index === 0) {
segment.startAngle = Math.PI * 1.5;
}
//Check to see if it's the last segment, if not get the next and update the start angle
if(index < this.segments.length - 1) {
this.segments[index + 1].startAngle = segment.endAngle;
}
}, this);
// ZUI change begin
if (this.options.reverseDrawOrder) {
helpers.each(this.segments.slice().reverse(), function(segment, index) {
segment.draw();
}, this);
}
/// ZUI change end
/// ZUI change begin
if(this.options.scaleShowLabels) {
var segmentsArray = this.segments.slice().sort(function(a,b){return b.value - a.value;});
var labelPositionMap = {};
helpers.each(segmentsArray, function(segment, index) {
if(segment.showLabel) this.drawLabel(segment, easeDecimal, labelPositionMap);
}, this);
}
/// ZUI change end
}
|
javascript
|
{
"resource": ""
}
|
|
q23881
|
normalizeCaps
|
train
|
function normalizeCaps(settings) {
var features = settings.required_features, caps = {};
function resolve(feature, value, strict) {
// Feature notation is deprecated, use caps (this thing here is required for backward compatibility)
var map = {
chunks: 'slice_blob',
jpgresize: 'send_binary_string',
pngresize: 'send_binary_string',
progress: 'report_upload_progress',
multi_selection: 'select_multiple',
dragdrop: 'drag_and_drop',
drop_element: 'drag_and_drop',
headers: 'send_custom_headers',
urlstream_upload: 'send_binary_string',
canSendBinary: 'send_binary',
triggerDialog: 'summon_file_dialog'
};
if (map[feature]) {
caps[map[feature]] = value;
} else if (!strict) {
caps[feature] = value;
}
}
if (typeof(features) === 'string') {
plupload.each(features.split(/\s*,\s*/), function(feature) {
resolve(feature, true);
});
} else if (typeof(features) === 'object') {
plupload.each(features, function(value, feature) {
resolve(feature, value);
});
} else if (features === true) {
// check settings for required features
if (settings.chunk_size && settings.chunk_size > 0) {
caps.slice_blob = true;
}
if (!plupload.isEmptyObj(settings.resize) || settings.multipart === false) {
caps.send_binary_string = true;
}
if (settings.http_method) {
caps.use_http_method = settings.http_method;
}
plupload.each(settings, function(value, feature) {
resolve(feature, !!value, true); // strict check
});
}
return caps;
}
|
javascript
|
{
"resource": ""
}
|
q23882
|
train
|
function(str) {
var xmlEncodeChars = {'<' : 'lt', '>' : 'gt', '&' : 'amp', '"' : 'quot', '\'' : '#39'}, xmlEncodeRegExp = /[<>&\"\']/g;
return str ? ('' + str).replace(xmlEncodeRegExp, function(chr) {
return xmlEncodeChars[chr] ? '&' + xmlEncodeChars[chr] + ';' : chr;
}) : str;
}
|
javascript
|
{
"resource": ""
}
|
|
q23883
|
train
|
function(url, items) {
var query = '';
plupload.each(items, function(value, name) {
query += (query ? '&' : '') + encodeURIComponent(name) + '=' + encodeURIComponent(value);
});
if (query) {
url += (url.indexOf('?') > 0 ? '&' : '?') + query;
}
return url;
}
|
javascript
|
{
"resource": ""
}
|
|
q23884
|
train
|
function(size) {
if (size === undef || /\D/.test(size)) {
return plupload.translate('N/A');
}
function round(num, precision) {
return Math.round(num * Math.pow(10, precision)) / Math.pow(10, precision);
}
var boundary = Math.pow(1024, 4);
// TB
if (size > boundary) {
return round(size / boundary, 1) + " " + plupload.translate('tb');
}
// GB
if (size > (boundary/=1024)) {
return round(size / boundary, 1) + " " + plupload.translate('gb');
}
// MB
if (size > (boundary/=1024)) {
return round(size / boundary, 1) + " " + plupload.translate('mb');
}
// KB
if (size > 1024) {
return Math.round(size / 1024) + " " + plupload.translate('kb');
}
return size + " " + plupload.translate('b');
}
|
javascript
|
{
"resource": ""
}
|
|
q23885
|
onBeforeUpload
|
train
|
function onBeforeUpload(up, file) {
// Generate unique target filenames
if (up.settings.unique_names) {
var matches = file.name.match(/\.([^.]+)$/), ext = "part";
if (matches) {
ext = matches[1];
}
file.target_name = file.id + '.' + ext;
}
}
|
javascript
|
{
"resource": ""
}
|
q23886
|
train
|
function(id) {
var i;
for (i = files.length - 1; i >= 0; i--) {
if (files[i].id === id) {
return files[i];
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q23887
|
train
|
function(file) {
var id = typeof(file) === 'string' ? file : file.id;
for (var i = files.length - 1; i >= 0; i--) {
if (files[i].id === id) {
return this.splice(i, 1)[0];
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q23888
|
train
|
function(start, length) {
// Splice and trigger events
var removed = files.splice(start === undef ? 0 : start, length === undef ? files.length : length);
// if upload is in progress we need to stop it and restart after files are removed
var restartRequired = false;
if (this.state == plupload.STARTED) { // upload in progress
plupload.each(removed, function(file) {
if (file.status === plupload.UPLOADING) {
restartRequired = true; // do not restart, unless file that is being removed is uploading
return false;
}
});
if (restartRequired) {
this.stop();
}
}
this.trigger("FilesRemoved", removed);
// Dispose any resources allocated by those files
plupload.each(removed, function(file) {
file.destroy();
});
if (restartRequired) {
this.start();
}
return removed;
}
|
javascript
|
{
"resource": ""
}
|
|
q23889
|
train
|
function(type) {
var list, args, result;
type = type.toLowerCase();
list = this.hasEventListener(type);
if (list) {
// sort event list by priority
list.sort(function(a, b) { return b.priority - a.priority; });
// first argument should be current plupload.Uploader instance
args = [].slice.call(arguments);
args.shift();
args.unshift(this);
for (var i = 0; i < list.length; i++) {
// Fire event, break chain if false is returned
if (list[i].fn.apply(list[i].scope, args) === false) {
return false;
}
}
}
return true;
}
|
javascript
|
{
"resource": ""
}
|
|
q23890
|
train
|
function() {
var file = this.getSource().getSource();
return plupload.inArray(plupload.typeOf(file), ['blob', 'file']) !== -1 ? file : null;
}
|
javascript
|
{
"resource": ""
}
|
|
q23891
|
train
|
function(element, options) {
this.name = name;
this.$ = $(element);
this.id = $.zui.uuid();
this.selectOrder = 1;
this.selections = {};
this.getOptions(options);
this._init();
}
|
javascript
|
{
"resource": ""
}
|
|
q23892
|
getTagState
|
train
|
function getTagState(string) {
for (let i = string.length - 1; i >= 0; i--) {
const char = string[i];
if (char === '>') {
return 0;
} else if (char === '<') {
return 1;
}
}
return -1;
}
|
javascript
|
{
"resource": ""
}
|
q23893
|
unsafeHTMLDirective
|
train
|
function unsafeHTMLDirective(value) {
return function(part) {
if (!isNodePart(part)) {
throw Error('The `unsafeHTML` directive can only be used in text nodes');
}
part.setValue(`${unsafePrefixString}${value}`);
};
}
|
javascript
|
{
"resource": ""
}
|
q23894
|
reduce
|
train
|
function reduce(buffer, chunks, chunk, deep = false) {
if (Buffer.isBuffer(chunk)) {
return Buffer.concat([buffer, chunk], buffer.length + chunk.length);
} else if (isTemplateResult(chunk)) {
if (deep) {
return reduce(buffer, chunks, chunk.read(deep), deep);
} else {
chunks.push(buffer, chunk);
return emptyStringBuffer;
}
} else if (Array.isArray(chunk)) {
return chunk.reduce((buffer, chunk) => reduce(buffer, chunks, chunk), buffer);
} else if (isPromise(chunk) || isAsyncIterator(chunk)) {
chunks.push(buffer, chunk);
return emptyStringBuffer;
}
}
|
javascript
|
{
"resource": ""
}
|
q23895
|
repeatDirective
|
train
|
function repeatDirective(items, keyFnOrTemplate, template) {
if (template === undefined) {
template = keyFnOrTemplate;
}
return function(part) {
part.setValue(items.map((item, index) => template(item, index)));
};
}
|
javascript
|
{
"resource": ""
}
|
q23896
|
getTemplateResultChunk
|
train
|
function getTemplateResultChunk(result, stack) {
let chunk = result.readChunk();
// Skip empty strings
if (Buffer.isBuffer(chunk) && chunk.length === 0) {
chunk = result.readChunk();
}
// Finished reading, dispose
if (chunk === null) {
stack.shift();
} else if (isTemplateResult(chunk)) {
// Add to top of stack
stack.unshift(chunk);
chunk = getTemplateResultChunk(chunk, stack);
}
return chunk;
}
|
javascript
|
{
"resource": ""
}
|
q23897
|
classMapDirective
|
train
|
function classMapDirective(classInfo) {
return function(part) {
if (!isAttributePart(part) || part.name !== 'class') {
throw Error('The `classMap` directive can only be used in the `class` attribute');
}
let value = '';
for (const key in classInfo) {
if (classInfo[key]) {
value += `${value.length ? ' ' : ''}${key}`;
}
}
part.setValue(value);
};
}
|
javascript
|
{
"resource": ""
}
|
q23898
|
ifDefinedDirective
|
train
|
function ifDefinedDirective(value) {
return function(part) {
if (value === undefined && isAttributePart(part)) {
return part.setValue(nothingString);
}
part.setValue(value);
};
}
|
javascript
|
{
"resource": ""
}
|
q23899
|
resolveAttributeValue
|
train
|
function resolveAttributeValue(value, part) {
if (isDirective(value)) {
value = resolveDirectiveValue(value, part);
}
if (value === nothingString) {
return value;
}
if (isTemplateResult(value)) {
value = value.read();
}
if (isPrimitive(value)) {
const string = typeof value !== 'string' ? String(value) : value;
// Escape if not prefixed with unsafePrefixString, otherwise strip prefix
return Buffer.from(
string.indexOf(unsafePrefixString) === 0 ? string.slice(33) : escapeHTML(string)
);
} else if (Buffer.isBuffer(value)) {
return value;
} else if (isPromise(value)) {
return value.then((value) => resolveAttributeValue(value, part));
} else if (isSyncIterator(value)) {
if (!Array.isArray(value)) {
value = Array.from(value);
}
return Buffer.concat(
value.reduce((values, value) => {
value = resolveAttributeValue(value, part);
// Flatten
if (Array.isArray(value)) {
return values.concat(value);
}
values.push(value);
return values;
}, [])
);
} else {
throw Error('unknown AttributPart value', value);
}
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.