id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
10,400
jsbin/jsbin
public/js/vendor/codemirror3/keymap/vim.js
repeatLastEdit
function repeatLastEdit(cm, vim, repeat, repeatForInsert) { var macroModeState = vimGlobalState.macroModeState; macroModeState.inReplay = true; var isAction = !!vim.lastEditActionCommand; var cachedInputState = vim.inputState; function repeatCommand() { if (isAction) { commandDispatcher.processAction(cm, vim, vim.lastEditActionCommand); } else { commandDispatcher.evalInput(cm, vim); } } function repeatInsert(repeat) { if (macroModeState.lastInsertModeChanges.changes.length > 0) { // For some reason, repeat cw in desktop VIM will does not repeat // insert mode changes. Will conform to that behavior. repeat = !vim.lastEditActionCommand ? 1 : repeat; repeatLastInsertModeChanges(cm, repeat, macroModeState); } } vim.inputState = vim.lastEditInputState; if (isAction && vim.lastEditActionCommand.interlaceInsertRepeat) { // o and O repeat have to be interlaced with insert repeats so that the // insertions appear on separate lines instead of the last line. for (var i = 0; i < repeat; i++) { repeatCommand(); repeatInsert(1); } } else { if (!repeatForInsert) { // Hack to get the cursor to end up at the right place. If I is // repeated in insert mode repeat, cursor will be 1 insert // change set left of where it should be. repeatCommand(); } repeatInsert(repeat); } vim.inputState = cachedInputState; if (vim.insertMode && !repeatForInsert) { // Don't exit insert mode twice. If repeatForInsert is set, then we // were called by an exitInsertMode call lower on the stack. exitInsertMode(cm); } macroModeState.inReplay = false; }
javascript
function repeatLastEdit(cm, vim, repeat, repeatForInsert) { var macroModeState = vimGlobalState.macroModeState; macroModeState.inReplay = true; var isAction = !!vim.lastEditActionCommand; var cachedInputState = vim.inputState; function repeatCommand() { if (isAction) { commandDispatcher.processAction(cm, vim, vim.lastEditActionCommand); } else { commandDispatcher.evalInput(cm, vim); } } function repeatInsert(repeat) { if (macroModeState.lastInsertModeChanges.changes.length > 0) { // For some reason, repeat cw in desktop VIM will does not repeat // insert mode changes. Will conform to that behavior. repeat = !vim.lastEditActionCommand ? 1 : repeat; repeatLastInsertModeChanges(cm, repeat, macroModeState); } } vim.inputState = vim.lastEditInputState; if (isAction && vim.lastEditActionCommand.interlaceInsertRepeat) { // o and O repeat have to be interlaced with insert repeats so that the // insertions appear on separate lines instead of the last line. for (var i = 0; i < repeat; i++) { repeatCommand(); repeatInsert(1); } } else { if (!repeatForInsert) { // Hack to get the cursor to end up at the right place. If I is // repeated in insert mode repeat, cursor will be 1 insert // change set left of where it should be. repeatCommand(); } repeatInsert(repeat); } vim.inputState = cachedInputState; if (vim.insertMode && !repeatForInsert) { // Don't exit insert mode twice. If repeatForInsert is set, then we // were called by an exitInsertMode call lower on the stack. exitInsertMode(cm); } macroModeState.inReplay = false; }
[ "function", "repeatLastEdit", "(", "cm", ",", "vim", ",", "repeat", ",", "repeatForInsert", ")", "{", "var", "macroModeState", "=", "vimGlobalState", ".", "macroModeState", ";", "macroModeState", ".", "inReplay", "=", "true", ";", "var", "isAction", "=", "!", "!", "vim", ".", "lastEditActionCommand", ";", "var", "cachedInputState", "=", "vim", ".", "inputState", ";", "function", "repeatCommand", "(", ")", "{", "if", "(", "isAction", ")", "{", "commandDispatcher", ".", "processAction", "(", "cm", ",", "vim", ",", "vim", ".", "lastEditActionCommand", ")", ";", "}", "else", "{", "commandDispatcher", ".", "evalInput", "(", "cm", ",", "vim", ")", ";", "}", "}", "function", "repeatInsert", "(", "repeat", ")", "{", "if", "(", "macroModeState", ".", "lastInsertModeChanges", ".", "changes", ".", "length", ">", "0", ")", "{", "// For some reason, repeat cw in desktop VIM will does not repeat", "// insert mode changes. Will conform to that behavior.", "repeat", "=", "!", "vim", ".", "lastEditActionCommand", "?", "1", ":", "repeat", ";", "repeatLastInsertModeChanges", "(", "cm", ",", "repeat", ",", "macroModeState", ")", ";", "}", "}", "vim", ".", "inputState", "=", "vim", ".", "lastEditInputState", ";", "if", "(", "isAction", "&&", "vim", ".", "lastEditActionCommand", ".", "interlaceInsertRepeat", ")", "{", "// o and O repeat have to be interlaced with insert repeats so that the", "// insertions appear on separate lines instead of the last line.", "for", "(", "var", "i", "=", "0", ";", "i", "<", "repeat", ";", "i", "++", ")", "{", "repeatCommand", "(", ")", ";", "repeatInsert", "(", "1", ")", ";", "}", "}", "else", "{", "if", "(", "!", "repeatForInsert", ")", "{", "// Hack to get the cursor to end up at the right place. If I is", "// repeated in insert mode repeat, cursor will be 1 insert", "// change set left of where it should be.", "repeatCommand", "(", ")", ";", "}", "repeatInsert", "(", "repeat", ")", ";", "}", "vim", ".", "inputState", "=", "cachedInputState", ";", "if", "(", "vim", ".", "insertMode", "&&", "!", "repeatForInsert", ")", "{", "// Don't exit insert mode twice. If repeatForInsert is set, then we", "// were called by an exitInsertMode call lower on the stack.", "exitInsertMode", "(", "cm", ")", ";", "}", "macroModeState", ".", "inReplay", "=", "false", ";", "}" ]
Repeats the last edit, which includes exactly 1 command and at most 1 insert. Operator and motion commands are read from lastEditInputState, while action commands are read from lastEditActionCommand. If repeatForInsert is true, then the function was called by exitInsertMode to repeat the insert mode changes the user just made. The corresponding enterInsertMode call was made with a count.
[ "Repeats", "the", "last", "edit", "which", "includes", "exactly", "1", "command", "and", "at", "most", "1", "insert", ".", "Operator", "and", "motion", "commands", "are", "read", "from", "lastEditInputState", "while", "action", "commands", "are", "read", "from", "lastEditActionCommand", "." ]
d962c36fff71104acad98ac07629c1331704d420
https://github.com/jsbin/jsbin/blob/d962c36fff71104acad98ac07629c1331704d420/public/js/vendor/codemirror3/keymap/vim.js#L3710-L3754
10,401
jsbin/jsbin
public/js/vendor/pretty-date.js
prettyDate
function prettyDate(time){ 'use strict'; // Remy Sharp edit: July 13, 2014 specific to JS Bin // Need to replace Z in ISO8601 timestamp with +0000 so prettyDate() doesn't // completely remove it (and parse the date using the local timezone). var date = new Date((time || '').replace('Z', '+0000').replace(/-/g,'/').replace(/[TZ]/g,' ')), diff = (((new Date()).getTime() - date.getTime()) / 1000), dayDiff = Math.floor(diff / 86400); if ( isNaN(dayDiff) || dayDiff < 0 ) { return; } return dayDiff === 0 && ( diff < 60 && 'just now' || diff < 120 && '1 minute ago' || diff < 3600 && Math.floor( diff / 60 ) + ' minutes ago' || diff < 7200 && '1 hour ago' || diff < 86400 && Math.floor( diff / 3600 ) + ' hours ago') || shortDate(date.getTime()); }
javascript
function prettyDate(time){ 'use strict'; // Remy Sharp edit: July 13, 2014 specific to JS Bin // Need to replace Z in ISO8601 timestamp with +0000 so prettyDate() doesn't // completely remove it (and parse the date using the local timezone). var date = new Date((time || '').replace('Z', '+0000').replace(/-/g,'/').replace(/[TZ]/g,' ')), diff = (((new Date()).getTime() - date.getTime()) / 1000), dayDiff = Math.floor(diff / 86400); if ( isNaN(dayDiff) || dayDiff < 0 ) { return; } return dayDiff === 0 && ( diff < 60 && 'just now' || diff < 120 && '1 minute ago' || diff < 3600 && Math.floor( diff / 60 ) + ' minutes ago' || diff < 7200 && '1 hour ago' || diff < 86400 && Math.floor( diff / 3600 ) + ' hours ago') || shortDate(date.getTime()); }
[ "function", "prettyDate", "(", "time", ")", "{", "'use strict'", ";", "// Remy Sharp edit: July 13, 2014 specific to JS Bin", "// Need to replace Z in ISO8601 timestamp with +0000 so prettyDate() doesn't", "// completely remove it (and parse the date using the local timezone).", "var", "date", "=", "new", "Date", "(", "(", "time", "||", "''", ")", ".", "replace", "(", "'Z'", ",", "'+0000'", ")", ".", "replace", "(", "/", "-", "/", "g", ",", "'/'", ")", ".", "replace", "(", "/", "[TZ]", "/", "g", ",", "' '", ")", ")", ",", "diff", "=", "(", "(", "(", "new", "Date", "(", ")", ")", ".", "getTime", "(", ")", "-", "date", ".", "getTime", "(", ")", ")", "/", "1000", ")", ",", "dayDiff", "=", "Math", ".", "floor", "(", "diff", "/", "86400", ")", ";", "if", "(", "isNaN", "(", "dayDiff", ")", "||", "dayDiff", "<", "0", ")", "{", "return", ";", "}", "return", "dayDiff", "===", "0", "&&", "(", "diff", "<", "60", "&&", "'just now'", "||", "diff", "<", "120", "&&", "'1 minute ago'", "||", "diff", "<", "3600", "&&", "Math", ".", "floor", "(", "diff", "/", "60", ")", "+", "' minutes ago'", "||", "diff", "<", "7200", "&&", "'1 hour ago'", "||", "diff", "<", "86400", "&&", "Math", ".", "floor", "(", "diff", "/", "3600", ")", "+", "' hours ago'", ")", "||", "shortDate", "(", "date", ".", "getTime", "(", ")", ")", ";", "}" ]
Takes an ISO time and returns a string representing how long ago the date represents.
[ "Takes", "an", "ISO", "time", "and", "returns", "a", "string", "representing", "how", "long", "ago", "the", "date", "represents", "." ]
d962c36fff71104acad98ac07629c1331704d420
https://github.com/jsbin/jsbin/blob/d962c36fff71104acad98ac07629c1331704d420/public/js/vendor/pretty-date.js#L9-L31
10,402
jsbin/jsbin
public/js/editors/tern.js
function(name, file) { if (!ternLoaded[name]) { $.ajax({ url: file, dataType: 'json', success: function(data) { addTernDefinition(data); ternLoaded[name] = true; } }); } }
javascript
function(name, file) { if (!ternLoaded[name]) { $.ajax({ url: file, dataType: 'json', success: function(data) { addTernDefinition(data); ternLoaded[name] = true; } }); } }
[ "function", "(", "name", ",", "file", ")", "{", "if", "(", "!", "ternLoaded", "[", "name", "]", ")", "{", "$", ".", "ajax", "(", "{", "url", ":", "file", ",", "dataType", ":", "'json'", ",", "success", ":", "function", "(", "data", ")", "{", "addTernDefinition", "(", "data", ")", ";", "ternLoaded", "[", "name", "]", "=", "true", ";", "}", "}", ")", ";", "}", "}" ]
Load the json defition of the library
[ "Load", "the", "json", "defition", "of", "the", "library" ]
d962c36fff71104acad98ac07629c1331704d420
https://github.com/jsbin/jsbin/blob/d962c36fff71104acad98ac07629c1331704d420/public/js/editors/tern.js#L43-L54
10,403
jsbin/jsbin
public/js/editors/tern.js
function(name, file) { if (!ternLoaded[name]) { $.ajax({ url: file, dataType: 'script', success: function(data) { ternServer.server.addFile(name, data); ternLoaded[name] = true; } }); } }
javascript
function(name, file) { if (!ternLoaded[name]) { $.ajax({ url: file, dataType: 'script', success: function(data) { ternServer.server.addFile(name, data); ternLoaded[name] = true; } }); } }
[ "function", "(", "name", ",", "file", ")", "{", "if", "(", "!", "ternLoaded", "[", "name", "]", ")", "{", "$", ".", "ajax", "(", "{", "url", ":", "file", ",", "dataType", ":", "'script'", ",", "success", ":", "function", "(", "data", ")", "{", "ternServer", ".", "server", ".", "addFile", "(", "name", ",", "data", ")", ";", "ternLoaded", "[", "name", "]", "=", "true", ";", "}", "}", ")", ";", "}", "}" ]
Load the actual js library
[ "Load", "the", "actual", "js", "library" ]
d962c36fff71104acad98ac07629c1331704d420
https://github.com/jsbin/jsbin/blob/d962c36fff71104acad98ac07629c1331704d420/public/js/editors/tern.js#L57-L68
10,404
jsbin/jsbin
lib/models/bin.js
function (data, fn) { this.store.generateBinId(data.length, 0, function generateBinId(err, id) { if (err) { return fn(err); } data.url = id; data.revision = 1; data.latest = true; data.streamingKey = this.createStreamingKey(id, data.revision); this.store.setBin(data, function (err, id) { data.id = id; fn(err || null, err ? undefined : data); }); }.bind(this)); }
javascript
function (data, fn) { this.store.generateBinId(data.length, 0, function generateBinId(err, id) { if (err) { return fn(err); } data.url = id; data.revision = 1; data.latest = true; data.streamingKey = this.createStreamingKey(id, data.revision); this.store.setBin(data, function (err, id) { data.id = id; fn(err || null, err ? undefined : data); }); }.bind(this)); }
[ "function", "(", "data", ",", "fn", ")", "{", "this", ".", "store", ".", "generateBinId", "(", "data", ".", "length", ",", "0", ",", "function", "generateBinId", "(", "err", ",", "id", ")", "{", "if", "(", "err", ")", "{", "return", "fn", "(", "err", ")", ";", "}", "data", ".", "url", "=", "id", ";", "data", ".", "revision", "=", "1", ";", "data", ".", "latest", "=", "true", ";", "data", ".", "streamingKey", "=", "this", ".", "createStreamingKey", "(", "id", ",", "data", ".", "revision", ")", ";", "this", ".", "store", ".", "setBin", "(", "data", ",", "function", "(", "err", ",", "id", ")", "{", "data", ".", "id", "=", "id", ";", "fn", "(", "err", "||", "null", ",", "err", "?", "undefined", ":", "data", ")", ";", "}", ")", ";", "}", ".", "bind", "(", "this", ")", ")", ";", "}" ]
Create a new bin.
[ "Create", "a", "new", "bin", "." ]
d962c36fff71104acad98ac07629c1331704d420
https://github.com/jsbin/jsbin/blob/d962c36fff71104acad98ac07629c1331704d420/lib/models/bin.js#L103-L118
10,405
jsbin/jsbin
lib/models/bin.js
function (data, fn) { data.streamingKey = this.createStreamingKey(data.url, data.revision); this.store.setBin(data, function (err, id) { data.id = id; fn(err || null, err ? undefined : data); }); }
javascript
function (data, fn) { data.streamingKey = this.createStreamingKey(data.url, data.revision); this.store.setBin(data, function (err, id) { data.id = id; fn(err || null, err ? undefined : data); }); }
[ "function", "(", "data", ",", "fn", ")", "{", "data", ".", "streamingKey", "=", "this", ".", "createStreamingKey", "(", "data", ".", "url", ",", "data", ".", "revision", ")", ";", "this", ".", "store", ".", "setBin", "(", "data", ",", "function", "(", "err", ",", "id", ")", "{", "data", ".", "id", "=", "id", ";", "fn", "(", "err", "||", "null", ",", "err", "?", "undefined", ":", "data", ")", ";", "}", ")", ";", "}" ]
Create a new revision.
[ "Create", "a", "new", "revision", "." ]
d962c36fff71104acad98ac07629c1331704d420
https://github.com/jsbin/jsbin/blob/d962c36fff71104acad98ac07629c1331704d420/lib/models/bin.js#L120-L126
10,406
jsbin/jsbin
lib/spike/index.js
function (req, res, next) { // Check request's accepts header for event-stream. Move on if it doesn't // support it. if (!req.headers.accept || req.headers.accept.indexOf('text/event-stream') === -1) { return next(); } // Restore or create a session for the bin var session = utils.sessionForBin(req.bin, true), key = utils.keyForBin(req.bin), userSession = req.session, checksum = req.param('checksum'), // cache the bin because req.bin is just a reference and gets changed when // the revision gets bumped. bin = req.bin, keepalive = null, close, closeTimer; if (isOwnerWithWrite(userSession, bin, checksum) && pendingToKillStreaming[key]) { clearTimeout(pendingToKillStreaming[key] || null); } openSpikes += 1; metrics.gauge('spike.open', openSpikes); // console.log('STREAM ACCEPTED', req.originalUrl); res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache' }); res.write('id: 0\n\n'); session.res.push(res); if (req.keepLatest) { if (!sessionsFromUser[req.user.name]) { sessionsFromUser[req.user.name] = []; } sessionsFromUser[req.user.name].push({ key: key, res: res }); } keepalive = setInterval(function () { if (!res.connection.writable) { return close(); } res.write('id: 0\n\n'); }, 15 * 1000); // FIXME this will break when using /rem/last/ as req.bin won't be the same bin anymore. var closed = false; close = function () { if (closed) { return; } closed = true; if (isOwnerWithWrite(userSession, bin, checksum)) { // this means the owner has disconnected from jsbin, and it's possible // that we can remove their write access to the bin (and thus not add // streaming to full previews). So we set a timer, and if this eventsource // isn't reopened then we assume it's closed. If this eventsource *does* // reopen, then we clear the timer, and they can continue to stream. pendingToKillStreaming[key] = setTimeout(function () { binModel.updateBinData(req.bin, {streaming_key: ''}, function (error) { if (error) { console.error(error); } }); }, 24 * 60 * 1000); // leave it open for 24 hours } clearInterval(keepalive); clearTimeout(closeTimer); utils.removeConnection(utils.keyForBin(req.bin), res); // ping stats spike.ping(req.bin, {}, true); }; // every 5 minutes, let's let them reconnect closeTimer = setTimeout(function () { res.end(); req.emit('close'); }, 15 * 60 * 1000); res.socket.on('close', close); req.on('close', close); res.req = req; // ping stats spike.ping(req.bin, {}, true); }
javascript
function (req, res, next) { // Check request's accepts header for event-stream. Move on if it doesn't // support it. if (!req.headers.accept || req.headers.accept.indexOf('text/event-stream') === -1) { return next(); } // Restore or create a session for the bin var session = utils.sessionForBin(req.bin, true), key = utils.keyForBin(req.bin), userSession = req.session, checksum = req.param('checksum'), // cache the bin because req.bin is just a reference and gets changed when // the revision gets bumped. bin = req.bin, keepalive = null, close, closeTimer; if (isOwnerWithWrite(userSession, bin, checksum) && pendingToKillStreaming[key]) { clearTimeout(pendingToKillStreaming[key] || null); } openSpikes += 1; metrics.gauge('spike.open', openSpikes); // console.log('STREAM ACCEPTED', req.originalUrl); res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache' }); res.write('id: 0\n\n'); session.res.push(res); if (req.keepLatest) { if (!sessionsFromUser[req.user.name]) { sessionsFromUser[req.user.name] = []; } sessionsFromUser[req.user.name].push({ key: key, res: res }); } keepalive = setInterval(function () { if (!res.connection.writable) { return close(); } res.write('id: 0\n\n'); }, 15 * 1000); // FIXME this will break when using /rem/last/ as req.bin won't be the same bin anymore. var closed = false; close = function () { if (closed) { return; } closed = true; if (isOwnerWithWrite(userSession, bin, checksum)) { // this means the owner has disconnected from jsbin, and it's possible // that we can remove their write access to the bin (and thus not add // streaming to full previews). So we set a timer, and if this eventsource // isn't reopened then we assume it's closed. If this eventsource *does* // reopen, then we clear the timer, and they can continue to stream. pendingToKillStreaming[key] = setTimeout(function () { binModel.updateBinData(req.bin, {streaming_key: ''}, function (error) { if (error) { console.error(error); } }); }, 24 * 60 * 1000); // leave it open for 24 hours } clearInterval(keepalive); clearTimeout(closeTimer); utils.removeConnection(utils.keyForBin(req.bin), res); // ping stats spike.ping(req.bin, {}, true); }; // every 5 minutes, let's let them reconnect closeTimer = setTimeout(function () { res.end(); req.emit('close'); }, 15 * 60 * 1000); res.socket.on('close', close); req.on('close', close); res.req = req; // ping stats spike.ping(req.bin, {}, true); }
[ "function", "(", "req", ",", "res", ",", "next", ")", "{", "// Check request's accepts header for event-stream. Move on if it doesn't", "// support it.", "if", "(", "!", "req", ".", "headers", ".", "accept", "||", "req", ".", "headers", ".", "accept", ".", "indexOf", "(", "'text/event-stream'", ")", "===", "-", "1", ")", "{", "return", "next", "(", ")", ";", "}", "// Restore or create a session for the bin", "var", "session", "=", "utils", ".", "sessionForBin", "(", "req", ".", "bin", ",", "true", ")", ",", "key", "=", "utils", ".", "keyForBin", "(", "req", ".", "bin", ")", ",", "userSession", "=", "req", ".", "session", ",", "checksum", "=", "req", ".", "param", "(", "'checksum'", ")", ",", "// cache the bin because req.bin is just a reference and gets changed when", "// the revision gets bumped.", "bin", "=", "req", ".", "bin", ",", "keepalive", "=", "null", ",", "close", ",", "closeTimer", ";", "if", "(", "isOwnerWithWrite", "(", "userSession", ",", "bin", ",", "checksum", ")", "&&", "pendingToKillStreaming", "[", "key", "]", ")", "{", "clearTimeout", "(", "pendingToKillStreaming", "[", "key", "]", "||", "null", ")", ";", "}", "openSpikes", "+=", "1", ";", "metrics", ".", "gauge", "(", "'spike.open'", ",", "openSpikes", ")", ";", "// console.log('STREAM ACCEPTED', req.originalUrl);", "res", ".", "writeHead", "(", "200", ",", "{", "'Content-Type'", ":", "'text/event-stream'", ",", "'Cache-Control'", ":", "'no-cache'", "}", ")", ";", "res", ".", "write", "(", "'id: 0\\n\\n'", ")", ";", "session", ".", "res", ".", "push", "(", "res", ")", ";", "if", "(", "req", ".", "keepLatest", ")", "{", "if", "(", "!", "sessionsFromUser", "[", "req", ".", "user", ".", "name", "]", ")", "{", "sessionsFromUser", "[", "req", ".", "user", ".", "name", "]", "=", "[", "]", ";", "}", "sessionsFromUser", "[", "req", ".", "user", ".", "name", "]", ".", "push", "(", "{", "key", ":", "key", ",", "res", ":", "res", "}", ")", ";", "}", "keepalive", "=", "setInterval", "(", "function", "(", ")", "{", "if", "(", "!", "res", ".", "connection", ".", "writable", ")", "{", "return", "close", "(", ")", ";", "}", "res", ".", "write", "(", "'id: 0\\n\\n'", ")", ";", "}", ",", "15", "*", "1000", ")", ";", "// FIXME this will break when using /rem/last/ as req.bin won't be the same bin anymore.", "var", "closed", "=", "false", ";", "close", "=", "function", "(", ")", "{", "if", "(", "closed", ")", "{", "return", ";", "}", "closed", "=", "true", ";", "if", "(", "isOwnerWithWrite", "(", "userSession", ",", "bin", ",", "checksum", ")", ")", "{", "// this means the owner has disconnected from jsbin, and it's possible", "// that we can remove their write access to the bin (and thus not add", "// streaming to full previews). So we set a timer, and if this eventsource", "// isn't reopened then we assume it's closed. If this eventsource *does*", "// reopen, then we clear the timer, and they can continue to stream.", "pendingToKillStreaming", "[", "key", "]", "=", "setTimeout", "(", "function", "(", ")", "{", "binModel", ".", "updateBinData", "(", "req", ".", "bin", ",", "{", "streaming_key", ":", "''", "}", ",", "function", "(", "error", ")", "{", "if", "(", "error", ")", "{", "console", ".", "error", "(", "error", ")", ";", "}", "}", ")", ";", "}", ",", "24", "*", "60", "*", "1000", ")", ";", "// leave it open for 24 hours", "}", "clearInterval", "(", "keepalive", ")", ";", "clearTimeout", "(", "closeTimer", ")", ";", "utils", ".", "removeConnection", "(", "utils", ".", "keyForBin", "(", "req", ".", "bin", ")", ",", "res", ")", ";", "// ping stats", "spike", ".", "ping", "(", "req", ".", "bin", ",", "{", "}", ",", "true", ")", ";", "}", ";", "// every 5 minutes, let's let them reconnect", "closeTimer", "=", "setTimeout", "(", "function", "(", ")", "{", "res", ".", "end", "(", ")", ";", "req", ".", "emit", "(", "'close'", ")", ";", "}", ",", "15", "*", "60", "*", "1000", ")", ";", "res", ".", "socket", ".", "on", "(", "'close'", ",", "close", ")", ";", "req", ".", "on", "(", "'close'", ",", "close", ")", ";", "res", ".", "req", "=", "req", ";", "// ping stats", "spike", ".", "ping", "(", "req", ".", "bin", ",", "{", "}", ",", "true", ")", ";", "}" ]
Setup an event stream for the client. This is hit on all bin endpoints.
[ "Setup", "an", "event", "stream", "for", "the", "client", ".", "This", "is", "hit", "on", "all", "bin", "endpoints", "." ]
d962c36fff71104acad98ac07629c1331704d420
https://github.com/jsbin/jsbin/blob/d962c36fff71104acad98ac07629c1331704d420/lib/spike/index.js#L174-L267
10,407
jsbin/jsbin
lib/spike/index.js
function (bin) { var session = utils.sessionForBin(bin); if (session) { session.res.forEach(function (res) { res.write('event: reload\ndata: 0\n\n'); if (res.ajax) { res.end(); // lets older browsers finish their xhr request res.req.emit('close'); } }); } }
javascript
function (bin) { var session = utils.sessionForBin(bin); if (session) { session.res.forEach(function (res) { res.write('event: reload\ndata: 0\n\n'); if (res.ajax) { res.end(); // lets older browsers finish their xhr request res.req.emit('close'); } }); } }
[ "function", "(", "bin", ")", "{", "var", "session", "=", "utils", ".", "sessionForBin", "(", "bin", ")", ";", "if", "(", "session", ")", "{", "session", ".", "res", ".", "forEach", "(", "function", "(", "res", ")", "{", "res", ".", "write", "(", "'event: reload\\ndata: 0\\n\\n'", ")", ";", "if", "(", "res", ".", "ajax", ")", "{", "res", ".", "end", "(", ")", ";", "// lets older browsers finish their xhr request", "res", ".", "req", ".", "emit", "(", "'close'", ")", ";", "}", "}", ")", ";", "}", "}" ]
Reload all connected clients
[ "Reload", "all", "connected", "clients" ]
d962c36fff71104acad98ac07629c1331704d420
https://github.com/jsbin/jsbin/blob/d962c36fff71104acad98ac07629c1331704d420/lib/spike/index.js#L272-L285
10,408
jsbin/jsbin
lib/spike/index.js
function (oldBin, newBin) { if (!newBin || !newBin.url) { // FIXME this is just patching a problem, the source of which I'm not sure console.error('spike/index.js#bump-revision - missing newBin', newBin); return; } var oldSession = utils.sessionForBin(oldBin), oldKey = utils.keyForBin(oldBin), newSession = utils.sessionForBin(newBin, true), newKey = utils.keyForBin(newBin); if (!oldSession) { return; } // Move connections from one session to another oldSession.res.forEach(function (res) { // Add the connection to the new session's list newSession.res.push(res); // Upgrade the connection with the new bin res.req.bin = newBin; // Tell the client to bump their revision res.write(utils.makeEvent('bump-revision', newKey)); if (res.ajax) { // lets older browsers finish their xhr request res.end(); res.req.emit('close'); } return false; }); // There should be no more connections to this bin, so byebye! oldSession.res = []; delete sessions[oldKey]; }
javascript
function (oldBin, newBin) { if (!newBin || !newBin.url) { // FIXME this is just patching a problem, the source of which I'm not sure console.error('spike/index.js#bump-revision - missing newBin', newBin); return; } var oldSession = utils.sessionForBin(oldBin), oldKey = utils.keyForBin(oldBin), newSession = utils.sessionForBin(newBin, true), newKey = utils.keyForBin(newBin); if (!oldSession) { return; } // Move connections from one session to another oldSession.res.forEach(function (res) { // Add the connection to the new session's list newSession.res.push(res); // Upgrade the connection with the new bin res.req.bin = newBin; // Tell the client to bump their revision res.write(utils.makeEvent('bump-revision', newKey)); if (res.ajax) { // lets older browsers finish their xhr request res.end(); res.req.emit('close'); } return false; }); // There should be no more connections to this bin, so byebye! oldSession.res = []; delete sessions[oldKey]; }
[ "function", "(", "oldBin", ",", "newBin", ")", "{", "if", "(", "!", "newBin", "||", "!", "newBin", ".", "url", ")", "{", "// FIXME this is just patching a problem, the source of which I'm not sure", "console", ".", "error", "(", "'spike/index.js#bump-revision - missing newBin'", ",", "newBin", ")", ";", "return", ";", "}", "var", "oldSession", "=", "utils", ".", "sessionForBin", "(", "oldBin", ")", ",", "oldKey", "=", "utils", ".", "keyForBin", "(", "oldBin", ")", ",", "newSession", "=", "utils", ".", "sessionForBin", "(", "newBin", ",", "true", ")", ",", "newKey", "=", "utils", ".", "keyForBin", "(", "newBin", ")", ";", "if", "(", "!", "oldSession", ")", "{", "return", ";", "}", "// Move connections from one session to another", "oldSession", ".", "res", ".", "forEach", "(", "function", "(", "res", ")", "{", "// Add the connection to the new session's list", "newSession", ".", "res", ".", "push", "(", "res", ")", ";", "// Upgrade the connection with the new bin", "res", ".", "req", ".", "bin", "=", "newBin", ";", "// Tell the client to bump their revision", "res", ".", "write", "(", "utils", ".", "makeEvent", "(", "'bump-revision'", ",", "newKey", ")", ")", ";", "if", "(", "res", ".", "ajax", ")", "{", "// lets older browsers finish their xhr request", "res", ".", "end", "(", ")", ";", "res", ".", "req", ".", "emit", "(", "'close'", ")", ";", "}", "return", "false", ";", "}", ")", ";", "// There should be no more connections to this bin, so byebye!", "oldSession", ".", "res", "=", "[", "]", ";", "delete", "sessions", "[", "oldKey", "]", ";", "}" ]
Update spikes when a new revision is created.
[ "Update", "spikes", "when", "a", "new", "revision", "is", "created", "." ]
d962c36fff71104acad98ac07629c1331704d420
https://github.com/jsbin/jsbin/blob/d962c36fff71104acad98ac07629c1331704d420/lib/spike/index.js#L318-L353
10,409
jsbin/jsbin
lib/spike/index.js
function (bin, data, statsRequest) { var id = bin.id, delayTrigger = 500; if (!pending[id]) { pending[id] = {}; } pending[id].bin = bin; pending[id][data.panelId] = utils.process(data, bin.settings); // Clear the previous ping clearTimeout(pending[id].timer); // NOTE: this will only fire once per jsbin session - // not for every panel sent - because we clear the timer pending[id].timer = setTimeout(function () { var session = utils.sessionForBin(bin), data = null, ping = pending[id]; if (!ping) { return; } // Javascript and HTML cause reloads. CSS is injected. data = ping.javascript || ping.html || ping.css || (statsRequest ? {} : false); // Forget this ping, it's done with now delete pending[id]; if (!data) { return; } if (!session) { return; } // Send the update to all connected sessions in original and raw flavours session.res.forEach(function (res) { var raw = data.raw || data.content; if (!res.req.stats) { res.write(utils.makeEvent(data.panelId, raw)); res.write(utils.makeEvent(data.panelId + ':processed', data.content)); } res.write(utils.makeEvent('stats', { connections: session.res.filter(function (res) { return !res.req.stats; }).length })); if (res.ajax && !statsRequest) { res.end(); // lets older browsers finish their xhr request res.req.emit('close'); } }); }, delayTrigger); }
javascript
function (bin, data, statsRequest) { var id = bin.id, delayTrigger = 500; if (!pending[id]) { pending[id] = {}; } pending[id].bin = bin; pending[id][data.panelId] = utils.process(data, bin.settings); // Clear the previous ping clearTimeout(pending[id].timer); // NOTE: this will only fire once per jsbin session - // not for every panel sent - because we clear the timer pending[id].timer = setTimeout(function () { var session = utils.sessionForBin(bin), data = null, ping = pending[id]; if (!ping) { return; } // Javascript and HTML cause reloads. CSS is injected. data = ping.javascript || ping.html || ping.css || (statsRequest ? {} : false); // Forget this ping, it's done with now delete pending[id]; if (!data) { return; } if (!session) { return; } // Send the update to all connected sessions in original and raw flavours session.res.forEach(function (res) { var raw = data.raw || data.content; if (!res.req.stats) { res.write(utils.makeEvent(data.panelId, raw)); res.write(utils.makeEvent(data.panelId + ':processed', data.content)); } res.write(utils.makeEvent('stats', { connections: session.res.filter(function (res) { return !res.req.stats; }).length })); if (res.ajax && !statsRequest) { res.end(); // lets older browsers finish their xhr request res.req.emit('close'); } }); }, delayTrigger); }
[ "function", "(", "bin", ",", "data", ",", "statsRequest", ")", "{", "var", "id", "=", "bin", ".", "id", ",", "delayTrigger", "=", "500", ";", "if", "(", "!", "pending", "[", "id", "]", ")", "{", "pending", "[", "id", "]", "=", "{", "}", ";", "}", "pending", "[", "id", "]", ".", "bin", "=", "bin", ";", "pending", "[", "id", "]", "[", "data", ".", "panelId", "]", "=", "utils", ".", "process", "(", "data", ",", "bin", ".", "settings", ")", ";", "// Clear the previous ping", "clearTimeout", "(", "pending", "[", "id", "]", ".", "timer", ")", ";", "// NOTE: this will only fire once per jsbin session -", "// not for every panel sent - because we clear the timer", "pending", "[", "id", "]", ".", "timer", "=", "setTimeout", "(", "function", "(", ")", "{", "var", "session", "=", "utils", ".", "sessionForBin", "(", "bin", ")", ",", "data", "=", "null", ",", "ping", "=", "pending", "[", "id", "]", ";", "if", "(", "!", "ping", ")", "{", "return", ";", "}", "// Javascript and HTML cause reloads. CSS is injected.", "data", "=", "ping", ".", "javascript", "||", "ping", ".", "html", "||", "ping", ".", "css", "||", "(", "statsRequest", "?", "{", "}", ":", "false", ")", ";", "// Forget this ping, it's done with now", "delete", "pending", "[", "id", "]", ";", "if", "(", "!", "data", ")", "{", "return", ";", "}", "if", "(", "!", "session", ")", "{", "return", ";", "}", "// Send the update to all connected sessions in original and raw flavours", "session", ".", "res", ".", "forEach", "(", "function", "(", "res", ")", "{", "var", "raw", "=", "data", ".", "raw", "||", "data", ".", "content", ";", "if", "(", "!", "res", ".", "req", ".", "stats", ")", "{", "res", ".", "write", "(", "utils", ".", "makeEvent", "(", "data", ".", "panelId", ",", "raw", ")", ")", ";", "res", ".", "write", "(", "utils", ".", "makeEvent", "(", "data", ".", "panelId", "+", "':processed'", ",", "data", ".", "content", ")", ")", ";", "}", "res", ".", "write", "(", "utils", ".", "makeEvent", "(", "'stats'", ",", "{", "connections", ":", "session", ".", "res", ".", "filter", "(", "function", "(", "res", ")", "{", "return", "!", "res", ".", "req", ".", "stats", ";", "}", ")", ".", "length", "}", ")", ")", ";", "if", "(", "res", ".", "ajax", "&&", "!", "statsRequest", ")", "{", "res", ".", "end", "(", ")", ";", "// lets older browsers finish their xhr request", "res", ".", "req", ".", "emit", "(", "'close'", ")", ";", "}", "}", ")", ";", "}", ",", "delayTrigger", ")", ";", "}" ]
Notify connected clients of an update to a bin
[ "Notify", "connected", "clients", "of", "an", "update", "to", "a", "bin" ]
d962c36fff71104acad98ac07629c1331704d420
https://github.com/jsbin/jsbin/blob/d962c36fff71104acad98ac07629c1331704d420/lib/spike/index.js#L358-L408
10,410
jsbin/jsbin
lib/middleware.js
function () { return function (req, res, next) { var headers = req.header('Access-Control-Request-Headers'); var origin = req.header('Origin'); // TODO should this check if the request is via the API? if (req.method === 'OPTIONS' || (req.method === 'GET' && req.headers.origin)) { res.header({ 'Access-Control-Allow-Origin': origin, 'Access-Control-Allow-Headers': headers, 'Access-Control-Allow-Credentials': 'true' }); req.cors = true; } if (req.method === 'OPTIONS') { res.send(204); } else { next(); } }; }
javascript
function () { return function (req, res, next) { var headers = req.header('Access-Control-Request-Headers'); var origin = req.header('Origin'); // TODO should this check if the request is via the API? if (req.method === 'OPTIONS' || (req.method === 'GET' && req.headers.origin)) { res.header({ 'Access-Control-Allow-Origin': origin, 'Access-Control-Allow-Headers': headers, 'Access-Control-Allow-Credentials': 'true' }); req.cors = true; } if (req.method === 'OPTIONS') { res.send(204); } else { next(); } }; }
[ "function", "(", ")", "{", "return", "function", "(", "req", ",", "res", ",", "next", ")", "{", "var", "headers", "=", "req", ".", "header", "(", "'Access-Control-Request-Headers'", ")", ";", "var", "origin", "=", "req", ".", "header", "(", "'Origin'", ")", ";", "// TODO should this check if the request is via the API?", "if", "(", "req", ".", "method", "===", "'OPTIONS'", "||", "(", "req", ".", "method", "===", "'GET'", "&&", "req", ".", "headers", ".", "origin", ")", ")", "{", "res", ".", "header", "(", "{", "'Access-Control-Allow-Origin'", ":", "origin", ",", "'Access-Control-Allow-Headers'", ":", "headers", ",", "'Access-Control-Allow-Credentials'", ":", "'true'", "}", ")", ";", "req", ".", "cors", "=", "true", ";", "}", "if", "(", "req", ".", "method", "===", "'OPTIONS'", ")", "{", "res", ".", "send", "(", "204", ")", ";", "}", "else", "{", "next", "(", ")", ";", "}", "}", ";", "}" ]
Add relevant CORS headers for the application.
[ "Add", "relevant", "CORS", "headers", "for", "the", "application", "." ]
d962c36fff71104acad98ac07629c1331704d420
https://github.com/jsbin/jsbin/blob/d962c36fff71104acad98ac07629c1331704d420/lib/middleware.js#L40-L61
10,411
jsbin/jsbin
lib/middleware.js
function (options) { var ignore = options.ignore || [], csrf = csurf(options), always = {OPTIONS: 1, GET: 1, HEAD: 1}; return function (req, res, next) { if (always[req.method]) { return csrf(req, res, next); } else { var url = parse(req.url); var skipCSRF = false; ignore.forEach(function(matcher) { if (typeof matcher === 'string') { if (matcher === url.pathname) { skipCSRF = true; } } else { // regular expression matcher if (url.pathname.match(matcher)) { skipCSRF = true; } } }); if (skipCSRF) { next(); } else { return csrf(req, res, next); } } }; }
javascript
function (options) { var ignore = options.ignore || [], csrf = csurf(options), always = {OPTIONS: 1, GET: 1, HEAD: 1}; return function (req, res, next) { if (always[req.method]) { return csrf(req, res, next); } else { var url = parse(req.url); var skipCSRF = false; ignore.forEach(function(matcher) { if (typeof matcher === 'string') { if (matcher === url.pathname) { skipCSRF = true; } } else { // regular expression matcher if (url.pathname.match(matcher)) { skipCSRF = true; } } }); if (skipCSRF) { next(); } else { return csrf(req, res, next); } } }; }
[ "function", "(", "options", ")", "{", "var", "ignore", "=", "options", ".", "ignore", "||", "[", "]", ",", "csrf", "=", "csurf", "(", "options", ")", ",", "always", "=", "{", "OPTIONS", ":", "1", ",", "GET", ":", "1", ",", "HEAD", ":", "1", "}", ";", "return", "function", "(", "req", ",", "res", ",", "next", ")", "{", "if", "(", "always", "[", "req", ".", "method", "]", ")", "{", "return", "csrf", "(", "req", ",", "res", ",", "next", ")", ";", "}", "else", "{", "var", "url", "=", "parse", "(", "req", ".", "url", ")", ";", "var", "skipCSRF", "=", "false", ";", "ignore", ".", "forEach", "(", "function", "(", "matcher", ")", "{", "if", "(", "typeof", "matcher", "===", "'string'", ")", "{", "if", "(", "matcher", "===", "url", ".", "pathname", ")", "{", "skipCSRF", "=", "true", ";", "}", "}", "else", "{", "// regular expression matcher", "if", "(", "url", ".", "pathname", ".", "match", "(", "matcher", ")", ")", "{", "skipCSRF", "=", "true", ";", "}", "}", "}", ")", ";", "if", "(", "skipCSRF", ")", "{", "next", "(", ")", ";", "}", "else", "{", "return", "csrf", "(", "req", ",", "res", ",", "next", ")", ";", "}", "}", "}", ";", "}" ]
monkey patch for express' own csrf method, so we can ignore specific url patterns
[ "monkey", "patch", "for", "express", "own", "csrf", "method", "so", "we", "can", "ignore", "specific", "url", "patterns" ]
d962c36fff71104acad98ac07629c1331704d420
https://github.com/jsbin/jsbin/blob/d962c36fff71104acad98ac07629c1331704d420/lib/middleware.js#L118-L149
10,412
jsbin/jsbin
lib/middleware.js
function () { return function (req, res, next) { var apphost = config.url.host, outputHost = undefsafe(config, 'security.preview'), host = req.header('Host', ''), offset = host.indexOf(apphost); if (host === outputHost) { offset = host.indexOf(outputHost); } if (offset > 0) { // Slice the host from the subdomain and subtract 1 for // trailing . on the subdomain. req.subdomain = host.slice(0, offset - 1); } next(); }; }
javascript
function () { return function (req, res, next) { var apphost = config.url.host, outputHost = undefsafe(config, 'security.preview'), host = req.header('Host', ''), offset = host.indexOf(apphost); if (host === outputHost) { offset = host.indexOf(outputHost); } if (offset > 0) { // Slice the host from the subdomain and subtract 1 for // trailing . on the subdomain. req.subdomain = host.slice(0, offset - 1); } next(); }; }
[ "function", "(", ")", "{", "return", "function", "(", "req", ",", "res", ",", "next", ")", "{", "var", "apphost", "=", "config", ".", "url", ".", "host", ",", "outputHost", "=", "undefsafe", "(", "config", ",", "'security.preview'", ")", ",", "host", "=", "req", ".", "header", "(", "'Host'", ",", "''", ")", ",", "offset", "=", "host", ".", "indexOf", "(", "apphost", ")", ";", "if", "(", "host", "===", "outputHost", ")", "{", "offset", "=", "host", ".", "indexOf", "(", "outputHost", ")", ";", "}", "if", "(", "offset", ">", "0", ")", "{", "// Slice the host from the subdomain and subtract 1 for", "// trailing . on the subdomain.", "req", ".", "subdomain", "=", "host", ".", "slice", "(", "0", ",", "offset", "-", "1", ")", ";", "}", "next", "(", ")", ";", "}", ";", "}" ]
Checks for a subdomain in the current url, if found it sets the req.subdomain property. This supports existing behaviour that allows subdomains to load custom config files.
[ "Checks", "for", "a", "subdomain", "in", "the", "current", "url", "if", "found", "it", "sets", "the", "req", ".", "subdomain", "property", ".", "This", "supports", "existing", "behaviour", "that", "allows", "subdomains", "to", "load", "custom", "config", "files", "." ]
d962c36fff71104acad98ac07629c1331704d420
https://github.com/jsbin/jsbin/blob/d962c36fff71104acad98ac07629c1331704d420/lib/middleware.js#L153-L171
10,413
jsbin/jsbin
lib/middleware.js
function (options) { // Parse a string representing a file size and convert it into bytes. // A number on it's own will be assumed to be bytes. A multiple such as // "k" or "m" can be appended to the string to handle larger numbers. This // is case insensitive and uses powers of 1024 rather than (1000). // So both 1kB and 1kb == 1024. function parseLimit(string) { var matches = ('' + string).toLowerCase().match(regexp), bytes = null, power; if (matches) { bytes = parseFloat(matches[1]); power = powers[matches[2]]; if (bytes && power) { bytes = Math.pow(bytes * 1024, power); } } return bytes || null; } var powers = { k: 1, m: 2, g: 3, t: 4 }, regexp = /^(\d+(?:.\d+)?)\s*([kmgt]?)b?$/, limit = options && parseLimit(options.limit); return function (req, res, next) { if (limit) { var contentLength = parseInt(req.header('Content-Length', 0), 10), message = 'Sorry, the content you have uploaded is larger than JS Bin can handle. Max size is ' + options.limit; if (limit && contentLength > limit) { return next(new errors.RequestEntityTooLarge(message)); } } next(); }; }
javascript
function (options) { // Parse a string representing a file size and convert it into bytes. // A number on it's own will be assumed to be bytes. A multiple such as // "k" or "m" can be appended to the string to handle larger numbers. This // is case insensitive and uses powers of 1024 rather than (1000). // So both 1kB and 1kb == 1024. function parseLimit(string) { var matches = ('' + string).toLowerCase().match(regexp), bytes = null, power; if (matches) { bytes = parseFloat(matches[1]); power = powers[matches[2]]; if (bytes && power) { bytes = Math.pow(bytes * 1024, power); } } return bytes || null; } var powers = { k: 1, m: 2, g: 3, t: 4 }, regexp = /^(\d+(?:.\d+)?)\s*([kmgt]?)b?$/, limit = options && parseLimit(options.limit); return function (req, res, next) { if (limit) { var contentLength = parseInt(req.header('Content-Length', 0), 10), message = 'Sorry, the content you have uploaded is larger than JS Bin can handle. Max size is ' + options.limit; if (limit && contentLength > limit) { return next(new errors.RequestEntityTooLarge(message)); } } next(); }; }
[ "function", "(", "options", ")", "{", "// Parse a string representing a file size and convert it into bytes.", "// A number on it's own will be assumed to be bytes. A multiple such as", "// \"k\" or \"m\" can be appended to the string to handle larger numbers. This", "// is case insensitive and uses powers of 1024 rather than (1000).", "// So both 1kB and 1kb == 1024.", "function", "parseLimit", "(", "string", ")", "{", "var", "matches", "=", "(", "''", "+", "string", ")", ".", "toLowerCase", "(", ")", ".", "match", "(", "regexp", ")", ",", "bytes", "=", "null", ",", "power", ";", "if", "(", "matches", ")", "{", "bytes", "=", "parseFloat", "(", "matches", "[", "1", "]", ")", ";", "power", "=", "powers", "[", "matches", "[", "2", "]", "]", ";", "if", "(", "bytes", "&&", "power", ")", "{", "bytes", "=", "Math", ".", "pow", "(", "bytes", "*", "1024", ",", "power", ")", ";", "}", "}", "return", "bytes", "||", "null", ";", "}", "var", "powers", "=", "{", "k", ":", "1", ",", "m", ":", "2", ",", "g", ":", "3", ",", "t", ":", "4", "}", ",", "regexp", "=", "/", "^(\\d+(?:.\\d+)?)\\s*([kmgt]?)b?$", "/", ",", "limit", "=", "options", "&&", "parseLimit", "(", "options", ".", "limit", ")", ";", "return", "function", "(", "req", ",", "res", ",", "next", ")", "{", "if", "(", "limit", ")", "{", "var", "contentLength", "=", "parseInt", "(", "req", ".", "header", "(", "'Content-Length'", ",", "0", ")", ",", "10", ")", ",", "message", "=", "'Sorry, the content you have uploaded is larger than JS Bin can handle. Max size is '", "+", "options", ".", "limit", ";", "if", "(", "limit", "&&", "contentLength", ">", "limit", ")", "{", "return", "next", "(", "new", "errors", ".", "RequestEntityTooLarge", "(", "message", ")", ")", ";", "}", "}", "next", "(", ")", ";", "}", ";", "}" ]
Limit the file size that can be uploaded.
[ "Limit", "the", "file", "size", "that", "can", "be", "uploaded", "." ]
d962c36fff71104acad98ac07629c1331704d420
https://github.com/jsbin/jsbin/blob/d962c36fff71104acad98ac07629c1331704d420/lib/middleware.js#L174-L211
10,414
jsbin/jsbin
lib/middleware.js
function () { return function (req, res, next) { var userModel = models.user; if (req.url.indexOf('/api') === 0) { req.isApi = true; // Make the API requests stateless by removin the cookie set by middleware cookieSession onHeaders(res, () => res.removeHeader('Set-Cookie')); if (config.api.requireSSL) { if (!req.secure && (String(req.headers['x-forwarded-proto']).toLowerCase() !== 'https') ) { res.status(403); // forbidden res.json({ error: 'All API requests must be made over SSL/TLS' }); return; } } if (req.query.api_key) { req.apiKey = req.query.api_key; } else if (req.headers.authorization) { req.apiKey = req.headers.authorization.replace(/token\s/i,''); } var validateApiRequest = function () { if (config.api.allowAnonymousReadWrite || (config.api.allowAnonymousRead && req.method === 'GET')) { next(); } else { if (!req.apiKey) { res.status(403); // forbidden res.json({ error: 'You need to provide a valid API key when using this API' }); } else { next(); } } }; if (req.apiKey) { userModel.loadByApiKey(req.apiKey, function (err, user) { if (err) { return next(err); } if (user) { req.session.user = user; // since we're setting the user session via the API // we need to ensure that the user is totally trashed // from the session to avoid abuse directly in the browser // i.e. stolen api key can only create bins, nothing more. onHeaders(res, () => delete req.session); validateApiRequest(); } else { res.status(403); // forbidden res.json({ error: 'The API key you provided is not valid' }); } }); } else { validateApiRequest(); } } else { next(); } }; }
javascript
function () { return function (req, res, next) { var userModel = models.user; if (req.url.indexOf('/api') === 0) { req.isApi = true; // Make the API requests stateless by removin the cookie set by middleware cookieSession onHeaders(res, () => res.removeHeader('Set-Cookie')); if (config.api.requireSSL) { if (!req.secure && (String(req.headers['x-forwarded-proto']).toLowerCase() !== 'https') ) { res.status(403); // forbidden res.json({ error: 'All API requests must be made over SSL/TLS' }); return; } } if (req.query.api_key) { req.apiKey = req.query.api_key; } else if (req.headers.authorization) { req.apiKey = req.headers.authorization.replace(/token\s/i,''); } var validateApiRequest = function () { if (config.api.allowAnonymousReadWrite || (config.api.allowAnonymousRead && req.method === 'GET')) { next(); } else { if (!req.apiKey) { res.status(403); // forbidden res.json({ error: 'You need to provide a valid API key when using this API' }); } else { next(); } } }; if (req.apiKey) { userModel.loadByApiKey(req.apiKey, function (err, user) { if (err) { return next(err); } if (user) { req.session.user = user; // since we're setting the user session via the API // we need to ensure that the user is totally trashed // from the session to avoid abuse directly in the browser // i.e. stolen api key can only create bins, nothing more. onHeaders(res, () => delete req.session); validateApiRequest(); } else { res.status(403); // forbidden res.json({ error: 'The API key you provided is not valid' }); } }); } else { validateApiRequest(); } } else { next(); } }; }
[ "function", "(", ")", "{", "return", "function", "(", "req", ",", "res", ",", "next", ")", "{", "var", "userModel", "=", "models", ".", "user", ";", "if", "(", "req", ".", "url", ".", "indexOf", "(", "'/api'", ")", "===", "0", ")", "{", "req", ".", "isApi", "=", "true", ";", "// Make the API requests stateless by removin the cookie set by middleware cookieSession", "onHeaders", "(", "res", ",", "(", ")", "=>", "res", ".", "removeHeader", "(", "'Set-Cookie'", ")", ")", ";", "if", "(", "config", ".", "api", ".", "requireSSL", ")", "{", "if", "(", "!", "req", ".", "secure", "&&", "(", "String", "(", "req", ".", "headers", "[", "'x-forwarded-proto'", "]", ")", ".", "toLowerCase", "(", ")", "!==", "'https'", ")", ")", "{", "res", ".", "status", "(", "403", ")", ";", "// forbidden", "res", ".", "json", "(", "{", "error", ":", "'All API requests must be made over SSL/TLS'", "}", ")", ";", "return", ";", "}", "}", "if", "(", "req", ".", "query", ".", "api_key", ")", "{", "req", ".", "apiKey", "=", "req", ".", "query", ".", "api_key", ";", "}", "else", "if", "(", "req", ".", "headers", ".", "authorization", ")", "{", "req", ".", "apiKey", "=", "req", ".", "headers", ".", "authorization", ".", "replace", "(", "/", "token\\s", "/", "i", ",", "''", ")", ";", "}", "var", "validateApiRequest", "=", "function", "(", ")", "{", "if", "(", "config", ".", "api", ".", "allowAnonymousReadWrite", "||", "(", "config", ".", "api", ".", "allowAnonymousRead", "&&", "req", ".", "method", "===", "'GET'", ")", ")", "{", "next", "(", ")", ";", "}", "else", "{", "if", "(", "!", "req", ".", "apiKey", ")", "{", "res", ".", "status", "(", "403", ")", ";", "// forbidden", "res", ".", "json", "(", "{", "error", ":", "'You need to provide a valid API key when using this API'", "}", ")", ";", "}", "else", "{", "next", "(", ")", ";", "}", "}", "}", ";", "if", "(", "req", ".", "apiKey", ")", "{", "userModel", ".", "loadByApiKey", "(", "req", ".", "apiKey", ",", "function", "(", "err", ",", "user", ")", "{", "if", "(", "err", ")", "{", "return", "next", "(", "err", ")", ";", "}", "if", "(", "user", ")", "{", "req", ".", "session", ".", "user", "=", "user", ";", "// since we're setting the user session via the API", "// we need to ensure that the user is totally trashed", "// from the session to avoid abuse directly in the browser", "// i.e. stolen api key can only create bins, nothing more.", "onHeaders", "(", "res", ",", "(", ")", "=>", "delete", "req", ".", "session", ")", ";", "validateApiRequest", "(", ")", ";", "}", "else", "{", "res", ".", "status", "(", "403", ")", ";", "// forbidden", "res", ".", "json", "(", "{", "error", ":", "'The API key you provided is not valid'", "}", ")", ";", "}", "}", ")", ";", "}", "else", "{", "validateApiRequest", "(", ")", ";", "}", "}", "else", "{", "next", "(", ")", ";", "}", "}", ";", "}" ]
detect if this is an API request and add flag isApi to the request object
[ "detect", "if", "this", "is", "an", "API", "request", "and", "add", "flag", "isApi", "to", "the", "request", "object" ]
d962c36fff71104acad98ac07629c1331704d420
https://github.com/jsbin/jsbin/blob/d962c36fff71104acad98ac07629c1331704d420/lib/middleware.js#L214-L278
10,415
jsbin/jsbin
public/js/render/console.js
function (cmd, cb) { var internalCmd = internalCommand(cmd); if (internalCmd) { return cb(['info', internalCmd]); } $document.trigger('console:run', cmd); }
javascript
function (cmd, cb) { var internalCmd = internalCommand(cmd); if (internalCmd) { return cb(['info', internalCmd]); } $document.trigger('console:run', cmd); }
[ "function", "(", "cmd", ",", "cb", ")", "{", "var", "internalCmd", "=", "internalCommand", "(", "cmd", ")", ";", "if", "(", "internalCmd", ")", "{", "return", "cb", "(", "[", "'info'", ",", "internalCmd", "]", ")", ";", "}", "$document", ".", "trigger", "(", "'console:run'", ",", "cmd", ")", ";", "}" ]
Run a console command.
[ "Run", "a", "console", "command", "." ]
d962c36fff71104acad98ac07629c1331704d420
https://github.com/jsbin/jsbin/blob/d962c36fff71104acad98ac07629c1331704d420/public/js/render/console.js#L22-L28
10,416
jsbin/jsbin
public/js/render/console.js
function (cmd, blind, response) { var toecho = ''; if (typeof cmd !== 'string') { toecho = cmd.echo; blind = cmd.blind; response = cmd.response; cmd = cmd.cmd; } else { toecho = cmd; } cmd = trim(cmd); // Add the command to the user's history – unless this was blind if (!blind) { history.push(cmd.trim()); setHistory(history); } // Show the user what they typed echo(toecho.trim()); // If we were handed a response, show the response straight away – otherwise // runs it if (response) return showResponse(response); run(cmd, showResponse); setCursorTo(''); }
javascript
function (cmd, blind, response) { var toecho = ''; if (typeof cmd !== 'string') { toecho = cmd.echo; blind = cmd.blind; response = cmd.response; cmd = cmd.cmd; } else { toecho = cmd; } cmd = trim(cmd); // Add the command to the user's history – unless this was blind if (!blind) { history.push(cmd.trim()); setHistory(history); } // Show the user what they typed echo(toecho.trim()); // If we were handed a response, show the response straight away – otherwise // runs it if (response) return showResponse(response); run(cmd, showResponse); setCursorTo(''); }
[ "function", "(", "cmd", ",", "blind", ",", "response", ")", "{", "var", "toecho", "=", "''", ";", "if", "(", "typeof", "cmd", "!==", "'string'", ")", "{", "toecho", "=", "cmd", ".", "echo", ";", "blind", "=", "cmd", ".", "blind", ";", "response", "=", "cmd", ".", "response", ";", "cmd", "=", "cmd", ".", "cmd", ";", "}", "else", "{", "toecho", "=", "cmd", ";", "}", "cmd", "=", "trim", "(", "cmd", ")", ";", "// Add the command to the user's history – unless this was blind", "if", "(", "!", "blind", ")", "{", "history", ".", "push", "(", "cmd", ".", "trim", "(", ")", ")", ";", "setHistory", "(", "history", ")", ";", "}", "// Show the user what they typed", "echo", "(", "toecho", ".", "trim", "(", ")", ")", ";", "// If we were handed a response, show the response straight away – otherwise", "// runs it", "if", "(", "response", ")", "return", "showResponse", "(", "response", ")", ";", "run", "(", "cmd", ",", "showResponse", ")", ";", "setCursorTo", "(", "''", ")", ";", "}" ]
Run and show response to a command fired from the console
[ "Run", "and", "show", "response", "to", "a", "command", "fired", "from", "the", "console" ]
d962c36fff71104acad98ac07629c1331704d420
https://github.com/jsbin/jsbin/blob/d962c36fff71104acad98ac07629c1331704d420/public/js/render/console.js#L33-L62
10,417
jsbin/jsbin
public/js/render/console.js
function (response) { // order so it appears at the top var el = document.createElement('div'), li = document.createElement('li'), span = document.createElement('span'), parent = output.parentNode; historyPosition = history.length; if (typeof response === 'undefined') return; el.className = 'response'; span.innerHTML = response[1]; if (response[0] != 'info') prettyPrint([span]); el.appendChild(span); li.className = response[0]; li.innerHTML = '<span class="gutter"></span>'; li.appendChild(el); appendLog(li); exec.value = ''; if (enableCC) { try { if (jsbin.panels && jsbin.panels.focused.id === 'console') { if (!jsbin.embed) { getCursor().focus(); } document.execCommand('selectAll', false, null); document.execCommand('delete', false, null); } } catch (e) {} } }
javascript
function (response) { // order so it appears at the top var el = document.createElement('div'), li = document.createElement('li'), span = document.createElement('span'), parent = output.parentNode; historyPosition = history.length; if (typeof response === 'undefined') return; el.className = 'response'; span.innerHTML = response[1]; if (response[0] != 'info') prettyPrint([span]); el.appendChild(span); li.className = response[0]; li.innerHTML = '<span class="gutter"></span>'; li.appendChild(el); appendLog(li); exec.value = ''; if (enableCC) { try { if (jsbin.panels && jsbin.panels.focused.id === 'console') { if (!jsbin.embed) { getCursor().focus(); } document.execCommand('selectAll', false, null); document.execCommand('delete', false, null); } } catch (e) {} } }
[ "function", "(", "response", ")", "{", "// order so it appears at the top", "var", "el", "=", "document", ".", "createElement", "(", "'div'", ")", ",", "li", "=", "document", ".", "createElement", "(", "'li'", ")", ",", "span", "=", "document", ".", "createElement", "(", "'span'", ")", ",", "parent", "=", "output", ".", "parentNode", ";", "historyPosition", "=", "history", ".", "length", ";", "if", "(", "typeof", "response", "===", "'undefined'", ")", "return", ";", "el", ".", "className", "=", "'response'", ";", "span", ".", "innerHTML", "=", "response", "[", "1", "]", ";", "if", "(", "response", "[", "0", "]", "!=", "'info'", ")", "prettyPrint", "(", "[", "span", "]", ")", ";", "el", ".", "appendChild", "(", "span", ")", ";", "li", ".", "className", "=", "response", "[", "0", "]", ";", "li", ".", "innerHTML", "=", "'<span class=\"gutter\"></span>'", ";", "li", ".", "appendChild", "(", "el", ")", ";", "appendLog", "(", "li", ")", ";", "exec", ".", "value", "=", "''", ";", "if", "(", "enableCC", ")", "{", "try", "{", "if", "(", "jsbin", ".", "panels", "&&", "jsbin", ".", "panels", ".", "focused", ".", "id", "===", "'console'", ")", "{", "if", "(", "!", "jsbin", ".", "embed", ")", "{", "getCursor", "(", ")", ".", "focus", "(", ")", ";", "}", "document", ".", "execCommand", "(", "'selectAll'", ",", "false", ",", "null", ")", ";", "document", ".", "execCommand", "(", "'delete'", ",", "false", ",", "null", ")", ";", "}", "}", "catch", "(", "e", ")", "{", "}", "}", "}" ]
Display the result of a command to the user
[ "Display", "the", "result", "of", "a", "command", "to", "the", "user" ]
d962c36fff71104acad98ac07629c1331704d420
https://github.com/jsbin/jsbin/blob/d962c36fff71104acad98ac07629c1331704d420/public/js/render/console.js#L67-L104
10,418
jsbin/jsbin
public/js/vendor/codemirror3/mode/stex/stex.js
getMostPowerful
function getMostPowerful(state) { var context = state.cmdState; for (var i = context.length - 1; i >= 0; i--) { var plug = context[i]; if (plug.name == "DEFAULT") { continue; } return plug; } return { styleIdentifier: function() { return null; } }; }
javascript
function getMostPowerful(state) { var context = state.cmdState; for (var i = context.length - 1; i >= 0; i--) { var plug = context[i]; if (plug.name == "DEFAULT") { continue; } return plug; } return { styleIdentifier: function() { return null; } }; }
[ "function", "getMostPowerful", "(", "state", ")", "{", "var", "context", "=", "state", ".", "cmdState", ";", "for", "(", "var", "i", "=", "context", ".", "length", "-", "1", ";", "i", ">=", "0", ";", "i", "--", ")", "{", "var", "plug", "=", "context", "[", "i", "]", ";", "if", "(", "plug", ".", "name", "==", "\"DEFAULT\"", ")", "{", "continue", ";", "}", "return", "plug", ";", "}", "return", "{", "styleIdentifier", ":", "function", "(", ")", "{", "return", "null", ";", "}", "}", ";", "}" ]
returns the non-default plugin closest to the end of the list
[ "returns", "the", "non", "-", "default", "plugin", "closest", "to", "the", "end", "of", "the", "list" ]
d962c36fff71104acad98ac07629c1331704d420
https://github.com/jsbin/jsbin/blob/d962c36fff71104acad98ac07629c1331704d420/public/js/vendor/codemirror3/mode/stex/stex.js#L29-L39
10,419
jsbin/jsbin
lib/helpers.js
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
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); } }
[ "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", ")", ";", "}", "}" ]
Renders the analytics snippet. Accepts a callback that recieves and error and html object.
[ "Renders", "the", "analytics", "snippet", ".", "Accepts", "a", "callback", "that", "recieves", "and", "error", "and", "html", "object", "." ]
d962c36fff71104acad98ac07629c1331704d420
https://github.com/jsbin/jsbin/blob/d962c36fff71104acad98ac07629c1331704d420/lib/helpers.js#L30-L53
10,420
jsbin/jsbin
lib/helpers.js
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
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; }
[ "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", ";", "}" ]
Generates a url for the path provided including prefix. If the second full parameter is provided then a full url including domain and protocol will be returned.
[ "Generates", "a", "url", "for", "the", "path", "provided", "including", "prefix", ".", "If", "the", "second", "full", "parameter", "is", "provided", "then", "a", "full", "url", "including", "domain", "and", "protocol", "will", "be", "returned", "." ]
d962c36fff71104acad98ac07629c1331704d420
https://github.com/jsbin/jsbin/blob/d962c36fff71104acad98ac07629c1331704d420/lib/helpers.js#L58-L79
10,421
jsbin/jsbin
lib/helpers.js
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
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; }
[ "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", ";", "}" ]
Returns a gravatar url for the email address provided. An optional size parameter can be provided to specify the size of the avatar to generate.
[ "Returns", "a", "gravatar", "url", "for", "the", "email", "address", "provided", ".", "An", "optional", "size", "parameter", "can", "be", "provided", "to", "specify", "the", "size", "of", "the", "avatar", "to", "generate", "." ]
d962c36fff71104acad98ac07629c1331704d420
https://github.com/jsbin/jsbin/blob/d962c36fff71104acad98ac07629c1331704d420/lib/helpers.js#L121-L146
10,422
jsbin/jsbin
lib/helpers.js
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
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; }
[ "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", ";", "}" ]
Returns a url for a static resource.
[ "Returns", "a", "url", "for", "a", "static", "resource", "." ]
d962c36fff71104acad98ac07629c1331704d420
https://github.com/jsbin/jsbin/blob/d962c36fff71104acad98ac07629c1331704d420/lib/helpers.js#L149-L168
10,423
jsbin/jsbin
public/js/vendor/codemirror3/addon/merge/merge.js
clearMarks
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
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; }
[ "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", ";", "}" ]
Updating the marks for editor content
[ "Updating", "the", "marks", "for", "editor", "content" ]
d962c36fff71104acad98ac07629c1331704d420
https://github.com/jsbin/jsbin/blob/d962c36fff71104acad98ac07629c1331704d420/public/js/vendor/codemirror3/addon/merge/merge.js#L152-L164
10,424
jsbin/jsbin
public/js/vendor/codemirror3/addon/merge/merge.js
updateMarks
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
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; } } }); }
[ "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", ";", "}", "}", "}", ")", ";", "}" ]
FIXME maybe add a margin around viewport to prevent too many updates
[ "FIXME", "maybe", "add", "a", "margin", "around", "viewport", "to", "prevent", "too", "many", "updates" ]
d962c36fff71104acad98ac07629c1331704d420
https://github.com/jsbin/jsbin/blob/d962c36fff71104acad98ac07629c1331704d420/public/js/vendor/codemirror3/addon/merge/merge.js#L167-L185
10,425
jsbin/jsbin
public/js/vendor/codemirror3/addon/merge/merge.js
drawConnectors
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
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"; }); }
[ "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\"", ";", "}", ")", ";", "}" ]
Updating the gap between editor and original
[ "Updating", "the", "gap", "between", "editor", "and", "original" ]
d962c36fff71104acad98ac07629c1331704d420
https://github.com/jsbin/jsbin/blob/d962c36fff71104acad98ac07629c1331704d420/public/js/vendor/codemirror3/addon/merge/merge.js#L234-L270
10,426
jsbin/jsbin
lib/handlers/bin.js
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
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]); }
[ "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", "]", ")", ";", "}" ]
applies the processors to the bin and generates the html, js, etc based on the appropriate processor. Used in the previews and the API requests.
[ "applies", "the", "processors", "to", "the", "bin", "and", "generates", "the", "html", "js", "etc", "based", "on", "the", "appropriate", "processor", ".", "Used", "in", "the", "previews", "and", "the", "API", "requests", "." ]
d962c36fff71104acad98ac07629c1331704d420
https://github.com/jsbin/jsbin/blob/d962c36fff71104acad98ac07629c1331704d420/lib/handlers/bin.js#L1674-L1736
10,427
jsbin/jsbin
public/js/embed.js
getLinks
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
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; }
[ "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", ";", "}" ]
1. find all links with class=jsbin
[ "1", ".", "find", "all", "links", "with", "class", "=", "jsbin" ]
d962c36fff71104acad98ac07629c1331704d420
https://github.com/jsbin/jsbin/blob/d962c36fff71104acad98ac07629c1331704d420/public/js/embed.js#L105-L116
10,428
jsbin/jsbin
public/js/vendor/jshint/jshint.js
peek
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
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; }
[ "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", ";", "}" ]
We need a peek function. If it has an argument, it peeks that much farther ahead. It is used to distinguish for ( var i in ... from for ( var i = ...
[ "We", "need", "a", "peek", "function", ".", "If", "it", "has", "an", "argument", "it", "peeks", "that", "much", "farther", "ahead", ".", "It", "is", "used", "to", "distinguish", "for", "(", "var", "i", "in", "...", "from", "for", "(", "var", "i", "=", "..." ]
d962c36fff71104acad98ac07629c1331704d420
https://github.com/jsbin/jsbin/blob/d962c36fff71104acad98ac07629c1331704d420/public/js/vendor/jshint/jshint.js#L53595-L53606
10,429
jsbin/jsbin
public/js/vendor/jshint/jshint.js
nobreaknonadjacent
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
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); } }
[ "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", ")", ";", "}", "}" ]
Functions for conformance of style.
[ "Functions", "for", "conformance", "of", "style", "." ]
d962c36fff71104acad98ac07629c1331704d420
https://github.com/jsbin/jsbin/blob/d962c36fff71104acad98ac07629c1331704d420/public/js/vendor/jshint/jshint.js#L53795-L53801
10,430
jsbin/jsbin
public/js/vendor/jshint/jshint.js
identifier
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
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); } }
[ "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", ")", ";", "}", "}" ]
fnparam means that this identifier is being defined as a function argument prop means that this identifier is that of an object property
[ "fnparam", "means", "that", "this", "identifier", "is", "being", "defined", "as", "a", "function", "argument", "prop", "means", "that", "this", "identifier", "is", "that", "of", "an", "object", "property" ]
d962c36fff71104acad98ac07629c1331704d420
https://github.com/jsbin/jsbin/blob/d962c36fff71104acad98ac07629c1331704d420/public/js/vendor/jshint/jshint.js#L54267-L54277
10,431
jsbin/jsbin
public/js/vendor/jshint/jshint.js
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
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; }
[ "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", ";", "}" ]
this function is used to determine wether a squarebracket or a curlybracket expression is a comprehension array, destructuring assignment or a json value.
[ "this", "function", "is", "used", "to", "determine", "wether", "a", "squarebracket", "or", "a", "curlybracket", "expression", "is", "a", "comprehension", "array", "destructuring", "assignment", "or", "a", "json", "value", "." ]
d962c36fff71104acad98ac07629c1331704d420
https://github.com/jsbin/jsbin/blob/d962c36fff71104acad98ac07629c1331704d420/public/js/vendor/jshint/jshint.js#L56974-L57006
10,432
jsbin/jsbin
public/js/vendor/jshint/jshint.js
commentToken
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
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 }; }
[ "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", "}", ";", "}" ]
Create a comment token object and make sure it has all the data JSHint needs to work with special comments.
[ "Create", "a", "comment", "token", "object", "and", "make", "sure", "it", "has", "all", "the", "data", "JSHint", "needs", "to", "work", "with", "special", "comments", "." ]
d962c36fff71104acad98ac07629c1331704d420
https://github.com/jsbin/jsbin/blob/d962c36fff71104acad98ac07629c1331704d420/public/js/vendor/jshint/jshint.js#L58134-L58193
10,433
jsbin/jsbin
public/js/vendor/beautify/beautify.js
split_newlines
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
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; }
[ "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", ";", "}" ]
we could use just string.split, but IE doesn't like returning empty strings
[ "we", "could", "use", "just", "string", ".", "split", "but", "IE", "doesn", "t", "like", "returning", "empty", "strings" ]
d962c36fff71104acad98ac07629c1331704d420
https://github.com/jsbin/jsbin/blob/d962c36fff71104acad98ac07629c1331704d420/public/js/vendor/beautify/beautify.js#L382-L397
10,434
jsbin/jsbin
lib/stripe/handlers/index.js
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
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); }); }
[ "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", ")", ";", "}", ")", ";", "}" ]
stripe sent us a webhook, so respond appropriately
[ "stripe", "sent", "us", "a", "webhook", "so", "respond", "appropriately" ]
d962c36fff71104acad98ac07629c1331704d420
https://github.com/jsbin/jsbin/blob/d962c36fff71104acad98ac07629c1331704d420/lib/stripe/handlers/index.js#L47-L65
10,435
jsbin/jsbin
public/js/render/live.js
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
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; }); }
[ "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", ";", "}", ")", ";", "}" ]
The big daddy that handles postmessaging the runner.
[ "The", "big", "daddy", "that", "handles", "postmessaging", "the", "runner", "." ]
d962c36fff71104acad98ac07629c1331704d420
https://github.com/jsbin/jsbin/blob/d962c36fff71104acad98ac07629c1331704d420/public/js/render/live.js#L365-L402
10,436
jsbin/jsbin
public/js/vendor/codemirror3/addon/tern/tern.js
updateArgHints
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
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); }); }
[ "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", ")", ";", "}", ")", ";", "}" ]
Maintaining argument hints
[ "Maintaining", "argument", "hints" ]
d962c36fff71104acad98ac07629c1331704d420
https://github.com/jsbin/jsbin/blob/d962c36fff71104acad98ac07629c1331704d420/public/js/vendor/codemirror3/addon/tern/tern.js#L246-L286
10,437
jsbin/jsbin
public/js/vendor/codemirror3/addon/tern/tern.js
buildRequest
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
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}; }
[ "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", "}", ";", "}" ]
Generic request-building helper
[ "Generic", "request", "-", "building", "helper" ]
d962c36fff71104acad98ac07629c1331704d420
https://github.com/jsbin/jsbin/blob/d962c36fff71104acad98ac07629c1331704d420/public/js/vendor/codemirror3/addon/tern/tern.js#L455-L495
10,438
jsbin/jsbin
public/js/spike.js
stringify
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
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; }
[ "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", ";", "}" ]
from console.js
[ "from", "console", ".", "js" ]
d962c36fff71104acad98ac07629c1331704d420
https://github.com/jsbin/jsbin/blob/d962c36fff71104acad98ac07629c1331704d420/public/js/spike.js#L28-L76
10,439
jsbin/jsbin
public/js/spike.js
function (rawData) { var data = stringify(rawData); if (useSS) { sessionStorage.spike = data; } else { window.name = data; } return data; }
javascript
function (rawData) { var data = stringify(rawData); if (useSS) { sessionStorage.spike = data; } else { window.name = data; } return data; }
[ "function", "(", "rawData", ")", "{", "var", "data", "=", "stringify", "(", "rawData", ")", ";", "if", "(", "useSS", ")", "{", "sessionStorage", ".", "spike", "=", "data", ";", "}", "else", "{", "window", ".", "name", "=", "data", ";", "}", "return", "data", ";", "}" ]
Save data to SS or window.name
[ "Save", "data", "to", "SS", "or", "window", ".", "name" ]
d962c36fff71104acad98ac07629c1331704d420
https://github.com/jsbin/jsbin/blob/d962c36fff71104acad98ac07629c1331704d420/public/js/spike.js#L109-L117
10,440
jsbin/jsbin
public/js/spike.js
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
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; }
[ "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", ";", "}" ]
Get data back from SS or window.name
[ "Get", "data", "back", "from", "SS", "or", "window", ".", "name" ]
d962c36fff71104acad98ac07629c1331704d420
https://github.com/jsbin/jsbin/blob/d962c36fff71104acad98ac07629c1331704d420/public/js/spike.js#L121-L130
10,441
jsbin/jsbin
public/js/spike.js
restore
function restore() { var data = store.get() || {}; addEvent('load', function () { //console.log('scrolling to', data.y); window.scrollTo(data.x, data.y); }); }
javascript
function restore() { var data = store.get() || {}; addEvent('load', function () { //console.log('scrolling to', data.y); window.scrollTo(data.x, data.y); }); }
[ "function", "restore", "(", ")", "{", "var", "data", "=", "store", ".", "get", "(", ")", "||", "{", "}", ";", "addEvent", "(", "'load'", ",", "function", "(", ")", "{", "//console.log('scrolling to', data.y);", "window", ".", "scrollTo", "(", "data", ".", "x", ",", "data", ".", "y", ")", ";", "}", ")", ";", "}" ]
Restore data from sessionStorage or the window.name when page is reloaded.
[ "Restore", "data", "from", "sessionStorage", "or", "the", "window", ".", "name", "when", "page", "is", "reloaded", "." ]
d962c36fff71104acad98ac07629c1331704d420
https://github.com/jsbin/jsbin/blob/d962c36fff71104acad98ac07629c1331704d420/public/js/spike.js#L137-L143
10,442
jsbin/jsbin
public/js/vendor/acorn/util/walk.js
makeScope
function makeScope(prev, isCatch) { return {vars: Object.create(null), prev: prev, isCatch: isCatch}; }
javascript
function makeScope(prev, isCatch) { return {vars: Object.create(null), prev: prev, isCatch: isCatch}; }
[ "function", "makeScope", "(", "prev", ",", "isCatch", ")", "{", "return", "{", "vars", ":", "Object", ".", "create", "(", "null", ")", ",", "prev", ":", "prev", ",", "isCatch", ":", "isCatch", "}", ";", "}" ]
A custom walker that keeps track of the scope chain and the variables defined in it.
[ "A", "custom", "walker", "that", "keeps", "track", "of", "the", "scope", "chain", "and", "the", "variables", "defined", "in", "it", "." ]
d962c36fff71104acad98ac07629c1331704d420
https://github.com/jsbin/jsbin/blob/d962c36fff71104acad98ac07629c1331704d420/public/js/vendor/acorn/util/walk.js#L275-L277
10,443
jsbin/jsbin
public/js/editors/panel.js
function(cm) { if (CodeMirror.snippets(cm) === CodeMirror.Pass) { return CodeMirror.simpleHint(cm, CodeMirror.hint.javascript); } }
javascript
function(cm) { if (CodeMirror.snippets(cm) === CodeMirror.Pass) { return CodeMirror.simpleHint(cm, CodeMirror.hint.javascript); } }
[ "function", "(", "cm", ")", "{", "if", "(", "CodeMirror", ".", "snippets", "(", "cm", ")", "===", "CodeMirror", ".", "Pass", ")", "{", "return", "CodeMirror", ".", "simpleHint", "(", "cm", ",", "CodeMirror", ".", "hint", ".", "javascript", ")", ";", "}", "}" ]
Save a reference to this autocomplete function to use it when Tern scripts are loaded but not used, since they will automatically overwrite the CodeMirror autocomplete function with CodeMirror.showHint
[ "Save", "a", "reference", "to", "this", "autocomplete", "function", "to", "use", "it", "when", "Tern", "scripts", "are", "loaded", "but", "not", "used", "since", "they", "will", "automatically", "overwrite", "the", "CodeMirror", "autocomplete", "function", "with", "CodeMirror", ".", "showHint" ]
d962c36fff71104acad98ac07629c1331704d420
https://github.com/jsbin/jsbin/blob/d962c36fff71104acad98ac07629c1331704d420/public/js/editors/panel.js#L38-L42
10,444
rickbergfalk/sqlpad
server/drivers/presto/_presto.js
getHeaders
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
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; }
[ "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", ";", "}" ]
Get Presto headers from config
[ "Get", "Presto", "headers", "from", "config" ]
84525a66a5480e9bffc559a1f34d59e1cea88d14
https://github.com/rickbergfalk/sqlpad/blob/84525a66a5480e9bffc559a1f34d59e1cea88d14/server/drivers/presto/_presto.js#L12-L21
10,445
rickbergfalk/sqlpad
server/drivers/presto/_presto.js
send
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
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)); }
[ "function", "send", "(", "config", ",", "query", ")", "{", "if", "(", "!", "config", ".", "url", ")", "{", "return", "Promise", ".", "reject", "(", "new", "Error", "(", "'config.url is required'", ")", ")", ";", "}", "const", "results", "=", "{", "data", ":", "[", "]", "}", ";", "return", "fetch", "(", "`", "${", "config", ".", "url", "}", "`", ",", "{", "method", ":", "'POST'", ",", "body", ":", "query", ",", "headers", ":", "getHeaders", "(", "config", ")", "}", ")", ".", "then", "(", "response", "=>", "response", ".", "json", "(", ")", ")", ".", "then", "(", "statement", "=>", "handleStatementAndGetMore", "(", "results", ",", "statement", ",", "config", ")", ")", ";", "}" ]
Given config and query, returns promise with the results
[ "Given", "config", "and", "query", "returns", "promise", "with", "the", "results" ]
84525a66a5480e9bffc559a1f34d59e1cea88d14
https://github.com/rickbergfalk/sqlpad/blob/84525a66a5480e9bffc559a1f34d59e1cea88d14/server/drivers/presto/_presto.js#L24-L38
10,446
rickbergfalk/sqlpad
server/drivers/cassandra/index.js
getSchema
function getSchema(connection) { connection.maxRows = 1000000; return runQuery(SCHEMA_SQL, connection).then(queryResult => formatSchemaQueryResults(queryResult) ); }
javascript
function getSchema(connection) { connection.maxRows = 1000000; return runQuery(SCHEMA_SQL, connection).then(queryResult => formatSchemaQueryResults(queryResult) ); }
[ "function", "getSchema", "(", "connection", ")", "{", "connection", ".", "maxRows", "=", "1000000", ";", "return", "runQuery", "(", "SCHEMA_SQL", ",", "connection", ")", ".", "then", "(", "queryResult", "=>", "formatSchemaQueryResults", "(", "queryResult", ")", ")", ";", "}" ]
Get schema for connection Cassandra driver doesn't accept MAX_SAFE_INTEGER as a fetch limit so we default to one million @param {*} connection
[ "Get", "schema", "for", "connection", "Cassandra", "driver", "doesn", "t", "accept", "MAX_SAFE_INTEGER", "as", "a", "fetch", "limit", "so", "we", "default", "to", "one", "million" ]
84525a66a5480e9bffc559a1f34d59e1cea88d14
https://github.com/rickbergfalk/sqlpad/blob/84525a66a5480e9bffc559a1f34d59e1cea88d14/server/drivers/cassandra/index.js#L83-L88
10,447
rickbergfalk/sqlpad
server/lib/migrate-schema.js
runMigrations
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
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); }); }
[ "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", ")", ";", "}", ")", ";", "}" ]
Run migrations until latest version @param {*} db @param {*} currentVersion @returns {Promise}
[ "Run", "migrations", "until", "latest", "version" ]
84525a66a5480e9bffc559a1f34d59e1cea88d14
https://github.com/rickbergfalk/sqlpad/blob/84525a66a5480e9bffc559a1f34d59e1cea88d14/server/lib/migrate-schema.js#L68-L92
10,448
rickbergfalk/sqlpad
server/drivers/index.js
validateFunction
function validateFunction(path, driver, functionName) { if (typeof driver[functionName] !== 'function') { console.error(`${path} missing .${functionName}() implementation`); process.exit(1); } }
javascript
function validateFunction(path, driver, functionName) { if (typeof driver[functionName] !== 'function') { console.error(`${path} missing .${functionName}() implementation`); process.exit(1); } }
[ "function", "validateFunction", "(", "path", ",", "driver", ",", "functionName", ")", "{", "if", "(", "typeof", "driver", "[", "functionName", "]", "!==", "'function'", ")", "{", "console", ".", "error", "(", "`", "${", "path", "}", "${", "functionName", "}", "`", ")", ";", "process", ".", "exit", "(", "1", ")", ";", "}", "}" ]
Validate that the driver implementation has a function by name provided @param {string} path @param {object} driver @param {string} functionName
[ "Validate", "that", "the", "driver", "implementation", "has", "a", "function", "by", "name", "provided" ]
84525a66a5480e9bffc559a1f34d59e1cea88d14
https://github.com/rickbergfalk/sqlpad/blob/84525a66a5480e9bffc559a1f34d59e1cea88d14/server/drivers/index.js#L14-L19
10,449
rickbergfalk/sqlpad
server/drivers/index.js
validateArray
function validateArray(path, driver, arrayName) { const arr = driver[arrayName]; if (!Array.isArray(arr)) { console.error(`${path} missing ${arrayName} array`); process.exit(1); } }
javascript
function validateArray(path, driver, arrayName) { const arr = driver[arrayName]; if (!Array.isArray(arr)) { console.error(`${path} missing ${arrayName} array`); process.exit(1); } }
[ "function", "validateArray", "(", "path", ",", "driver", ",", "arrayName", ")", "{", "const", "arr", "=", "driver", "[", "arrayName", "]", ";", "if", "(", "!", "Array", ".", "isArray", "(", "arr", ")", ")", "{", "console", ".", "error", "(", "`", "${", "path", "}", "${", "arrayName", "}", "`", ")", ";", "process", ".", "exit", "(", "1", ")", ";", "}", "}" ]
Validate that the driver implementation has an array by name provided @param {string} path @param {object} driver @param {string} arrayName
[ "Validate", "that", "the", "driver", "implementation", "has", "an", "array", "by", "name", "provided" ]
84525a66a5480e9bffc559a1f34d59e1cea88d14
https://github.com/rickbergfalk/sqlpad/blob/84525a66a5480e9bffc559a1f34d59e1cea88d14/server/drivers/index.js#L27-L33
10,450
rickbergfalk/sqlpad
server/drivers/index.js
requireValidate
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
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; }
[ "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", "}", "`", ")", ";", "process", ".", "exit", "(", "1", ")", ";", "}", "if", "(", "!", "driver", ".", "name", ")", "{", "console", ".", "error", "(", "`", "${", "path", "}", "`", ")", ";", "process", ".", "exit", "(", "1", ")", ";", "}", "if", "(", "drivers", "[", "driver", ".", "id", "]", ")", "{", "console", ".", "error", "(", "`", "${", "driver", ".", "id", "}", "`", ")", ";", "console", ".", "error", "(", "`", "${", "path", "}", "`", ")", ";", "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", ";", "}" ]
Require driver implementation for provided path and validate that it meets implementation spec as possible @param {string} path
[ "Require", "driver", "implementation", "for", "provided", "path", "and", "validate", "that", "it", "meets", "implementation", "spec", "as", "possible" ]
84525a66a5480e9bffc559a1f34d59e1cea88d14
https://github.com/rickbergfalk/sqlpad/blob/84525a66a5480e9bffc559a1f34d59e1cea88d14/server/drivers/index.js#L40-L83
10,451
rickbergfalk/sqlpad
server/drivers/index.js
runQuery
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
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; }); }
[ "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", "}", "`", ")", ";", "}", "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", ";", "}", ")", ";", "}" ]
Run query using driver implementation of connection @param {*} query @param {*} connection @param {object} [user] user may not be provided if chart links turned on @returns {Promise}
[ "Run", "query", "using", "driver", "implementation", "of", "connection" ]
84525a66a5480e9bffc559a1f34d59e1cea88d14
https://github.com/rickbergfalk/sqlpad/blob/84525a66a5480e9bffc559a1f34d59e1cea88d14/server/drivers/index.js#L109-L158
10,452
rickbergfalk/sqlpad
server/drivers/index.js
getDrivers
function getDrivers() { return Object.keys(drivers).map(id => { return { id, name: drivers[id].name, fields: drivers[id].fields }; }); }
javascript
function getDrivers() { return Object.keys(drivers).map(id => { return { id, name: drivers[id].name, fields: drivers[id].fields }; }); }
[ "function", "getDrivers", "(", ")", "{", "return", "Object", ".", "keys", "(", "drivers", ")", ".", "map", "(", "id", "=>", "{", "return", "{", "id", ",", "name", ":", "drivers", "[", "id", "]", ".", "name", ",", "fields", ":", "drivers", "[", "id", "]", ".", "fields", "}", ";", "}", ")", ";", "}" ]
Gets array of driver objects @returns {array} drivers
[ "Gets", "array", "of", "driver", "objects" ]
84525a66a5480e9bffc559a1f34d59e1cea88d14
https://github.com/rickbergfalk/sqlpad/blob/84525a66a5480e9bffc559a1f34d59e1cea88d14/server/drivers/index.js#L187-L195
10,453
rickbergfalk/sqlpad
server/drivers/index.js
validateConnection
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
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; }
[ "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", "(", "`", "${", "connection", ".", "driver", "}", "`", ")", ";", "}", "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", ";", "}" ]
Validates connection object based on its driver Unnecessary fields will be stripped out @param {object} connection
[ "Validates", "connection", "object", "based", "on", "its", "driver", "Unnecessary", "fields", "will", "be", "stripped", "out" ]
84525a66a5480e9bffc559a1f34d59e1cea88d14
https://github.com/rickbergfalk/sqlpad/blob/84525a66a5480e9bffc559a1f34d59e1cea88d14/server/drivers/index.js#L202-L238
10,454
rickbergfalk/sqlpad
server/drivers/utils.js
formatSchemaQueryResults
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
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; }
[ "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", "]", ";", "}", "}", "}", "}", "/*\n At this point, tree should look like this:\n {\n \"schema-name\": {\n \"table-name\": [\n {\n column_name: \"the column name\",\n data_type: \"string\"\n }\n ]\n }\n }\n */", "return", "tree", ";", "}" ]
Formats schema query results into a nested map of objects representing schema tree @param {object} queryResult
[ "Formats", "schema", "query", "results", "into", "a", "nested", "map", "of", "objects", "representing", "schema", "tree" ]
84525a66a5480e9bffc559a1f34d59e1cea88d14
https://github.com/rickbergfalk/sqlpad/blob/84525a66a5480e9bffc559a1f34d59e1cea88d14/server/drivers/utils.js#L8-L51
10,455
rickbergfalk/sqlpad
server/drivers/utils.js
ensureBoolean
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
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}`); }
[ "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", "(", "`", "${", "value", "}", "`", ")", ";", "}" ]
Clean value to boolean If value is not a boolean or can't be converted, an error is thrown This is probably unnecessary but more a precaution @param {any} value
[ "Clean", "value", "to", "boolean", "If", "value", "is", "not", "a", "boolean", "or", "can", "t", "be", "converted", "an", "error", "is", "thrown", "This", "is", "probably", "unnecessary", "but", "more", "a", "precaution" ]
84525a66a5480e9bffc559a1f34d59e1cea88d14
https://github.com/rickbergfalk/sqlpad/blob/84525a66a5480e9bffc559a1f34d59e1cea88d14/server/drivers/utils.js#L59-L73
10,456
rickbergfalk/sqlpad
server/lib/getMeta.js
isNumeric
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
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; }
[ "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", ";", "}" ]
Derive whether value is a number number or number as a string If value is a string, it'll determine whether the string is numeric Zero-padded number strings are not considered numeric @param {*} value
[ "Derive", "whether", "value", "is", "a", "number", "number", "or", "number", "as", "a", "string", "If", "value", "is", "a", "string", "it", "ll", "determine", "whether", "the", "string", "is", "numeric", "Zero", "-", "padded", "number", "strings", "are", "not", "considered", "numeric" ]
84525a66a5480e9bffc559a1f34d59e1cea88d14
https://github.com/rickbergfalk/sqlpad/blob/84525a66a5480e9bffc559a1f34d59e1cea88d14/server/lib/getMeta.js#L9-L27
10,457
rickbergfalk/sqlpad
server/lib/email.js
fullUrl
function fullUrl(path) { const urlPort = port === 80 ? '' : ':' + port; const urlPublicUrl = publicUrl; const urlBaseUrl = baseUrl; return `${urlPublicUrl}${urlPort}${urlBaseUrl}${path}`; }
javascript
function fullUrl(path) { const urlPort = port === 80 ? '' : ':' + port; const urlPublicUrl = publicUrl; const urlBaseUrl = baseUrl; return `${urlPublicUrl}${urlPort}${urlBaseUrl}${path}`; }
[ "function", "fullUrl", "(", "path", ")", "{", "const", "urlPort", "=", "port", "===", "80", "?", "''", ":", "':'", "+", "port", ";", "const", "urlPublicUrl", "=", "publicUrl", ";", "const", "urlBaseUrl", "=", "baseUrl", ";", "return", "`", "${", "urlPublicUrl", "}", "${", "urlPort", "}", "${", "urlBaseUrl", "}", "${", "path", "}", "`", ";", "}" ]
Get full sqlpad url @param {string} path - path (leading slash)
[ "Get", "full", "sqlpad", "url" ]
84525a66a5480e9bffc559a1f34d59e1cea88d14
https://github.com/rickbergfalk/sqlpad/blob/84525a66a5480e9bffc559a1f34d59e1cea88d14/server/lib/email.js#L10-L15
10,458
xiazeyu/live2d-widget.js
src/wpPublicPath.js
getCurrentPath
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
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; } } */ } }
[ "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", ";", "/*\n // Method 2\n // parse the error stack trace maually\n // https://github.com/workhorsy/uncompress.js/blob/master/js/uncompress.js#L25\n\n let stack = e.stack;\n let line = null;\n\n // Chrome and IE\n if (stack.indexOf('@') !== -1) {\n line = stack.split('@')[1].split('\\n')[0];\n // Firefox\n } else {\n line = stack.split('(')[1].split(')')[0];\n }\n line = line.substring(0, line.lastIndexOf('/')) + '/';\n return line;\n*/", "/*\n // Method 3\n // https://www.cnblogs.com/rubylouvre/archive/2013/01/23/2872618.html\n\n let stack = e.stack;\n if(!stack && window.opera){\n // Opera 9没有e.stack,但有e.Backtrace,但不能直接取得,需要对e对象转字符串进行抽取\n stack = (String(e).match(/of linked script \\S+/g) || []).join(' ');\n }\n if(stack){\n // e.stack最后一行在所有支持的浏览器大致如下:\n      // chrome23:\n      // @ http://113.93.50.63/data.js:4:1\n      // firefox17:\n      // @http://113.93.50.63/query.js:4\n      // opera12:\n      // @http://113.93.50.63/data.js:4\n      // IE10:\n      // @ Global code (http://113.93.50.63/data.js:4:1)\n     stack = stack.split(/[@ ]/g).pop(); // 取得最后一行,最后一个空格或@之后的部分\n stack = stack[0] == '(' ? stack.slice(1,-1) : stack;\n return stack.replace(/(:\\d+)?:\\d+$/i, ''); // 去掉行号与或许存在的出错字符起始位置\n }\n let nodes = head.getElementsByTagName('script'); // 只在head标签中寻找\n for(var i = 0, node; node = nodes[i++];){\n if(node.readyState === 'interactive'){\n return node.className = node.src;\n }\n }\n*/", "}", "}" ]
Get current script path @return {String} The path of current script @example get 'file:///C:/git/live2d-widget/dev/bundle.js' or 'https://www.host.com/test/js/bundle.js'
[ "Get", "current", "script", "path" ]
fa8f2d831a1a9e96cd85bd1ef593a3336aeac720
https://github.com/xiazeyu/live2d-widget.js/blob/fa8f2d831a1a9e96cd85bd1ef593a3336aeac720/src/wpPublicPath.js#L15-L94
10,459
xiazeyu/live2d-widget.js
src/cLive2DApp.js
theRealInit
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
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(); }
[ "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", "(", ")", ";", "}" ]
Main function of live2d-widget @return {null}
[ "Main", "function", "of", "live2d", "-", "widget" ]
fa8f2d831a1a9e96cd85bd1ef593a3336aeac720
https://github.com/xiazeyu/live2d-widget.js/blob/fa8f2d831a1a9e96cd85bd1ef593a3336aeac720/src/cLive2DApp.js#L49-L88
10,460
xiazeyu/live2d-widget.js
src/elementMgr.js
createElement
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
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(); }
[ "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", "(", ")", ";", "}" ]
Create the canvas and styles using DOM @return {null}
[ "Create", "the", "canvas", "and", "styles", "using", "DOM" ]
fa8f2d831a1a9e96cd85bd1ef593a3336aeac720
https://github.com/xiazeyu/live2d-widget.js/blob/fa8f2d831a1a9e96cd85bd1ef593a3336aeac720/src/elementMgr.js#L30-L71
10,461
xiazeyu/live2d-widget.js
src/elementMgr.js
initWebGL
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
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; } }
[ "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", ";", "}", "}" ]
Find and set the current WebGL element to the container @return {null}
[ "Find", "and", "set", "the", "current", "WebGL", "element", "to", "the", "container" ]
fa8f2d831a1a9e96cd85bd1ef593a3336aeac720
https://github.com/xiazeyu/live2d-widget.js/blob/fa8f2d831a1a9e96cd85bd1ef593a3336aeac720/src/elementMgr.js#L78-L99
10,462
NUKnightLab/TimelineJS3
source/js/animation/TL.Animate.js
tween
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
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 } } }
[ "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", "}", "}", "}" ]
Core tween method that requests each frame @param duration: time in milliseconds. defaults to 1000 @param fn: tween frame callback function receiving 'position' @param done {optional}: complete callback function @param ease {optional}: easing method. defaults to easeOut @param from {optional}: integer to start from @param to {optional}: integer to end at @returns method to stop the animation
[ "Core", "tween", "method", "that", "requests", "each", "frame" ]
e06ea96ea3384aece169044a0091d5f316db7254
https://github.com/NUKnightLab/TimelineJS3/blob/e06ea96ea3384aece169044a0091d5f316db7254/source/js/animation/TL.Animate.js#L210-L243
10,463
NUKnightLab/TimelineJS3
source/js/animation/TL.Animate.js
nextColor
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
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('') }
[ "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", "(", "''", ")", "}" ]
this gets you the next hex in line according to a 'position'
[ "this", "gets", "you", "the", "next", "hex", "in", "line", "according", "to", "a", "position" ]
e06ea96ea3384aece169044a0091d5f316db7254
https://github.com/NUKnightLab/TimelineJS3/blob/e06ea96ea3384aece169044a0091d5f316db7254/source/js/animation/TL.Animate.js#L270-L280
10,464
NUKnightLab/TimelineJS3
source/js/animation/TL.Animate.js
getTweenVal
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
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 } }
[ "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", "}", "}" ]
this retreives the frame value within a sequence
[ "this", "retreives", "the", "frame", "value", "within", "a", "sequence" ]
e06ea96ea3384aece169044a0091d5f316db7254
https://github.com/NUKnightLab/TimelineJS3/blob/e06ea96ea3384aece169044a0091d5f316db7254/source/js/animation/TL.Animate.js#L283-L299
10,465
NUKnightLab/TimelineJS3
source/js/animation/TL.Animate.js
by
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
function by(val, start, m, r, i) { return (m = relVal.exec(val)) ? (i = parseFloat(m[2])) && (start + (m[1] == '+' ? 1 : -1) * i) : parseFloat(val) }
[ "function", "by", "(", "val", ",", "start", ",", "m", ",", "r", ",", "i", ")", "{", "return", "(", "m", "=", "relVal", ".", "exec", "(", "val", ")", ")", "?", "(", "i", "=", "parseFloat", "(", "m", "[", "2", "]", ")", ")", "&&", "(", "start", "+", "(", "m", "[", "1", "]", "==", "'+'", "?", "1", ":", "-", "1", ")", "*", "i", ")", ":", "parseFloat", "(", "val", ")", "}" ]
support for relative movement via '+=n' or '-=n'
[ "support", "for", "relative", "movement", "via", "+", "=", "n", "or", "-", "=", "n" ]
e06ea96ea3384aece169044a0091d5f316db7254
https://github.com/NUKnightLab/TimelineJS3/blob/e06ea96ea3384aece169044a0091d5f316db7254/source/js/animation/TL.Animate.js#L302-L306
10,466
NUKnightLab/TimelineJS3
source/js/slider/TL.StorySlider.js
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
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); }
[ "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", ")", ";", "}" ]
Reposition and redraw slides
[ "Reposition", "and", "redraw", "slides" ]
e06ea96ea3384aece169044a0091d5f316db7254
https://github.com/NUKnightLab/TimelineJS3/blob/e06ea96ea3384aece169044a0091d5f316db7254/source/js/slider/TL.StorySlider.js#L390-L399
10,467
NUKnightLab/TimelineJS3
source/js/core/TL.TimelineConfig.js
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
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 }
[ "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", "}" ]
Given a slide, verify that its ID is unique, or assign it one which is. The assignment happens in this function, and the assigned ID is also the return value. Not thread-safe, because ids are not reserved when assigned here.
[ "Given", "a", "slide", "verify", "that", "its", "ID", "is", "unique", "or", "assign", "it", "one", "which", "is", ".", "The", "assignment", "happens", "in", "this", "function", "and", "the", "assigned", "ID", "is", "also", "the", "return", "value", ".", "Not", "thread", "-", "safe", "because", "ids", "are", "not", "reserved", "when", "assigned", "here", "." ]
e06ea96ea3384aece169044a0091d5f316db7254
https://github.com/NUKnightLab/TimelineJS3/blob/e06ea96ea3384aece169044a0091d5f316db7254/source/js/core/TL.TimelineConfig.js#L144-L153
10,468
NUKnightLab/TimelineJS3
source/js/core/TL.TimelineConfig.js
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
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; }
[ "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", ";", "}" ]
Return the earliest date that this config knows about, whether it's a slide or an era
[ "Return", "the", "earliest", "date", "that", "this", "config", "knows", "about", "whether", "it", "s", "a", "slide", "or", "an", "era" ]
e06ea96ea3384aece169044a0091d5f316db7254
https://github.com/NUKnightLab/TimelineJS3/blob/e06ea96ea3384aece169044a0091d5f316db7254/source/js/core/TL.TimelineConfig.js#L248-L258
10,469
NUKnightLab/TimelineJS3
source/js/core/TL.TimelineConfig.js
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
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; }
[ "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", ";", "}" ]
Return the latest date that this config knows about, whether it's a slide or an era, taking end_dates into account.
[ "Return", "the", "latest", "date", "that", "this", "config", "knows", "about", "whether", "it", "s", "a", "slide", "or", "an", "era", "taking", "end_dates", "into", "account", "." ]
e06ea96ea3384aece169044a0091d5f316db7254
https://github.com/NUKnightLab/TimelineJS3/blob/e06ea96ea3384aece169044a0091d5f316db7254/source/js/core/TL.TimelineConfig.js#L262-L280
10,470
NUKnightLab/TimelineJS3
source/js/core/TL.Util.js
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
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; }
[ "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", ";", "}" ]
like TL.Util.mergeData but takes an arbitrarily long list of sources to merge.
[ "like", "TL", ".", "Util", ".", "mergeData", "but", "takes", "an", "arbitrarily", "long", "list", "of", "sources", "to", "merge", "." ]
e06ea96ea3384aece169044a0091d5f316db7254
https://github.com/NUKnightLab/TimelineJS3/blob/e06ea96ea3384aece169044a0091d5f316db7254/source/js/core/TL.Util.js#L17-L24
10,471
NUKnightLab/TimelineJS3
source/js/core/TL.Load.js
load
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
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]); } }
[ "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", "]", ")", ";", "}", "}" ]
Loads the specified resources, or the next resource of the specified type in the queue if no resources are specified. If a resource of the specified type is already being loaded, the new request will be queued until the first request has been finished. When an array of resource URLs is specified, those URLs will be loaded in parallel if it is possible to do so while preserving execution order. All browsers support parallel loading of CSS, but only Firefox and Opera support parallel loading of scripts. In other browsers, scripts will be queued and loaded one at a time to ensure correct execution order. @method load @param {String} type resource type ('css' or 'js') @param {String|Array} urls (optional) URL or array of URLs to load @param {Function} callback (optional) callback function to execute when the resource is loaded @param {Object} obj (optional) object to pass to the callback function @param {Object} context (optional) if provided, the callback function will be executed in this object's context @private
[ "Loads", "the", "specified", "resources", "or", "the", "next", "resource", "of", "the", "specified", "type", "in", "the", "queue", "if", "no", "resources", "are", "specified", ".", "If", "a", "resource", "of", "the", "specified", "type", "is", "already", "being", "loaded", "the", "new", "request", "will", "be", "queued", "until", "the", "first", "request", "has", "been", "finished", "." ]
e06ea96ea3384aece169044a0091d5f316db7254
https://github.com/NUKnightLab/TimelineJS3/blob/e06ea96ea3384aece169044a0091d5f316db7254/source/js/core/TL.Load.js#L211-L312
10,472
NUKnightLab/TimelineJS3
source/js/date/TL.Date.js
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
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); }
[ "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", ")", ";", "}" ]
Return a new TL.Date which has been 'floored' at the given scale. @scale = string value from TL.Date.SCALES
[ "Return", "a", "new", "TL", ".", "Date", "which", "has", "been", "floored", "at", "the", "given", "scale", "." ]
e06ea96ea3384aece169044a0091d5f316db7254
https://github.com/NUKnightLab/TimelineJS3/blob/e06ea96ea3384aece169044a0091d5f316db7254/source/js/date/TL.Date.js#L82-L91
10,473
NUKnightLab/TimelineJS3
source/js/date/TL.Date.js
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
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); }
[ "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", ")", ";", "}" ]
Return a new TL.BigDate which has been 'floored' at the given scale. @scale = string value from TL.BigDate.SCALES
[ "Return", "a", "new", "TL", ".", "BigDate", "which", "has", "been", "floored", "at", "the", "given", "scale", "." ]
e06ea96ea3384aece169044a0091d5f316db7254
https://github.com/NUKnightLab/TimelineJS3/blob/e06ea96ea3384aece169044a0091d5f316db7254/source/js/date/TL.Date.js#L383-L392
10,474
NUKnightLab/TimelineJS3
source/js/TL.Timeline.js
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
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); } }
[ "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", ")", ";", "}", "}" ]
Goto slide n
[ "Goto", "slide", "n" ]
e06ea96ea3384aece169044a0091d5f316db7254
https://github.com/NUKnightLab/TimelineJS3/blob/e06ea96ea3384aece169044a0091d5f316db7254/source/js/TL.Timeline.js#L307-L317
10,475
NUKnightLab/TimelineJS3
source/js/TL.Timeline.js
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
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}); } }
[ "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", "}", ")", ";", "}", "}" ]
Remove an event
[ "Remove", "an", "event" ]
e06ea96ea3384aece169044a0091d5f316db7254
https://github.com/NUKnightLab/TimelineJS3/blob/e06ea96ea3384aece169044a0091d5f316db7254/source/js/TL.Timeline.js#L360-L381
10,476
NUKnightLab/TimelineJS3
source/js/TL.Timeline.js
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
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); }
[ "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", ")", ";", "}" ]
Update hashbookmark in the url bar
[ "Update", "hashbookmark", "in", "the", "url", "bar" ]
e06ea96ea3384aece169044a0091d5f316db7254
https://github.com/NUKnightLab/TimelineJS3/blob/e06ea96ea3384aece169044a0091d5f316db7254/source/js/TL.Timeline.js#L614-L620
10,477
NUKnightLab/TimelineJS3
source/js/TL.Timeline.js
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
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); }
[ "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", ")", ";", "}" ]
Initialize the layout
[ "Initialize", "the", "layout" ]
e06ea96ea3384aece169044a0091d5f316db7254
https://github.com/NUKnightLab/TimelineJS3/blob/e06ea96ea3384aece169044a0091d5f316db7254/source/js/TL.Timeline.js#L682-L740
10,478
jhen0409/react-chrome-extension-boilerplate
app/utils/storage.js
setBadge
function setBadge(todos) { if (chrome.browserAction) { const count = todos.filter(todo => !todo.marked).length; chrome.browserAction.setBadgeText({ text: count > 0 ? count.toString() : '' }); } }
javascript
function setBadge(todos) { if (chrome.browserAction) { const count = todos.filter(todo => !todo.marked).length; chrome.browserAction.setBadgeText({ text: count > 0 ? count.toString() : '' }); } }
[ "function", "setBadge", "(", "todos", ")", "{", "if", "(", "chrome", ".", "browserAction", ")", "{", "const", "count", "=", "todos", ".", "filter", "(", "todo", "=>", "!", "todo", ".", "marked", ")", ".", "length", ";", "chrome", ".", "browserAction", ".", "setBadgeText", "(", "{", "text", ":", "count", ">", "0", "?", "count", ".", "toString", "(", ")", ":", "''", "}", ")", ";", "}", "}" ]
todos unmarked count
[ "todos", "unmarked", "count" ]
81284bbc7a949b37c1612966889b97232bc99d90
https://github.com/jhen0409/react-chrome-extension-boilerplate/blob/81284bbc7a949b37c1612966889b97232bc99d90/app/utils/storage.js#L6-L11
10,479
FortAwesome/react-fontawesome
index.js
function(string, options) { options = options || {}; var separator = options.separator || '_'; var split = options.split || /(?=[A-Z])/; return string.split(split).join(separator); }
javascript
function(string, options) { options = options || {}; var separator = options.separator || '_'; var split = options.split || /(?=[A-Z])/; return string.split(split).join(separator); }
[ "function", "(", "string", ",", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "var", "separator", "=", "options", ".", "separator", "||", "'_'", ";", "var", "split", "=", "options", ".", "split", "||", "/", "(?=[A-Z])", "/", ";", "return", "string", ".", "split", "(", "split", ")", ".", "join", "(", "separator", ")", ";", "}" ]
String conversion methods
[ "String", "conversion", "methods" ]
d79839bbf39a775702c9488deb0cb53cb13ce740
https://github.com/FortAwesome/react-fontawesome/blob/d79839bbf39a775702c9488deb0cb53cb13ce740/index.js#L151-L157
10,480
FortAwesome/react-fontawesome
index.js
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
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); } }
[ "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", ")", ";", "}", "}" ]
Sets up function which handles processing keys allowing the convert function to be modified by a callback
[ "Sets", "up", "function", "which", "handles", "processing", "keys", "allowing", "the", "convert", "function", "to", "be", "modified", "by", "a", "callback" ]
d79839bbf39a775702c9488deb0cb53cb13ce740
https://github.com/FortAwesome/react-fontawesome/blob/d79839bbf39a775702c9488deb0cb53cb13ce740/index.js#L212-L222
10,481
angular/in-memory-web-api
bundles/in-memory-web-api.umd.js
httpClientInMemBackendServiceFactory
function httpClientInMemBackendServiceFactory(dbService, options, xhrFactory) { var backend = new HttpClientBackendService(dbService, options, xhrFactory); return backend; }
javascript
function httpClientInMemBackendServiceFactory(dbService, options, xhrFactory) { var backend = new HttpClientBackendService(dbService, options, xhrFactory); return backend; }
[ "function", "httpClientInMemBackendServiceFactory", "(", "dbService", ",", "options", ",", "xhrFactory", ")", "{", "var", "backend", "=", "new", "HttpClientBackendService", "(", "dbService", ",", "options", ",", "xhrFactory", ")", ";", "return", "backend", ";", "}" ]
Internal - Creates the in-mem backend for the HttpClient module AoT requires factory to be exported
[ "Internal", "-", "Creates", "the", "in", "-", "mem", "backend", "for", "the", "HttpClient", "module", "AoT", "requires", "factory", "to", "be", "exported" ]
b71d39fd48cf189c831603e3ae8fd954216ce2ef
https://github.com/angular/in-memory-web-api/blob/b71d39fd48cf189c831603e3ae8fd954216ce2ef/bundles/in-memory-web-api.umd.js#L1294-L1297
10,482
wilddeer/stickyfill
dist/stickyfill.js
_loop2
function _loop2(i) { var node = nodeList[i]; stickies.some(function (sticky) { if (sticky._node === node) { sticky.remove(); return true; } }); }
javascript
function _loop2(i) { var node = nodeList[i]; stickies.some(function (sticky) { if (sticky._node === node) { sticky.remove(); return true; } }); }
[ "function", "_loop2", "(", "i", ")", "{", "var", "node", "=", "nodeList", "[", "i", "]", ";", "stickies", ".", "some", "(", "function", "(", "sticky", ")", "{", "if", "(", "sticky", ".", "_node", "===", "node", ")", "{", "sticky", ".", "remove", "(", ")", ";", "return", "true", ";", "}", "}", ")", ";", "}" ]
Remove the stickies bound to the nodes in the list
[ "Remove", "the", "stickies", "bound", "to", "the", "nodes", "in", "the", "list" ]
bae6e31466defc8ff3594509055ed36b068ee257
https://github.com/wilddeer/stickyfill/blob/bae6e31466defc8ff3594509055ed36b068ee257/dist/stickyfill.js#L439-L448
10,483
bitjson/typescript-starter
.vscode/debug-ts.js
TS2JS
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
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 }); }
[ "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", "}", ")", ";", "}" ]
get associated compiled js file path @param tsFile path @return string path
[ "get", "associated", "compiled", "js", "file", "path" ]
8eaf9636c6cfbd9b1b5c0b4393c32f35f06e8d7d
https://github.com/bitjson/typescript-starter/blob/8eaf9636c6cfbd9b1b5c0b4393c32f35f06e8d7d/.vscode/debug-ts.js#L29-L41
10,484
bitjson/typescript-starter
.vscode/debug-ts.js
replaceCLIArg
function replaceCLIArg(search, replace) { process.argv[process.argv.indexOf(search)] = replace; }
javascript
function replaceCLIArg(search, replace) { process.argv[process.argv.indexOf(search)] = replace; }
[ "function", "replaceCLIArg", "(", "search", ",", "replace", ")", "{", "process", ".", "argv", "[", "process", ".", "argv", ".", "indexOf", "(", "search", ")", "]", "=", "replace", ";", "}" ]
replace a value in CLI args @param search value to search @param replace value to replace @return void
[ "replace", "a", "value", "in", "CLI", "args" ]
8eaf9636c6cfbd9b1b5c0b4393c32f35f06e8d7d
https://github.com/bitjson/typescript-starter/blob/8eaf9636c6cfbd9b1b5c0b4393c32f35f06e8d7d/.vscode/debug-ts.js#L50-L52
10,485
krasimir/navigo
demo/html-template-demo/scripts.js
loadHTML
function loadHTML(url, id) { req = new XMLHttpRequest(); req.open('GET', url); req.send(); req.onload = () => { $id(id).innerHTML = req.responseText; }; }
javascript
function loadHTML(url, id) { req = new XMLHttpRequest(); req.open('GET', url); req.send(); req.onload = () => { $id(id).innerHTML = req.responseText; }; }
[ "function", "loadHTML", "(", "url", ",", "id", ")", "{", "req", "=", "new", "XMLHttpRequest", "(", ")", ";", "req", ".", "open", "(", "'GET'", ",", "url", ")", ";", "req", ".", "send", "(", ")", ";", "req", ".", "onload", "=", "(", ")", "=>", "{", "$id", "(", "id", ")", ".", "innerHTML", "=", "req", ".", "responseText", ";", "}", ";", "}" ]
asyncrhonously fetch the html template partial from the file directory, then set its contents to the html of the parent element
[ "asyncrhonously", "fetch", "the", "html", "template", "partial", "from", "the", "file", "directory", "then", "set", "its", "contents", "to", "the", "html", "of", "the", "parent", "element" ]
15823891c91d0d8edb3dbcba4e9c57ae78206a8d
https://github.com/krasimir/navigo/blob/15823891c91d0d8edb3dbcba4e9c57ae78206a8d/demo/html-template-demo/scripts.js#L8-L15
10,486
NASAWorldWind/WebWorldWind
src/shapes/AnnotationAttributes.js
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
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; }
[ "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", "(", ")", ";", "/**\n * Indicates whether this object's state key is invalid. Subclasses must set this value to true when their\n * attributes change. The state key will be automatically computed the next time it's requested. This flag\n * will be set to false when that occurs.\n * @type {Boolean}\n * @protected\n */", "this", ".", "stateKeyInvalid", "=", "true", ";", "}" ]
Constructs an annotation attributes bundle. @alias AnnotationAttributes @constructor @classdesc Holds attributes applied to {@link Annotation} shapes. @param {AnnotationAttributes} attributes Attributes to initialize this attributes instance to. May be null, in which case the new instance contains default attributes.
[ "Constructs", "an", "annotation", "attributes", "bundle", "." ]
399daee66deded581a2d1067a2ac04232c954b8f
https://github.com/NASAWorldWind/WebWorldWind/blob/399daee66deded581a2d1067a2ac04232c954b8f/src/shapes/AnnotationAttributes.js#L37-L60
10,487
NASAWorldWind/WebWorldWind
src/cache/MemoryCache.js
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
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 = []; }
[ "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", ";", "/**\n * The size currently used by this cache.\n * @type {Number}\n * @readonly\n */", "this", ".", "usedCapacity", "=", "0", ";", "/**\n * The size currently unused by this cache.\n * @type {Number}\n * @readonly\n */", "this", ".", "freeCapacity", "=", "capacity", ";", "// Private. The cache entries.", "this", ".", "entries", "=", "{", "}", ";", "// Private. The cache listeners.", "this", ".", "listeners", "=", "[", "]", ";", "}" ]
Constructs a memory cache of a specified size. @alias MemoryCache @constructor @classdesc Provides a limited-size memory cache of key-value pairs. The meaning of size depends on usage. Some instances of this class work in bytes while others work in counts. See the documentation for the specific use to determine the size units. @param {Number} capacity The cache's capacity. @param {Number} lowWater The size to clear the cache to when its capacity is exceeded. @throws {ArgumentError} If either the capacity is 0 or negative or the low-water value is greater than or equal to the capacity or less than 1.
[ "Constructs", "a", "memory", "cache", "of", "a", "specified", "size", "." ]
399daee66deded581a2d1067a2ac04232c954b8f
https://github.com/NASAWorldWind/WebWorldWind/blob/399daee66deded581a2d1067a2ac04232c954b8f/src/cache/MemoryCache.js#L40-L76
10,488
NASAWorldWind/WebWorldWind
src/geom/Matrix.js
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
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; }
[ "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", ";", "}" ]
Constructs a matrix. @alias Matrix @constructor @classdesc Represents a 4 x 4 double precision matrix stored in a Float64Array in row-major order. @param {Number} m11 matrix element at row 1, column 1. @param {Number} m12 matrix element at row 1, column 2. @param {Number} m13 matrix element at row 1, column 3. @param {Number} m14 matrix element at row 1, column 4. @param {Number} m21 matrix element at row 2, column 1. @param {Number} m22 matrix element at row 2, column 2. @param {Number} m23 matrix element at row 2, column 3. @param {Number} m24 matrix element at row 2, column 4. @param {Number} m31 matrix element at row 3, column 1. @param {Number} m32 matrix element at row 3, column 2. @param {Number} m33 matrix element at row 3, column 3. @param {Number} m34 matrix element at row 3, column 4. @param {Number} m41 matrix element at row 4, column 1. @param {Number} m42 matrix element at row 4, column 2. @param {Number} m43 matrix element at row 4, column 3. @param {Number} m44 matrix element at row 4, column 4.
[ "Constructs", "a", "matrix", "." ]
399daee66deded581a2d1067a2ac04232c954b8f
https://github.com/NASAWorldWind/WebWorldWind/blob/399daee66deded581a2d1067a2ac04232c954b8f/src/geom/Matrix.js#L64-L84
10,489
NASAWorldWind/WebWorldWind
src/BasicWorldWindowController.js
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
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; }
[ "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", ";", "}" ]
Constructs a window controller with basic capabilities. @alias BasicWorldWindowController @constructor @augments WorldWindowController @classDesc This class provides the default window controller for WorldWind for controlling the globe via user interaction. @param {WorldWindow} worldWindow The WorldWindow associated with this layer.
[ "Constructs", "a", "window", "controller", "with", "basic", "capabilities", "." ]
399daee66deded581a2d1067a2ac04232c954b8f
https://github.com/NASAWorldWind/WebWorldWind/blob/399daee66deded581a2d1067a2ac04232c954b8f/src/BasicWorldWindowController.js#L66-L122
10,490
NASAWorldWind/WebWorldWind
src/projections/ProjectionUPS.js
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
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 + " "; }
[ "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", "+", "\" \"", ";", "}" ]
Constructs a Uniform Polar Stereographic geographic projection. @alias ProjectionUPS @constructor @augments GeographicProjection @classdesc Represents a Uniform Polar Stereographic geographic projection. @param {String} pole Indicates the north or south aspect. Specify "North" for the north aspect or "South" for the south aspect.
[ "Constructs", "a", "Uniform", "Polar", "Stereographic", "geographic", "projection", "." ]
399daee66deded581a2d1067a2ac04232c954b8f
https://github.com/NASAWorldWind/WebWorldWind/blob/399daee66deded581a2d1067a2ac04232c954b8f/src/projections/ProjectionUPS.js#L47-L64
10,491
NASAWorldWind/WebWorldWind
src/gesture/RotationRecognizer.js
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
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 = []; }
[ "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", "=", "[", "]", ";", "}" ]
Constructs a rotation gesture recognizer. @alias RotationRecognizer @constructor @augments GestureRecognizer @classdesc A concrete gesture recognizer subclass that looks for two finger rotation gestures. @param {EventTarget} target The document element this gesture recognizer observes for mouse and touch events. @param {Function} callback An optional function to call when this gesture is recognized. If non-null, the function is called when this gesture is recognized, and is passed a single argument: this gesture recognizer, e.g., <code>gestureCallback(recognizer)</code>. @throws {ArgumentError} If the specified target is null or undefined.
[ "Constructs", "a", "rotation", "gesture", "recognizer", "." ]
399daee66deded581a2d1067a2ac04232c954b8f
https://github.com/NASAWorldWind/WebWorldWind/blob/399daee66deded581a2d1067a2ac04232c954b8f/src/gesture/RotationRecognizer.js#L40-L60
10,492
NASAWorldWind/WebWorldWind
src/util/measure/MeasurerUtils.js
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
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; }
[ "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", ";", "}" ]
Adds a position to a list of positions. If the path is following the terrain the elevation is also computed. @param {Globe} globe @param {Position[]} positions The list of positions to add to @param {Position} position The position to add to the list @param {Boolean} followTerrain @return {Position[]} The list of positions
[ "Adds", "a", "position", "to", "a", "list", "of", "positions", ".", "If", "the", "path", "is", "following", "the", "terrain", "the", "elevation", "is", "also", "computed", "." ]
399daee66deded581a2d1067a2ac04232c954b8f
https://github.com/NASAWorldWind/WebWorldWind/blob/399daee66deded581a2d1067a2ac04232c954b8f/src/util/measure/MeasurerUtils.js#L124-L131
10,493
NASAWorldWind/WebWorldWind
src/util/measure/MeasurerUtils.js
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
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; }
[ "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", ";", "}" ]
Determines whether a location is located inside a given polygon. @param {Location} location @param {Location[]}locations The list of positions describing the polygon. Last one should be the same as the first one. @return {Boolean} true if the location is inside the polygon.
[ "Determines", "whether", "a", "location", "is", "located", "inside", "a", "given", "polygon", "." ]
399daee66deded581a2d1067a2ac04232c954b8f
https://github.com/NASAWorldWind/WebWorldWind/blob/399daee66deded581a2d1067a2ac04232c954b8f/src/util/measure/MeasurerUtils.js#L142-L156
10,494
NASAWorldWind/WebWorldWind
src/util/measure/MeasurerUtils.js
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
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); }
[ "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", ")", ";", "}" ]
Computes the angle between two Vec3 in radians. @param {Vec3} v1 @param {Vec3} v2 @return {Number} The ange in radians
[ "Computes", "the", "angle", "between", "two", "Vec3", "in", "radians", "." ]
399daee66deded581a2d1067a2ac04232c954b8f
https://github.com/NASAWorldWind/WebWorldWind/blob/399daee66deded581a2d1067a2ac04232c954b8f/src/util/measure/MeasurerUtils.js#L166-L187
10,495
NASAWorldWind/WebWorldWind
src/geom/TileMatrixSet.js
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
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; }
[ "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.\"", ")", ")", ";", "}", "/**\n * The geographic coverage of this TileMatrixSet.\n */", "this", ".", "sector", "=", "sector", ";", "/**\n * An array of TileMatrix objects defining this TileMatrixSet.\n */", "this", ".", "entries", "=", "tileMatrixList", ";", "}" ]
TileMatrixSet defines a generic tiled space as defined by a geographic bounding area and an array of TileMatrix objects which define the tiled space at different resolutions. @param sector the geographic bounding area of this TileMatrixSet @param tileMatrixList the array of TileMatrix objects forming this TileMatrixSet @constructor
[ "TileMatrixSet", "defines", "a", "generic", "tiled", "space", "as", "defined", "by", "a", "geographic", "bounding", "area", "and", "an", "array", "of", "TileMatrix", "objects", "which", "define", "the", "tiled", "space", "at", "different", "resolutions", "." ]
399daee66deded581a2d1067a2ac04232c954b8f
https://github.com/NASAWorldWind/WebWorldWind/blob/399daee66deded581a2d1067a2ac04232c954b8f/src/geom/TileMatrixSet.js#L39-L60
10,496
NASAWorldWind/WebWorldWind
src/layer/BingWMSLayer.js
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
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"); }
[ "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\"", ")", ";", "}" ]
Intentionally not documented. For diagnostic use only.
[ "Intentionally", "not", "documented", ".", "For", "diagnostic", "use", "only", "." ]
399daee66deded581a2d1067a2ac04232c954b8f
https://github.com/NASAWorldWind/WebWorldWind/blob/399daee66deded581a2d1067a2ac04232c954b8f/src/layer/BingWMSLayer.js#L33-L42
10,497
NASAWorldWind/WebWorldWind
src/globe/EarthRestElevationCoverage.js
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
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); }
[ "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", ")", ";", "}" ]
Constructs an elevation coverage for Earth using a REST interface to retrieve the elevations from the server. @alias EarthRestElevationCoverage @constructor @classdesc Represents an Earth elevation coverage spanning the globe and using a REST interface to retrieve the elevations from the server. See [LevelRowColumnUrlBuilder]{@link LevelRowColumnUrlBuilder} for a description of the REST interface. @param {String} serverAddress The server address of the tile service. May be null, in which case the current origin is used (see <code>window.location</code>. @param {String} pathToData The path to the data directory relative to the specified server address. May be null, in which case the server address is assumed to be the full path to the data directory. @param {String} displayName The display name to associate with this elevation coverage.
[ "Constructs", "an", "elevation", "coverage", "for", "Earth", "using", "a", "REST", "interface", "to", "retrieve", "the", "elevations", "from", "the", "server", "." ]
399daee66deded581a2d1067a2ac04232c954b8f
https://github.com/NASAWorldWind/WebWorldWind/blob/399daee66deded581a2d1067a2ac04232c954b8f/src/globe/EarthRestElevationCoverage.js#L47-L62
10,498
NASAWorldWind/WebWorldWind
src/util/Tile.js
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
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; }
[ "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.\"", ")", ")", ";", "}", "/**\n * The sector represented by this tile.\n * @type {Sector}\n * @readonly\n */", "this", ".", "sector", "=", "sector", ";", "/**\n * The level at which this tile lies in a tile pyramid.\n * @type {Number}\n * @readonly\n */", "this", ".", "level", "=", "level", ";", "/**\n * The row in this tile's level in which this tile lies in a tile pyramid.\n * @type {Number}\n * @readonly\n */", "this", ".", "row", "=", "row", ";", "/**\n * The column in this tile's level in which this tile lies in a tile pyramid.\n * @type {Number}\n * @readonly\n */", "this", ".", "column", "=", "column", ";", "/**\n * The width in pixels or cells of this tile's associated resource.\n * @type {Number}\n */", "this", ".", "tileWidth", "=", "level", ".", "tileWidth", ";", "/**\n * The height in pixels or cells of this tile's associated resource.\n * @type {Number}\n */", "this", ".", "tileHeight", "=", "level", ".", "tileHeight", ";", "/**\n * The size in radians of pixels or cells of this tile's associated resource.\n * @type {Number}\n */", "this", ".", "texelSize", "=", "level", ".", "texelSize", ";", "/**\n * A key that uniquely identifies this tile within a level set.\n * @type {String}\n * @readonly\n */", "this", ".", "tileKey", "=", "Tile", ".", "computeTileKey", "(", "level", ".", "levelNumber", ",", "row", ",", "column", ")", ";", "/**\n * The Cartesian bounding box of this tile.\n * @type {BoundingBox}\n */", "this", ".", "extent", "=", "null", ";", "/**\n * The tile's local origin in model coordinates. Any model coordinate points associates with the tile\n * should be relative to this point.\n * @type {Vec3}\n */", "this", ".", "referencePoint", "=", "null", ";", "/**\n * This tile's opacity.\n * @type {Number}\n * @default 1\n */", "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", ";", "}" ]
Constructs a tile for a specified sector, level, row and column. @alias Tile @constructor @classdesc Represents a tile of terrain or imagery. Provides a base class for texture tiles used by tiled image layers and elevation tiles used by elevation models. Applications typically do not interact with this class. @param {Sector} sector The sector represented by this tile. @param {Level} level This tile's level in a tile pyramid. @param {Number} row This tile's row in the specified level in a tile pyramid. @param {Number} column This tile's column in the specified level in a tile pyramid. @throws {ArgumentError} If the specified sector or level is null or undefined or the row or column arguments are less than zero.
[ "Constructs", "a", "tile", "for", "a", "specified", "sector", "level", "row", "and", "column", "." ]
399daee66deded581a2d1067a2ac04232c954b8f
https://github.com/NASAWorldWind/WebWorldWind/blob/399daee66deded581a2d1067a2ac04232c954b8f/src/util/Tile.js#L50-L155
10,499
NASAWorldWind/WebWorldWind
src/formats/geotiff/GeoTiffUtil.js
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
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")); } }
[ "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\"", ")", ")", ";", "}", "}" ]
Get bytes from an arraybuffer depending on the size. Internal use only.
[ "Get", "bytes", "from", "an", "arraybuffer", "depending", "on", "the", "size", ".", "Internal", "use", "only", "." ]
399daee66deded581a2d1067a2ac04232c954b8f
https://github.com/NASAWorldWind/WebWorldWind/blob/399daee66deded581a2d1067a2ac04232c954b8f/src/formats/geotiff/GeoTiffUtil.js#L33-L71