_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q25400
train
function(render, fn) { if (typeof render === 'function') { fn = render; render = false; } // separate the tracking of the application over rendered pages if (render) { app.render('partials/analytics', function(error, html) { if (error) { return fn(error); } // hack :-\ (because the HTML gets cached) fn( error, html.replace(config.analytics.id, config.analytics['render-id']) ); }); } else { // this doesn't get called anymore app.render('analytics', { id: app.get('analytics id') }, fn); } }
javascript
{ "resource": "" }
q25401
train
function(path, full, secure) { var root = ''; if (full) { root = app.set('url full'); } else { root = app.set('url prefix'); } // Remove preceding slash if one exists. if (path && path[0] === '/') { path = path.slice(1); } if (secure) { root = undefsafe(config, 'url.ssl.host') || undefsafe(config, 'url.host'); root = 'https://' + root; } return path ? root + '/' + path : root; }
javascript
{ "resource": "" }
q25402
train
function(user, size) { var email = (user.email || '').trim().toLowerCase(); var name = user.name || 'default'; var d = 'd=blank'; if (!size || size < 120) { d = 'd=' + encodeURIComponent( 'https://jsbin-gravatar.herokuapp.com/' + name + '.png' ); } var hash = crypto .createHash('md5') .update(email) .digest('hex'); return user.email ? 'https://www.gravatar.com/avatar/' + hash + '?s=' + (size || 29) + '&' + d : user.avatar; }
javascript
{ "resource": "" }
q25403
train
function(path, secure) { var root = app.get('static url').replace(/.*:\/\//, ''); var proto = 'http'; if (path && path[0] === '/') { path = path.slice(1); } if (secure) { root = undefsafe(config, 'url.ssl.static') || undefsafe(config, 'url.static') || undefsafe(config, 'url.host'); proto = 'https'; } return path ? proto + '://' + root + '/' + (path || '') : proto + '://' + root; }
javascript
{ "resource": "" }
q25404
clearMarks
train
function clearMarks(editor, arr, classes) { for (var i = 0; i < arr.length; ++i) { var mark = arr[i]; if (mark instanceof CodeMirror.TextMarker) { mark.clear(); } else { editor.removeLineClass(mark, "background", classes.chunk); editor.removeLineClass(mark, "background", classes.start); editor.removeLineClass(mark, "background", classes.end); } } arr.length = 0; }
javascript
{ "resource": "" }
q25405
updateMarks
train
function updateMarks(editor, diff, state, type, classes) { var vp = editor.getViewport(); editor.operation(function() { if (state.from == state.to || vp.from - state.to > 20 || state.from - vp.to > 20) { clearMarks(editor, state.marked, classes); markChanges(editor, diff, type, state.marked, vp.from, vp.to, classes); state.from = vp.from; state.to = vp.to; } else { if (vp.from < state.from) { markChanges(editor, diff, type, state.marked, vp.from, state.from, classes); state.from = vp.from; } if (vp.to > state.to) { markChanges(editor, diff, type, state.marked, state.to, vp.to, classes); state.to = vp.to; } } }); }
javascript
{ "resource": "" }
q25406
drawConnectors
train
function drawConnectors(dv) { if (!dv.showDifferences) return; if (dv.svg) { clear(dv.svg); var w = dv.gap.offsetWidth; attrs(dv.svg, "width", w, "height", dv.gap.offsetHeight); } clear(dv.copyButtons); var flip = dv.type == "left"; var vpEdit = dv.edit.getViewport(), vpOrig = dv.orig.getViewport(); var sTopEdit = dv.edit.getScrollInfo().top, sTopOrig = dv.orig.getScrollInfo().top; iterateChunks(dv.diff, function(topOrig, botOrig, topEdit, botEdit) { if (topEdit > vpEdit.to || botEdit < vpEdit.from || topOrig > vpOrig.to || botOrig < vpOrig.from) return; var topLpx = dv.orig.heightAtLine(topOrig, "local") - sTopOrig, top = topLpx; if (dv.svg) { var topRpx = dv.edit.heightAtLine(topEdit, "local") - sTopEdit; if (flip) { var tmp = topLpx; topLpx = topRpx; topRpx = tmp; } var botLpx = dv.orig.heightAtLine(botOrig, "local") - sTopOrig; var botRpx = dv.edit.heightAtLine(botEdit, "local") - sTopEdit; if (flip) { var tmp = botLpx; botLpx = botRpx; botRpx = tmp; } var curveTop = " C " + w/2 + " " + topRpx + " " + w/2 + " " + topLpx + " " + (w + 2) + " " + topLpx; var curveBot = " C " + w/2 + " " + botLpx + " " + w/2 + " " + botRpx + " -1 " + botRpx; attrs(dv.svg.appendChild(document.createElementNS(svgNS, "path")), "d", "M -1 " + topRpx + curveTop + " L " + (w + 2) + " " + botLpx + curveBot + " z", "class", dv.classes.connect); } var copy = dv.copyButtons.appendChild(elt("div", dv.type == "left" ? "\u21dd" : "\u21dc", "CodeMirror-merge-copy")); copy.title = "Revert chunk"; copy.chunk = {topEdit: topEdit, botEdit: botEdit, topOrig: topOrig, botOrig: botOrig}; copy.style.top = top + "px"; }); }
javascript
{ "resource": "" }
q25407
train
function(bin) { var binSettings = {}; // self defence against muppertary if (typeof bin.settings === 'string') { try { binSettings = JSON.parse(bin.settings); } catch (e) {} } else { binSettings = bin.settings; } if ( binSettings && binSettings.processors && Object.keys(binSettings.processors).length ) { return Promise.all( Object.keys(binSettings.processors).map(function(panel) { var processorName = binSettings.processors[panel], code = bin[panel]; if (processors.support(processorName)) { bin['original_' + panel] = code; return processors .run(processorName, { source: code, url: bin.url, revision: bin.revision, }) .then(function(output) { var result = ''; if (output.result) { result = output.result; } else { result = output.errors .map(function(error) { return ( 'Line: ' + error.line + '\nCharacter: ' + error.ch + '\nMessage: ' + error.msg ); }) .join('\n\n'); } bin[panel] = result; return bin; }) .catch(function() { return bin; }); } else { return Promise.resolve(bin); } }) ); } // otherwise default to being resolved return Promise.resolve([bin]); }
javascript
{ "resource": "" }
q25408
getLinks
train
function getLinks() { var links = [], alllinks, i = 0, length; alllinks = document.getElementsByTagName('a'); length = alllinks.length; for (; i < length; i++) { if ((' ' + alllinks[i].className).indexOf(' jsbin-') !== -1) { links.push(alllinks[i]); } } return links; }
javascript
{ "resource": "" }
q25409
peek
train
function peek(p) { var i = p || 0, j = 0, t; while (j <= i) { t = lookahead[j]; if (!t) { t = lookahead[j] = lex.token(); } j += 1; } return t; }
javascript
{ "resource": "" }
q25410
nobreaknonadjacent
train
function nobreaknonadjacent(left, right) { left = left || state.tokens.curr; right = right || state.tokens.next; if (!state.option.laxbreak && left.line !== right.line) { warning("W014", right, right.value); } }
javascript
{ "resource": "" }
q25411
identifier
train
function identifier(fnparam, prop) { var i = optionalidentifier(fnparam, prop); if (i) { return i; } if (state.tokens.curr.id === "function" && state.tokens.next.id === "(") { warning("W025"); } else { error("E030", state.tokens.next, state.tokens.next.value); } }
javascript
{ "resource": "" }
q25412
train
function () { var pn, pn1; var i = -1; var bracketStack = 0; var ret = {}; if (_.contains(["[", "{"], state.tokens.curr.value)) bracketStack += 1; do { pn = (i === -1) ? state.tokens.next : peek(i); pn1 = peek(i + 1); i = i + 1; if (_.contains(["[", "{"], pn.value)) { bracketStack += 1; } else if (_.contains(["]", "}"], pn.value)) { bracketStack -= 1; } if (pn.identifier && pn.value === "for" && bracketStack === 1) { ret.isCompArray = true; ret.notJson = true; break; } if (_.contains(["}", "]"], pn.value) && pn1.value === "=" && bracketStack === 0) { ret.isDestAssign = true; ret.notJson = true; break; } if (pn.value === ";") { ret.isBlock = true; ret.notJson = true; } } while (bracketStack > 0 && pn.id !== "(end)" && i < 15); return ret; }
javascript
{ "resource": "" }
q25413
commentToken
train
function commentToken(label, body, opt) { var special = ["jshint", "jslint", "members", "member", "globals", "global", "exported"]; var isSpecial = false; var value = label + body; var commentType = "plain"; opt = opt || {}; if (opt.isMultiline) { value += "*/"; } special.forEach(function (str) { if (isSpecial) { return; } // Don't recognize any special comments other than jshint for single-line // comments. This introduced many problems with legit comments. if (label === "//" && str !== "jshint") { return; } if (body.substr(0, str.length) === str) { isSpecial = true; label = label + str; body = body.substr(str.length); } if (!isSpecial && body.charAt(0) === " " && body.substr(1, str.length) === str) { isSpecial = true; label = label + " " + str; body = body.substr(str.length + 1); } if (!isSpecial) { return; } switch (str) { case "member": commentType = "members"; break; case "global": commentType = "globals"; break; default: commentType = str; } }); return { type: Token.Comment, commentType: commentType, value: value, body: body, isSpecial: isSpecial, isMultiline: opt.isMultiline || false, isMalformed: opt.isMalformed || false }; }
javascript
{ "resource": "" }
q25414
split_newlines
train
function split_newlines(s) { //return s.split(/\x0d\x0a|\x0a/); s = s.replace(/\x0d/g, ''); var out = [], idx = s.indexOf("\n"); while (idx !== -1) { out.push(s.substring(0, idx)); s = s.substring(idx + 1); idx = s.indexOf("\n"); } if (s.length) { out.push(s); } return out; }
javascript
{ "resource": "" }
q25415
train
function (req, res) { var event = req.stripeEvent; var data = event.data.object; // takes care of unexpected event types var transactionMethod = stripeTransactions[event.type] || stripeTransactions.unhandled; transactionMethod(req, data, function (err){ if ( !err ) { return res.send(200); } console.log('stripe webhook error'); console.log(event.type); console.log(err.stack); res.send(500, err); }); }
javascript
{ "resource": "" }
q25416
train
function (requested) { // No postMessage? Don't render – the event-stream will handle it. if (!window.postMessage) { return; } // Inform other pages event streaming render to reload if (requested) { sendReload(); jsbin.state.hasBody = false; } getPreparedCode().then(function (source) { var includeJsInRealtime = jsbin.settings.includejs; // Tell the iframe to reload var visiblePanels = jsbin.panels.getVisible(); var outputPanelOpen = visiblePanels.indexOf(jsbin.panels.panels.live) > -1; var consolePanelOpen = visiblePanels.indexOf(jsbin.panels.panels.console) > -1; if (!outputPanelOpen && !consolePanelOpen) { return; } // this is a flag that helps detect crashed runners if (jsbin.settings.includejs) { store.sessionStorage.setItem('runnerPending', 1); } renderer.postMessage('render', { source: source, options: { injectCSS: jsbin.state.hasBody && jsbin.panels.focused.id === 'css', requested: requested, debug: jsbin.settings.debug, includeJsInRealtime: jsbin.settings.includejs, }, }); jsbin.state.hasBody = true; }); }
javascript
{ "resource": "" }
q25417
updateArgHints
train
function updateArgHints(ts, cm) { closeArgHints(ts); if (cm.somethingSelected()) return; var state = cm.getTokenAt(cm.getCursor()).state; var inner = CodeMirror.innerMode(cm.getMode(), state); if (inner.mode.name != "javascript") return; var lex = inner.state.lexical; if (lex.info != "call") return; var ch, argPos = lex.pos || 0, tabSize = cm.getOption("tabSize"); for (var line = cm.getCursor().line, e = Math.max(0, line - 9), found = false; line >= e; --line) { var str = cm.getLine(line), extra = 0; for (var pos = 0;;) { var tab = str.indexOf("\t", pos); if (tab == -1) break; extra += tabSize - (tab + extra) % tabSize - 1; pos = tab + 1; } ch = lex.column - extra; if (str.charAt(ch) == "(") {found = true; break;} } if (!found) return; var start = Pos(line, ch); var cache = ts.cachedArgHints; if (cache && cache.doc == cm.getDoc() && cmpPos(start, cache.start) == 0) return showArgHints(ts, cm, argPos); ts.request(cm, {type: "type", preferFunction: true, end: start}, function(error, data) { if (error || !data.type || !(/^fn\(/).test(data.type)) return; ts.cachedArgHints = { start: pos, type: parseFnType(data.type), name: data.exprName || data.name || "fn", guess: data.guess, doc: cm.getDoc() }; showArgHints(ts, cm, argPos); }); }
javascript
{ "resource": "" }
q25418
buildRequest
train
function buildRequest(ts, doc, query, pos) { var files = [], offsetLines = 0, allowFragments = !query.fullDocs; if (!allowFragments) delete query.fullDocs; if (typeof query == "string") query = {type: query}; query.lineCharPositions = true; if (query.end == null) { query.end = pos || doc.doc.getCursor("end"); if (doc.doc.somethingSelected()) query.start = doc.doc.getCursor("start"); } var startPos = query.start || query.end; if (doc.changed) { if (doc.doc.lineCount() > bigDoc && allowFragments !== false && doc.changed.to - doc.changed.from < 100 && doc.changed.from <= startPos.line && doc.changed.to > query.end.line) { files.push(getFragmentAround(doc, startPos, query.end)); query.file = "#0"; var offsetLines = files[0].offsetLines; if (query.start != null) query.start = Pos(query.start.line - -offsetLines, query.start.ch); query.end = Pos(query.end.line - offsetLines, query.end.ch); } else { files.push({type: "full", name: doc.name, text: docValue(ts, doc)}); query.file = doc.name; doc.changed = null; } } else { query.file = doc.name; } for (var name in ts.docs) { var cur = ts.docs[name]; if (cur.changed && cur != doc) { files.push({type: "full", name: cur.name, text: docValue(ts, cur)}); cur.changed = null; } } return {query: query, files: files}; }
javascript
{ "resource": "" }
q25419
stringify
train
function stringify(o, simple) { var json = '', i, type = ({}).toString.call(o), parts = [], names = []; if (type == '[object String]') { json = '"' + o.replace(/\n/g, '\\n').replace(/"/g, '\\"') + '"'; } else if (type == '[object Array]') { json = '['; for (i = 0; i < o.length; i++) { parts.push(stringify(o[i], simple)); } json += parts.join(', ') + ']'; json; } else if (type == '[object Object]') { json = '{'; for (i in o) { names.push(i); } names.sort(sortci); for (i = 0; i < names.length; i++) { parts.push(stringify(names[i]) + ': ' + stringify(o[names[i] ], simple)); } json += parts.join(', ') + '}'; } else if (type == '[object Number]') { json = o+''; } else if (type == '[object Boolean]') { json = o ? 'true' : 'false'; } else if (type == '[object Function]') { json = o.toString(); } else if (o === null) { json = 'null'; } else if (o === undefined) { json = 'undefined'; } else if (simple == undefined) { json = type + '{\n'; for (i in o) { names.push(i); } names.sort(sortci); for (i = 0; i < names.length; i++) { parts.push(names[i] + ': ' + stringify(o[names[i]], true)); // safety from max stack } json += parts.join(',\n') + '\n}'; } else { try { json = o+''; // should look like an object } catch (e) {} } return json; }
javascript
{ "resource": "" }
q25420
train
function (rawData) { var data = stringify(rawData); if (useSS) { sessionStorage.spike = data; } else { window.name = data; } return data; }
javascript
{ "resource": "" }
q25421
train
function () { var rawData = useSS ? sessionStorage.spike : window.name, data; if ((!useSS && window.name == 1) || !rawData) return data; try { // sketchy, but doesn't rely on native json support which might be a // problem in old mobiles eval('data = ' + rawData); } catch (e) {} return data; }
javascript
{ "resource": "" }
q25422
restore
train
function restore() { var data = store.get() || {}; addEvent('load', function () { //console.log('scrolling to', data.y); window.scrollTo(data.x, data.y); }); }
javascript
{ "resource": "" }
q25423
makeScope
train
function makeScope(prev, isCatch) { return {vars: Object.create(null), prev: prev, isCatch: isCatch}; }
javascript
{ "resource": "" }
q25424
train
function(cm) { if (CodeMirror.snippets(cm) === CodeMirror.Pass) { return CodeMirror.simpleHint(cm, CodeMirror.hint.javascript); } }
javascript
{ "resource": "" }
q25425
getHeaders
train
function getHeaders(config) { const headers = { 'X-Presto-User': config.user }; if (config.catalog) { headers['X-Presto-Catalog'] = config.catalog; } if (config.schema) { headers['X-Presto-Schema'] = config.schema; } return headers; }
javascript
{ "resource": "" }
q25426
send
train
function send(config, query) { if (!config.url) { return Promise.reject(new Error('config.url is required')); } const results = { data: [] }; return fetch(`${config.url}/v1/statement`, { method: 'POST', body: query, headers: getHeaders(config) }) .then(response => response.json()) .then(statement => handleStatementAndGetMore(results, statement, config)); }
javascript
{ "resource": "" }
q25427
getSchema
train
function getSchema(connection) { connection.maxRows = 1000000; return runQuery(SCHEMA_SQL, connection).then(queryResult => formatSchemaQueryResults(queryResult) ); }
javascript
{ "resource": "" }
q25428
runMigrations
train
function runMigrations(db, currentVersion) { return new Promise((resolve, reject) => { const nextVersion = currentVersion + 1; if (!migrations[nextVersion]) { return resolve(); } if (debug) { console.log('Migrating schema to v%d', nextVersion); } migrations[nextVersion](db) .then(() => { // write new schemaVersion file const json = JSON.stringify({ schemaVersion: nextVersion }); fs.writeFile(schemaVersionFilePath, json, err => { if (err) { return reject(err); } resolve(runMigrations(db, nextVersion)); }); }) .catch(reject); }); }
javascript
{ "resource": "" }
q25429
validateFunction
train
function validateFunction(path, driver, functionName) { if (typeof driver[functionName] !== 'function') { console.error(`${path} missing .${functionName}() implementation`); process.exit(1); } }
javascript
{ "resource": "" }
q25430
validateArray
train
function validateArray(path, driver, arrayName) { const arr = driver[arrayName]; if (!Array.isArray(arr)) { console.error(`${path} missing ${arrayName} array`); process.exit(1); } }
javascript
{ "resource": "" }
q25431
requireValidate
train
function requireValidate(path, optional = false) { let driver; try { driver = require(path); } catch (er) { if (optional) { console.log('optional driver ' + path + ' not available'); return; } else { // rethrow throw er; } } if (!driver.id) { console.error(`${path} must export a unique id`); process.exit(1); } if (!driver.name) { console.error(`${path} must export a name`); process.exit(1); } if (drivers[driver.id]) { console.error(`Driver with id ${driver.id} already loaded`); console.error(`Ensure ${path} has a unique id exported`); process.exit(1); } validateFunction(path, driver, 'getSchema'); validateFunction(path, driver, 'runQuery'); validateFunction(path, driver, 'testConnection'); validateArray(path, driver, 'fields'); driver.fieldsByKey = {}; driver.fields.forEach(field => { driver.fieldsByKey[field.key] = field; }); drivers[driver.id] = driver; }
javascript
{ "resource": "" }
q25432
runQuery
train
function runQuery(query, connection, user) { const driver = drivers[connection.driver]; const queryResult = { id: uuid.v4(), cacheKey: null, startTime: new Date(), stopTime: null, queryRunTime: null, fields: [], incomplete: false, meta: {}, rows: [] }; return driver.runQuery(query, connection).then(results => { const { rows, incomplete } = results; if (!Array.isArray(rows)) { throw new Error(`${connection.driver}.runQuery() must return rows array`); } queryResult.incomplete = incomplete || false; queryResult.rows = rows; queryResult.stopTime = new Date(); queryResult.queryRunTime = queryResult.stopTime - queryResult.startTime; queryResult.meta = getMeta(rows); queryResult.fields = Object.keys(queryResult.meta); if (debug) { const connectionName = connection.name; const rowCount = rows.length; const { startTime, stopTime, queryRunTime } = queryResult; console.log( JSON.stringify({ userId: user && user._id, userEmail: user && user.email, connectionName, startTime, stopTime, queryRunTime, rowCount, query }) ); } return queryResult; }); }
javascript
{ "resource": "" }
q25433
getDrivers
train
function getDrivers() { return Object.keys(drivers).map(id => { return { id, name: drivers[id].name, fields: drivers[id].fields }; }); }
javascript
{ "resource": "" }
q25434
validateConnection
train
function validateConnection(connection) { const coreFields = ['_id', 'name', 'driver', 'createdDate', 'modifiedDate']; if (!connection.name) { throw new Error('connection.name required'); } if (!connection.driver) { throw new Error('connection.driver required'); } const driver = drivers[connection.driver]; if (!driver) { throw new Error(`driver implementation ${connection.driver} not found`); } const validFields = driver.fields.map(field => field.key).concat(coreFields); const cleanedConnection = validFields.reduce( (cleanedConnection, fieldKey) => { if (connection.hasOwnProperty(fieldKey)) { let value = connection[fieldKey]; const fieldDefinition = drivers[connection.driver].fieldsByKey[fieldKey]; // field definition may not exist since // this could be a core field like _id, name if (fieldDefinition) { if (fieldDefinition.formType === 'CHECKBOX') { value = utils.ensureBoolean(value); } } cleanedConnection[fieldKey] = value; } return cleanedConnection; }, {} ); return cleanedConnection; }
javascript
{ "resource": "" }
q25435
formatSchemaQueryResults
train
function formatSchemaQueryResults(queryResult) { if (!queryResult || !queryResult.rows || !queryResult.rows.length) { return {}; } // queryResult row casing may not always be consistent with what is specified in query // HANA is always uppercase despire aliasing as lower case for example // To account for this loop through rows and normalize the case const rows = queryResult.rows.map(row => { const cleanRow = {}; Object.keys(row).forEach(key => { cleanRow[key.toLowerCase()] = row[key]; }); return cleanRow; }); const tree = {}; const bySchema = _.groupBy(rows, 'table_schema'); for (const schema in bySchema) { if (bySchema.hasOwnProperty(schema)) { tree[schema] = {}; const byTableName = _.groupBy(bySchema[schema], 'table_name'); for (const tableName in byTableName) { if (byTableName.hasOwnProperty(tableName)) { tree[schema][tableName] = byTableName[tableName]; } } } } /* At this point, tree should look like this: { "schema-name": { "table-name": [ { column_name: "the column name", data_type: "string" } ] } } */ return tree; }
javascript
{ "resource": "" }
q25436
ensureBoolean
train
function ensureBoolean(value) { if (typeof value === 'boolean') { return value; } if (typeof value === 'string' && value.toLowerCase() === 'true') { return true; } else if (typeof value === 'string' && value.toLowerCase() === 'false') { return false; } else if (value === 1) { return true; } else if (value === 0) { return false; } throw new Error(`Unexpected value for boolean: ${value}`); }
javascript
{ "resource": "" }
q25437
isNumeric
train
function isNumeric(value) { if (_.isNumber(value)) { return true; } if (_.isString(value)) { if (!isFinite(value)) { return false; } // str is a finite number, but not all number strings should be numbers // If the string starts with 0, is more than 1 character, and does not have a period, it should stay a string // It could be an account number for example if (value[0] === '0' && value.length > 1 && value.indexOf('.') === -1) { return false; } return true; } return false; }
javascript
{ "resource": "" }
q25438
fullUrl
train
function fullUrl(path) { const urlPort = port === 80 ? '' : ':' + port; const urlPublicUrl = publicUrl; const urlBaseUrl = baseUrl; return `${urlPublicUrl}${urlPort}${urlBaseUrl}${path}`; }
javascript
{ "resource": "" }
q25439
getCurrentPath
train
function getCurrentPath(){ try{ // FF, Chrome, Modern browsers // use their API to get the path of current script // a.b(); // console.log('wpStage1'); return document.currentScript.src; if(DOC.currentScript){ // FF 4+ return DOC.currentScript.src; } }catch(e){ // document.currentScript doesn't supports // console.log('wpStage2'); // Method 1 // https://github.com/mozilla/pdf.js/blob/e081a708c36cb2aacff7889048863723fcf23671/src/shared/compatibility.js#L97 // IE, Chrome < 29 let scripts = document.getElementsByTagName('script'); return scripts[scripts.length - 1].src; /* // Method 2 // parse the error stack trace maually // https://github.com/workhorsy/uncompress.js/blob/master/js/uncompress.js#L25 let stack = e.stack; let line = null; // Chrome and IE if (stack.indexOf('@') !== -1) { line = stack.split('@')[1].split('\n')[0]; // Firefox } else { line = stack.split('(')[1].split(')')[0]; } line = line.substring(0, line.lastIndexOf('/')) + '/'; return line; */ /* // Method 3 // https://www.cnblogs.com/rubylouvre/archive/2013/01/23/2872618.html let stack = e.stack; if(!stack && window.opera){ // Opera 9没有e.stack,但有e.Backtrace,但不能直接取得,需要对e对象转字符串进行抽取 stack = (String(e).match(/of linked script \S+/g) || []).join(' '); } if(stack){ // e.stack最后一行在所有支持的浏览器大致如下:       // chrome23:       // @ http://113.93.50.63/data.js:4:1       // firefox17:       // @http://113.93.50.63/query.js:4       // opera12:       // @http://113.93.50.63/data.js:4       // IE10:       // @ Global code (http://113.93.50.63/data.js:4:1)      stack = stack.split(/[@ ]/g).pop(); // 取得最后一行,最后一个空格或@之后的部分 stack = stack[0] == '(' ? stack.slice(1,-1) : stack; return stack.replace(/(:\d+)?:\d+$/i, ''); // 去掉行号与或许存在的出错字符起始位置 } let nodes = head.getElementsByTagName('script'); // 只在head标签中寻找 for(var i = 0, node; node = nodes[i++];){ if(node.readyState === 'interactive'){ return node.className = node.src; } } */ } }
javascript
{ "resource": "" }
q25440
theRealInit
train
function theRealInit (){ createElement(); initEvent(); live2DMgr = new cManager(L2Dwidget) dragMgr = new L2DTargetPoint(); let rect = currCanvas.getBoundingClientRect(); let ratio = rect.height / rect.width; let left = cDefine.VIEW_LOGICAL_LEFT; let right = cDefine.VIEW_LOGICAL_RIGHT; let bottom = -ratio; let top = ratio; viewMatrix = new L2DViewMatrix(); viewMatrix.setScreenRect(left, right, bottom, top); viewMatrix.setMaxScreenRect(cDefine.VIEW_LOGICAL_MAX_LEFT, cDefine.VIEW_LOGICAL_MAX_RIGHT, cDefine.VIEW_LOGICAL_MAX_BOTTOM, cDefine.VIEW_LOGICAL_MAX_TOP); modelScaling(device.mobile() && config.mobile.scale || config.model.scale) projMatrix = new L2DMatrix44(); projMatrix.multScale(1, (rect.width / rect.height)); deviceToScreen = new L2DMatrix44(); deviceToScreen.multTranslate(-rect.width / 2.0, -rect.height / 2.0); // #32 deviceToScreen.multScale(2 / rect.width, -2 / rect.height); // #32 Live2D.setGL(currWebGL); currWebGL.clearColor(0.0, 0.0, 0.0, 0.0); changeModel(config.model.jsonPath); startDraw(); }
javascript
{ "resource": "" }
q25441
createElement
train
function createElement() { let e = document.getElementById(config.name.div) if (e !== null) { document.body.removeChild(e); } let newElem = document.createElement('div'); newElem.id = config.name.div; newElem.className = 'live2d-widget-container'; newElem.style.setProperty('position', 'fixed'); newElem.style.setProperty(config.display.position, config.display.hOffset + 'px'); newElem.style.setProperty('bottom', config.display.vOffset + 'px'); newElem.style.setProperty('width', config.display.width + 'px'); newElem.style.setProperty('height', config.display.height + 'px'); newElem.style.setProperty('z-index', 99999); newElem.style.setProperty('opacity', config.react.opacity); newElem.style.setProperty('pointer-events', 'none'); document.body.appendChild(newElem); L2Dwidget.emit('create-container', newElem); if (config.dialog.enable) createDialogElement(newElem); let newCanvasElem = document.createElement('canvas'); newCanvasElem.setAttribute('id', config.name.canvas); newCanvasElem.setAttribute('width', config.display.width * config.display.superSample); newCanvasElem.setAttribute('height', config.display.height * config.display.superSample); newCanvasElem.style.setProperty('position', 'absolute'); newCanvasElem.style.setProperty('left', '0px'); newCanvasElem.style.setProperty('top', '0px'); newCanvasElem.style.setProperty('width', config.display.width + 'px'); newCanvasElem.style.setProperty('height', config.display.height + 'px'); if (config.dev.border) newCanvasElem.style.setProperty('border', 'dashed 1px #CCC'); newElem.appendChild(newCanvasElem); currCanvas = document.getElementById(config.name.canvas); L2Dwidget.emit('create-canvas', newCanvasElem); initWebGL(); }
javascript
{ "resource": "" }
q25442
initWebGL
train
function initWebGL() { var NAMES = ['webgl2', 'webgl', 'experimental-webgl2', 'experimental-webgl', 'webkit-3d', 'moz-webgl']; for (let i = 0; i < NAMES.length; i++) { try { let ctx = currCanvas.getContext(NAMES[i], { alpha: true, antialias: true, premultipliedAlpha: true, failIfMajorPerformanceCaveat: false, }); if (ctx) currWebGL = ctx; } catch (e) { } } if (!currWebGL) { console.error('Live2D widgets: Failed to create WebGL context.'); if (!window.WebGLRenderingContext) { console.error('Your browser may not support WebGL, check https://get.webgl.org/ for futher information.'); } return; } }
javascript
{ "resource": "" }
q25443
tween
train
function tween(duration, fn, done, ease, from, to) { ease = fun(ease) ? ease : morpheus.easings[ease] || nativeTween var time = duration || thousand , self = this , diff = to - from , start = now() , stop = 0 , end = 0 function run(t) { var delta = t - start if (delta > time || stop) { to = isFinite(to) ? to : 1 stop ? end && fn(to) : fn(to) die(run) return done && done.apply(self) } // if you don't specify a 'to' you can use tween as a generic delta tweener // cool, eh? isFinite(to) ? fn((diff * ease(delta / time)) + from) : fn(ease(delta / time)) } live(run) return { stop: function (jump) { stop = 1 end = jump // jump to end of animation? if (!jump) done = null // remove callback if not jumping to end } } }
javascript
{ "resource": "" }
q25444
nextColor
train
function nextColor(pos, start, finish) { var r = [], i, e, from, to for (i = 0; i < 6; i++) { from = Math.min(15, parseInt(start.charAt(i), 16)) to = Math.min(15, parseInt(finish.charAt(i), 16)) e = Math.floor((to - from) * pos + from) e = e > 15 ? 15 : e < 0 ? 0 : e r[i] = e.toString(16) } return '#' + r.join('') }
javascript
{ "resource": "" }
q25445
getTweenVal
train
function getTweenVal(pos, units, begin, end, k, i, v) { if (k == 'transform') { v = {} for (var t in begin[i][k]) { v[t] = (t in end[i][k]) ? Math.round(((end[i][k][t] - begin[i][k][t]) * pos + begin[i][k][t]) * thousand) / thousand : begin[i][k][t] } return v } else if (typeof begin[i][k] == 'string') { return nextColor(pos, begin[i][k], end[i][k]) } else { // round so we don't get crazy long floats v = Math.round(((end[i][k] - begin[i][k]) * pos + begin[i][k]) * thousand) / thousand // some css properties don't require a unit (like zIndex, lineHeight, opacity) if (!(k in unitless)) v += units[i][k] || 'px' return v } }
javascript
{ "resource": "" }
q25446
by
train
function by(val, start, m, r, i) { return (m = relVal.exec(val)) ? (i = parseFloat(m[2])) && (start + (m[1] == '+' ? 1 : -1) * i) : parseFloat(val) }
javascript
{ "resource": "" }
q25447
train
function() { var _layout = this.options.layout; for (var i = 0; i < this._slides.length; i++) { this._slides[i].updateDisplay(this.options.width, this.options.height, _layout); this._slides[i].setPosition({left:(this.slide_spacing * i), top:0}); }; this.goToId(this.current_id, true, false); }
javascript
{ "resource": "" }
q25448
train
function(slide) { var slide_id = slide.unique_id; if (!TL.Util.trim(slide_id)) { // give it an ID if it doesn't have one slide_id = (slide.text) ? TL.Util.slugify(slide.text.headline) : null; } // make sure it's unique and add it. slide.unique_id = TL.Util.ensureUniqueKey(this.event_dict,slide_id); return slide.unique_id }
javascript
{ "resource": "" }
q25449
train
function() { // counting that dates were sorted in initialization var date = this.events[0].start_date; if (this.eras && this.eras.length > 0) { if (this.eras[0].start_date.isBefore(date)) { return this.eras[0].start_date; } } return date; }
javascript
{ "resource": "" }
q25450
train
function() { var dates = []; for (var i = 0; i < this.events.length; i++) { if (this.events[i].end_date) { dates.push({ date: this.events[i].end_date }); } else { dates.push({ date: this.events[i].start_date }); } } for (var i = 0; i < this.eras.length; i++) { if (this.eras[i].end_date) { dates.push({ date: this.eras[i].end_date }); } else { dates.push({ date: this.eras[i].start_date }); } } TL.DateUtil.sortByDate(dates, 'date'); return dates.slice(-1)[0].date; }
javascript
{ "resource": "" }
q25451
train
function (/*Object*/ dest) /*-> Object*/ { // merge src properties into dest var sources = Array.prototype.slice.call(arguments, 1); for (var j = 0, len = sources.length, src; j < len; j++) { src = sources[j] || {}; TL.Util.mergeData(dest, src); } return dest; }
javascript
{ "resource": "" }
q25452
load
train
function load(type, urls, callback, obj, context) { var _finish = function () { finish(type); }, isCSS = type === 'css', nodes = [], i, len, node, p, pendingUrls, url; env || getEnv(); if (urls) { // If urls is a string, wrap it in an array. Otherwise assume it's an // array and create a copy of it so modifications won't be made to the // original. urls = typeof urls === 'string' ? [urls] : urls.concat(); // Create a request object for each URL. If multiple URLs are specified, // the callback will only be executed after all URLs have been loaded. // // Sadly, Firefox and Opera are the only browsers capable of loading // scripts in parallel while preserving execution order. In all other // browsers, scripts must be loaded sequentially. // // All browsers respect CSS specificity based on the order of the link // elements in the DOM, regardless of the order in which the stylesheets // are actually downloaded. if (isCSS || env.async || env.gecko || env.opera) { // Load in parallel. queue[type].push({ urls : urls, callback: callback, obj : obj, context : context }); } else { // Load sequentially. for (i = 0, len = urls.length; i < len; ++i) { queue[type].push({ urls : [urls[i]], callback: i === len - 1 ? callback : null, // callback is only added to the last URL obj : obj, context : context }); } } } // If a previous load request of this type is currently in progress, we'll // wait our turn. Otherwise, grab the next item in the queue. if (pending[type] || !(p = pending[type] = queue[type].shift())) { return; } head || (head = doc.head || doc.getElementsByTagName('head')[0]); pendingUrls = p.urls; for (i = 0, len = pendingUrls.length; i < len; ++i) { url = pendingUrls[i]; if (isCSS) { node = env.gecko ? createNode('style') : createNode('link', { href: url, rel : 'stylesheet' }); } else { node = createNode('script', {src: url}); node.async = false; } node.className = 'lazyload'; node.setAttribute('charset', 'utf-8'); if (env.ie && !isCSS) { node.onreadystatechange = function () { if (/loaded|complete/.test(node.readyState)) { node.onreadystatechange = null; _finish(); } }; } else if (isCSS && (env.gecko || env.webkit)) { // Gecko and WebKit don't support the onload event on link nodes. if (env.webkit) { // In WebKit, we can poll for changes to document.styleSheets to // figure out when stylesheets have loaded. p.urls[i] = node.href; // resolve relative URLs (or polling won't work) pollWebKit(); } else { // In Gecko, we can import the requested URL into a <style> node and // poll for the existence of node.sheet.cssRules. Props to Zach // Leatherman for calling my attention to this technique. node.innerHTML = '@import "' + url + '";'; pollGecko(node); } } else { node.onload = node.onerror = _finish; } nodes.push(node); } for (i = 0, len = nodes.length; i < len; ++i) { head.appendChild(nodes[i]); } }
javascript
{ "resource": "" }
q25453
train
function(scale) { var d = new Date(this.data.date_obj.getTime()); for (var i = 0; i < TL.Date.SCALES.length; i++) { // for JS dates, we iteratively apply flooring functions TL.Date.SCALES[i][2](d); if (TL.Date.SCALES[i][0] == scale) return new TL.Date(d); }; throw new TL.Error("invalid_scale_err", scale); }
javascript
{ "resource": "" }
q25454
train
function(scale) { for (var i = 0; i < TL.BigDate.SCALES.length; i++) { if (TL.BigDate.SCALES[i][0] == scale) { var floored = TL.BigDate.SCALES[i][2](this.data.date_obj); return new TL.BigDate(floored); } }; throw new TL.Error("invalid_scale_err", scale); }
javascript
{ "resource": "" }
q25455
train
function(n) { if(this.config.title) { if(n == 0) { this.goToId(this.config.title.unique_id); } else { this.goToId(this.config.events[n - 1].unique_id); } } else { this.goToId(this.config.events[n].unique_id); } }
javascript
{ "resource": "" }
q25456
train
function(n) { if(n >= 0 && n < this.config.events.length) { // If removing the current, nav to new one first if(this.config.events[n].unique_id == this.current_id) { if(n < this.config.events.length - 1) { this.goTo(n + 1); } else { this.goTo(n - 1); } } var event = this.config.events.splice(n, 1); delete this.config.event_dict[event[0].unique_id]; this._storyslider.destroySlide(this.config.title ? n+1 : n); this._storyslider._updateDrawSlides(); this._timenav.destroyMarker(n); this._timenav._updateDrawTimeline(false); this.fire("removed", {unique_id: event[0].unique_id}); } }
javascript
{ "resource": "" }
q25457
train
function(id) { var hash = "#" + "event-" + id.toString(); if (window.location.protocol != 'file:') { window.history.replaceState(null, "Browsing TimelineJS", hash); } this.fire("hash_updated", {unique_id:this.current_id, hashbookmark:"#" + "event-" + id.toString()}, this); }
javascript
{ "resource": "" }
q25458
train
function () { var self = this; this.message.removeFrom(this._el.container); this._el.container.innerHTML = ""; // Create Layout if (this.options.timenav_position == "top") { this._el.timenav = TL.Dom.create('div', 'tl-timenav', this._el.container); this._el.storyslider = TL.Dom.create('div', 'tl-storyslider', this._el.container); } else { this._el.storyslider = TL.Dom.create('div', 'tl-storyslider', this._el.container); this._el.timenav = TL.Dom.create('div', 'tl-timenav', this._el.container); } this._el.menubar = TL.Dom.create('div', 'tl-menubar', this._el.container); // Initial Default Layout this.options.width = this._el.container.offsetWidth; this.options.height = this._el.container.offsetHeight; // this._el.storyslider.style.top = "1px"; // Set TimeNav Height this.options.timenav_height = this._calculateTimeNavHeight(this.options.timenav_height); // Create TimeNav this._timenav = new TL.TimeNav(this._el.timenav, this.config, this.options); this._timenav.on('loaded', this._onTimeNavLoaded, this); this._timenav.on('update_timenav_min', this._updateTimeNavHeightMin, this); this._timenav.options.height = this.options.timenav_height; this._timenav.init(); // intial_zoom cannot be applied before the timenav has been created if (this.options.initial_zoom) { // at this point, this.options refers to the merged set of options this.setZoom(this.options.initial_zoom); } // Create StorySlider this._storyslider = new TL.StorySlider(this._el.storyslider, this.config, this.options); this._storyslider.on('loaded', this._onStorySliderLoaded, this); this._storyslider.init(); // Create Menu Bar this._menubar = new TL.MenuBar(this._el.menubar, this._el.container, this.options); // LAYOUT if (this.options.layout == "portrait") { this.options.storyslider_height = (this.options.height - this.options.timenav_height - 1); } else { this.options.storyslider_height = (this.options.height - 1); } // Update Display this._updateDisplay(this._timenav.options.height, true, 2000); }
javascript
{ "resource": "" }
q25459
setBadge
train
function setBadge(todos) { if (chrome.browserAction) { const count = todos.filter(todo => !todo.marked).length; chrome.browserAction.setBadgeText({ text: count > 0 ? count.toString() : '' }); } }
javascript
{ "resource": "" }
q25460
train
function(string, options) { options = options || {}; var separator = options.separator || '_'; var split = options.split || /(?=[A-Z])/; return string.split(split).join(separator); }
javascript
{ "resource": "" }
q25461
train
function(convert, options) { var callback = options && 'process' in options ? options.process : options; if(typeof(callback) !== 'function') { return convert; } return function(string, options) { return callback(string, convert, options); } }
javascript
{ "resource": "" }
q25462
httpClientInMemBackendServiceFactory
train
function httpClientInMemBackendServiceFactory(dbService, options, xhrFactory) { var backend = new HttpClientBackendService(dbService, options, xhrFactory); return backend; }
javascript
{ "resource": "" }
q25463
_loop2
train
function _loop2(i) { var node = nodeList[i]; stickies.some(function (sticky) { if (sticky._node === node) { sticky.remove(); return true; } }); }
javascript
{ "resource": "" }
q25464
TS2JS
train
function TS2JS(tsFile) { const srcFolder = path.join(__dirname, '..', 'src'); const distFolder = path.join(__dirname, '..', 'build', 'main'); const tsPathObj = path.parse(tsFile); return path.format({ dir: tsPathObj.dir.replace(srcFolder, distFolder), ext: '.js', name: tsPathObj.name, root: tsPathObj.root }); }
javascript
{ "resource": "" }
q25465
replaceCLIArg
train
function replaceCLIArg(search, replace) { process.argv[process.argv.indexOf(search)] = replace; }
javascript
{ "resource": "" }
q25466
loadHTML
train
function loadHTML(url, id) { req = new XMLHttpRequest(); req.open('GET', url); req.send(); req.onload = () => { $id(id).innerHTML = req.responseText; }; }
javascript
{ "resource": "" }
q25467
train
function (attributes) { // These are all documented with their property accessors below. this._cornerRadius = attributes ? attributes._cornerRadius : 0; this._insets = attributes ? attributes._insets : new Insets(0, 0, 0, 0); this._backgroundColor = attributes ? attributes._backgroundColor.clone() : Color.WHITE.clone(); this._leaderGapWidth = attributes ? attributes._leaderGapWidth : 40; this._leaderGapHeight = attributes ? attributes._leaderGapHeight : 30; this._opacity = attributes ? attributes._opacity : 1; this._scale = attributes ? attributes._scale : 1; this._drawLeader = attributes ? attributes._drawLeader : true; this._width = attributes ? attributes._width : 200; this._height = attributes ? attributes._height : 100; this._textAttributes = attributes ? attributes._textAttributes : this.createDefaultTextAttributes(); /** * Indicates whether this object's state key is invalid. Subclasses must set this value to true when their * attributes change. The state key will be automatically computed the next time it's requested. This flag * will be set to false when that occurs. * @type {Boolean} * @protected */ this.stateKeyInvalid = true; }
javascript
{ "resource": "" }
q25468
train
function (capacity, lowWater) { if (!capacity || capacity < 1) { throw new ArgumentError(Logger.logMessage(Logger.LEVEL_SEVERE, "MemoryCache", "constructor", "The specified capacity is undefined, zero or negative")); } if (!lowWater || lowWater >= capacity || lowWater < 0) { throw new ArgumentError(Logger.logMessage(Logger.LEVEL_SEVERE, "MemoryCache", "constructor", "The specified low-water value is undefined, greater than or equal to the capacity, or less than 1")); } // Documented with its property accessor below. this._capacity = capacity; // Documented with its property accessor below. this._lowWater = lowWater; /** * The size currently used by this cache. * @type {Number} * @readonly */ this.usedCapacity = 0; /** * The size currently unused by this cache. * @type {Number} * @readonly */ this.freeCapacity = capacity; // Private. The cache entries. this.entries = {}; // Private. The cache listeners. this.listeners = []; }
javascript
{ "resource": "" }
q25469
train
function (m11, m12, m13, m14, m21, m22, m23, m24, m31, m32, m33, m34, m41, m42, m43, m44) { this[0] = m11; this[1] = m12; this[2] = m13; this[3] = m14; this[4] = m21; this[5] = m22; this[6] = m23; this[7] = m24; this[8] = m31; this[9] = m32; this[10] = m33; this[11] = m34; this[12] = m41; this[13] = m42; this[14] = m43; this[15] = m44; }
javascript
{ "resource": "" }
q25470
train
function (worldWindow) { WorldWindowController.call(this, worldWindow); // base class checks for a valid worldWindow // Intentionally not documented. this.primaryDragRecognizer = new DragRecognizer(this.wwd, null); this.primaryDragRecognizer.addListener(this); // Intentionally not documented. this.secondaryDragRecognizer = new DragRecognizer(this.wwd, null); this.secondaryDragRecognizer.addListener(this); this.secondaryDragRecognizer.button = 2; // secondary mouse button // Intentionally not documented. this.panRecognizer = new PanRecognizer(this.wwd, null); this.panRecognizer.addListener(this); // Intentionally not documented. this.pinchRecognizer = new PinchRecognizer(this.wwd, null); this.pinchRecognizer.addListener(this); // Intentionally not documented. this.rotationRecognizer = new RotationRecognizer(this.wwd, null); this.rotationRecognizer.addListener(this); // Intentionally not documented. this.tiltRecognizer = new TiltRecognizer(this.wwd, null); this.tiltRecognizer.addListener(this); // Establish the dependencies between gesture recognizers. The pan, pinch and rotate gesture may recognize // simultaneously with each other. this.panRecognizer.recognizeSimultaneouslyWith(this.pinchRecognizer); this.panRecognizer.recognizeSimultaneouslyWith(this.rotationRecognizer); this.pinchRecognizer.recognizeSimultaneouslyWith(this.rotationRecognizer); // Since the tilt gesture is a subset of the pan gesture, pan will typically recognize before tilt, // effectively suppressing tilt. Establish a dependency between the other touch gestures and tilt to provide // tilt an opportunity to recognize. this.panRecognizer.requireRecognizerToFail(this.tiltRecognizer); this.pinchRecognizer.requireRecognizerToFail(this.tiltRecognizer); this.rotationRecognizer.requireRecognizerToFail(this.tiltRecognizer); // Intentionally not documented. // this.tapRecognizer = new TapRecognizer(this.wwd, null); // this.tapRecognizer.addListener(this); // Intentionally not documented. // this.clickRecognizer = new ClickRecognizer(this.wwd, null); // this.clickRecognizer.addListener(this); // Intentionally not documented. this.beginPoint = new Vec2(0, 0); this.lastPoint = new Vec2(0, 0); this.beginHeading = 0; this.beginTilt = 0; this.beginRange = 0; this.lastRotation = 0; }
javascript
{ "resource": "" }
q25471
train
function (pole) { // Internal. Intentionally not documented. this.north = !(pole === "South"); var limits = this.north ? new Sector(0, 90, -180, 180) : new Sector(-90, 0, -180, 180); GeographicProjection.call(this, "Uniform Polar Stereographic", false, limits); // Internal. Intentionally not documented. See "pole" property accessor below for public interface. this._pole = pole; // Documented in superclass. this.displayName = this.north ? "North UPS" : "South UPS"; // Internal. Intentionally not documented. See "stateKey" property accessor below for public interface. this._stateKey = "projection ups " + this._pole + " "; }
javascript
{ "resource": "" }
q25472
train
function (target, callback) { GestureRecognizer.call(this, target, callback); // Intentionally not documented. this._rotation = 0; // Intentionally not documented. this._offsetRotation = 0; // Intentionally not documented. this.referenceAngle = 0; // Intentionally not documented. this.interpretThreshold = 20; // Intentionally not documented. this.weight = 0.4; // Intentionally not documented. this.rotationTouches = []; }
javascript
{ "resource": "" }
q25473
train
function (globe, positions, position, followTerrain) { var elevation = position.altitude; if (followTerrain) { elevation = globe.elevationAtLocation(position.latitude, position.longitude); } positions.push(new Position(position.latitude, position.longitude, elevation)); return positions; }
javascript
{ "resource": "" }
q25474
train
function (location, locations) { var result = false; var p1 = locations[0]; for (var i = 1, len = locations.length; i < len; i++) { var p2 = locations[i]; if (((p2.latitude <= location.latitude && location.latitude < p1.latitude) || (p1.latitude <= location.latitude && location.latitude < p2.latitude)) && (location.longitude < (p1.longitude - p2.longitude) * (location.latitude - p2.latitude) / (p1.latitude - p2.latitude) + p2.longitude)) { result = !result; } p1 = p2; } return result; }
javascript
{ "resource": "" }
q25475
train
function (v1, v2) { var dot = v1.dot(v2); // Compute the sum of magnitudes. var length = v1.magnitude() * v2.magnitude(); // Normalize the dot product, if necessary. if (!(length === 0) && (length !== 1.0)) { dot /= length; } // The normalized dot product should be in the range [-1, 1]. Otherwise the result is an error from // floating point roundoff. So if dot is less than -1 or greater than +1, we treat it as -1 and +1 // respectively. if (dot < -1.0) { dot = -1.0; } else if (dot > 1.0) { dot = 1.0; } // Angle is arc-cosine of normalized dot product. return Math.acos(dot); }
javascript
{ "resource": "" }
q25476
train
function (sector, tileMatrixList) { if (!sector) { throw new ArgumentError( Logger.logMessage(Logger.LEVEL_SEVERE, "TileMatrixSet", "constructor", "missingSector")); } if (!tileMatrixList) { throw new ArgumentError( Logger.logMessage(Logger.LEVEL_SEVERE, "TileMatrixSet", "constructor", "The specified TileMatrix list is null or undefined.")); } /** * The geographic coverage of this TileMatrixSet. */ this.sector = sector; /** * An array of TileMatrix objects defining this TileMatrixSet. */ this.entries = tileMatrixList; }
javascript
{ "resource": "" }
q25477
train
function () { TiledImageLayer.call(this, Sector.FULL_SPHERE, new Location(45, 45), 16, "image/png", "BingWMS", 256, 256); this.displayName = "Bing WMS"; this.pickEnabled = false; this.maxActiveAltitude = 10e3; this.urlBuilder = new WmsUrlBuilder("https://worldwind27.arc.nasa.gov/wms/virtualearth", "ve", "", "1.3.0"); }
javascript
{ "resource": "" }
q25478
train
function (serverAddress, pathToData, displayName) { TiledElevationCoverage.call(this, { coverageSector: Sector.FULL_SPHERE, resolution: 0.00732421875, retrievalImageFormat: "application/bil16", minElevation: -11000, maxElevation: 8850, urlBuilder: new LevelRowColumnUrlBuilder(serverAddress, pathToData) }); this.displayName = displayName || "Earth Elevations"; // Override the default computed LevelSet. EarthRestElevationCoverage accesses a fixed set of tiles with // a 60x60 top level tile delta, 5 levels, and tile dimensions of 512x512 pixels. this.levels = new LevelSet(Sector.FULL_SPHERE, new Location(60, 60), 5, 512, 512); }
javascript
{ "resource": "" }
q25479
train
function (sector, level, row, column) { if (!sector) { throw new ArgumentError( Logger.logMessage(Logger.LEVEL_SEVERE, "Tile", "constructor", "missingSector")); } if (!level) { throw new ArgumentError( Logger.logMessage(Logger.LEVEL_SEVERE, "Tile", "constructor", "The specified level is null or undefined.")); } if (row < 0 || column < 0) { throw new ArgumentError( Logger.logMessage(Logger.LEVEL_SEVERE, "Tile", "constructor", "The specified row or column is less than zero.")); } /** * The sector represented by this tile. * @type {Sector} * @readonly */ this.sector = sector; /** * The level at which this tile lies in a tile pyramid. * @type {Number} * @readonly */ this.level = level; /** * The row in this tile's level in which this tile lies in a tile pyramid. * @type {Number} * @readonly */ this.row = row; /** * The column in this tile's level in which this tile lies in a tile pyramid. * @type {Number} * @readonly */ this.column = column; /** * The width in pixels or cells of this tile's associated resource. * @type {Number} */ this.tileWidth = level.tileWidth; /** * The height in pixels or cells of this tile's associated resource. * @type {Number} */ this.tileHeight = level.tileHeight; /** * The size in radians of pixels or cells of this tile's associated resource. * @type {Number} */ this.texelSize = level.texelSize; /** * A key that uniquely identifies this tile within a level set. * @type {String} * @readonly */ this.tileKey = Tile.computeTileKey(level.levelNumber, row, column); /** * The Cartesian bounding box of this tile. * @type {BoundingBox} */ this.extent = null; /** * The tile's local origin in model coordinates. Any model coordinate points associates with the tile * should be relative to this point. * @type {Vec3} */ this.referencePoint = null; /** * This tile's opacity. * @type {Number} * @default 1 */ this.opacity = 1; // Internal use only. Intentionally not documented. this.samplePoints = null; // Internal use only. Intentionally not documented. this.sampleElevations = null; // Internal use only. Intentionally not documented. this.updateTimestamp = null; // Internal use only. Intentionally not documented. this.updateVerticalExaggeration = null; // Internal use only. Intentionally not documented. this.updateGlobeStateKey = null; }
javascript
{ "resource": "" }
q25480
train
function (geoTiffData, byteOffset, numOfBytes, isLittleEndian, isSigned) { if (numOfBytes <= 0) { throw new ArgumentError( Logger.logMessage(Logger.LEVEL_SEVERE, "GeoTiffReader", "getBytes", "noBytesRequested")); } else if (numOfBytes <= 1) { if (isSigned) { return geoTiffData.getInt8(byteOffset, isLittleEndian); } else { return geoTiffData.getUint8(byteOffset, isLittleEndian); } } else if (numOfBytes <= 2) { if (isSigned) { return geoTiffData.getInt16(byteOffset, isLittleEndian); } else { return geoTiffData.getUint16(byteOffset, isLittleEndian); } } else if (numOfBytes <= 3) { if (isSigned) { return geoTiffData.getInt32(byteOffset, isLittleEndian) >>> 8; } else { return geoTiffData.getUint32(byteOffset, isLittleEndian) >>> 8; } } else if (numOfBytes <= 4) { if (isSigned) { return geoTiffData.getInt32(byteOffset, isLittleEndian); } else { return geoTiffData.getUint32(byteOffset, isLittleEndian); } } else if (numOfBytes <= 8) { return geoTiffData.getFloat64(byteOffset, isLittleEndian); } else { throw new ArgumentError( Logger.logMessage(Logger.LEVEL_SEVERE, "GeoTiffReader", "getBytes", "tooManyBytesRequested")); } }
javascript
{ "resource": "" }
q25481
train
function (geoTiffData, byteOffset, numOfBytes, sampleFormat, isLittleEndian) { var res; switch (sampleFormat) { case TiffConstants.SampleFormat.UNSIGNED: res = this.getBytes(geoTiffData, byteOffset, numOfBytes, isLittleEndian, false); break; case TiffConstants.SampleFormat.SIGNED: res = this.getBytes(geoTiffData, byteOffset, numOfBytes, isLittleEndian, true); break; case TiffConstants.SampleFormat.IEEE_FLOAT: if (numOfBytes == 3) { res = geoTiffData.getFloat32(byteOffset, isLittleEndian) >>> 8; } else if (numOfBytes == 4) { res = geoTiffData.getFloat32(byteOffset, isLittleEndian); } else if (numOfBytes == 8) { res = geoTiffData.getFloat64(byteOffset, isLittleEndian); } else { Logger.log(Logger.LEVEL_WARNING, "Do not attempt to parse the data not handled: " + numOfBytes); } break; case TiffConstants.SampleFormat.UNDEFINED: default: res = this.getBytes(geoTiffData, byteOffset, numOfBytes, isLittleEndian, false); break; } return res; }
javascript
{ "resource": "" }
q25482
train
function (colorSample, bitsPerSample) { var multiplier = Math.pow(2, 8 - bitsPerSample); return Math.floor((colorSample * multiplier) + (multiplier - 1)); }
javascript
{ "resource": "" }
q25483
train
function (target, callback) { GestureRecognizer.call(this, target, callback); // Intentionally not documented. this._scale = 1; // Intentionally not documented. this._offsetScale = 1; // Intentionally not documented. this.referenceDistance = 0; // Intentionally not documented. this.interpretThreshold = 20; // Intentionally not documented. this.weight = 0.4; // Intentionally not documented. this.pinchTouches = []; }
javascript
{ "resource": "" }
q25484
train
function (o) { // The input argument is either an Event or a TapRecognizer. Both have the same properties for determining // the mouse or tap location. var x = o.clientX, y = o.clientY; var redrawRequired = highlightedItems.length > 0; // must redraw if we de-highlight previously picked items // De-highlight any previously highlighted placemarks. for (var h = 0; h < highlightedItems.length; h++) { highlightedItems[h].highlighted = false; } highlightedItems = []; // Perform the pick. Must first convert from window coordinates to canvas coordinates, which are // relative to the upper left corner of the canvas rather than the upper left corner of the page. var pickList = wwd.pick(wwd.canvasCoordinates(x, y)); //console.log(wwd.frameStatistics.frameTime); if (pickList.objects.length > 0) { redrawRequired = true; } // Highlight the items picked by simply setting their highlight flag to true. if (pickList.objects.length > 0) { for (var p = 0; p < pickList.objects.length; p++) { pickList.objects[p].userObject.highlighted = true; // Keep track of highlighted items in order to de-highlight them later. highlightedItems.push(pickList.objects[p].userObject); } } // Update the window if we changed anything. if (redrawRequired) { wwd.redraw(); // redraw to make the highlighting changes take effect on the screen } }
javascript
{ "resource": "" }
q25485
train
function (left, right, bottom, top, near, far) { if (!left || !right || !bottom || !top || !near || !far) { throw new ArgumentError( Logger.logMessage(Logger.LEVEL_SEVERE, "Frustum", "constructor", "missingPlane")); } // Internal. Intentionally not documented. See property accessors below for public interface. this._left = left; this._right = right; this._bottom = bottom; this._top = top; this._near = near; this._far = far; // Internal. Intentionally not documented. this._planes = [this._left, this._right, this._top, this._bottom, this._near, this._far]; }
javascript
{ "resource": "" }
q25486
train
function (identifier, clientX, clientY) { /** * A number uniquely identifying this touch point. * @type {Number} * @readonly */ this.identifier = identifier; // Intentionally not documented. this._clientX = clientX; // Intentionally not documented. this._clientY = clientY; // Intentionally not documented. this._clientStartX = clientX; // Intentionally not documented. this._clientStartY = clientY; }
javascript
{ "resource": "" }
q25487
train
function (top, left, bottom, right) { if (arguments.length !== 4) { throw new ArgumentError( Logger.logMessage(Logger.LEVEL_SEVERE, "Insets", "constructor", "invalidArgumentCount")); } // These are all documented with their property accessors below. this._top = top; this._left = left; this._bottom = bottom; this._right = right; }
javascript
{ "resource": "" }
q25488
train
function (element) { if (!element) { throw new ArgumentError( Logger.logMessage(Logger.LEVEL_SEVERE, "OwsServiceProvider", "constructor", "missingDomElement")); } var children = element.children || element.childNodes; for (var c = 0; c < children.length; c++) { var child = children[c]; if (child.localName === "ProviderName") { this.providerName = child.textContent; } else if (child.localName === "ProviderSite") { this.providerSiteUrl = child.getAttribute("xlink:href"); } else if (child.localName === "ServiceContact") { this.serviceContact = OwsServiceProvider.assembleServiceContact(child); } } }
javascript
{ "resource": "" }
q25489
train
function (position, config) { if (!position) { throw new ArgumentError( Logger.logMessage(Logger.LEVEL_SEVERE, "ColladaLoader", "constructor", "missingPosition")); } this.position = position; this.dirPath = '/'; this.init(config); }
javascript
{ "resource": "" }
q25490
train
function (target, callback) { GestureRecognizer.call(this, target, callback); /** * * @type {Number} */ this.numberOfTaps = 1; /** * * @type {Number} */ this.numberOfTouches = 1; // Intentionally not documented. this.maxTouchMovement = 20; // Intentionally not documented. this.maxTapDuration = 500; // Intentionally not documented. this.maxTapInterval = 400; // Intentionally not documented. this.taps = []; // Intentionally not documented. this.timeout = null; }
javascript
{ "resource": "" }
q25491
train
function (resolution) { if (!resolution) { throw new ArgumentError( Logger.logMessage(Logger.LEVEL_SEVERE, "ElevationCoverage", "constructor", "missingResolution")); } /** * Indicates the last time this coverage changed, in milliseconds since midnight Jan 1, 1970. * @type {Number} * @readonly * @default Date.now() at construction */ this.timestamp = Date.now(); /** * Indicates this coverage's display name. * @type {String} * @default "Coverage" */ this.displayName = "Coverage"; /** * Indicates whether or not to use this coverage. * @type {Boolean} * @default true */ this._enabled = true; /** * The resolution of this coverage in degrees. * @type {Number} */ this.resolution = resolution; /** * The sector this coverage spans. * @type {Sector} * @readonly */ this.coverageSector = Sector.FULL_SPHERE; }
javascript
{ "resource": "" }
q25492
train
function () { // CONUS Extent: (-124.848974, 24.396308) - (-66.885444, 49.384358) // TODO: Expand this extent to cover HI when the server NO_DATA value issue is resolved. TiledElevationCoverage.call(this, { coverageSector: new Sector(24.396308, 49.384358, -124.848974, -66.885444), resolution: 0.000092592592593, retrievalImageFormat: "application/bil16", minElevation: -11000, maxElevation: 8850, urlBuilder: new WmsUrlBuilder("https://worldwind26.arc.nasa.gov/elev", "USGS-NED", "", "1.3.0") }); this.displayName = "USGS NED Earth Elevation Coverage"; }
javascript
{ "resource": "" }
q25493
train
function (shapeAttributes) { RenderableLayer.call(this, "Tectonic Plates"); if (shapeAttributes) { this._attributes = shapeAttributes; } else { this._attributes = new ShapeAttributes(null); this._attributes.drawInterior = false; this._attributes.drawOutline = true; this._attributes.outlineColor = Color.RED; } this.loadPlateData(); }
javascript
{ "resource": "" }
q25494
train
function (date) { if (date instanceof Date === false) { throw new ArgumentError( Logger.logMessage(Logger.LEVEL_SEVERE, "SunPosition", "getAsGeographicLocation", "missingDate")); } var celestialLocation = this.getAsCelestialLocation(date); return this.celestialToGeographic(celestialLocation, date); }
javascript
{ "resource": "" }
q25495
train
function (date) { if (date instanceof Date === false) { throw new ArgumentError( Logger.logMessage(Logger.LEVEL_SEVERE, "SunPosition", "getAsCelestialLocation", "missingDate")); } var julianDate = this.computeJulianDate(date); //number of days (positive or negative) since Greenwich noon, Terrestrial Time, on 1 January 2000 (J2000.0) var numDays = julianDate - 2451545; var meanLongitude = WWMath.normalizeAngle360(280.460 + 0.9856474 * numDays); var meanAnomaly = WWMath.normalizeAngle360(357.528 + 0.9856003 * numDays) * Angle.DEGREES_TO_RADIANS; var eclipticLongitude = meanLongitude + 1.915 * Math.sin(meanAnomaly) + 0.02 * Math.sin(2 * meanAnomaly); var eclipticLongitudeRad = eclipticLongitude * Angle.DEGREES_TO_RADIANS; var obliquityOfTheEcliptic = (23.439 - 0.0000004 * numDays) * Angle.DEGREES_TO_RADIANS; var declination = Math.asin(Math.sin(obliquityOfTheEcliptic) * Math.sin(eclipticLongitudeRad)) * Angle.RADIANS_TO_DEGREES; var rightAscension = Math.atan(Math.cos(obliquityOfTheEcliptic) * Math.tan(eclipticLongitudeRad)) * Angle.RADIANS_TO_DEGREES; //compensate for atan result if (eclipticLongitude >= 90 && eclipticLongitude < 270) { rightAscension += 180; } rightAscension = WWMath.normalizeAngle360(rightAscension); return { declination: declination, rightAscension: rightAscension }; }
javascript
{ "resource": "" }
q25496
train
function (date) { if (date instanceof Date === false) { throw new ArgumentError( Logger.logMessage(Logger.LEVEL_SEVERE, "SunPosition", "computeJulianDate", "missingDate")); } var year = date.getUTCFullYear(); var month = date.getUTCMonth() + 1; var day = date.getUTCDate(); var hour = date.getUTCHours(); var minute = date.getUTCMinutes(); var second = date.getUTCSeconds(); var dayFraction = (hour + minute / 60 + second / 3600) / 24; if (month <= 2) { year -= 1; month += 12; } var A = Math.floor(year / 100); var B = 2 - A + Math.floor(A / 4); var JD0h = Math.floor(365.25 * (year + 4716)) + Math.floor(30.6001 * (month + 1)) + day + B - 1524.5; return JD0h + dayFraction; }
javascript
{ "resource": "" }
q25497
train
function (worldWindow) { var self = this; this.createPlayer(); // Intentionally not documented. this.slider = $("#timeSeriesSlider"); this.sliderThumb = $(this.slider.children('.ui-slider-handle')); this.timeDisplay = $("#timeSeriesDisplay");// $('<span style="position: absolute; width: 50px">Sat Aug 14, 2015</span>'); /** * The WorldWindow associated with this player, as specified to the constructor. * @type {WorldWindow} * @readonly */ this.wwd = worldWindow; /** * The time in milliseconds to display each frame of the time sequence. * @type {Number} * @default 1000 milliseconds */ this.frameTime = 1000; /** * The time sequence this player controls. * @type {PeriodicTimeSequence} * @default null */ this.timeSequence = null; /** * The layer this player controls. * @type {Layer} * @default null */ this.layer = null; //this.timeSequence = new WorldWind.PeriodicTimeSequence("2000-01-01/2001-12-01/P1M"); $("#timeSeriesBackward").on("click", function (event) { self.onStepBackwardButton(event); }); $("#timeSeriesForward").on("click", function (event) { self.onStepForwardButton(event); }); $("#timeSeriesPlay").on("click", function (event) { self.onPlayButton(event); }); $("#timeSeriesRepeat").on("click", function (event) { self.onRepeatButton(event); }); this.slider.on("slide", function (event, ui) { self.onSlide(event, ui); }); this.slider.on("slidechange", function (event, ui) { self.onSliderChange(event, ui); }); }
javascript
{ "resource": "" }
q25498
train
function (options) { Renderable.call(this); options = options || {}; if (!options.objectNode) { throw new ArgumentError( Logger.logMessage(Logger.LEVEL_SEVERE, "KmlObject", "constructor", "Passed node isn't defined.") ); } this._node = options.objectNode; this._cache = {}; this._controls = options.controls || []; // It should be possible to keep the context here? this._factory = new KmlElementsFactoryCached({controls: this._controls}); this.hook(this._controls, options); }
javascript
{ "resource": "" }
q25499
train
function (starDataSource) { Layer.call(this, 'StarField'); // The StarField Layer is not pickable. this.pickEnabled = false; /** * The size of the Sun in pixels. * This can not exceed the maximum allowed pointSize of the GPU. * A warning will be given if the size is too big and the allowed max size will be used. * @type {Number} * @default 128 */ this.sunSize = 128; /** * Indicates weather to show or hide the Sun * @type {Boolean} * @default true */ this.showSun = true; //Documented in defineProperties below. this._starDataSource = starDataSource || WorldWind.configuration.baseUrl + 'images/stars.json'; this._sunImageSource = WorldWind.configuration.baseUrl + 'images/sunTexture.png'; //Internal use only. //The MVP matrix of this layer. this._matrix = Matrix.fromIdentity(); //Internal use only. //gpu cache key for the stars vbo. this._starsPositionsVboCacheKey = null; //Internal use only. this._numStars = 0; //Internal use only. this._starData = null; //Internal use only. this._minMagnitude = Number.MAX_VALUE; this._maxMagnitude = Number.MIN_VALUE; //Internal use only. //A flag to indicate the star data is currently being retrieved. this._loadStarted = false; //Internal use only. this._minScale = 10e6; //Internal use only. this._sunPositionsCacheKey = ''; this._sunBufferView = new Float32Array(4); //Internal use only. this._MAX_GL_POINT_SIZE = 0; }
javascript
{ "resource": "" }