_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q21900
train
function (renderer, size) { renderer.saveClear(); var viewport = renderer.viewport; var x = 0, y = 0; var width = size || viewport.width / 4; var height = width; if (this.softShadow === ShadowMapPass.VSM) { this._outputDepthPass.material.define('fragment', 'USE_VSM'); } else { this._outputDepthPass.material.undefine('fragment', 'USE_VSM'); } for (var name in this._textures) { var texture = this._textures[name]; renderer.setViewport(x, y, width * texture.width / texture.height, height); this._outputDepthPass.setUniform('depthMap', texture); this._outputDepthPass.render(renderer); x += width * texture.width / texture.height; } renderer.setViewport(viewport); renderer.restoreClear(); }
javascript
{ "resource": "" }
q21901
train
function (x, y, forcePickAll) { var out = this.pickAll(x, y, [], forcePickAll); return out[0] || null; }
javascript
{ "resource": "" }
q21902
train
function (x, y, output, forcePickAll) { this.renderer.screenToNDC(x, y, this._ndc); this.camera.castRay(this._ndc, this._ray); output = output || []; this._intersectNode(this.scene, output, forcePickAll || false); output.sort(this._intersectionCompareFunc); return output; }
javascript
{ "resource": "" }
q21903
train
function () { for (var i = 0; i < this.nodes.length; i++) { this.nodes[i].clear(); } // Traverse all the nodes and build the graph for (var i = 0; i < this.nodes.length; i++) { var node = this.nodes[i]; if (!node.inputs) { continue; } for (var inputName in node.inputs) { if (!node.inputs[inputName]) { continue; } if (node.pass && !node.pass.material.isUniformEnabled(inputName)) { console.warn('Pin ' + node.name + '.' + inputName + ' not used.'); continue; } var fromPinInfo = node.inputs[inputName]; var fromPin = this.findPin(fromPinInfo); if (fromPin) { node.link(inputName, fromPin.node, fromPin.pin); } else { if (typeof fromPinInfo === 'string') { console.warn('Node ' + fromPinInfo + ' not exist'); } else { console.warn('Pin of ' + fromPinInfo.node + '.' + fromPinInfo.pin + ' not exist'); } } } } }
javascript
{ "resource": "" }
q21904
train
function (width, height) { if (this._gBufferTex1.width === width && this._gBufferTex1.height === height ) { return; } this._gBufferTex1.width = width; this._gBufferTex1.height = height; this._gBufferTex2.width = width; this._gBufferTex2.height = height; this._gBufferTex3.width = width; this._gBufferTex3.height = height; this._gBufferTex4.width = width; this._gBufferTex4.height = height; }
javascript
{ "resource": "" }
q21905
train
function() { var cone = new Cone$1({ topRadius: this.radius, bottomRadius: this.radius, capSegments: this.capSegments, heightSegments: this.heightSegments, height: this.height }); this.attributes.position.value = cone.attributes.position.value; this.attributes.normal.value = cone.attributes.normal.value; this.attributes.texcoord0.value = cone.attributes.texcoord0.value; this.indices = cone.indices; this.boundingBox = cone.boundingBox; }
javascript
{ "resource": "" }
q21906
train
function (light) { var volumeMesh; if (light.volumeMesh) { volumeMesh = light.volumeMesh; } else { switch (light.type) { // Only local light (point and spot) needs volume mesh. // Directional and ambient light renders in full quad case 'POINT_LIGHT': case 'SPHERE_LIGHT': var shader = light.type === 'SPHERE_LIGHT' ? this._sphereLightShader : this._pointLightShader; // Volume mesh created automatically if (!light.__volumeMesh) { light.__volumeMesh = new Mesh({ material: this._createLightPassMat(shader), geometry: this._lightSphereGeo, // Disable culling // if light volume mesh intersect camera near plane // We need mesh inside can still be rendered culling: false }); } volumeMesh = light.__volumeMesh; var r = light.range + (light.radius || 0); volumeMesh.scale.set(r, r, r); break; case 'SPOT_LIGHT': light.__volumeMesh = light.__volumeMesh || new Mesh({ material: this._createLightPassMat(this._spotLightShader), geometry: this._lightConeGeo, culling: false }); volumeMesh = light.__volumeMesh; var aspect = Math.tan(light.penumbraAngle * Math.PI / 180); var range = light.range; volumeMesh.scale.set(aspect * range, aspect * range, range / 2); break; case 'TUBE_LIGHT': light.__volumeMesh = light.__volumeMesh || new Mesh({ material: this._createLightPassMat(this._tubeLightShader), geometry: this._lightCylinderGeo, culling: false }); volumeMesh = light.__volumeMesh; var range = light.range; volumeMesh.scale.set(light.length / 2 + range, range, range); break; } } if (volumeMesh) { volumeMesh.update(); // Apply light transform Matrix4.multiply(volumeMesh.worldTransform, light.worldTransform, volumeMesh.worldTransform); var hasShadow = this.shadowMapPass && light.castShadow; volumeMesh.material[hasShadow ? 'define' : 'undefine']('fragment', 'SHADOWMAP_ENABLED'); } }
javascript
{ "resource": "" }
q21907
train
function(out) { var amount = Math.min(this._particlePool.length, this.amount); var particle; for (var i = 0; i < amount; i++) { particle = this._particlePool.pop(); // Initialize particle status if (this.position) { this.position.get(particle.position); } if (this.rotation) { this.rotation.get(particle.rotation); } if (this.velocity) { this.velocity.get(particle.velocity); } if (this.angularVelocity) { this.angularVelocity.get(particle.angularVelocity); } if (this.life) { particle.life = this.life.get(); } if (this.spriteSize) { particle.spriteSize = this.spriteSize.get(); } if (this.weight) { particle.weight = this.weight.get(); } particle.age = 0; out.push(particle); } }
javascript
{ "resource": "" }
q21908
train
function() { // Put all the particles back for (var i = 0; i < this._particles.length; i++) { var p = this._particles[i]; p.emitter.kill(p); } this._particles.length = 0; this._elapsedTime = 0; this._emitting = true; }
javascript
{ "resource": "" }
q21909
train
function(ratio) { this._texture.width = this.width * ratio; this._texture.height = this.height * ratio; this.downSampleRatio = ratio; }
javascript
{ "resource": "" }
q21910
train
function(scene, camera) { var renderer = this.renderer; if (renderer.getWidth() !== this.width || renderer.getHeight() !== this.height) { this.resize(renderer.width, renderer.height); } this._frameBuffer.attach(this._texture); this._frameBuffer.bind(renderer); this._idOffset = this.lookupOffset; this._setMaterial(scene); renderer.render(scene, camera); this._restoreMaterial(); this._frameBuffer.unbind(renderer); }
javascript
{ "resource": "" }
q21911
train
function(x, y) { var renderer = this.renderer; var ratio = this.downSampleRatio; x = Math.ceil(ratio * x); y = Math.ceil(ratio * (this.height - y)); this._frameBuffer.bind(renderer); var pixel = new Uint8Array(4); var _gl = renderer.gl; // TODO out of bounds ? // preserveDrawingBuffer ? _gl.readPixels(x, y, 1, 1, _gl.RGBA, _gl.UNSIGNED_BYTE, pixel); this._frameBuffer.unbind(renderer); // Skip interpolated pixel because of anti alias if (pixel[3] === 255) { var id = unpackID(pixel[0], pixel[1], pixel[2]); if (id) { var el = this._lookupTable[id - this.lookupOffset]; return el; } } }
javascript
{ "resource": "" }
q21912
train
function (frameTime) { var target = this.target; var position = this.target.position; var xAxis = target.localTransform.x.normalize(); var zAxis = target.localTransform.z.normalize(); if (this.verticalMoveLock) { zAxis.y = 0; zAxis.normalize(); } var speed = this.speed * frameTime / 20; if (this._moveForward) { // Opposite direction of z position.scaleAndAdd(zAxis, -speed); } if (this._moveBackward) { position.scaleAndAdd(zAxis, speed); } if (this._moveLeft) { position.scaleAndAdd(xAxis, -speed / 2); } if (this._moveRight) { position.scaleAndAdd(xAxis, speed / 2); } target.rotateAround(target.position, this.up, -this._offsetPitch * frameTime * Math.PI / 360); var xAxis = target.localTransform.x; target.rotateAround(target.position, xAxis, -this._offsetRoll * frameTime * Math.PI / 360); this._offsetRoll = this._offsetPitch = 0; }
javascript
{ "resource": "" }
q21913
train
function() { /** * When user begins to interact with connected gamepad: * * @see https://w3c.github.io/gamepad/#dom-gamepadevent */ vendor.addEventListener(window, 'gamepadconnected', this._checkGamepadCompatibility); if (this.timeline) { this.timeline.on('frame', this.update); } vendor.addEventListener(window, 'gamepaddisconnected', this._disconnectGamepad); }
javascript
{ "resource": "" }
q21914
train
function() { vendor.removeEventListener(window, 'gamepadconnected', this._checkGamepadCompatibility); if (this.timeline) { this.timeline.off('frame', this.update); } vendor.removeEventListener(window, 'gamepaddisconnected', this._disconnectGamepad); }
javascript
{ "resource": "" }
q21915
train
function (frameTime) { if (!this._standardGamepadAvailable) { return; } this._scanPressedGamepadButtons(); this._scanInclinedGamepadAxes(); // Update target depending on user input. var target = this.target; var position = this.target.position; var xAxis = target.localTransform.x.normalize(); var zAxis = target.localTransform.z.normalize(); var moveSpeed = this.moveSpeed * frameTime / 20; if (this._moveForward) { // Opposite direction of z. position.scaleAndAdd(zAxis, -moveSpeed); } if (this._moveBackward) { position.scaleAndAdd(zAxis, moveSpeed); } if (this._moveLeft) { position.scaleAndAdd(xAxis, -moveSpeed); } if (this._moveRight) { position.scaleAndAdd(xAxis, moveSpeed); } target.rotateAround(target.position, this.up, -this._offsetPitch * frameTime * Math.PI / 360); var xAxis = target.localTransform.x; target.rotateAround(target.position, xAxis, -this._offsetRoll * frameTime * Math.PI / 360); /* * If necessary: trigger `update` event. * XXX This can economize rendering OPs. */ if (this._moveForward === true || this._moveBackward === true || this._moveLeft === true || this._moveRight === true || this._offsetPitch !== 0 || this._offsetRoll !== 0) { this.trigger('update'); } // Reset values to avoid lost of control. this._moveForward = this._moveBackward = this._moveLeft = this._moveRight = false; this._offsetPitch = this._offsetRoll = 0; }
javascript
{ "resource": "" }
q21916
train
function () { var dom = this.domElement; vendor.addEventListener(dom, 'touchstart', this._mouseDownHandler); vendor.addEventListener(dom, 'mousedown', this._mouseDownHandler); vendor.addEventListener(dom, 'wheel', this._mouseWheelHandler); if (this.timeline) { this.timeline.on('frame', this.update, this); } if (this.target) { this.decomposeTransform(); } }
javascript
{ "resource": "" }
q21917
train
function () { var dom = this.domElement; vendor.removeEventListener(dom, 'touchstart', this._mouseDownHandler); vendor.removeEventListener(dom, 'touchmove', this._mouseMoveHandler); vendor.removeEventListener(dom, 'touchend', this._mouseUpHandler); vendor.removeEventListener(dom, 'mousedown', this._mouseDownHandler); vendor.removeEventListener(dom, 'mousemove', this._mouseMoveHandler); vendor.removeEventListener(dom, 'mouseup', this._mouseUpHandler); vendor.removeEventListener(dom, 'wheel', this._mouseWheelHandler); vendor.removeEventListener(dom, 'mouseout', this._mouseUpHandler); if (this.timeline) { this.timeline.off('frame', this.update); } this.stopAllAnimation(); }
javascript
{ "resource": "" }
q21918
train
function (alpha) { alpha = Math.max(Math.min(this.maxAlpha, alpha), this.minAlpha); this._theta = alpha / 180 * Math.PI; this._needsUpdate = true; }
javascript
{ "resource": "" }
q21919
train
function (beta) { beta = Math.max(Math.min(this.maxBeta, beta), this.minBeta); this._phi = -beta / 180 * Math.PI; this._needsUpdate = true; }
javascript
{ "resource": "" }
q21920
train
function () { for (var i = 0; i < this._animators.length; i++) { this._animators[i].stop(); } this._animators.length = 0; }
javascript
{ "resource": "" }
q21921
train
function (deltaTime) { deltaTime = deltaTime || 16; if (this._rotating) { var radian = (this.autoRotateDirection === 'cw' ? 1 : -1) * this.autoRotateSpeed / 180 * Math.PI; this._phi -= radian * deltaTime / 1000; this._needsUpdate = true; } else if (this._rotateVelocity.len() > 0) { this._needsUpdate = true; } if (Math.abs(this._zoomSpeed) > 0.01 || this._panVelocity.len() > 0) { this._needsUpdate = true; } if (!this._needsUpdate) { return; } // Fixed deltaTime this._updateDistanceOrSize(Math.min(deltaTime, 50)); this._updatePan(Math.min(deltaTime, 50)); this._updateRotate(Math.min(deltaTime, 50)); this._updateTransform(); this.target.update(); this.trigger('update'); this._needsUpdate = false; }
javascript
{ "resource": "" }
q21922
train
function (geometry, shallow) { if (!geometry) { return null; } var data = { metadata : util$1.extend({}, META) }; //transferable buffers var buffers = []; //dynamic data.dynamic = geometry.dynamic; //bounding box if (geometry.boundingBox) { data.boundingBox = { min : geometry.boundingBox.min.toArray(), max : geometry.boundingBox.max.toArray() }; } //indices if (geometry.indices && geometry.indices.length > 0) { data.indices = copyIfNecessary(geometry.indices, shallow); buffers.push(data.indices.buffer); } //attributes data.attributes = {}; for (var p in geometry.attributes) { if (geometry.attributes.hasOwnProperty(p)) { var attr = geometry.attributes[p]; //ignore empty attributes if (attr && attr.value && attr.value.length > 0) { attr = data.attributes[p] = copyAttribute(attr, shallow); buffers.push(attr.value.buffer); } } } return { data : data, buffers : buffers }; }
javascript
{ "resource": "" }
q21923
train
function (object) { if (!object) { return null; } if (object.data && object.buffers) { return transferableUtil.toGeometry(object.data); } if (!object.metadata || object.metadata.generator !== META.generator) { throw new Error('[util.transferable.toGeometry] the object is not generated by util.transferable.'); } //basic options var options = { dynamic : object.dynamic, indices : object.indices }; if (object.boundingBox) { var min = new Vector3().setArray(object.boundingBox.min); var max = new Vector3().setArray(object.boundingBox.max); options.boundingBox = new BoundingBox(min, max); } var geometry = new Geometry(options); //attributes for (var p in object.attributes) { if (object.attributes.hasOwnProperty(p)) { var attr = object.attributes[p]; geometry.attributes[p] = new Geometry.Attribute(attr.name, attr.type, attr.size, attr.semantic); geometry.attributes[p].value = attr.value; } } return geometry; }
javascript
{ "resource": "" }
q21924
canIuseNativeCustom
train
function canIuseNativeCustom() { try { const p = new NativeCustomEvent('t', { detail: { a: 'b' } }); return 't' === p.type && 'b' === p.detail.a; } catch (e) { } /* istanbul ignore next: hard to reproduce on test environment */ return false; }
javascript
{ "resource": "" }
q21925
CustomEvent
train
function CustomEvent(type, params) { const e = document.createEvent('CustomEvent'); if (params) { e.initCustomEvent(type, params.bubbles, params.cancelable, params.detail); } else { e.initCustomEvent(type, false, false, undefined); } return e; }
javascript
{ "resource": "" }
q21926
emitFirst
train
function emitFirst (emitter, events, handler) { handler = once(handler) events.forEach((e) => { emitter.once(e, (...args) => { events.forEach((ev) => { emitter.removeListener(ev, handler) }) handler.apply(emitter, args) }) }) }
javascript
{ "resource": "" }
q21927
getSections
train
function getSections(sections, config, parentDepth) { return sections.map(section => processSection(section, config, parentDepth)) }
javascript
{ "resource": "" }
q21928
processSection
train
function processSection(section, config, parentDepth) { const contentRelativePath = section.content // Try to load section content file let content if (contentRelativePath) { const contentAbsolutePath = path.resolve(config.configDir, contentRelativePath) if (!fs.existsSync(contentAbsolutePath)) { throw new Error(`Styleguidist: Section content file not found: ${contentAbsolutePath}`) } content = requireIt(`!!${examplesLoader}?customLangs=vue|js|jsx!${contentAbsolutePath}`) } let sectionDepth if (parentDepth === undefined) { sectionDepth = section.sectionDepth !== undefined ? section.sectionDepth : 0 } else { sectionDepth = parentDepth === 0 ? 0 : parentDepth - 1 } return { name: section.name, exampleMode: section.exampleMode || config.exampleMode, usageMode: section.usageMode || config.usageMode, sectionDepth, description: section.description, slug: slugger.slug(section.name), sections: getSections(section.sections || [], config, sectionDepth), filepath: contentRelativePath, href: section.href, components: getSectionComponents(section, config), content, external: section.external } }
javascript
{ "resource": "" }
q21929
getComponentMetadataPath
train
function getComponentMetadataPath(filepath) { const extname = path.extname(filepath) return filepath.substring(0, filepath.length - extname.length) + '.json' }
javascript
{ "resource": "" }
q21930
findConfigFile
train
function findConfigFile() { let configDir try { configDir = findup.sync(process.cwd(), CONFIG_FILENAME) } catch (exception) { return false } return path.join(configDir, CONFIG_FILENAME) }
javascript
{ "resource": "" }
q21931
runRecognition
train
function runRecognition() { var stdin = process.openStdin(); // Read the text to recognize write('Enter the text to recognize: '); stdin.addListener('data', function (e) { var input = e.toString().trim(); if (input) { // Exit if (input.toLowerCase() === 'exit') { return process.exit(); } else { // Retrieve all the ModelResult recognized from the user input var results = parseAll(input, defaultCulture); results = [].concat.apply([], results); // Write results on console write(); write(results.length > 0 ? "I found the following entities (" + results.length + "):" : "I found no entities."); write(); results.forEach(function (result) { write(JSON.stringify(result, null, "\t")); write(); }); } } // Read the text to recognize write('\nEnter the text to recognize: '); }); }
javascript
{ "resource": "" }
q21932
shouldCompressGzip
train
function shouldCompressGzip(req) { const headers = req.headers; return headers && headers['accept-encoding'] && headers['accept-encoding'] .split(',') .some(el => ['*', 'compress', 'gzip', 'deflate'].indexOf(el.trim()) !== -1) ; }
javascript
{ "resource": "" }
q21933
tryServeWithGzip
train
function tryServeWithGzip() { fs.stat(gzippedFile, (err, stat) => { if (!err && stat.isFile()) { hasGzipId12(gzippedFile, (gzipErr, isGzip) => { if (!gzipErr && isGzip) { file = gzippedFile; serve(stat); } else { statFile(); } }); } else { statFile(); } }); }
javascript
{ "resource": "" }
q21934
tryServeWithBrotli
train
function tryServeWithBrotli(shouldTryGzip) { fs.stat(brotliFile, (err, stat) => { if (!err && stat.isFile()) { file = brotliFile; serve(stat); } else if (shouldTryGzip) { tryServeWithGzip(); } else { statFile(); } }); }
javascript
{ "resource": "" }
q21935
getXHR
train
function getXHR () { if (root.XMLHttpRequest && ('file:' != root.location.protocol || !root.ActiveXObject)) { return new XMLHttpRequest } else { try { return new ActiveXObject('Microsoft.XMLHTTP') } catch(e) {} try { return new ActiveXObject('Msxml2.XMLHTTP.6.0') } catch(e) {} try { return new ActiveXObject('Msxml2.XMLHTTP.3.0') } catch(e) {} try { return new ActiveXObject('Msxml2.XMLHTTP') } catch(e) {} } return false }
javascript
{ "resource": "" }
q21936
params
train
function params (str){ return reduce(str.split(/ *; */), function (obj, str){ var parts = str.split(/ *= */), key = parts.shift(), val = parts.shift() if (key && val) obj[key] = val return obj }, {}) }
javascript
{ "resource": "" }
q21937
search
train
function search (){ var replaced = 0 var scripts = document.querySelectorAll('script') var script for (var i = 0; i < scripts.length; i++) { script = scripts[i] if (!script.src) continue if (/\/slackin\.js(\?.*)?$/.test(script.src)) { // replace script with iframe replace(script) // we abort the search for subsequent // slackin.js executions to exhaust // the queue return true } } }
javascript
{ "resource": "" }
q21938
replace
train
function replace (script){ var parent = script.parentNode if (!parent) return LARGE = /\?large/.test(script.src) var iframe = document.createElement('iframe') var iframePath = '/iframe' + (LARGE ? '?large' : '') iframe.src = script.src.replace(/\/slackin\.js.*/, iframePath) iframe.style.borderWidth = 0 iframe.className = '__slackin' // a decent aproximation that we adjust later // once we have the knowledge of the actual // numbers of users, based on a user count // of 3 digits by 3 digits iframe.style.width = (LARGE ? 190 : 140) + 'px' // height depends on target size iframe.style.height = (LARGE ? 30 : 20) + 'px' // hidden by default to avoid flicker iframe.style.visibility = 'hidden' parent.insertBefore(iframe, script) parent.removeChild(script) // setup iframe RPC iframe.onload = function (){ setup(iframe) } }
javascript
{ "resource": "" }
q21939
setup
train
function setup (iframe){ var id = Math.random() * (1 << 24) | 0 iframe.contentWindow.postMessage('slackin:' + id, '*') window.addEventListener('message', function (e){ if (typeof e.data !== 'string') return // show dialog upon click if ('slackin-click:' + id === e.data) { showDialog(iframe) } // update width var wp = 'slackin-width:' + id + ':' if (wp === e.data.substr(0, wp.length)) { var width = e.data.substr(wp.length) iframe.style.width = width + 'px' // ensure it's shown (since first time hidden) iframe.style.visibility = 'visible' } // redirect to URL var redir = 'slackin-redirect:' + id + ':' if (redir === e.data.substr(0, redir.length)) { location.href = e.data.substr(redir.length) } }) }
javascript
{ "resource": "" }
q21940
text
train
function text ({str, x, y}){ return [ svg(`text fill=#010101 fill-opacity=.3 x=${x} y=${y + 1}`, str), svg(`text fill=#fff x=${x} y=${y}`, str) ] }
javascript
{ "resource": "" }
q21941
topLevelRedirect
train
function topLevelRedirect (url) { if (window === top) location.href = url else parent.postMessage('slackin-redirect:' + id + ':' + url, '*') // Q: Why can't we just `top.location.href = url;`? // A: // [sandboxing]: http://www.html5rocks.com/en/tutorials/security/sandboxed-iframes/ // [CSP]: http://www.html5rocks.com/en/tutorials/security/content-security-policy/ // [nope]: http://output.jsbin.com/popawuk/16 }
javascript
{ "resource": "" }
q21942
getClassName
train
function getClassName(propValue) { if (!propValue.constructor || !propValue.constructor.name) { return ANONYMOUS; } return propValue.constructor.name; }
javascript
{ "resource": "" }
q21943
writeBuildscriptHookForCrashlytics
train
function writeBuildscriptHookForCrashlytics(enable) { var scriptPath = path.join(appRoot, "hooks", "after-prepare", "firebase-crashlytics-buildscript.js"); if (!enable) { if (fs.existsSync(scriptPath)) { fs.unlinkSync(scriptPath); } return } console.log("Install Crashlytics buildscript hook."); try { var scriptContent = `const fs = require('fs-extra'); const path = require('path'); const xcode = require('xcode'); const pattern1 = /\\n\\s*\\/\\/Crashlytics 1 BEGIN[\\s\\S]*\\/\\/Crashlytics 1 END.*\\n/m; const pattern2 = /\\n\\s*\\/\\/Crashlytics 2 BEGIN[\\s\\S]*\\/\\/Crashlytics 2 END.*\\n/m; const pattern3 = /\\n\\s*\\/\\/Crashlytics 3 BEGIN[\\s\\S]*\\/\\/Crashlytics 3 END.*\\n/m; const string1 = \` //Crashlytics 1 BEGIN #else #import <Crashlytics/CLSLogging.h> #endif //Crashlytics 1 END \`; const string2 = \` //Crashlytics 2 BEGIN #if DEBUG #else static int redirect_cls(const char *prefix, const char *buffer, int size) { CLSLog(@"%s: %.*s", prefix, size, buffer); return size; } static int stderr_redirect(void *inFD, const char *buffer, int size) { return redirect_cls("stderr", buffer, size); } static int stdout_redirect(void *inFD, const char *buffer, int size) { return redirect_cls("stdout", buffer, size); } #endif //Crashlytics 2 END \`; const string3 = \` //Crashlytics 3 BEGIN #if DEBUG #else // Per https://docs.fabric.io/apple/crashlytics/enhanced-reports.html#custom-logs : // Crashlytics ensures that all log entries are recorded, even if the very next line of code crashes. // This means that logging must incur some IO. Be careful when logging in performance-critical areas. // As per the note above, enabling this can affect performance if too much logging is present. // stdout->_write = stdout_redirect; // stderr usually only occurs during critical failures; // so it is usually essential to identifying crashes, especially in JS stderr->_write = stderr_redirect; #endif //Crashlytics 3 END \`; module.exports = function($logger, $projectData, hookArgs) { const platform = hookArgs.platform.toLowerCase(); return new Promise(function(resolve, reject) { const isNativeProjectPrepared = !hookArgs.nativePrepare || !hookArgs.nativePrepare.skipNativePrepare; if (isNativeProjectPrepared) { try { if (platform === 'ios') { const sanitizedAppName = path.basename($projectData.projectDir).split('').filter((c) => /[a-zA-Z0-9]/.test(c)).join(''); // write buildscript for dSYM upload const xcodeProjectPath = path.join($projectData.platformsDir, 'ios', sanitizedAppName + '.xcodeproj', 'project.pbxproj'); $logger.trace('Using Xcode project', xcodeProjectPath); if (fs.existsSync(xcodeProjectPath)) { var xcodeProject = xcode.project(xcodeProjectPath); xcodeProject.parseSync(); var options = { shellPath: '/bin/sh', shellScript: '\"\${PODS_ROOT}/Fabric/run\"' }; xcodeProject.addBuildPhase( [], 'PBXShellScriptBuildPhase', 'Configure Crashlytics', undefined, options ).buildPhase; fs.writeFileSync(xcodeProjectPath, xcodeProject.writeSync()); $logger.trace('Xcode project written'); } else { $logger.error(xcodeProjectPath + ' is missing.'); reject(); return; } // Logging from stdout/stderr $logger.out('Add iOS crash logging'); const mainmPath = path.join($projectData.platformsDir, 'ios', 'internal', 'main.m'); if (fs.existsSync(mainmPath)) { let mainmContent = fs.readFileSync(mainmPath).toString(); // string1 mainmContent = pattern1.test(mainmContent) ? mainmContent.replace(pattern1, string1) : mainmContent.replace(/(\\n#endif\\n)/, string1); // string2 mainmContent = pattern2.test(mainmContent) ? mainmContent.replace(pattern2, string2) : mainmContent.replace(/(\\nint main.*)/, string2 + '$1'); // string3 mainmContent = pattern3.test(mainmContent) ? mainmContent.replace(pattern3, string3) : mainmContent.replace(/(int main.*\\n)/, '$1' + string3 + '\\n'); fs.writeFileSync(mainmPath, mainmContent); } else { $logger.error(mainmPath + ' is missing.'); reject(); return; } resolve(); } else { resolve(); } } catch (e) { $logger.error('Unknown error during prepare Crashlytics', e); reject(); } } else { $logger.trace("Native project not prepared."); resolve(); } }); }; `; var afterPrepareDirPath = path.dirname(scriptPath); var hooksDirPath = path.dirname(afterPrepareDirPath); if (!fs.existsSync(afterPrepareDirPath)) { if (!fs.existsSync(hooksDirPath)) { fs.mkdirSync(hooksDirPath); } fs.mkdirSync(afterPrepareDirPath); } fs.writeFileSync(scriptPath, scriptContent); } catch (e) { console.log("Failed to install Crashlytics buildscript hook."); console.log(e); } }
javascript
{ "resource": "" }
q21944
renderSimpleRuby
train
function renderSimpleRuby( $ruby ) { var frag = $.create( '!' ) var clazz = $ruby.classList var $rb, $ru frag.appendChild( $.clone( $ruby )) $ .tag( 'rt', frag.firstChild ) .forEach(function( $rt ) { var $rb = $.create( '!' ) var airb = [] var irb // Consider the previous nodes the implied // ruby base do { irb = ( irb || $rt ).previousSibling if ( !irb || irb.nodeName.match( /((?:h\-)?r[ubt])/i )) break $rb.insertBefore( $.clone( irb ), $rb.firstChild ) airb.push( irb ) } while ( !irb.nodeName.match( /((?:h\-)?r[ubt])/i )) // Create a real `<h-ru>` to append. $ru = clazz.contains( 'zhuyin' ) ? createZhuyinRu( $rb, $rt ) : createNormalRu( $rb, $rt ) // Replace the ruby text with the new `<h-ru>`, // and remove the original implied ruby base(s) try { $rt.parentNode.replaceChild( $ru, $rt ) airb.map( $.remove ) } catch ( e ) {} }) return createCustomRuby( frag ) }
javascript
{ "resource": "" }
q21945
renderComplexRuby
train
function renderComplexRuby( $ruby ) { var frag = $.create( '!' ) var clazz = $ruby.classList var $cloned, $rb, $ru, maxspan frag.appendChild( $.clone( $ruby )) $cloned = frag.firstChild $rb = $ru = $.tag( 'rb', $cloned ) maxspan = $rb.length // First of all, deal with Zhuyin containers // individually // // Note that we only support one single Zhuyin // container in each complex ruby void function( $rtc ) { if ( !$rtc ) return $ru = $ .tag( 'rt', $rtc ) .map(function( $rt, i ) { if ( !$rb[ i ] ) return var ret = createZhuyinRu( $rb[ i ], $rt ) try { $rb[ i ].parentNode.replaceChild( ret, $rb[ i ] ) } catch ( e ) {} return ret }) // Remove the container once it's useless $.remove( $rtc ) $cloned.setAttribute( 'rightangle', 'true' ) }( $cloned.querySelector( 'rtc.zhuyin' )) // Then, normal annotations other than Zhuyin $ .qsa( 'rtc:not(.zhuyin)', $cloned ) .forEach(function( $rtc, order ) { var ret ret = $ .tag( 'rt', $rtc ) .map(function( $rt, i ) { var rbspan = Number( $rt.getAttribute( 'rbspan' ) || 1 ) var span = 0 var aRb = [] var $rb, ret if ( rbspan > maxspan ) rbspan = maxspan do { try { $rb = $ru.shift() aRb.push( $rb ) } catch (e) {} if ( typeof $rb === 'undefined' ) break span += Number( $rb.getAttribute( 'span' ) || 1 ) } while ( rbspan > span ) if ( rbspan < span ) { if ( aRb.length > 1 ) { console.error( 'An impossible `rbspan` value detected.', ruby ) return } aRb = $.tag( 'rb', aRb[0] ) $ru = aRb.slice( rbspan ).concat( $ru ) aRb = aRb.slice( 0, rbspan ) span = rbspan } ret = createNormalRu( aRb, $rt, { 'class': clazz, span: span, order: order }) try { aRb[0].parentNode.replaceChild( ret, aRb.shift() ) aRb.map( $.remove ) } catch (e) {} return ret }) $ru = ret if ( order === 1 ) $cloned.setAttribute( 'doubleline', 'true' ) // Remove the container once it's useless $.remove( $rtc ) }) return createCustomRuby( frag ) }
javascript
{ "resource": "" }
q21946
getZhuyinHTML
train
function getZhuyinHTML( rt ) { // #### Explanation #### // * `zhuyin`: the entire phonetic annotation // * `yin`: the plain pronunciation (w/out tone) // * `diao`: the tone // * `len`: the length of the plain pronunciation (`yin`) var zhuyin = typeof rt === 'string' ? rt : rt.textContent var yin, diao, len yin = zhuyin.replace( TYPESET.zhuyin.diao, '' ) len = yin ? yin.length : 0 diao = zhuyin .replace( yin, '' ) .replace( /[\u02C5]/g, '\u02C7' ) .replace( /[\u030D\u0358]/g, '\u0307' ) return len === 0 ? '' : '<h-zhuyin length="' + len + '" diao="' + diao + '"><h-yin>' + yin + '</h-yin><h-diao>' + diao + '</h-diao></h-zhuyin>' }
javascript
{ "resource": "" }
q21947
train
function( target, attr ) { if ( typeof attr !== 'object' ) return var len = attr.length // Native `NamedNodeMap``: if ( typeof attr[0] === 'object' && 'name' in attr[0] ) { for ( var i = 0; i < len; i++ ) { if ( attr[ i ].value !== undefined ) { target.setAttribute( attr[ i ].name, attr[ i ].value ) } } // Plain object: } else { for ( var name in attr ) { if ( attr.hasOwnProperty( name ) && attr[ name ] !== undefined ) { target.setAttribute( name, attr[ name ] ) } } } return target }
javascript
{ "resource": "" }
q21948
train
function( target, object ) { if (( typeof target === 'object' || typeof target === 'function' ) && typeof object === 'object' ) { for ( var name in object ) { if (object.hasOwnProperty( name )) { target[ name ] = object[ name ] } } } return target }
javascript
{ "resource": "" }
q21949
train
function() { var match var matchIndex = 0 var offset = 0 var regex = this.options.find var textAggregation = this.getAggregateText() var matches = [] var self = this regex = typeof regex === 'string' ? RegExp(escapeRegExp(regex), 'g') : regex matchAggregation(textAggregation) function matchAggregation(textAggregation) { for (var i = 0, l = textAggregation.length; i < l; ++i) { var text = textAggregation[i] if (typeof text !== 'string') { // Deal with nested contexts: (recursive) matchAggregation(text) continue } if (regex.global) { while (match = regex.exec(text)) { matches.push(self.prepMatch(match, matchIndex++, offset)) } } else { if (match = text.match(regex)) { matches.push(self.prepMatch(match, 0, offset)) } } offset += text.length } } return matches }
javascript
{ "resource": "" }
q21950
train
function() { var elementFilter = this.options.filterElements var forceContext = this.options.forceContext return getText(this.node) /** * Gets aggregate text of a node without resorting * to broken innerText/textContent */ function getText(node, txt) { if (node.nodeType === 3) { return [node.data] } if (elementFilter && !elementFilter(node)) { return [] } var txt = [''] var i = 0 if (node = node.firstChild) do { if (node.nodeType === 3) { txt[i] += node.data continue } var innerText = getText(node) if ( forceContext && node.nodeType === 1 && (forceContext === true || forceContext(node)) ) { txt[++i] = innerText txt[++i] = '' } else { if (typeof innerText[0] === 'string') { // Bridge nested text-node data so that they're // not considered their own contexts: // I.e. ['some', ['thing']] -> ['something'] txt[i] += innerText.shift() } if (innerText.length) { txt[++i] = innerText txt[++i] = '' } } } while (node = node.nextSibling) return txt } }
javascript
{ "resource": "" }
q21951
train
function() { var matches = this.matches var node = this.node var elementFilter = this.options.filterElements var startPortion, endPortion, innerPortions = [], curNode = node, match = matches.shift(), atIndex = 0, // i.e. nodeAtIndex matchIndex = 0, portionIndex = 0, doAvoidNode, nodeStack = [node] out: while (true) { if (curNode.nodeType === 3) { if (!endPortion && curNode.length + atIndex >= match.endIndex) { // We've found the ending endPortion = { node: curNode, index: portionIndex++, text: curNode.data.substring(match.startIndex - atIndex, match.endIndex - atIndex), indexInMatch: atIndex - match.startIndex, indexInNode: match.startIndex - atIndex, // always zero for end-portions endIndexInNode: match.endIndex - atIndex, isEnd: true } } else if (startPortion) { // Intersecting node innerPortions.push({ node: curNode, index: portionIndex++, text: curNode.data, indexInMatch: atIndex - match.startIndex, indexInNode: 0 // always zero for inner-portions }) } if (!startPortion && curNode.length + atIndex > match.startIndex) { // We've found the match start startPortion = { node: curNode, index: portionIndex++, indexInMatch: 0, indexInNode: match.startIndex - atIndex, endIndexInNode: match.endIndex - atIndex, text: curNode.data.substring(match.startIndex - atIndex, match.endIndex - atIndex) } } atIndex += curNode.data.length } doAvoidNode = curNode.nodeType === 1 && elementFilter && !elementFilter(curNode) if (startPortion && endPortion) { curNode = this.replaceMatch(match, startPortion, innerPortions, endPortion) // processMatches has to return the node that replaced the endNode // and then we step back so we can continue from the end of the // match: atIndex -= (endPortion.node.data.length - endPortion.endIndexInNode) startPortion = null endPortion = null innerPortions = [] match = matches.shift() portionIndex = 0 matchIndex++ if (!match) { break; // no more matches } } else if ( !doAvoidNode && (curNode.firstChild || curNode.nextSibling) ) { // Move down or forward: if (curNode.firstChild) { nodeStack.push(curNode) curNode = curNode.firstChild } else { curNode = curNode.nextSibling } continue } // Move forward or up: while (true) { if (curNode.nextSibling) { curNode = curNode.nextSibling break } curNode = nodeStack.pop() if (curNode === node) { break out } } } }
javascript
{ "resource": "" }
q21952
train
function( routine ) { var it = this var routine = Array.isArray( routine ) ? routine : this.routine routine .forEach(function( method ) { if ( typeof method === 'string' && typeof it[ method ] === 'function' ) { it[ method ]() } else if ( Array.isArray( method ) && typeof it[ method[0] ] === 'function' ) { it[ method.shift() ].apply( it, method ) } }) return this }
javascript
{ "resource": "" }
q21953
train
function( selector ) { return ( this .filter( selector || null ) .avoid( 'h-jinze' ) .replace( TYPESET.jinze.touwei, function( portion, match ) { var elem = $.create( 'h-jinze', 'touwei' ) elem.innerHTML = match[0] return (( portion.index === 0 && portion.isEnd ) || portion.index === 1 ) ? elem : '' } ) .replace( TYPESET.jinze.wei, function( portion, match ) { var elem = $.create( 'h-jinze', 'wei' ) elem.innerHTML = match[0] return portion.index === 0 ? elem : '' } ) .replace( TYPESET.jinze.tou, function( portion, match ) { var elem = $.create( 'h-jinze', 'tou' ) elem.innerHTML = match[0] return (( portion.index === 0 && portion.isEnd ) || portion.index === 1 ) ? elem : '' } ) .replace( TYPESET.jinze.middle, function( portion, match ) { var elem = $.create( 'h-jinze', 'middle' ) elem.innerHTML = match[0] return (( portion.index === 0 && portion.isEnd ) || portion.index === 1 ) ? elem : '' } ) .endAvoid() .endFilter() ) }
javascript
{ "resource": "" }
q21954
train
function( context, target ) { var $$target = $.qsa( target || 'u, ins', context ) var i = $$target.length traverse: while ( i-- ) { var $this = $$target[ i ] var $prev = null // Ignore all `<wbr>` and comments in between, // and add class `.adjacent` once two targets // are next to each other. ignore: do { $prev = ( $prev || $this ).previousSibling if ( !$prev ) { continue traverse } else if ( $$target[ i-1 ] === $prev ) { $this.classList.add( 'adjacent' ) } } while ( $.isIgnorable( $prev )) } }
javascript
{ "resource": "" }
q21955
train
function( context, target ) { var method = target ? 'qsa' : 'tag' var target = target || 'em' var $target = $[ method ]( target, context ) $target .forEach(function( elem ) { var $elem = Han( elem ) if ( Locale.support.textemphasis ) { $elem .avoid( 'rt, h-char' ) .charify({ biaodian: true, punct: true }) } else { $elem .avoid( 'rt, h-char, h-char-group' ) .jinzify() .groupify({ western: true }) .charify({ hanzi: true, biaodian: true, punct: true, latin: true, ellinika: true, kirillica: true }) } }) }
javascript
{ "resource": "" }
q21956
inherits
train
function inherits(subClass, superClass) { // if (typeof superClass !== "function" && superClass !== null) { // throw new TypeError( // "Super expression must either be null or a function, not " + // typeof superClass // ); // } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true, }, }); // if (superClass) // Object.setPrototypeOf // ? Object.setPrototypeOf(subClass, superClass) // : (subClass.__proto__ = superClass); }
javascript
{ "resource": "" }
q21957
canRoute
train
function canRoute(url) { for (let i=ROUTERS.length; i--; ) { if (ROUTERS[i].canRoute(url)) return true; } return false; }
javascript
{ "resource": "" }
q21958
routeTo
train
function routeTo(url) { let didRoute = false; for (let i=0; i<ROUTERS.length; i++) { if (ROUTERS[i].routeTo(url)===true) { didRoute = true; } } for (let i=subscribers.length; i--; ) { subscribers[i](url); } return didRoute; }
javascript
{ "resource": "" }
q21959
compareNodeNames
train
function compareNodeNames(fromEl, toEl) { var fromNodeName = fromEl.nodeName; var toNodeName = toEl.nodeName; if (fromNodeName === toNodeName) { return true; } if (toEl.actualize && fromNodeName.charCodeAt(0) < 91 && /* from tag name is upper case */ toNodeName.charCodeAt(0) > 90 /* target tag name is lower case */) { // If the target element is a virtual DOM node then we may need to normalize the tag name // before comparing. Normal HTML elements that are in the "http://www.w3.org/1999/xhtml" // are converted to upper case return fromNodeName === toNodeName.toUpperCase(); } else { return false; } }
javascript
{ "resource": "" }
q21960
createElementNS
train
function createElementNS(name, namespaceURI) { return !namespaceURI || namespaceURI === NS_XHTML ? doc.createElement(name) : doc.createElementNS(namespaceURI, name); }
javascript
{ "resource": "" }
q21961
moveChildren
train
function moveChildren(fromEl, toEl) { var curChild = fromEl.firstChild; while (curChild) { var nextChild = curChild.nextSibling; toEl.appendChild(curChild); curChild = nextChild; } return toEl; }
javascript
{ "resource": "" }
q21962
removeNode
train
function removeNode(node, parentNode, skipKeyedNodes) { if (onBeforeNodeDiscarded(node) === false) { return; } if (parentNode) { parentNode.removeChild(node); } onNodeDiscarded(node); walkDiscardedChildNodes(node, skipKeyedNodes); }
javascript
{ "resource": "" }
q21963
processCallbacks
train
function processCallbacks(items, cb){ if(!items || items.length === 0){ // empty or no list, invoke callback return cb(); } // invoke current function, pass the next part as continuation items[0](function(){ processCallbacks(items.slice(1), cb); }); }
javascript
{ "resource": "" }
q21964
processDirectory
train
function processDirectory (directory, path, items, cb) { var dirReader = directory.createReader(); var allEntries = []; function readEntries () { dirReader.readEntries(function(entries){ if (entries.length) { allEntries = allEntries.concat(entries); return readEntries(); } // process all conversion callbacks, finally invoke own one processCallbacks( allEntries.map(function(entry){ // bind all properties except for callback return processItem.bind(null, entry, path, items); }), cb ); }); } readEntries(); }
javascript
{ "resource": "" }
q21965
loadFiles
train
function loadFiles(items, event) { if(!items.length){ return; // nothing to do } $.fire('beforeAdd'); var files = []; processCallbacks( Array.prototype.map.call(items, function(item){ // bind all properties except for callback var entry = item; if('function' === typeof item.webkitGetAsEntry){ entry = item.webkitGetAsEntry(); } return processItem.bind(null, entry, "", files); }), function(){ if(files.length){ // at least one file found appendFilesFromFileList(files, event); } } ); }
javascript
{ "resource": "" }
q21966
train
function(name, options) { name = defaultValue(name, "Conditions"); options = defaultValue(options, defaultValue.EMPTY_OBJECT); DisplayVariablesConcept.call(this, name, options); }
javascript
{ "resource": "" }
q21967
closeDescendants
train
function closeDescendants(concept) { concept.isOpen = false; concept.items.forEach(child => { if (child.items) { closeDescendants(child); } }); }
javascript
{ "resource": "" }
q21968
train
function(terria) { CatalogMember.call(this, terria); this._loadingPromise = undefined; this._lastLoadInfluencingValues = undefined; this._parameters = []; /** * Gets or sets a value indicating whether the group is currently loading. This property * is observable. * @type {Boolean} */ this.isLoading = false; /** * A catalog item that will be enabled while preparing to invoke this catalog function, in order to * provide context for the function. * @type {CatalogItem} */ this.contextItem = undefined; knockout.track(this, ["isLoading"]); }
javascript
{ "resource": "" }
q21969
replaceUnderscores
train
function replaceUnderscores(string) { if (typeof string === "string" || string instanceof String) { return string.replace(/_/g, " "); } return string; }
javascript
{ "resource": "" }
q21970
extractValues
train
function extractValues(response) { var observationData = response.GetObservationResponse && response.GetObservationResponse.observationData; if (defined(observationData)) { if (!Array.isArray(observationData)) { observationData = [observationData]; } var observations = observationData.map(o => o.OM_Observation); observations.forEach(observation => { if (!defined(observation)) { return; } var points = observation.result.MeasurementTimeseries.point; if (!defined(points)) { return; } if (!Array.isArray(points)) { points = [points]; } var measurements = points.map(point => point.MeasurementTVP); // TVP = Time value pairs, I think. // var procedureTitle = defined(observation.procedure) ? observation.procedure['xlink:title'] : 'value'; // var featureName = observation.featureOfInterest['xlink:title']; var featureIdentifier = observation.featureOfInterest["xlink:href"]; dateValues.push( ...measurements.map(measurement => typeof measurement.time === "object" ? null : measurement.time ) ); valueValues.push( ...measurements.map(measurement => typeof measurement.value === "object" ? null : parseFloat(measurement.value) ) ); // These 5 arrays constitute columns in the table, some of which (like this one) have the same // value in each row. featureValues.push(...measurements.map(_ => featureIdentifier)); procedureValues.push(...measurements.map(_ => procedure.identifier)); observedPropertyValues.push( ...measurements.map(_ => observableProperty.identifier) ); }); } }
javascript
{ "resource": "" }
q21971
loadObservationData
train
function loadObservationData(item) { if (!item._featureMapping) { return; } var featuresOfInterest = Object.keys(item._featureMapping); // Are there too many features to load observations (or we've been asked not to try)? if ( !item.tryToLoadObservationData || featuresOfInterest.length > item.requestSizeLimit * item.requestNumberLimit ) { // MODE 1. Do not load observation data for the features. // Just show where the features are, and when the feature info panel is opened, then load the feature's observation data // (via the 'chart' column in _tableStructure, which generates a call to item.loadIntoTableStructure). var tableStructure = item._tableStructure; if (!defined(tableStructure)) { tableStructure = new TableStructure(item.name); } var columns = createColumnsFromMapping(item, tableStructure); tableStructure.columns = columns; if (!defined(item._tableStructure)) { item._tableStyle.dataVariable = null; // Turn off the legend and give all the points a single colour. item.initializeFromTableStructure(tableStructure); } else { item._tableStructure.columns = tableStructure.columns; } return when(); } // MODE 2. Create a big time-varying tableStructure with all the observations for all the features. // In this mode, the feature info panel shows a chart through as a standard time-series, like it would for any time-varying csv. return item .loadIntoTableStructure(featuresOfInterest) .then(function(observationTableStructure) { if ( !defined(observationTableStructure) || observationTableStructure.columns[0].values.length === 0 ) { throw new TerriaError({ sender: item, title: item.name, message: "The Sensor Observation Service did not return any features matching your query." }); } // Add the extra columns from the mapping into the table. var identifiers = observationTableStructure.getColumnWithName( "identifier" ).values; var newColumns = createColumnsFromMapping( item, observationTableStructure, identifiers ); observationTableStructure.activeTimeColumnNameIdOrIndex = undefined; observationTableStructure.columns = observationTableStructure.columns.concat( newColumns ); observationTableStructure.idColumnNames = item._idColumnNames; if (item.showFeaturesAtAllTimes) { // Set finalEndJulianDate so that adding new null-valued feature rows doesn't mess with the final date calculations. // To do this, we need to set the active time column, so that finishJulianDates is calculated. observationTableStructure.setActiveTimeColumn( item.tableStyle.timeColumn ); var finishDates = observationTableStructure.finishJulianDates.map(d => Number(JulianDate.toDate(d)) ); // I thought we'd need to unset the time column, because we're about to change the columns again, and there can be interactions // - but it works without unsetting it. // observationTableStructure.setActiveTimeColumn(undefined); observationTableStructure.finalEndJulianDate = JulianDate.fromDate( new Date(Math.max.apply(null, finishDates)) ); observationTableStructure.columns = observationTableStructure.getColumnsWithFeatureRowsAtStartAndEndDates( "date", "value" ); } if (!defined(item._tableStructure)) { observationTableStructure.name = item.name; item.initializeFromTableStructure(observationTableStructure); } else { observationTableStructure.setActiveTimeColumn( item.tableStyle.timeColumn ); // Moving this isActive statement earlier stops all points appearing on the map/globe. observationTableStructure.columns.filter( column => column.id === "value" )[0].isActive = true; item._tableStructure.columns = observationTableStructure.columns; // TODO: doesn't do anything. // Force the timeline (terria.clock) to update by toggling "isShown" (see CatalogItem's isShownChanged). if (item.isShown) { item.isShown = false; item.isShown = true; } // Changing the columns triggers a knockout change of the TableDataSource that uses this table. } }); }
javascript
{ "resource": "" }
q21972
createColumnsFromMapping
train
function createColumnsFromMapping(item, tableStructure, identifiers) { var featureMapping = item._featureMapping; var addChartColumn = !defined(identifiers); if (!defined(identifiers)) { identifiers = Object.keys(featureMapping); } var rows = identifiers.map(identifier => featureMapping[identifier]); var columnOptions = { tableStructure: tableStructure }; var chartColumnOptions = { tableStructure: tableStructure, id: "chart" }; // So the chart column can be referred to in the FeatureInfoTemplate as 'chart'. var result = [ new TableColumn("type", rows.map(row => row.type), columnOptions), new TableColumn("name", rows.map(row => row.name), columnOptions), new TableColumn("id", rows.map(row => row.id), columnOptions), new TableColumn("lat", rows.map(row => row.lat), columnOptions), new TableColumn("lon", rows.map(row => row.lon), columnOptions) ]; if (addChartColumn) { var procedure = getObjectCorrespondingToSelectedConcept(item, "procedures"); var observableProperty = getObjectCorrespondingToSelectedConcept( item, "observableProperties" ); var chartName = procedure.title || observableProperty.title || "chart"; var chartId = procedure.title + "_" + observableProperty.title; var charts = rows.map(row => getChartTagFromFeatureIdentifier(row.identifier, chartId) ); result.push( new TableColumn( "identifier", rows.map(row => row.identifier), columnOptions ), new TableColumn(chartName, charts, chartColumnOptions) ); } return result; }
javascript
{ "resource": "" }
q21973
train
function(terria) { const that = this; this._terria = terria; // Note: We create a persistant object and define a transient property, since knockout needs a persistant variable // to track, but for state we want a 'maybe' intervalId. this._eventLoopState = {}; this._manualAlignment = false; this._maximumUpdatesPerSecond = AugmentedVirtuality.DEFAULT_MAXIMUM_UPDATES_PER_SECOND; this._orientationUpdated = false; this._alpha = 0; this._beta = 0; this._gamma = 0; this._realignAlpha = 0; this._realignHeading = 0; // Set the default height to be the last height so that when we first toggle (and increment) we cycle and go to the first height. this._hoverLevel = AugmentedVirtuality.PRESET_HEIGHTS.length - 1; // Always run the device orientation event, this way as soon as we enable we know where we are and set the // orientation rather then having to wait for the next update. // The following is disabled because chrome does not currently support deviceorientationabsolute correctly: // if ('ondeviceorientationabsolute' in window) // { // window.addEventListener('deviceorientationabsolute', function(event) {that._orientationUpdate(event);} ); // } // else if ("ondeviceorientation" in window) { window.addEventListener("deviceorientation", function(event) { that._storeOrientation(event); }); } // Make the variables used by the object properties knockout observable so that changes in the state notify the UI // and cause a UI update. Note: These are all of the variables used just by the getters (not the setters), since // these unqiquely define what the current state is and are the only things that can effect/cause the state to change // (note: _eventLoopState is hidden behind ._eventLoopRunning() ). knockout.track(this, [ "_eventLoopState", "_manualAlignment", "_maximumUpdatesPerSecond", "_realignAlpha", "_realignHeading", "_hoverLevel" ]); // Note: The following properties are defined as knockout properties so that they can be used to trigger updates on the UI. /** * Gets or sets whether Augmented Virtuality mode is currently enabled (true) or not (false). * * Note: If {@link AugmentedVirtuality#manualAlignment} is enabled and the state is changed it will be disabled. * * @memberOf AugmentedVirtuality.prototype * @member {Boolean} enabled */ knockout.defineProperty(this, "enabled", { get: function() { return this._eventLoopRunning() || this._manualAlignment; }, set: function(enable) { if (enable !== true) { enable = false; this.resetAlignment(); } if (enable !== this.enabled) { // If we are changing the enabled state then disable manual alignment. // We only do this if we are changing the enabled state so that the client can repeatedly call the // setting without having any effect if they aren't changing the enabled state, but so that every time // that the state is changed that the manual alignment is turned back off initally. this._manualAlignment = false; this._startEventLoop(enable); } } }); /** * Gets or sets whether manual realignment mode is currently enabled (true) or not (false). * * @memberOf AugmentedVirtuality.prototype * @member {Boolean} manualAlignment */ knockout.defineProperty(this, "manualAlignment", { get: function() { return this._getManualAlignment(); }, set: function(startEnd) { this._setManualAlignment(startEnd); } }); /** * Gets whether a manual realignment has been specified (true) or not (false). * * @memberOf AugmentedVirtuality.prototype * @member {Boolean} manualAlignmentSet */ knockout.defineProperty(this, "manualAlignmentSet", { get: function() { return this._realignAlpha !== 0.0 || this._realignHeading !== 0.0; } }); /** * Gets the index of the current hover level. * * Use <code>AugmentedVirtuality.PRESET_HEIGHTS.length</code> to find the total avaliable levels. * * @memberOf AugmentedVirtuality.prototype * @member {int} hoverLevel */ knockout.defineProperty(this, "hoverLevel", { get: function() { return this._hoverLevel; } }); /** * Gets or sets the the maximum number of times that the camera orientation will be updated per second. This is * the number of camera orientation updates per seconds is capped to (explicitly the number of times the * orientation is updated per second might be less but it won't be more then this number). We want the number of * times that the orientation is updated capped so that we don't consume to much battery life updating to * frequently, but responsiveness is still acceptable. * * @memberOf AugmentedVirtuality.prototype * @member {Float} maximumUpdatesPerSecond */ knockout.defineProperty(this, "maximumUpdatesPerSecond", { get: function() { return this._maximumUpdatesPerSecond; }, set: function(maximumUpdatesPerSecond) { this._maximumUpdatesPerSecond = maximumUpdatesPerSecond; // If we are currently enabled reset to update the timing interval used. if (this._eventLoopRunning()) { this._startEventLoop(false); this._startEventLoop(true); } } }); this.enabled = false; }
javascript
{ "resource": "" }
q21974
MapInteractionMode
train
function MapInteractionMode(options) { /** * Gets or sets a callback that is invoked when the user cancels the interaction mode. If this property is undefined, * the interaction mode cannot be canceled. * @type {Function} */ this.onCancel = options.onCancel; /** * Gets or sets the details of a custom user interface for this map interaction mode. This property is not used by * the `MapInteractionMode` itself, so it can be anything that is suitable for the user interface. In the standard * React-based user interface included with TerriaJS, this property is a function that is called with no parameters * and is expected to return a React component. * @type {Any} */ this.customUi = defaultValue(options.customUi, undefined); /** * Gets or sets the html formatted message displayed on the map when in this mode. * @type {Function} */ this.message = function() { return options.message; }; /** * Set the text of the button for the dialog the message is displayed on. * @type {String} */ this.buttonText = defaultValue(options.buttonText, "Cancel"); /** * Gets or sets the features that are currently picked. * @type {PickedFeatures} */ this.pickedFeatures = undefined; /** * Determines whether a rectangle will be requested from the user rather than a set of pickedFeatures. * @type {Boolean} */ this.drawRectangle = defaultValue(options.drawRectangle, false); knockout.track(this, ["message", "pickedFeatures", "customUi"]); }
javascript
{ "resource": "" }
q21975
train
function(options) { this._uriTemplate = new URITemplate(options.url); if (typeof options.layerName !== "string") { throw new DeveloperError( "MapboxVectorTileImageryProvider requires a layer name passed as options.layerName" ); } this._layerName = options.layerName; this._subdomains = defaultValue(options.subdomains, []); if (!(options.styleFunc instanceof Function)) { throw new DeveloperError( "MapboxVectorTileImageryProvider requires a styling function passed as options.styleFunc" ); } this._styleFunc = options.styleFunc; this._tilingScheme = new WebMercatorTilingScheme(); this._tileWidth = 256; this._tileHeight = 256; this._minimumLevel = defaultValue(options.minimumZoom, 0); this._maximumLevel = defaultValue(options.maximumZoom, Infinity); this._maximumNativeLevel = defaultValue( options.maximumNativeZoom, this._maximumLevel ); this._rectangle = defined(options.rectangle) ? Rectangle.intersection(options.rectangle, this._tilingScheme.rectangle) : this._tilingScheme.rectangle; this._uniqueIdProp = options.uniqueIdProp; this._featureInfoFunc = options.featureInfoFunc; //this._featurePicking = options.featurePicking; // Check the number of tiles at the minimum level. If it's more than four, // throw an exception, because starting at the higher minimum // level will cause too many tiles to be downloaded and rendered. var swTile = this._tilingScheme.positionToTileXY( Rectangle.southwest(this._rectangle), this._minimumLevel ); var neTile = this._tilingScheme.positionToTileXY( Rectangle.northeast(this._rectangle), this._minimumLevel ); var tileCount = (Math.abs(neTile.x - swTile.x) + 1) * (Math.abs(neTile.y - swTile.y) + 1); if (tileCount > 4) { throw new DeveloperError( "The imagery provider's rectangle and minimumLevel indicate that there are " + tileCount + " tiles at the minimum level. Imagery providers with more than four tiles at the minimum level are not supported." ); } this._errorEvent = new CesiumEvent(); this._ready = true; }
javascript
{ "resource": "" }
q21976
overzoomGeometry
train
function overzoomGeometry(rings, nativeTile, newExtent, newTile) { var diffZ = newTile.level - nativeTile.level; if (diffZ === 0) { return rings; } else { var newRings = []; // (offsetX, offsetY) is the (0,0) of the new tile var offsetX = newExtent * (newTile.x - (nativeTile.x << diffZ)); var offsetY = newExtent * (newTile.y - (nativeTile.y << diffZ)); for (var i = 0; i < rings.length; i++) { var ring = []; for (var i2 = 0; i2 < rings[i].length; i2++) { ring.push(rings[i][i2].sub(new Point(offsetX, offsetY))); } newRings.push(ring); } return newRings; } }
javascript
{ "resource": "" }
q21977
inside
train
function inside(point, vs) { // ray-casting algorithm based on // http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html var x = point.x, y = point.y; var inside = false; for (var i = 0, j = vs.length - 1; i < vs.length; j = i++) { var xi = vs[i].x, yi = vs[i].y; var xj = vs[j].x, yj = vs[j].y; var intersect = yi > y !== yj > y && x < ((xj - xi) * (y - yi)) / (yj - yi) + xi; if (intersect) inside = !inside; } return inside; }
javascript
{ "resource": "" }
q21978
updateColumns
train
function updateColumns(item, newColumns) { item._tableStructure.columns = newColumns; if (item._tableStructure.columns.length === 0) { // Nothing to show, so the attempt to redraw will fail; need to explicitly hide the existing regions. item._regionMapping.hideImageryLayer(); item.terria.currentViewer.notifyRepaintRequired(); } // Close any picked features, as the description of any associated with this catalog item may change. item.terria.pickedFeatures = undefined; }
javascript
{ "resource": "" }
q21979
fixSelectedInitially
train
function fixSelectedInitially(item, conceptDimensions) { conceptDimensions.forEach(dimension => { if (defined(item.selectedInitially)) { var thisSelectedInitially = item.selectedInitially[dimension.id]; if (thisSelectedInitially) { var valueIds = dimension.values.map(value => value.id); if ( !thisSelectedInitially.some( initialValue => valueIds.indexOf(initialValue) >= 0 ) ) { console.warn( "Ignoring invalid initial selection " + thisSelectedInitially + " on " + dimension.name ); item.selectedInitially[dimension.id] = undefined; } } } }); }
javascript
{ "resource": "" }
q21980
buildConcepts
train
function buildConcepts(item, fullDimensions) { function isInitiallyActive(dimensionId, value, index) { if (!defined(item.selectedInitially)) { return index === 0; } var dimensionSelectedInitially = item.selectedInitially[dimensionId]; if (!defined(dimensionSelectedInitially)) { return index === 0; } return dimensionSelectedInitially.indexOf(value.id) >= 0; } var conceptDimensions = getShownDimensions( item, fullDimensions, fullDimensions ); fixSelectedInitially(item, conceptDimensions); // Note side-effect. var concepts = conceptDimensions.map(function(dimension, i) { var allowMultiple = item.allSingleValuedDimensionIds.indexOf(dimension.id) === -1; var concept = new DisplayVariablesConcept(dimension.name, { isOpen: false, allowMultiple: allowMultiple, requireSomeActive: true, exclusiveChildIds: getTotalValueIdsForDimensionId(item, dimension.id) }); concept.id = dimension.id; concept.items = dimension.values.map(function(value, index) { return new VariableConcept(renameValue(item, value.name), { parent: concept, id: value.id, active: isInitiallyActive(concept.id, value, index) }); }); return concept; }); if (concepts.length > 0) { return [new SummaryConcept(undefined, { items: concepts, isOpen: false })]; } return []; }
javascript
{ "resource": "" }
q21981
canTotalBeCalculatedAndIfNotWarnUser
train
function canTotalBeCalculatedAndIfNotWarnUser(item) { if (canResultsBeSummed(item)) { return true; } var conceptItems = item._concepts[0].items; var changedActive = []; conceptItems.forEach(concept => { var numberActive = concept.items.filter(function(subconcept) { return subconcept.isActive; }).length; if (numberActive > 1) { changedActive.push('"' + concept.name + '"'); } }); if (changedActive.length > 0) { item.terria.error.raiseEvent( new TerriaError({ sender: item, title: "Cannot calculate a total", message: "You have selected multiple values for " + changedActive.join(" and ") + ", but the measure you now have chosen cannot be totalled across them. \ As a result, there is no obvious measure to use to shade the regions (although you can still choose a region to view its data).\ To see the regions shaded again, please select only one value for " + changedActive.join(" and ") + ", or select a different measure." }) ); return false; } return true; }
javascript
{ "resource": "" }
q21982
changedActiveItems
train
function changedActiveItems(item) { if (!defined(item._dataflowUrl)) { // All the data is already here, just update the total columns. var shownDimensionCombinations = calculateShownDimensionCombinations( item, item._fullDimensions ); var columns = item._tableStructure.columns.slice( 0, shownDimensionCombinations.ids.length + item._numberOfInitialColumns ); if (columns.length > 0) { columns = columns.concat( buildTotalSelectedColumn(item, shownDimensionCombinations) ); updateColumns(item, columns); } return when(); } else { // Get the URL for the data request, and load & build the appropriate table. var activeConceptIds = calculateActiveConceptIds(item); var dimensionRequestString = calculateDimensionRequestString( item, activeConceptIds, item._fullDimensions ); if (!defined(dimensionRequestString)) { return; // No value for a dimension, so ignore. } return loadAndBuildTable(item, dimensionRequestString); } }
javascript
{ "resource": "" }
q21983
getUrlFromDimensionRequestString
train
function getUrlFromDimensionRequestString(item, dimensionRequestString) { var url = item._originalUrl; if (url[url.length - 1] !== "/") { url += "/"; } url += dimensionRequestString + "/" + item.providerId; if (defined(item.startTime)) { url += "?startTime=" + item.startTime; if (defined(item.endTime)) { url += "&endTime=" + item.endTime; } } else if (defined(item.endTime)) { url += "?endTime=" + item.endTime; } return url; }
javascript
{ "resource": "" }
q21984
hashFromString
train
function hashFromString(s) { return Math.abs( s.split("").reduce(function(prev, c) { var hash = (prev << 5) - prev + c.charCodeAt(0); return hash; }, 0) ); }
javascript
{ "resource": "" }
q21985
correctEntityHeight
train
function correctEntityHeight( entity, currentCartographicPosition, terrainProvider, levelHint ) { sampleTerrain(terrainProvider, levelHint, [currentCartographicPosition]).then( function(updatedPositions) { if (updatedPositions[0].height !== undefined) { entity.position = Ellipsoid.WGS84.cartographicToCartesian( updatedPositions[0] ); } else if (levelHint > 0) { correctEntityHeight( entity, currentCartographicPosition, terrainProvider, levelHint - 1 ); } } ); }
javascript
{ "resource": "" }
q21986
indexWithDescendants
train
function indexWithDescendants(items, index) { items.forEach(function(item) { item.allShareKeys.forEach(function(key) { var insertionKey = key; if (index[insertionKey]) { insertionKey = generateUniqueKey(index, key); if (item.uniqueId === key) { // If this duplicate was the item's main key that will be used for sharing it in general, set this // to the new key. This means that sharing the item will still work most of the time. item.id = insertionKey; } console.warn( "Duplicate shareKey: " + key + ". Inserting new item under " + insertionKey ); } index[insertionKey] = item; }, this); if (defined(item.items)) { indexWithDescendants(item.items, index); } }); }
javascript
{ "resource": "" }
q21987
generateUniqueKey
train
function generateUniqueKey(index, initialKey) { var currentCandidate = initialKey; var counter = 0; while (index[currentCandidate]) { var numberAtEndOfKeyMatches = currentCandidate.match( NUMBER_AT_END_OF_KEY_REGEX ); if (numberAtEndOfKeyMatches !== null) { var nextNumber = parseInt(numberAtEndOfKeyMatches[1], 10) + 1; currentCandidate = currentCandidate.replace( NUMBER_AT_END_OF_KEY_REGEX, "(" + nextNumber + ")" ); } else { currentCandidate += " (1)"; } // This loop should always find something eventually, but because it's a bit dangerous looping endlessly... counter++; if (counter >= 100000) { throw new DeveloperError( "Was not able to find a unique key for " + initialKey + " after 100000 iterations." + " This is probably because the regex for matching keys was somehow unable to work for that key." ); } } return currentCandidate; }
javascript
{ "resource": "" }
q21988
deIndexWithDescendants
train
function deIndexWithDescendants(items, index) { items.forEach(function(item) { item.allShareKeys.forEach(function(key) { index[key] = undefined; }, this); if (defined(item.items)) { deIndexWithDescendants(item.items, index); } }); }
javascript
{ "resource": "" }
q21989
findGroup
train
function findGroup(catalogGroup, keywordsGroups, record) { for (var i = 0; i < keywordsGroups.length; i++) { var kg = keywordsGroups[i]; var fields = record[kg.field]; var matched = false; if (defined(fields)) { if (fields instanceof String || typeof fields === "string") { fields = [fields]; } for (var j = 0; j < fields.length; j++) { var field = fields[j]; if (matchValue(kg.value, field, kg.regex)) { matched = true; break; } } } if (matched) { var newGroup = addGroupIfNotAlreadyPresent( kg.group ? kg.group : kg.value, catalogGroup ); if (kg.children && defined(newGroup)) { // recurse to see if it fits into any of the children catalogGroup = findGroup(newGroup, kg.children, record); if (!defined(catalogGroup)) { //console.log("No match in children for record "+record.title+"::"+record.subject+"::"+record.title+", will assign to "+newGroup.name); catalogGroup = newGroup; } } else if (defined(newGroup)) { catalogGroup = newGroup; } return catalogGroup; } } }
javascript
{ "resource": "" }
q21990
toArrayOfRows
train
function toArrayOfRows(columnValueArrays, columnNames) { if (columnValueArrays.length < 1) { return; } const rows = columnValueArrays[0].map(function(value0, rowIndex) { return columnValueArrays.map(function(values) { return values[rowIndex]; }); }); rows.unshift(columnNames); return rows; }
javascript
{ "resource": "" }
q21991
getHeightValue
train
function getHeightValue(data, recordIndex, heightIndex) { if (recordIndex > 720) { recordIndex = 720; } else if (recordIndex < 0) { recordIndex = 0; } if (heightIndex > 1439) { heightIndex -= 1440; } else if (heightIndex < 0) { heightIndex += 1440; } return data[recordIndex * 1440 + heightIndex]; }
javascript
{ "resource": "" }
q21992
train
function(terria) { CatalogFunction.call(this, terria); this.url = undefined; this.name = "Regions like this"; this.description = "Identifies regions that are _most like_ a given region according to a given set of characteristics."; this._regionTypeParameter = new RegionTypeParameter({ terria: this.terria, catalogFunction: this, id: "regionType", name: "Region Type", description: "The type of region to analyze." }); this._regionParameter = new RegionParameter({ terria: this.terria, catalogFunction: this, id: "region", name: "Region", description: "The region to analyze. The analysis will determine which regions are most similar to this one.", regionProvider: this._regionTypeParameter }); this._dataParameter = new RegionDataParameter({ terria: this.terria, catalogFunction: this, id: "data", name: "Characteristics", description: "The region characteristics to include in the analysis.", regionProvider: this._regionTypeParameter }); this._parameters = [ this._regionTypeParameter, this._regionParameter, this._dataParameter ]; }
javascript
{ "resource": "" }
q21993
applyHintsToName
train
function applyHintsToName(hintSet, name, unallowedTypes) { for (var i in hintSet) { if (hintSet[i].hint.test(name)) { var guess = hintSet[i].type; if (unallowedTypes.indexOf(guess) === -1) { return guess; } } } }
javascript
{ "resource": "" }
q21994
formatPropertyValue
train
function formatPropertyValue(value, options) { if (typeof value === "number") { return formatNumberForLocale(value, options); } else if (typeof value === "string") { // do not linkify if it contains html elements, which we detect by looking for <x...> // this could catch some non-html strings such as "a<3 && b>1", but not linkifying those is no big deal if (!/<[a-z][\s\S]*>/i.test(value)) { return linkifyContent(value); } } return value; }
javascript
{ "resource": "" }
q21995
serializeToJson
train
function serializeToJson(target, filterFunction, options) { options = defaultValue(options, defaultValue.EMPTY_OBJECT); filterFunction = defaultValue(filterFunction, function() { return true; }); var result = {}; for (var propertyName in target) { if ( target.hasOwnProperty(propertyName) && propertyName.length > 0 && propertyName[0] !== "_" && propertyName !== "parent" && filterFunction(propertyName, target) ) { if (target.serializers && target.serializers[propertyName]) { target.serializers[propertyName](target, result, propertyName, options); } else { result[propertyName] = target[propertyName]; } } } return result; }
javascript
{ "resource": "" }
q21996
train
function(catalogItem, tableStructure, tableStyle) { this._tableStructure = defined(tableStructure) ? tableStructure : new TableStructure(); if (defined(tableStyle) && !(tableStyle instanceof TableStyle)) { throw new DeveloperError("Please pass a TableStyle object."); } this._tableStyle = tableStyle; // Can be undefined. this._changed = new CesiumEvent(); this._legendHelper = undefined; this._legendUrl = undefined; this._extent = undefined; this._loadingData = false; this._catalogItem = catalogItem; this._regionMappingDefinitionsUrl = defined(catalogItem) ? catalogItem.terria.configParameters.regionMappingDefinitionsUrl : undefined; this._regionDetails = undefined; // For caching the region details. this._imageryLayer = undefined; this._nextImageryLayer = undefined; // For pre-rendering time-varying layers this._nextImageryLayerInterval = undefined; this._hadImageryAtLayerIndex = undefined; this._hasDisplayedFeedback = false; // So that we only show the feedback once. this._constantRegionRowObjects = undefined; this._constantRegionRowDescriptions = undefined; // Track _tableStructure so that the catalogItem's concepts are maintained. // Track _legendUrl so that the catalogItem can update the legend if it changes. // Track _regionDetails so that when it is discovered that region mapping applies, // it updates the legendHelper via activeItems, and catalogItem properties like supportsReordering. knockout.track(this, ["_tableStructure", "_legendUrl", "_regionDetails"]); // Whenever the active item is changed, recalculate the legend and the display of all the entities. // This is triggered both on deactivation and on reactivation, ie. twice per change; it would be nicer to trigger once. knockout .getObservable(this._tableStructure, "activeItems") .subscribe(changedActiveItems.bind(null, this), this); knockout .getObservable(this._catalogItem, "currentTime") .subscribe(function() { if (this.hasActiveTimeColumn) { onClockTick(this); } }, this); }
javascript
{ "resource": "" }
q21997
loadRegionIds
train
function loadRegionIds(regionMapping, rawRegionDetails) { var promises = rawRegionDetails.map(function(rawRegionDetail) { return rawRegionDetail.regionProvider.loadRegionIDs(); }); return when .all(promises) .then(function() { // Cache the details in a nicer format, storing the actual columns rather than just the column names. regionMapping._regionDetails = rawRegionDetails.map(function( rawRegionDetail ) { return { regionProvider: rawRegionDetail.regionProvider, columnName: rawRegionDetail.variableName, disambigColumnName: rawRegionDetail.disambigVariableName }; }); return regionMapping._regionDetails; }) .otherwise(function(e) { console.log("error loading region ids", e); }); }
javascript
{ "resource": "" }
q21998
calculateRegionIndices
train
function calculateRegionIndices( regionMapping, time, failedMatches, ambiguousMatches ) { // As described in load, currently we only use the first possible region column. var regionDetail = regionMapping._regionDetails[0]; var tableStructure = regionMapping._tableStructure; var regionColumn = tableStructure.getColumnWithNameIdOrIndex( regionDetail.columnName ); if (!defined(regionColumn)) { return; } var regionColumnValues = regionColumn.values; // Wipe out the region names from the rows that do not apply at this time, if there is a time column. var timeColumn = tableStructure.activeTimeColumn; var disambigColumn = defined(regionDetail.disambigColumnName) ? tableStructure.getColumnWithNameIdOrIndex(regionDetail.disambigColumnName) : undefined; // regionIndices will be an array the same length as regionProvider.regions, giving the index of each region into the table. var regionIndices = regionDetail.regionProvider.mapRegionsToIndicesInto( regionColumnValues, disambigColumn && disambigColumn.values, failedMatches, ambiguousMatches, defined(timeColumn) ? timeColumn.timeIntervals : undefined, time ); return regionIndices; }
javascript
{ "resource": "" }
q21999
train
function(tableColumn, tableStyle, regionProvider, name) { this.tableColumn = tableColumn; this.tableStyle = defined(tableStyle) ? tableStyle : new TableStyle(); // instead of defaultValue, so new object only created if needed. this.tableColumnStyle = getTableColumnStyle(tableColumn, this.tableStyle); this.name = name; var noColumnIndex = hashFromString(name || "") % defaultNoColumnColorCodes.length; this._noColumnColorArray = getColorArrayFromCssColorString( defaultNoColumnColorCodes[noColumnIndex], defaultNoColumnColorAlpha ); this._legend = undefined; // We could make a getter for this if it is ever needed. this._colorGradient = undefined; this._binColors = undefined; // An array of objects with upperBound and colorArray properties. this._regionProvider = regionProvider; if (defined(this.tableColumnStyle.nullColor)) { this._nullColorArray = getColorArrayFromCssColorString( this.tableColumnStyle.nullColor ); } else { this._nullColorArray = defined(regionProvider) ? noColorArray : defaultColorArray; } this._cycleEnumValues = false; this._cycleColors = undefined; // Array of colors used for the cycle method this.tableColumnStyle.legendTicks = defaultValue( this.tableColumnStyle.legendTicks, 0 ); this.tableColumnStyle.scale = defaultValue(this.tableColumnStyle.scale, 1); }
javascript
{ "resource": "" }