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
18,500
NodeRedis/node-redis-parser
lib/parser.js
pushArrayCache
function pushArrayCache (parser, array, pos) { parser.arrayCache.push(array) parser.arrayPos.push(pos) }
javascript
function pushArrayCache (parser, array, pos) { parser.arrayCache.push(array) parser.arrayPos.push(pos) }
[ "function", "pushArrayCache", "(", "parser", ",", "array", ",", "pos", ")", "{", "parser", ".", "arrayCache", ".", "push", "(", "array", ")", "parser", ".", "arrayPos", ".", "push", "(", "pos", ")", "}" ]
Push a partly parsed array to the stack @param {JavascriptRedisParser} parser @param {any[]} array @param {number} pos @returns {undefined}
[ "Push", "a", "partly", "parsed", "array", "to", "the", "stack" ]
44ef4189b5da92ac301729cd5fc41079017544fd
https://github.com/NodeRedis/node-redis-parser/blob/44ef4189b5da92ac301729cd5fc41079017544fd/lib/parser.js#L224-L227
18,501
NodeRedis/node-redis-parser
lib/parser.js
parseArrayChunks
function parseArrayChunks (parser) { var arr = parser.arrayCache.pop() var pos = parser.arrayPos.pop() if (parser.arrayCache.length) { const res = parseArrayChunks(parser) if (res === undefined) { pushArrayCache(parser, arr, pos) return } arr[pos++] = res } return parseArrayElements(parser, arr, pos) }
javascript
function parseArrayChunks (parser) { var arr = parser.arrayCache.pop() var pos = parser.arrayPos.pop() if (parser.arrayCache.length) { const res = parseArrayChunks(parser) if (res === undefined) { pushArrayCache(parser, arr, pos) return } arr[pos++] = res } return parseArrayElements(parser, arr, pos) }
[ "function", "parseArrayChunks", "(", "parser", ")", "{", "var", "arr", "=", "parser", ".", "arrayCache", ".", "pop", "(", ")", "var", "pos", "=", "parser", ".", "arrayPos", ".", "pop", "(", ")", "if", "(", "parser", ".", "arrayCache", ".", "length", ")", "{", "const", "res", "=", "parseArrayChunks", "(", "parser", ")", "if", "(", "res", "===", "undefined", ")", "{", "pushArrayCache", "(", "parser", ",", "arr", ",", "pos", ")", "return", "}", "arr", "[", "pos", "++", "]", "=", "res", "}", "return", "parseArrayElements", "(", "parser", ",", "arr", ",", "pos", ")", "}" ]
Parse chunked redis array response @param {JavascriptRedisParser} parser @returns {undefined|any[]}
[ "Parse", "chunked", "redis", "array", "response" ]
44ef4189b5da92ac301729cd5fc41079017544fd
https://github.com/NodeRedis/node-redis-parser/blob/44ef4189b5da92ac301729cd5fc41079017544fd/lib/parser.js#L234-L246
18,502
NodeRedis/node-redis-parser
lib/parser.js
parseArrayElements
function parseArrayElements (parser, responses, i) { const bufferLength = parser.buffer.length while (i < responses.length) { const offset = parser.offset if (parser.offset >= bufferLength) { pushArrayCache(parser, responses, i) return } const response = parseType(parser, parser.buffer[parser.offset++]) if (response === undefined) { if (!(parser.arrayCache.length || parser.bufferCache.length)) { parser.offset = offset } pushArrayCache(parser, responses, i) return } responses[i] = response i++ } return responses }
javascript
function parseArrayElements (parser, responses, i) { const bufferLength = parser.buffer.length while (i < responses.length) { const offset = parser.offset if (parser.offset >= bufferLength) { pushArrayCache(parser, responses, i) return } const response = parseType(parser, parser.buffer[parser.offset++]) if (response === undefined) { if (!(parser.arrayCache.length || parser.bufferCache.length)) { parser.offset = offset } pushArrayCache(parser, responses, i) return } responses[i] = response i++ } return responses }
[ "function", "parseArrayElements", "(", "parser", ",", "responses", ",", "i", ")", "{", "const", "bufferLength", "=", "parser", ".", "buffer", ".", "length", "while", "(", "i", "<", "responses", ".", "length", ")", "{", "const", "offset", "=", "parser", ".", "offset", "if", "(", "parser", ".", "offset", ">=", "bufferLength", ")", "{", "pushArrayCache", "(", "parser", ",", "responses", ",", "i", ")", "return", "}", "const", "response", "=", "parseType", "(", "parser", ",", "parser", ".", "buffer", "[", "parser", ".", "offset", "++", "]", ")", "if", "(", "response", "===", "undefined", ")", "{", "if", "(", "!", "(", "parser", ".", "arrayCache", ".", "length", "||", "parser", ".", "bufferCache", ".", "length", ")", ")", "{", "parser", ".", "offset", "=", "offset", "}", "pushArrayCache", "(", "parser", ",", "responses", ",", "i", ")", "return", "}", "responses", "[", "i", "]", "=", "response", "i", "++", "}", "return", "responses", "}" ]
Parse redis array response elements @param {JavascriptRedisParser} parser @param {Array} responses @param {number} i @returns {undefined|null|any[]}
[ "Parse", "redis", "array", "response", "elements" ]
44ef4189b5da92ac301729cd5fc41079017544fd
https://github.com/NodeRedis/node-redis-parser/blob/44ef4189b5da92ac301729cd5fc41079017544fd/lib/parser.js#L255-L276
18,503
NodeRedis/node-redis-parser
lib/parser.js
decreaseBufferPool
function decreaseBufferPool () { if (bufferPool.length > 50 * 1024) { if (counter === 1 || notDecreased > counter * 2) { const minSliceLen = Math.floor(bufferPool.length / 10) const sliceLength = minSliceLen < bufferOffset ? bufferOffset : minSliceLen bufferOffset = 0 bufferPool = bufferPool.slice(sliceLength, bufferPool.length) } else { notDecreased++ counter-- } } else { clearInterval(interval) counter = 0 notDecreased = 0 interval = null } }
javascript
function decreaseBufferPool () { if (bufferPool.length > 50 * 1024) { if (counter === 1 || notDecreased > counter * 2) { const minSliceLen = Math.floor(bufferPool.length / 10) const sliceLength = minSliceLen < bufferOffset ? bufferOffset : minSliceLen bufferOffset = 0 bufferPool = bufferPool.slice(sliceLength, bufferPool.length) } else { notDecreased++ counter-- } } else { clearInterval(interval) counter = 0 notDecreased = 0 interval = null } }
[ "function", "decreaseBufferPool", "(", ")", "{", "if", "(", "bufferPool", ".", "length", ">", "50", "*", "1024", ")", "{", "if", "(", "counter", "===", "1", "||", "notDecreased", ">", "counter", "*", "2", ")", "{", "const", "minSliceLen", "=", "Math", ".", "floor", "(", "bufferPool", ".", "length", "/", "10", ")", "const", "sliceLength", "=", "minSliceLen", "<", "bufferOffset", "?", "bufferOffset", ":", "minSliceLen", "bufferOffset", "=", "0", "bufferPool", "=", "bufferPool", ".", "slice", "(", "sliceLength", ",", "bufferPool", ".", "length", ")", "}", "else", "{", "notDecreased", "++", "counter", "--", "}", "}", "else", "{", "clearInterval", "(", "interval", ")", "counter", "=", "0", "notDecreased", "=", "0", "interval", "=", "null", "}", "}" ]
Decrease the bufferPool size over time Balance between increasing and decreasing the bufferPool. Decrease the bufferPool by 10% by removing the first 10% of the current pool. @returns {undefined}
[ "Decrease", "the", "bufferPool", "size", "over", "time" ]
44ef4189b5da92ac301729cd5fc41079017544fd
https://github.com/NodeRedis/node-redis-parser/blob/44ef4189b5da92ac301729cd5fc41079017544fd/lib/parser.js#L315-L334
18,504
NodeRedis/node-redis-parser
lib/parser.js
resizeBuffer
function resizeBuffer (length) { if (bufferPool.length < length + bufferOffset) { const multiplier = length > 1024 * 1024 * 75 ? 2 : 3 if (bufferOffset > 1024 * 1024 * 111) { bufferOffset = 1024 * 1024 * 50 } bufferPool = Buffer.allocUnsafe(length * multiplier + bufferOffset) bufferOffset = 0 counter++ if (interval === null) { interval = setInterval(decreaseBufferPool, 50) } } }
javascript
function resizeBuffer (length) { if (bufferPool.length < length + bufferOffset) { const multiplier = length > 1024 * 1024 * 75 ? 2 : 3 if (bufferOffset > 1024 * 1024 * 111) { bufferOffset = 1024 * 1024 * 50 } bufferPool = Buffer.allocUnsafe(length * multiplier + bufferOffset) bufferOffset = 0 counter++ if (interval === null) { interval = setInterval(decreaseBufferPool, 50) } } }
[ "function", "resizeBuffer", "(", "length", ")", "{", "if", "(", "bufferPool", ".", "length", "<", "length", "+", "bufferOffset", ")", "{", "const", "multiplier", "=", "length", ">", "1024", "*", "1024", "*", "75", "?", "2", ":", "3", "if", "(", "bufferOffset", ">", "1024", "*", "1024", "*", "111", ")", "{", "bufferOffset", "=", "1024", "*", "1024", "*", "50", "}", "bufferPool", "=", "Buffer", ".", "allocUnsafe", "(", "length", "*", "multiplier", "+", "bufferOffset", ")", "bufferOffset", "=", "0", "counter", "++", "if", "(", "interval", "===", "null", ")", "{", "interval", "=", "setInterval", "(", "decreaseBufferPool", ",", "50", ")", "}", "}", "}" ]
Check if the requested size fits in the current bufferPool. If it does not, reset and increase the bufferPool accordingly. @param {number} length @returns {undefined}
[ "Check", "if", "the", "requested", "size", "fits", "in", "the", "current", "bufferPool", ".", "If", "it", "does", "not", "reset", "and", "increase", "the", "bufferPool", "accordingly", "." ]
44ef4189b5da92ac301729cd5fc41079017544fd
https://github.com/NodeRedis/node-redis-parser/blob/44ef4189b5da92ac301729cd5fc41079017544fd/lib/parser.js#L343-L356
18,505
NodeRedis/node-redis-parser
lib/parser.js
concatBulkString
function concatBulkString (parser) { const list = parser.bufferCache const oldOffset = parser.offset var chunks = list.length var offset = parser.bigStrSize - parser.totalChunkSize parser.offset = offset if (offset <= 2) { if (chunks === 2) { return list[0].toString('utf8', oldOffset, list[0].length + offset - 2) } chunks-- offset = list[list.length - 2].length + offset } var res = decoder.write(list[0].slice(oldOffset)) for (var i = 1; i < chunks - 1; i++) { res += decoder.write(list[i]) } res += decoder.end(list[i].slice(0, offset - 2)) return res }
javascript
function concatBulkString (parser) { const list = parser.bufferCache const oldOffset = parser.offset var chunks = list.length var offset = parser.bigStrSize - parser.totalChunkSize parser.offset = offset if (offset <= 2) { if (chunks === 2) { return list[0].toString('utf8', oldOffset, list[0].length + offset - 2) } chunks-- offset = list[list.length - 2].length + offset } var res = decoder.write(list[0].slice(oldOffset)) for (var i = 1; i < chunks - 1; i++) { res += decoder.write(list[i]) } res += decoder.end(list[i].slice(0, offset - 2)) return res }
[ "function", "concatBulkString", "(", "parser", ")", "{", "const", "list", "=", "parser", ".", "bufferCache", "const", "oldOffset", "=", "parser", ".", "offset", "var", "chunks", "=", "list", ".", "length", "var", "offset", "=", "parser", ".", "bigStrSize", "-", "parser", ".", "totalChunkSize", "parser", ".", "offset", "=", "offset", "if", "(", "offset", "<=", "2", ")", "{", "if", "(", "chunks", "===", "2", ")", "{", "return", "list", "[", "0", "]", ".", "toString", "(", "'utf8'", ",", "oldOffset", ",", "list", "[", "0", "]", ".", "length", "+", "offset", "-", "2", ")", "}", "chunks", "--", "offset", "=", "list", "[", "list", ".", "length", "-", "2", "]", ".", "length", "+", "offset", "}", "var", "res", "=", "decoder", ".", "write", "(", "list", "[", "0", "]", ".", "slice", "(", "oldOffset", ")", ")", "for", "(", "var", "i", "=", "1", ";", "i", "<", "chunks", "-", "1", ";", "i", "++", ")", "{", "res", "+=", "decoder", ".", "write", "(", "list", "[", "i", "]", ")", "}", "res", "+=", "decoder", ".", "end", "(", "list", "[", "i", "]", ".", "slice", "(", "0", ",", "offset", "-", "2", ")", ")", "return", "res", "}" ]
Concat a bulk string containing multiple chunks Notes: 1) The first chunk might contain the whole bulk string including the \r 2) We are only safe to fully add up elements that are neither the first nor any of the last two elements @param {JavascriptRedisParser} parser @returns {String}
[ "Concat", "a", "bulk", "string", "containing", "multiple", "chunks" ]
44ef4189b5da92ac301729cd5fc41079017544fd
https://github.com/NodeRedis/node-redis-parser/blob/44ef4189b5da92ac301729cd5fc41079017544fd/lib/parser.js#L368-L387
18,506
NodeRedis/node-redis-parser
lib/parser.js
concatBulkBuffer
function concatBulkBuffer (parser) { const list = parser.bufferCache const oldOffset = parser.offset const length = parser.bigStrSize - oldOffset - 2 var chunks = list.length var offset = parser.bigStrSize - parser.totalChunkSize parser.offset = offset if (offset <= 2) { if (chunks === 2) { return list[0].slice(oldOffset, list[0].length + offset - 2) } chunks-- offset = list[list.length - 2].length + offset } resizeBuffer(length) const start = bufferOffset list[0].copy(bufferPool, start, oldOffset, list[0].length) bufferOffset += list[0].length - oldOffset for (var i = 1; i < chunks - 1; i++) { list[i].copy(bufferPool, bufferOffset) bufferOffset += list[i].length } list[i].copy(bufferPool, bufferOffset, 0, offset - 2) bufferOffset += offset - 2 return bufferPool.slice(start, bufferOffset) }
javascript
function concatBulkBuffer (parser) { const list = parser.bufferCache const oldOffset = parser.offset const length = parser.bigStrSize - oldOffset - 2 var chunks = list.length var offset = parser.bigStrSize - parser.totalChunkSize parser.offset = offset if (offset <= 2) { if (chunks === 2) { return list[0].slice(oldOffset, list[0].length + offset - 2) } chunks-- offset = list[list.length - 2].length + offset } resizeBuffer(length) const start = bufferOffset list[0].copy(bufferPool, start, oldOffset, list[0].length) bufferOffset += list[0].length - oldOffset for (var i = 1; i < chunks - 1; i++) { list[i].copy(bufferPool, bufferOffset) bufferOffset += list[i].length } list[i].copy(bufferPool, bufferOffset, 0, offset - 2) bufferOffset += offset - 2 return bufferPool.slice(start, bufferOffset) }
[ "function", "concatBulkBuffer", "(", "parser", ")", "{", "const", "list", "=", "parser", ".", "bufferCache", "const", "oldOffset", "=", "parser", ".", "offset", "const", "length", "=", "parser", ".", "bigStrSize", "-", "oldOffset", "-", "2", "var", "chunks", "=", "list", ".", "length", "var", "offset", "=", "parser", ".", "bigStrSize", "-", "parser", ".", "totalChunkSize", "parser", ".", "offset", "=", "offset", "if", "(", "offset", "<=", "2", ")", "{", "if", "(", "chunks", "===", "2", ")", "{", "return", "list", "[", "0", "]", ".", "slice", "(", "oldOffset", ",", "list", "[", "0", "]", ".", "length", "+", "offset", "-", "2", ")", "}", "chunks", "--", "offset", "=", "list", "[", "list", ".", "length", "-", "2", "]", ".", "length", "+", "offset", "}", "resizeBuffer", "(", "length", ")", "const", "start", "=", "bufferOffset", "list", "[", "0", "]", ".", "copy", "(", "bufferPool", ",", "start", ",", "oldOffset", ",", "list", "[", "0", "]", ".", "length", ")", "bufferOffset", "+=", "list", "[", "0", "]", ".", "length", "-", "oldOffset", "for", "(", "var", "i", "=", "1", ";", "i", "<", "chunks", "-", "1", ";", "i", "++", ")", "{", "list", "[", "i", "]", ".", "copy", "(", "bufferPool", ",", "bufferOffset", ")", "bufferOffset", "+=", "list", "[", "i", "]", ".", "length", "}", "list", "[", "i", "]", ".", "copy", "(", "bufferPool", ",", "bufferOffset", ",", "0", ",", "offset", "-", "2", ")", "bufferOffset", "+=", "offset", "-", "2", "return", "bufferPool", ".", "slice", "(", "start", ",", "bufferOffset", ")", "}" ]
Concat the collected chunks from parser.bufferCache. Increases the bufferPool size beforehand if necessary. @param {JavascriptRedisParser} parser @returns {Buffer}
[ "Concat", "the", "collected", "chunks", "from", "parser", ".", "bufferCache", "." ]
44ef4189b5da92ac301729cd5fc41079017544fd
https://github.com/NodeRedis/node-redis-parser/blob/44ef4189b5da92ac301729cd5fc41079017544fd/lib/parser.js#L397-L422
18,507
endlessm/electron-installer-flatpak
src/installer.js
function (options, callback) { var licenseSrc = path.join(options.src, 'LICENSE') try { fs.accessSync(licenseSrc) } catch (err) { try { licenseSrc = path.join(options.src, 'LICENSE.txt') fs.accessSync(licenseSrc) } catch (err) { licenseSrc = path.join(options.src, 'LICENSE.md') fs.accessSync(licenseSrc) } } options.logger('Reading license file from ' + licenseSrc) fs.readFile(licenseSrc, callback) }
javascript
function (options, callback) { var licenseSrc = path.join(options.src, 'LICENSE') try { fs.accessSync(licenseSrc) } catch (err) { try { licenseSrc = path.join(options.src, 'LICENSE.txt') fs.accessSync(licenseSrc) } catch (err) { licenseSrc = path.join(options.src, 'LICENSE.md') fs.accessSync(licenseSrc) } } options.logger('Reading license file from ' + licenseSrc) fs.readFile(licenseSrc, callback) }
[ "function", "(", "options", ",", "callback", ")", "{", "var", "licenseSrc", "=", "path", ".", "join", "(", "options", ".", "src", ",", "'LICENSE'", ")", "try", "{", "fs", ".", "accessSync", "(", "licenseSrc", ")", "}", "catch", "(", "err", ")", "{", "try", "{", "licenseSrc", "=", "path", ".", "join", "(", "options", ".", "src", ",", "'LICENSE.txt'", ")", "fs", ".", "accessSync", "(", "licenseSrc", ")", "}", "catch", "(", "err", ")", "{", "licenseSrc", "=", "path", ".", "join", "(", "options", ".", "src", ",", "'LICENSE.md'", ")", "fs", ".", "accessSync", "(", "licenseSrc", ")", "}", "}", "options", ".", "logger", "(", "'Reading license file from '", "+", "licenseSrc", ")", "fs", ".", "readFile", "(", "licenseSrc", ",", "callback", ")", "}" ]
Read `LICENSE` from the root of the app.
[ "Read", "LICENSE", "from", "the", "root", "of", "the", "app", "." ]
589fb44dbd8f503e636ce5d6e351c4856dcc4be9
https://github.com/endlessm/electron-installer-flatpak/blob/589fb44dbd8f503e636ce5d6e351c4856dcc4be9/src/installer.js#L75-L91
18,508
endlessm/electron-installer-flatpak
src/installer.js
function (data, callback) { async.parallel([ async.apply(readMeta, data) ], function (err, results) { var pkg = results[0] || {} var defaults = { id: getAppId(pkg.name, pkg.homepage), productName: pkg.productName || pkg.name, genericName: pkg.genericName || pkg.productName || pkg.name, description: pkg.description, branch: 'master', arch: undefined, base: 'io.atom.electron.BaseApp', baseVersion: 'master', baseFlatpakref: 'https://s3-us-west-2.amazonaws.com/electron-flatpak.endlessm.com/electron-base-app-master.flatpakref', runtime: 'org.freedesktop.Platform', runtimeVersion: '1.4', runtimeFlatpakref: 'https://raw.githubusercontent.com/endlessm/flatpak-bundler/master/refs/freedesktop-runtime-1.4.flatpakref', sdk: 'org.freedesktop.Sdk', sdkFlatpakref: 'https://raw.githubusercontent.com/endlessm/flatpak-bundler/master/refs/freedesktop-sdk-1.4.flatpakref', finishArgs: [ // X Rendering '--socket=x11', '--share=ipc', // Open GL '--device=dri', // Audio output '--socket=pulseaudio', // Read/write home directory access '--filesystem=home', // Chromium uses a socket in tmp for its singleton check '--filesystem=/tmp', // Allow communication with network '--share=network', // System notifications with libnotify '--talk-name=org.freedesktop.Notifications' ], modules: [], bin: pkg.productName || pkg.name || 'electron', icon: path.resolve(__dirname, '../resources/icon.png'), files: [], symlinks: [], categories: [ 'GNOME', 'GTK', 'Utility' ], mimeType: [] } callback(err, defaults) }) }
javascript
function (data, callback) { async.parallel([ async.apply(readMeta, data) ], function (err, results) { var pkg = results[0] || {} var defaults = { id: getAppId(pkg.name, pkg.homepage), productName: pkg.productName || pkg.name, genericName: pkg.genericName || pkg.productName || pkg.name, description: pkg.description, branch: 'master', arch: undefined, base: 'io.atom.electron.BaseApp', baseVersion: 'master', baseFlatpakref: 'https://s3-us-west-2.amazonaws.com/electron-flatpak.endlessm.com/electron-base-app-master.flatpakref', runtime: 'org.freedesktop.Platform', runtimeVersion: '1.4', runtimeFlatpakref: 'https://raw.githubusercontent.com/endlessm/flatpak-bundler/master/refs/freedesktop-runtime-1.4.flatpakref', sdk: 'org.freedesktop.Sdk', sdkFlatpakref: 'https://raw.githubusercontent.com/endlessm/flatpak-bundler/master/refs/freedesktop-sdk-1.4.flatpakref', finishArgs: [ // X Rendering '--socket=x11', '--share=ipc', // Open GL '--device=dri', // Audio output '--socket=pulseaudio', // Read/write home directory access '--filesystem=home', // Chromium uses a socket in tmp for its singleton check '--filesystem=/tmp', // Allow communication with network '--share=network', // System notifications with libnotify '--talk-name=org.freedesktop.Notifications' ], modules: [], bin: pkg.productName || pkg.name || 'electron', icon: path.resolve(__dirname, '../resources/icon.png'), files: [], symlinks: [], categories: [ 'GNOME', 'GTK', 'Utility' ], mimeType: [] } callback(err, defaults) }) }
[ "function", "(", "data", ",", "callback", ")", "{", "async", ".", "parallel", "(", "[", "async", ".", "apply", "(", "readMeta", ",", "data", ")", "]", ",", "function", "(", "err", ",", "results", ")", "{", "var", "pkg", "=", "results", "[", "0", "]", "||", "{", "}", "var", "defaults", "=", "{", "id", ":", "getAppId", "(", "pkg", ".", "name", ",", "pkg", ".", "homepage", ")", ",", "productName", ":", "pkg", ".", "productName", "||", "pkg", ".", "name", ",", "genericName", ":", "pkg", ".", "genericName", "||", "pkg", ".", "productName", "||", "pkg", ".", "name", ",", "description", ":", "pkg", ".", "description", ",", "branch", ":", "'master'", ",", "arch", ":", "undefined", ",", "base", ":", "'io.atom.electron.BaseApp'", ",", "baseVersion", ":", "'master'", ",", "baseFlatpakref", ":", "'https://s3-us-west-2.amazonaws.com/electron-flatpak.endlessm.com/electron-base-app-master.flatpakref'", ",", "runtime", ":", "'org.freedesktop.Platform'", ",", "runtimeVersion", ":", "'1.4'", ",", "runtimeFlatpakref", ":", "'https://raw.githubusercontent.com/endlessm/flatpak-bundler/master/refs/freedesktop-runtime-1.4.flatpakref'", ",", "sdk", ":", "'org.freedesktop.Sdk'", ",", "sdkFlatpakref", ":", "'https://raw.githubusercontent.com/endlessm/flatpak-bundler/master/refs/freedesktop-sdk-1.4.flatpakref'", ",", "finishArgs", ":", "[", "// X Rendering", "'--socket=x11'", ",", "'--share=ipc'", ",", "// Open GL", "'--device=dri'", ",", "// Audio output", "'--socket=pulseaudio'", ",", "// Read/write home directory access", "'--filesystem=home'", ",", "// Chromium uses a socket in tmp for its singleton check", "'--filesystem=/tmp'", ",", "// Allow communication with network", "'--share=network'", ",", "// System notifications with libnotify", "'--talk-name=org.freedesktop.Notifications'", "]", ",", "modules", ":", "[", "]", ",", "bin", ":", "pkg", ".", "productName", "||", "pkg", ".", "name", "||", "'electron'", ",", "icon", ":", "path", ".", "resolve", "(", "__dirname", ",", "'../resources/icon.png'", ")", ",", "files", ":", "[", "]", ",", "symlinks", ":", "[", "]", ",", "categories", ":", "[", "'GNOME'", ",", "'GTK'", ",", "'Utility'", "]", ",", "mimeType", ":", "[", "]", "}", "callback", "(", "err", ",", "defaults", ")", "}", ")", "}" ]
Get the hash of default options for the installer. Some come from the info read from `package.json`, and some are hardcoded.
[ "Get", "the", "hash", "of", "default", "options", "for", "the", "installer", ".", "Some", "come", "from", "the", "info", "read", "from", "package", ".", "json", "and", "some", "are", "hardcoded", "." ]
589fb44dbd8f503e636ce5d6e351c4856dcc4be9
https://github.com/endlessm/electron-installer-flatpak/blob/589fb44dbd8f503e636ce5d6e351c4856dcc4be9/src/installer.js#L97-L154
18,509
endlessm/electron-installer-flatpak
src/installer.js
function (data, defaults, callback) { // Flatten everything for ease of use. var options = _.defaults({}, data, data.options, defaults) callback(null, options) }
javascript
function (data, defaults, callback) { // Flatten everything for ease of use. var options = _.defaults({}, data, data.options, defaults) callback(null, options) }
[ "function", "(", "data", ",", "defaults", ",", "callback", ")", "{", "// Flatten everything for ease of use.", "var", "options", "=", "_", ".", "defaults", "(", "{", "}", ",", "data", ",", "data", ".", "options", ",", "defaults", ")", "callback", "(", "null", ",", "options", ")", "}" ]
Get the hash of options for the installer.
[ "Get", "the", "hash", "of", "options", "for", "the", "installer", "." ]
589fb44dbd8f503e636ce5d6e351c4856dcc4be9
https://github.com/endlessm/electron-installer-flatpak/blob/589fb44dbd8f503e636ce5d6e351c4856dcc4be9/src/installer.js#L159-L164
18,510
endlessm/electron-installer-flatpak
src/installer.js
function (options, file, callback) { options.logger('Generating template from ' + file) async.waterfall([ async.apply(fs.readFile, file), function (template, callback) { var result = _.template(template)(options) options.logger('Generated template from ' + file + '\n' + result) callback(null, result) } ], callback) }
javascript
function (options, file, callback) { options.logger('Generating template from ' + file) async.waterfall([ async.apply(fs.readFile, file), function (template, callback) { var result = _.template(template)(options) options.logger('Generated template from ' + file + '\n' + result) callback(null, result) } ], callback) }
[ "function", "(", "options", ",", "file", ",", "callback", ")", "{", "options", ".", "logger", "(", "'Generating template from '", "+", "file", ")", "async", ".", "waterfall", "(", "[", "async", ".", "apply", "(", "fs", ".", "readFile", ",", "file", ")", ",", "function", "(", "template", ",", "callback", ")", "{", "var", "result", "=", "_", ".", "template", "(", "template", ")", "(", "options", ")", "options", ".", "logger", "(", "'Generated template from '", "+", "file", "+", "'\\n'", "+", "result", ")", "callback", "(", "null", ",", "result", ")", "}", "]", ",", "callback", ")", "}" ]
Fill in a template with the hash of options.
[ "Fill", "in", "a", "template", "with", "the", "hash", "of", "options", "." ]
589fb44dbd8f503e636ce5d6e351c4856dcc4be9
https://github.com/endlessm/electron-installer-flatpak/blob/589fb44dbd8f503e636ce5d6e351c4856dcc4be9/src/installer.js#L169-L180
18,511
endlessm/electron-installer-flatpak
src/installer.js
function (options, dir, callback) { var desktopSrc = path.resolve(__dirname, '../resources/desktop.ejs') var desktopDest = path.join(dir, 'share/applications', options.id + '.desktop') options.logger('Creating desktop file at ' + desktopDest) async.waterfall([ async.apply(generateTemplate, options, desktopSrc), async.apply(fs.outputFile, desktopDest) ], function (err) { callback(err && new Error('Error creating desktop file: ' + (err.message || err))) }) }
javascript
function (options, dir, callback) { var desktopSrc = path.resolve(__dirname, '../resources/desktop.ejs') var desktopDest = path.join(dir, 'share/applications', options.id + '.desktop') options.logger('Creating desktop file at ' + desktopDest) async.waterfall([ async.apply(generateTemplate, options, desktopSrc), async.apply(fs.outputFile, desktopDest) ], function (err) { callback(err && new Error('Error creating desktop file: ' + (err.message || err))) }) }
[ "function", "(", "options", ",", "dir", ",", "callback", ")", "{", "var", "desktopSrc", "=", "path", ".", "resolve", "(", "__dirname", ",", "'../resources/desktop.ejs'", ")", "var", "desktopDest", "=", "path", ".", "join", "(", "dir", ",", "'share/applications'", ",", "options", ".", "id", "+", "'.desktop'", ")", "options", ".", "logger", "(", "'Creating desktop file at '", "+", "desktopDest", ")", "async", ".", "waterfall", "(", "[", "async", ".", "apply", "(", "generateTemplate", ",", "options", ",", "desktopSrc", ")", ",", "async", ".", "apply", "(", "fs", ".", "outputFile", ",", "desktopDest", ")", "]", ",", "function", "(", "err", ")", "{", "callback", "(", "err", "&&", "new", "Error", "(", "'Error creating desktop file: '", "+", "(", "err", ".", "message", "||", "err", ")", ")", ")", "}", ")", "}" ]
Create the desktop file for the package. See: http://standards.freedesktop.org/desktop-entry-spec/latest/
[ "Create", "the", "desktop", "file", "for", "the", "package", "." ]
589fb44dbd8f503e636ce5d6e351c4856dcc4be9
https://github.com/endlessm/electron-installer-flatpak/blob/589fb44dbd8f503e636ce5d6e351c4856dcc4be9/src/installer.js#L187-L198
18,512
endlessm/electron-installer-flatpak
src/installer.js
function (options, dir, callback) { var iconFile = path.join(dir, getPixmapPath(options)) options.logger('Creating icon file at ' + iconFile) fs.copy(options.icon, iconFile, function (err) { callback(err && new Error('Error creating icon file: ' + (err.message || err))) }) }
javascript
function (options, dir, callback) { var iconFile = path.join(dir, getPixmapPath(options)) options.logger('Creating icon file at ' + iconFile) fs.copy(options.icon, iconFile, function (err) { callback(err && new Error('Error creating icon file: ' + (err.message || err))) }) }
[ "function", "(", "options", ",", "dir", ",", "callback", ")", "{", "var", "iconFile", "=", "path", ".", "join", "(", "dir", ",", "getPixmapPath", "(", "options", ")", ")", "options", ".", "logger", "(", "'Creating icon file at '", "+", "iconFile", ")", "fs", ".", "copy", "(", "options", ".", "icon", ",", "iconFile", ",", "function", "(", "err", ")", "{", "callback", "(", "err", "&&", "new", "Error", "(", "'Error creating icon file: '", "+", "(", "err", ".", "message", "||", "err", ")", ")", ")", "}", ")", "}" ]
Create pixmap icon for the package.
[ "Create", "pixmap", "icon", "for", "the", "package", "." ]
589fb44dbd8f503e636ce5d6e351c4856dcc4be9
https://github.com/endlessm/electron-installer-flatpak/blob/589fb44dbd8f503e636ce5d6e351c4856dcc4be9/src/installer.js#L203-L210
18,513
endlessm/electron-installer-flatpak
src/installer.js
function (options, dir, callback) { async.forEachOf(options.icon, function (icon, resolution, callback) { var iconFile = path.join(dir, 'share/icons/hicolor', resolution, 'apps', options.id + '.png') options.logger('Creating icon file at ' + iconFile) fs.copy(icon, iconFile, callback) }, function (err) { callback(err && new Error('Error creating icon file: ' + (err.message || err))) }) }
javascript
function (options, dir, callback) { async.forEachOf(options.icon, function (icon, resolution, callback) { var iconFile = path.join(dir, 'share/icons/hicolor', resolution, 'apps', options.id + '.png') options.logger('Creating icon file at ' + iconFile) fs.copy(icon, iconFile, callback) }, function (err) { callback(err && new Error('Error creating icon file: ' + (err.message || err))) }) }
[ "function", "(", "options", ",", "dir", ",", "callback", ")", "{", "async", ".", "forEachOf", "(", "options", ".", "icon", ",", "function", "(", "icon", ",", "resolution", ",", "callback", ")", "{", "var", "iconFile", "=", "path", ".", "join", "(", "dir", ",", "'share/icons/hicolor'", ",", "resolution", ",", "'apps'", ",", "options", ".", "id", "+", "'.png'", ")", "options", ".", "logger", "(", "'Creating icon file at '", "+", "iconFile", ")", "fs", ".", "copy", "(", "icon", ",", "iconFile", ",", "callback", ")", "}", ",", "function", "(", "err", ")", "{", "callback", "(", "err", "&&", "new", "Error", "(", "'Error creating icon file: '", "+", "(", "err", ".", "message", "||", "err", ")", ")", ")", "}", ")", "}" ]
Create hicolor icon for the package.
[ "Create", "hicolor", "icon", "for", "the", "package", "." ]
589fb44dbd8f503e636ce5d6e351c4856dcc4be9
https://github.com/endlessm/electron-installer-flatpak/blob/589fb44dbd8f503e636ce5d6e351c4856dcc4be9/src/installer.js#L215-L224
18,514
endlessm/electron-installer-flatpak
src/installer.js
function (options, dir, callback) { if (_.isObject(options.icon)) { createHicolorIcon(options, dir, callback) } else if (options.icon) { createPixmapIcon(options, dir, callback) } else { callback() } }
javascript
function (options, dir, callback) { if (_.isObject(options.icon)) { createHicolorIcon(options, dir, callback) } else if (options.icon) { createPixmapIcon(options, dir, callback) } else { callback() } }
[ "function", "(", "options", ",", "dir", ",", "callback", ")", "{", "if", "(", "_", ".", "isObject", "(", "options", ".", "icon", ")", ")", "{", "createHicolorIcon", "(", "options", ",", "dir", ",", "callback", ")", "}", "else", "if", "(", "options", ".", "icon", ")", "{", "createPixmapIcon", "(", "options", ",", "dir", ",", "callback", ")", "}", "else", "{", "callback", "(", ")", "}", "}" ]
Create icon for the package.
[ "Create", "icon", "for", "the", "package", "." ]
589fb44dbd8f503e636ce5d6e351c4856dcc4be9
https://github.com/endlessm/electron-installer-flatpak/blob/589fb44dbd8f503e636ce5d6e351c4856dcc4be9/src/installer.js#L229-L237
18,515
endlessm/electron-installer-flatpak
src/installer.js
function (options, dir, callback) { var copyrightFile = path.join(dir, 'share/doc', options.id, 'copyright') options.logger('Creating copyright file at ' + copyrightFile) async.waterfall([ async.apply(readLicense, options), async.apply(fs.outputFile, copyrightFile) ], function (err) { callback(err && new Error('Error creating copyright file: ' + (err.message || err))) }) }
javascript
function (options, dir, callback) { var copyrightFile = path.join(dir, 'share/doc', options.id, 'copyright') options.logger('Creating copyright file at ' + copyrightFile) async.waterfall([ async.apply(readLicense, options), async.apply(fs.outputFile, copyrightFile) ], function (err) { callback(err && new Error('Error creating copyright file: ' + (err.message || err))) }) }
[ "function", "(", "options", ",", "dir", ",", "callback", ")", "{", "var", "copyrightFile", "=", "path", ".", "join", "(", "dir", ",", "'share/doc'", ",", "options", ".", "id", ",", "'copyright'", ")", "options", ".", "logger", "(", "'Creating copyright file at '", "+", "copyrightFile", ")", "async", ".", "waterfall", "(", "[", "async", ".", "apply", "(", "readLicense", ",", "options", ")", ",", "async", ".", "apply", "(", "fs", ".", "outputFile", ",", "copyrightFile", ")", "]", ",", "function", "(", "err", ")", "{", "callback", "(", "err", "&&", "new", "Error", "(", "'Error creating copyright file: '", "+", "(", "err", ".", "message", "||", "err", ")", ")", ")", "}", ")", "}" ]
Create copyright for the package.
[ "Create", "copyright", "for", "the", "package", "." ]
589fb44dbd8f503e636ce5d6e351c4856dcc4be9
https://github.com/endlessm/electron-installer-flatpak/blob/589fb44dbd8f503e636ce5d6e351c4856dcc4be9/src/installer.js#L242-L252
18,516
endlessm/electron-installer-flatpak
src/installer.js
function (options, dir, callback) { var applicationDir = path.join(dir, 'lib', options.id) options.logger('Copying application to ' + applicationDir) async.waterfall([ async.apply(fs.ensureDir, applicationDir), async.apply(fs.copy, options.src, applicationDir) ], function (err) { callback(err && new Error('Error copying application directory: ' + (err.message || err))) }) }
javascript
function (options, dir, callback) { var applicationDir = path.join(dir, 'lib', options.id) options.logger('Copying application to ' + applicationDir) async.waterfall([ async.apply(fs.ensureDir, applicationDir), async.apply(fs.copy, options.src, applicationDir) ], function (err) { callback(err && new Error('Error copying application directory: ' + (err.message || err))) }) }
[ "function", "(", "options", ",", "dir", ",", "callback", ")", "{", "var", "applicationDir", "=", "path", ".", "join", "(", "dir", ",", "'lib'", ",", "options", ".", "id", ")", "options", ".", "logger", "(", "'Copying application to '", "+", "applicationDir", ")", "async", ".", "waterfall", "(", "[", "async", ".", "apply", "(", "fs", ".", "ensureDir", ",", "applicationDir", ")", ",", "async", ".", "apply", "(", "fs", ".", "copy", ",", "options", ".", "src", ",", "applicationDir", ")", "]", ",", "function", "(", "err", ")", "{", "callback", "(", "err", "&&", "new", "Error", "(", "'Error copying application directory: '", "+", "(", "err", ".", "message", "||", "err", ")", ")", ")", "}", ")", "}" ]
Copy the application into the package.
[ "Copy", "the", "application", "into", "the", "package", "." ]
589fb44dbd8f503e636ce5d6e351c4856dcc4be9
https://github.com/endlessm/electron-installer-flatpak/blob/589fb44dbd8f503e636ce5d6e351c4856dcc4be9/src/installer.js#L257-L267
18,517
endlessm/electron-installer-flatpak
src/installer.js
function (options, callback) { options.logger('Creating temporary directory') async.waterfall([ async.apply(temp.mkdir, 'electron-'), function (dir, callback) { dir = path.join(dir, options.id + '_' + options.version + '_' + options.arch) fs.ensureDir(dir, callback) } ], function (err, dir) { callback(err && new Error('Error creating temporary directory: ' + (err.message || err)), dir) }) }
javascript
function (options, callback) { options.logger('Creating temporary directory') async.waterfall([ async.apply(temp.mkdir, 'electron-'), function (dir, callback) { dir = path.join(dir, options.id + '_' + options.version + '_' + options.arch) fs.ensureDir(dir, callback) } ], function (err, dir) { callback(err && new Error('Error creating temporary directory: ' + (err.message || err)), dir) }) }
[ "function", "(", "options", ",", "callback", ")", "{", "options", ".", "logger", "(", "'Creating temporary directory'", ")", "async", ".", "waterfall", "(", "[", "async", ".", "apply", "(", "temp", ".", "mkdir", ",", "'electron-'", ")", ",", "function", "(", "dir", ",", "callback", ")", "{", "dir", "=", "path", ".", "join", "(", "dir", ",", "options", ".", "id", "+", "'_'", "+", "options", ".", "version", "+", "'_'", "+", "options", ".", "arch", ")", "fs", ".", "ensureDir", "(", "dir", ",", "callback", ")", "}", "]", ",", "function", "(", "err", ",", "dir", ")", "{", "callback", "(", "err", "&&", "new", "Error", "(", "'Error creating temporary directory: '", "+", "(", "err", ".", "message", "||", "err", ")", ")", ",", "dir", ")", "}", ")", "}" ]
Create temporary directory where the contents of the package will live.
[ "Create", "temporary", "directory", "where", "the", "contents", "of", "the", "package", "will", "live", "." ]
589fb44dbd8f503e636ce5d6e351c4856dcc4be9
https://github.com/endlessm/electron-installer-flatpak/blob/589fb44dbd8f503e636ce5d6e351c4856dcc4be9/src/installer.js#L272-L284
18,518
endlessm/electron-installer-flatpak
src/installer.js
function (options, dir, callback) { options.logger('Creating contents of package') async.parallel([ async.apply(createDesktop, options, dir), async.apply(createIcon, options, dir), async.apply(createCopyright, options, dir), async.apply(createApplication, options, dir) ], function (err) { callback(err, dir) }) }
javascript
function (options, dir, callback) { options.logger('Creating contents of package') async.parallel([ async.apply(createDesktop, options, dir), async.apply(createIcon, options, dir), async.apply(createCopyright, options, dir), async.apply(createApplication, options, dir) ], function (err) { callback(err, dir) }) }
[ "function", "(", "options", ",", "dir", ",", "callback", ")", "{", "options", ".", "logger", "(", "'Creating contents of package'", ")", "async", ".", "parallel", "(", "[", "async", ".", "apply", "(", "createDesktop", ",", "options", ",", "dir", ")", ",", "async", ".", "apply", "(", "createIcon", ",", "options", ",", "dir", ")", ",", "async", ".", "apply", "(", "createCopyright", ",", "options", ",", "dir", ")", ",", "async", ".", "apply", "(", "createApplication", ",", "options", ",", "dir", ")", "]", ",", "function", "(", "err", ")", "{", "callback", "(", "err", ",", "dir", ")", "}", ")", "}" ]
Create the contents of the package.
[ "Create", "the", "contents", "of", "the", "package", "." ]
589fb44dbd8f503e636ce5d6e351c4856dcc4be9
https://github.com/endlessm/electron-installer-flatpak/blob/589fb44dbd8f503e636ce5d6e351c4856dcc4be9/src/installer.js#L289-L300
18,519
endlessm/electron-installer-flatpak
src/installer.js
function (options, dir, callback) { var name = _.template('<%= id %>_<%= branch %>_<%= arch %>.flatpak')(options) var dest = options.rename(options.dest, name) options.logger('Creating package at ' + dest) var extraExports = [] if (options.icon && !_.isObject(options.icon)) extraExports.push(getPixmapPath(options)) var files = [ [dir, '/'] ] var symlinks = [ [path.join('/lib', options.id, options.bin), path.join('/bin', options.bin)] ] flatpak.bundle({ id: options.id, branch: options.branch, base: options.base, baseVersion: options.baseVersion, baseFlatpakref: options.baseFlatpakref, runtime: options.runtime, runtimeVersion: options.runtimeVersion, runtimeFlatpakref: options.runtimeFlatpakref, sdk: options.sdk, sdkFlatpakref: options.sdkFlatpakref, finishArgs: options.finishArgs, command: options.bin, files: files.concat(options.files), symlinks: symlinks.concat(options.symlinks), extraExports: extraExports, modules: options.modules }, { arch: options.arch, bundlePath: dest }, function (err) { callback(err, dir) }) }
javascript
function (options, dir, callback) { var name = _.template('<%= id %>_<%= branch %>_<%= arch %>.flatpak')(options) var dest = options.rename(options.dest, name) options.logger('Creating package at ' + dest) var extraExports = [] if (options.icon && !_.isObject(options.icon)) extraExports.push(getPixmapPath(options)) var files = [ [dir, '/'] ] var symlinks = [ [path.join('/lib', options.id, options.bin), path.join('/bin', options.bin)] ] flatpak.bundle({ id: options.id, branch: options.branch, base: options.base, baseVersion: options.baseVersion, baseFlatpakref: options.baseFlatpakref, runtime: options.runtime, runtimeVersion: options.runtimeVersion, runtimeFlatpakref: options.runtimeFlatpakref, sdk: options.sdk, sdkFlatpakref: options.sdkFlatpakref, finishArgs: options.finishArgs, command: options.bin, files: files.concat(options.files), symlinks: symlinks.concat(options.symlinks), extraExports: extraExports, modules: options.modules }, { arch: options.arch, bundlePath: dest }, function (err) { callback(err, dir) }) }
[ "function", "(", "options", ",", "dir", ",", "callback", ")", "{", "var", "name", "=", "_", ".", "template", "(", "'<%= id %>_<%= branch %>_<%= arch %>.flatpak'", ")", "(", "options", ")", "var", "dest", "=", "options", ".", "rename", "(", "options", ".", "dest", ",", "name", ")", "options", ".", "logger", "(", "'Creating package at '", "+", "dest", ")", "var", "extraExports", "=", "[", "]", "if", "(", "options", ".", "icon", "&&", "!", "_", ".", "isObject", "(", "options", ".", "icon", ")", ")", "extraExports", ".", "push", "(", "getPixmapPath", "(", "options", ")", ")", "var", "files", "=", "[", "[", "dir", ",", "'/'", "]", "]", "var", "symlinks", "=", "[", "[", "path", ".", "join", "(", "'/lib'", ",", "options", ".", "id", ",", "options", ".", "bin", ")", ",", "path", ".", "join", "(", "'/bin'", ",", "options", ".", "bin", ")", "]", "]", "flatpak", ".", "bundle", "(", "{", "id", ":", "options", ".", "id", ",", "branch", ":", "options", ".", "branch", ",", "base", ":", "options", ".", "base", ",", "baseVersion", ":", "options", ".", "baseVersion", ",", "baseFlatpakref", ":", "options", ".", "baseFlatpakref", ",", "runtime", ":", "options", ".", "runtime", ",", "runtimeVersion", ":", "options", ".", "runtimeVersion", ",", "runtimeFlatpakref", ":", "options", ".", "runtimeFlatpakref", ",", "sdk", ":", "options", ".", "sdk", ",", "sdkFlatpakref", ":", "options", ".", "sdkFlatpakref", ",", "finishArgs", ":", "options", ".", "finishArgs", ",", "command", ":", "options", ".", "bin", ",", "files", ":", "files", ".", "concat", "(", "options", ".", "files", ")", ",", "symlinks", ":", "symlinks", ".", "concat", "(", "options", ".", "symlinks", ")", ",", "extraExports", ":", "extraExports", ",", "modules", ":", "options", ".", "modules", "}", ",", "{", "arch", ":", "options", ".", "arch", ",", "bundlePath", ":", "dest", "}", ",", "function", "(", "err", ")", "{", "callback", "(", "err", ",", "dir", ")", "}", ")", "}" ]
Bundle everything using `flatpak-bundler`.
[ "Bundle", "everything", "using", "flatpak", "-", "bundler", "." ]
589fb44dbd8f503e636ce5d6e351c4856dcc4be9
https://github.com/endlessm/electron-installer-flatpak/blob/589fb44dbd8f503e636ce5d6e351c4856dcc4be9/src/installer.js#L305-L342
18,520
brigand/babel-plugin-flow-react-proptypes
src/makePropTypesAst.js
makeShapeAstForShapeIntersectRuntime
function makeShapeAstForShapeIntersectRuntime(propTypeData) { const runtimeMerge = makeObjectMergeAstForShapeIntersectRuntime(propTypeData); return t.callExpression( t.memberExpression( makePropTypeImportNode(), t.identifier('shape'), ), [runtimeMerge], ); }
javascript
function makeShapeAstForShapeIntersectRuntime(propTypeData) { const runtimeMerge = makeObjectMergeAstForShapeIntersectRuntime(propTypeData); return t.callExpression( t.memberExpression( makePropTypeImportNode(), t.identifier('shape'), ), [runtimeMerge], ); }
[ "function", "makeShapeAstForShapeIntersectRuntime", "(", "propTypeData", ")", "{", "const", "runtimeMerge", "=", "makeObjectMergeAstForShapeIntersectRuntime", "(", "propTypeData", ")", ";", "return", "t", ".", "callExpression", "(", "t", ".", "memberExpression", "(", "makePropTypeImportNode", "(", ")", ",", "t", ".", "identifier", "(", "'shape'", ")", ",", ")", ",", "[", "runtimeMerge", "]", ",", ")", ";", "}" ]
Like makeShapeAstForShapeIntersectRuntime, but wraps the props in a shape. This is useful for nested uses.
[ "Like", "makeShapeAstForShapeIntersectRuntime", "but", "wraps", "the", "props", "in", "a", "shape", "." ]
d39eef29755af43e769ebf19dccbd13c6f316ffb
https://github.com/brigand/babel-plugin-flow-react-proptypes/blob/d39eef29755af43e769ebf19dccbd13c6f316ffb/src/makePropTypesAst.js#L182-L191
18,521
productboard/webpack-deploy
tasks/rollbar-source-map.js
findByHash
function findByHash(config, hash) { const re = new RegExp(injectHashIntoPath(config.sourceMapPath, hash)); return glob .sync('./**') .filter(file => re.test(file)) .map(sourceMapPath => { // strip relative path characters const sourceMapPathMatch = sourceMapPath.match(re); if (sourceMapPathMatch) { const minifiedUrl = sourceMapPathMatch[0].replace( re, injectHashIntoPath(config.minifiedUrl, hash), ); return { sourceMapPath, minifiedUrl, }; } }) .filter(Boolean); }
javascript
function findByHash(config, hash) { const re = new RegExp(injectHashIntoPath(config.sourceMapPath, hash)); return glob .sync('./**') .filter(file => re.test(file)) .map(sourceMapPath => { // strip relative path characters const sourceMapPathMatch = sourceMapPath.match(re); if (sourceMapPathMatch) { const minifiedUrl = sourceMapPathMatch[0].replace( re, injectHashIntoPath(config.minifiedUrl, hash), ); return { sourceMapPath, minifiedUrl, }; } }) .filter(Boolean); }
[ "function", "findByHash", "(", "config", ",", "hash", ")", "{", "const", "re", "=", "new", "RegExp", "(", "injectHashIntoPath", "(", "config", ".", "sourceMapPath", ",", "hash", ")", ")", ";", "return", "glob", ".", "sync", "(", "'./**'", ")", ".", "filter", "(", "file", "=>", "re", ".", "test", "(", "file", ")", ")", ".", "map", "(", "sourceMapPath", "=>", "{", "// strip relative path characters", "const", "sourceMapPathMatch", "=", "sourceMapPath", ".", "match", "(", "re", ")", ";", "if", "(", "sourceMapPathMatch", ")", "{", "const", "minifiedUrl", "=", "sourceMapPathMatch", "[", "0", "]", ".", "replace", "(", "re", ",", "injectHashIntoPath", "(", "config", ".", "minifiedUrl", ",", "hash", ")", ",", ")", ";", "return", "{", "sourceMapPath", ",", "minifiedUrl", ",", "}", ";", "}", "}", ")", ".", "filter", "(", "Boolean", ")", ";", "}" ]
Finds corresponding hashed source map file name
[ "Finds", "corresponding", "hashed", "source", "map", "file", "name" ]
5d14526118ffb68a1310e3b366364355f12e2f7a
https://github.com/productboard/webpack-deploy/blob/5d14526118ffb68a1310e3b366364355f12e2f7a/tasks/rollbar-source-map.js#L59-L82
18,522
pillarjs/parseurl
index.js
parseurl
function parseurl (req) { var url = req.url if (url === undefined) { // URL is undefined return undefined } var parsed = req._parsedUrl if (fresh(url, parsed)) { // Return cached URL parse return parsed } // Parse the URL parsed = fastparse(url) parsed._raw = url return (req._parsedUrl = parsed) }
javascript
function parseurl (req) { var url = req.url if (url === undefined) { // URL is undefined return undefined } var parsed = req._parsedUrl if (fresh(url, parsed)) { // Return cached URL parse return parsed } // Parse the URL parsed = fastparse(url) parsed._raw = url return (req._parsedUrl = parsed) }
[ "function", "parseurl", "(", "req", ")", "{", "var", "url", "=", "req", ".", "url", "if", "(", "url", "===", "undefined", ")", "{", "// URL is undefined", "return", "undefined", "}", "var", "parsed", "=", "req", ".", "_parsedUrl", "if", "(", "fresh", "(", "url", ",", "parsed", ")", ")", "{", "// Return cached URL parse", "return", "parsed", "}", "// Parse the URL", "parsed", "=", "fastparse", "(", "url", ")", "parsed", ".", "_raw", "=", "url", "return", "(", "req", ".", "_parsedUrl", "=", "parsed", ")", "}" ]
Parse the `req` url with memoization. @param {ServerRequest} req @return {Object} @public
[ "Parse", "the", "req", "url", "with", "memoization", "." ]
0a5323370b02f4eff4069472d1e96a0094aef621
https://github.com/pillarjs/parseurl/blob/0a5323370b02f4eff4069472d1e96a0094aef621/index.js#L35-L55
18,523
pillarjs/parseurl
index.js
originalurl
function originalurl (req) { var url = req.originalUrl if (typeof url !== 'string') { // Fallback return parseurl(req) } var parsed = req._parsedOriginalUrl if (fresh(url, parsed)) { // Return cached URL parse return parsed } // Parse the URL parsed = fastparse(url) parsed._raw = url return (req._parsedOriginalUrl = parsed) }
javascript
function originalurl (req) { var url = req.originalUrl if (typeof url !== 'string') { // Fallback return parseurl(req) } var parsed = req._parsedOriginalUrl if (fresh(url, parsed)) { // Return cached URL parse return parsed } // Parse the URL parsed = fastparse(url) parsed._raw = url return (req._parsedOriginalUrl = parsed) }
[ "function", "originalurl", "(", "req", ")", "{", "var", "url", "=", "req", ".", "originalUrl", "if", "(", "typeof", "url", "!==", "'string'", ")", "{", "// Fallback", "return", "parseurl", "(", "req", ")", "}", "var", "parsed", "=", "req", ".", "_parsedOriginalUrl", "if", "(", "fresh", "(", "url", ",", "parsed", ")", ")", "{", "// Return cached URL parse", "return", "parsed", "}", "// Parse the URL", "parsed", "=", "fastparse", "(", "url", ")", "parsed", ".", "_raw", "=", "url", "return", "(", "req", ".", "_parsedOriginalUrl", "=", "parsed", ")", "}" ]
Parse the `req` original url with fallback and memoization. @param {ServerRequest} req @return {Object} @public
[ "Parse", "the", "req", "original", "url", "with", "fallback", "and", "memoization", "." ]
0a5323370b02f4eff4069472d1e96a0094aef621
https://github.com/pillarjs/parseurl/blob/0a5323370b02f4eff4069472d1e96a0094aef621/index.js#L65-L85
18,524
pillarjs/parseurl
index.js
fastparse
function fastparse (str) { if (typeof str !== 'string' || str.charCodeAt(0) !== 0x2f /* / */) { return parse(str) } var pathname = str var query = null var search = null // This takes the regexp from https://github.com/joyent/node/pull/7878 // Which is /^(\/[^?#\s]*)(\?[^#\s]*)?$/ // And unrolls it into a for loop for (var i = 1; i < str.length; i++) { switch (str.charCodeAt(i)) { case 0x3f: /* ? */ if (search === null) { pathname = str.substring(0, i) query = str.substring(i + 1) search = str.substring(i) } break case 0x09: /* \t */ case 0x0a: /* \n */ case 0x0c: /* \f */ case 0x0d: /* \r */ case 0x20: /* */ case 0x23: /* # */ case 0xa0: case 0xfeff: return parse(str) } } var url = Url !== undefined ? new Url() : {} url.path = str url.href = str url.pathname = pathname if (search !== null) { url.query = query url.search = search } return url }
javascript
function fastparse (str) { if (typeof str !== 'string' || str.charCodeAt(0) !== 0x2f /* / */) { return parse(str) } var pathname = str var query = null var search = null // This takes the regexp from https://github.com/joyent/node/pull/7878 // Which is /^(\/[^?#\s]*)(\?[^#\s]*)?$/ // And unrolls it into a for loop for (var i = 1; i < str.length; i++) { switch (str.charCodeAt(i)) { case 0x3f: /* ? */ if (search === null) { pathname = str.substring(0, i) query = str.substring(i + 1) search = str.substring(i) } break case 0x09: /* \t */ case 0x0a: /* \n */ case 0x0c: /* \f */ case 0x0d: /* \r */ case 0x20: /* */ case 0x23: /* # */ case 0xa0: case 0xfeff: return parse(str) } } var url = Url !== undefined ? new Url() : {} url.path = str url.href = str url.pathname = pathname if (search !== null) { url.query = query url.search = search } return url }
[ "function", "fastparse", "(", "str", ")", "{", "if", "(", "typeof", "str", "!==", "'string'", "||", "str", ".", "charCodeAt", "(", "0", ")", "!==", "0x2f", "/* / */", ")", "{", "return", "parse", "(", "str", ")", "}", "var", "pathname", "=", "str", "var", "query", "=", "null", "var", "search", "=", "null", "// This takes the regexp from https://github.com/joyent/node/pull/7878", "// Which is /^(\\/[^?#\\s]*)(\\?[^#\\s]*)?$/", "// And unrolls it into a for loop", "for", "(", "var", "i", "=", "1", ";", "i", "<", "str", ".", "length", ";", "i", "++", ")", "{", "switch", "(", "str", ".", "charCodeAt", "(", "i", ")", ")", "{", "case", "0x3f", ":", "/* ? */", "if", "(", "search", "===", "null", ")", "{", "pathname", "=", "str", ".", "substring", "(", "0", ",", "i", ")", "query", "=", "str", ".", "substring", "(", "i", "+", "1", ")", "search", "=", "str", ".", "substring", "(", "i", ")", "}", "break", "case", "0x09", ":", "/* \\t */", "case", "0x0a", ":", "/* \\n */", "case", "0x0c", ":", "/* \\f */", "case", "0x0d", ":", "/* \\r */", "case", "0x20", ":", "/* */", "case", "0x23", ":", "/* # */", "case", "0xa0", ":", "case", "0xfeff", ":", "return", "parse", "(", "str", ")", "}", "}", "var", "url", "=", "Url", "!==", "undefined", "?", "new", "Url", "(", ")", ":", "{", "}", "url", ".", "path", "=", "str", "url", ".", "href", "=", "str", "url", ".", "pathname", "=", "pathname", "if", "(", "search", "!==", "null", ")", "{", "url", ".", "query", "=", "query", "url", ".", "search", "=", "search", "}", "return", "url", "}" ]
Parse the `str` url with fast-path short-cut. @param {string} str @return {Object} @private
[ "Parse", "the", "str", "url", "with", "fast", "-", "path", "short", "-", "cut", "." ]
0a5323370b02f4eff4069472d1e96a0094aef621
https://github.com/pillarjs/parseurl/blob/0a5323370b02f4eff4069472d1e96a0094aef621/index.js#L95-L142
18,525
pillarjs/parseurl
index.js
fresh
function fresh (url, parsedUrl) { return typeof parsedUrl === 'object' && parsedUrl !== null && (Url === undefined || parsedUrl instanceof Url) && parsedUrl._raw === url }
javascript
function fresh (url, parsedUrl) { return typeof parsedUrl === 'object' && parsedUrl !== null && (Url === undefined || parsedUrl instanceof Url) && parsedUrl._raw === url }
[ "function", "fresh", "(", "url", ",", "parsedUrl", ")", "{", "return", "typeof", "parsedUrl", "===", "'object'", "&&", "parsedUrl", "!==", "null", "&&", "(", "Url", "===", "undefined", "||", "parsedUrl", "instanceof", "Url", ")", "&&", "parsedUrl", ".", "_raw", "===", "url", "}" ]
Determine if parsed is still fresh for url. @param {string} url @param {object} parsedUrl @return {boolean} @private
[ "Determine", "if", "parsed", "is", "still", "fresh", "for", "url", "." ]
0a5323370b02f4eff4069472d1e96a0094aef621
https://github.com/pillarjs/parseurl/blob/0a5323370b02f4eff4069472d1e96a0094aef621/index.js#L153-L158
18,526
uPortal-contrib/uPortal-web-components
@uportal/esco-content-menu/src/services/portlet-registry-to-array.js
customUnique
function customUnique(array) { const unique = uniqBy(array, 'fname'); // we construct unique portlets array will all linked categories (reversing category and portlets child) unique.forEach((elem) => { const dupl = array.filter((e) => e.fname === elem.fname); const allCategories = dupl.flatMap(({categories}) => categories); elem.categories = [...new Set(allCategories)]; }); return unique; }
javascript
function customUnique(array) { const unique = uniqBy(array, 'fname'); // we construct unique portlets array will all linked categories (reversing category and portlets child) unique.forEach((elem) => { const dupl = array.filter((e) => e.fname === elem.fname); const allCategories = dupl.flatMap(({categories}) => categories); elem.categories = [...new Set(allCategories)]; }); return unique; }
[ "function", "customUnique", "(", "array", ")", "{", "const", "unique", "=", "uniqBy", "(", "array", ",", "'fname'", ")", ";", "// we construct unique portlets array will all linked categories (reversing category and portlets child)", "unique", ".", "forEach", "(", "(", "elem", ")", "=>", "{", "const", "dupl", "=", "array", ".", "filter", "(", "(", "e", ")", "=>", "e", ".", "fname", "===", "elem", ".", "fname", ")", ";", "const", "allCategories", "=", "dupl", ".", "flatMap", "(", "(", "{", "categories", "}", ")", "=>", "categories", ")", ";", "elem", ".", "categories", "=", "[", "...", "new", "Set", "(", "allCategories", ")", "]", ";", "}", ")", ";", "return", "unique", ";", "}" ]
Custom function to remove duplicates portlet on fname, but with merging categories. @param {Array<Portlet>} array - Portlet List with duplicates. @return {Array<Portlet>} Portlet List without duplicates.
[ "Custom", "function", "to", "remove", "duplicates", "portlet", "on", "fname", "but", "with", "merging", "categories", "." ]
943e1e8daf6960232712c27491d09bc0c31c60a0
https://github.com/uPortal-contrib/uPortal-web-components/blob/943e1e8daf6960232712c27491d09bc0c31c60a0/@uportal/esco-content-menu/src/services/portlet-registry-to-array.js#L57-L66
18,527
byte-foundry/plumin.js
src/Font.js
function( buffer, enFamilyName, noMerge) { //cancelling in browser merge clearTimeout(this.mergeTimeout); if ( !enFamilyName ) { enFamilyName = this.ot.getEnglishName('fontFamily'); } if ( this.fontMap[ enFamilyName ] ) { document.fonts.delete( this.fontMap[ enFamilyName ] ); } var fontface = this.fontMap[ enFamilyName ] = ( new window.FontFace( enFamilyName, buffer || this.toArrayBuffer() ) ); if ( fontface.status === 'error' ) { throw new Error('Fontface is invalid and cannot be displayed'); } document.fonts.add( fontface ); //we merge font that haven't been merge if ( !noMerge ) { var timeoutRef = this.mergeTimeout = setTimeout(function() { mergeFont( 'https://merge.prototypo.io', { style: 'forbrowserdisplay', template: 'noidea', family: 'forbrowserdisplay' }, 'plumin', buffer, true, function(mergedBuffer) { if (timeoutRef === this.mergeTimeout) { this.addToFonts(mergedBuffer, enFamilyName, true); } }.bind(this) ); }.bind(this), 300); } return this; }
javascript
function( buffer, enFamilyName, noMerge) { //cancelling in browser merge clearTimeout(this.mergeTimeout); if ( !enFamilyName ) { enFamilyName = this.ot.getEnglishName('fontFamily'); } if ( this.fontMap[ enFamilyName ] ) { document.fonts.delete( this.fontMap[ enFamilyName ] ); } var fontface = this.fontMap[ enFamilyName ] = ( new window.FontFace( enFamilyName, buffer || this.toArrayBuffer() ) ); if ( fontface.status === 'error' ) { throw new Error('Fontface is invalid and cannot be displayed'); } document.fonts.add( fontface ); //we merge font that haven't been merge if ( !noMerge ) { var timeoutRef = this.mergeTimeout = setTimeout(function() { mergeFont( 'https://merge.prototypo.io', { style: 'forbrowserdisplay', template: 'noidea', family: 'forbrowserdisplay' }, 'plumin', buffer, true, function(mergedBuffer) { if (timeoutRef === this.mergeTimeout) { this.addToFonts(mergedBuffer, enFamilyName, true); } }.bind(this) ); }.bind(this), 300); } return this; }
[ "function", "(", "buffer", ",", "enFamilyName", ",", "noMerge", ")", "{", "//cancelling in browser merge", "clearTimeout", "(", "this", ".", "mergeTimeout", ")", ";", "if", "(", "!", "enFamilyName", ")", "{", "enFamilyName", "=", "this", ".", "ot", ".", "getEnglishName", "(", "'fontFamily'", ")", ";", "}", "if", "(", "this", ".", "fontMap", "[", "enFamilyName", "]", ")", "{", "document", ".", "fonts", ".", "delete", "(", "this", ".", "fontMap", "[", "enFamilyName", "]", ")", ";", "}", "var", "fontface", "=", "this", ".", "fontMap", "[", "enFamilyName", "]", "=", "(", "new", "window", ".", "FontFace", "(", "enFamilyName", ",", "buffer", "||", "this", ".", "toArrayBuffer", "(", ")", ")", ")", ";", "if", "(", "fontface", ".", "status", "===", "'error'", ")", "{", "throw", "new", "Error", "(", "'Fontface is invalid and cannot be displayed'", ")", ";", "}", "document", ".", "fonts", ".", "add", "(", "fontface", ")", ";", "//we merge font that haven't been merge", "if", "(", "!", "noMerge", ")", "{", "var", "timeoutRef", "=", "this", ".", "mergeTimeout", "=", "setTimeout", "(", "function", "(", ")", "{", "mergeFont", "(", "'https://merge.prototypo.io'", ",", "{", "style", ":", "'forbrowserdisplay'", ",", "template", ":", "'noidea'", ",", "family", ":", "'forbrowserdisplay'", "}", ",", "'plumin'", ",", "buffer", ",", "true", ",", "function", "(", "mergedBuffer", ")", "{", "if", "(", "timeoutRef", "===", "this", ".", "mergeTimeout", ")", "{", "this", ".", "addToFonts", "(", "mergedBuffer", ",", "enFamilyName", ",", "true", ")", ";", "}", "}", ".", "bind", "(", "this", ")", ")", ";", "}", ".", "bind", "(", "this", ")", ",", "300", ")", ";", "}", "return", "this", ";", "}" ]
CSS font loading, lightning fast
[ "CSS", "font", "loading", "lightning", "fast" ]
cce40c03f51f16638332c2c27a42f236feaaf3e3
https://github.com/byte-foundry/plumin.js/blob/cce40c03f51f16638332c2c27a42f236feaaf3e3/src/Font.js#L286-L334
18,528
trilogy-group/ignite-chute-opensource-json-schema-defaults
lib/defaults.js
function(target, source) { target = cloneJSON(target); for (var key in source) { if (source.hasOwnProperty(key)) { if (isObject(target[key]) && isObject(source[key])) { target[key] = merge(target[key], source[key]); } else { target[key] = source[key]; } } } return target; }
javascript
function(target, source) { target = cloneJSON(target); for (var key in source) { if (source.hasOwnProperty(key)) { if (isObject(target[key]) && isObject(source[key])) { target[key] = merge(target[key], source[key]); } else { target[key] = source[key]; } } } return target; }
[ "function", "(", "target", ",", "source", ")", "{", "target", "=", "cloneJSON", "(", "target", ")", ";", "for", "(", "var", "key", "in", "source", ")", "{", "if", "(", "source", ".", "hasOwnProperty", "(", "key", ")", ")", "{", "if", "(", "isObject", "(", "target", "[", "key", "]", ")", "&&", "isObject", "(", "source", "[", "key", "]", ")", ")", "{", "target", "[", "key", "]", "=", "merge", "(", "target", "[", "key", "]", ",", "source", "[", "key", "]", ")", ";", "}", "else", "{", "target", "[", "key", "]", "=", "source", "[", "key", "]", ";", "}", "}", "}", "return", "target", ";", "}" ]
returns a result of deep merge of two objects @param {Object} target @param {Object} source @return {Object}
[ "returns", "a", "result", "of", "deep", "merge", "of", "two", "objects" ]
0c448d7939c9021dd66f54e5f9f1697153bbc570
https://github.com/trilogy-group/ignite-chute-opensource-json-schema-defaults/blob/0c448d7939c9021dd66f54e5f9f1697153bbc570/lib/defaults.js#L54-L67
18,529
trilogy-group/ignite-chute-opensource-json-schema-defaults
lib/defaults.js
function(path, definitions) { path = path.replace(/^#\/definitions\//, '').split('/'); var find = function(path, root) { var key = path.shift(); if (!root[key]) { return {}; } else if (!path.length) { return root[key]; } else { return find(path, root[key]); } }; var result = find(path, definitions); if (!isObject(result)) { return result; } return cloneJSON(result); }
javascript
function(path, definitions) { path = path.replace(/^#\/definitions\//, '').split('/'); var find = function(path, root) { var key = path.shift(); if (!root[key]) { return {}; } else if (!path.length) { return root[key]; } else { return find(path, root[key]); } }; var result = find(path, definitions); if (!isObject(result)) { return result; } return cloneJSON(result); }
[ "function", "(", "path", ",", "definitions", ")", "{", "path", "=", "path", ".", "replace", "(", "/", "^#\\/definitions\\/", "/", ",", "''", ")", ".", "split", "(", "'/'", ")", ";", "var", "find", "=", "function", "(", "path", ",", "root", ")", "{", "var", "key", "=", "path", ".", "shift", "(", ")", ";", "if", "(", "!", "root", "[", "key", "]", ")", "{", "return", "{", "}", ";", "}", "else", "if", "(", "!", "path", ".", "length", ")", "{", "return", "root", "[", "key", "]", ";", "}", "else", "{", "return", "find", "(", "path", ",", "root", "[", "key", "]", ")", ";", "}", "}", ";", "var", "result", "=", "find", "(", "path", ",", "definitions", ")", ";", "if", "(", "!", "isObject", "(", "result", ")", ")", "{", "return", "result", ";", "}", "return", "cloneJSON", "(", "result", ")", ";", "}" ]
get object by reference. works only with local references that points on definitions object @param {String} path @param {Object} definitions @return {Object}
[ "get", "object", "by", "reference", ".", "works", "only", "with", "local", "references", "that", "points", "on", "definitions", "object" ]
0c448d7939c9021dd66f54e5f9f1697153bbc570
https://github.com/trilogy-group/ignite-chute-opensource-json-schema-defaults/blob/0c448d7939c9021dd66f54e5f9f1697153bbc570/lib/defaults.js#L78-L98
18,530
trilogy-group/ignite-chute-opensource-json-schema-defaults
lib/defaults.js
function(schema, definitions) { if (typeof schema['default'] !== 'undefined') { return schema['default']; } else if (typeof schema.allOf !== 'undefined') { var mergedItem = mergeAllOf(schema.allOf, definitions); return defaults(mergedItem, definitions); } else if (typeof schema.$ref !== 'undefined') { var reference = getLocalRef(schema.$ref, definitions); return defaults(reference, definitions); } else if (schema.type === 'object') { if (!schema.properties) { return {}; } for (var key in schema.properties) { if (schema.properties.hasOwnProperty(key)) { schema.properties[key] = defaults(schema.properties[key], definitions); if (typeof schema.properties[key] === 'undefined') { delete schema.properties[key]; } } } return schema.properties; } else if (schema.type === 'array') { if (!schema.items) { return []; } // minimum item count var ct = schema.minItems || 0; // tuple-typed arrays if (schema.items.constructor === Array) { var values = schema.items.map(function (item) { return defaults(item, definitions); }); // remove undefined items at the end (unless required by minItems) for (var i = values.length - 1; i >= 0; i--) { if (typeof values[i] !== 'undefined') { break; } if (i + 1 > ct) { values.pop(); } } return values; } // object-typed arrays var value = defaults(schema.items, definitions); if (typeof value === 'undefined') { return []; } else { var values = []; for (var i = 0; i < Math.max(1, ct); i++) { values.push(cloneJSON(value)); } return values; } } }
javascript
function(schema, definitions) { if (typeof schema['default'] !== 'undefined') { return schema['default']; } else if (typeof schema.allOf !== 'undefined') { var mergedItem = mergeAllOf(schema.allOf, definitions); return defaults(mergedItem, definitions); } else if (typeof schema.$ref !== 'undefined') { var reference = getLocalRef(schema.$ref, definitions); return defaults(reference, definitions); } else if (schema.type === 'object') { if (!schema.properties) { return {}; } for (var key in schema.properties) { if (schema.properties.hasOwnProperty(key)) { schema.properties[key] = defaults(schema.properties[key], definitions); if (typeof schema.properties[key] === 'undefined') { delete schema.properties[key]; } } } return schema.properties; } else if (schema.type === 'array') { if (!schema.items) { return []; } // minimum item count var ct = schema.minItems || 0; // tuple-typed arrays if (schema.items.constructor === Array) { var values = schema.items.map(function (item) { return defaults(item, definitions); }); // remove undefined items at the end (unless required by minItems) for (var i = values.length - 1; i >= 0; i--) { if (typeof values[i] !== 'undefined') { break; } if (i + 1 > ct) { values.pop(); } } return values; } // object-typed arrays var value = defaults(schema.items, definitions); if (typeof value === 'undefined') { return []; } else { var values = []; for (var i = 0; i < Math.max(1, ct); i++) { values.push(cloneJSON(value)); } return values; } } }
[ "function", "(", "schema", ",", "definitions", ")", "{", "if", "(", "typeof", "schema", "[", "'default'", "]", "!==", "'undefined'", ")", "{", "return", "schema", "[", "'default'", "]", ";", "}", "else", "if", "(", "typeof", "schema", ".", "allOf", "!==", "'undefined'", ")", "{", "var", "mergedItem", "=", "mergeAllOf", "(", "schema", ".", "allOf", ",", "definitions", ")", ";", "return", "defaults", "(", "mergedItem", ",", "definitions", ")", ";", "}", "else", "if", "(", "typeof", "schema", ".", "$ref", "!==", "'undefined'", ")", "{", "var", "reference", "=", "getLocalRef", "(", "schema", ".", "$ref", ",", "definitions", ")", ";", "return", "defaults", "(", "reference", ",", "definitions", ")", ";", "}", "else", "if", "(", "schema", ".", "type", "===", "'object'", ")", "{", "if", "(", "!", "schema", ".", "properties", ")", "{", "return", "{", "}", ";", "}", "for", "(", "var", "key", "in", "schema", ".", "properties", ")", "{", "if", "(", "schema", ".", "properties", ".", "hasOwnProperty", "(", "key", ")", ")", "{", "schema", ".", "properties", "[", "key", "]", "=", "defaults", "(", "schema", ".", "properties", "[", "key", "]", ",", "definitions", ")", ";", "if", "(", "typeof", "schema", ".", "properties", "[", "key", "]", "===", "'undefined'", ")", "{", "delete", "schema", ".", "properties", "[", "key", "]", ";", "}", "}", "}", "return", "schema", ".", "properties", ";", "}", "else", "if", "(", "schema", ".", "type", "===", "'array'", ")", "{", "if", "(", "!", "schema", ".", "items", ")", "{", "return", "[", "]", ";", "}", "// minimum item count", "var", "ct", "=", "schema", ".", "minItems", "||", "0", ";", "// tuple-typed arrays", "if", "(", "schema", ".", "items", ".", "constructor", "===", "Array", ")", "{", "var", "values", "=", "schema", ".", "items", ".", "map", "(", "function", "(", "item", ")", "{", "return", "defaults", "(", "item", ",", "definitions", ")", ";", "}", ")", ";", "// remove undefined items at the end (unless required by minItems)", "for", "(", "var", "i", "=", "values", ".", "length", "-", "1", ";", "i", ">=", "0", ";", "i", "--", ")", "{", "if", "(", "typeof", "values", "[", "i", "]", "!==", "'undefined'", ")", "{", "break", ";", "}", "if", "(", "i", "+", "1", ">", "ct", ")", "{", "values", ".", "pop", "(", ")", ";", "}", "}", "return", "values", ";", "}", "// object-typed arrays", "var", "value", "=", "defaults", "(", "schema", ".", "items", ",", "definitions", ")", ";", "if", "(", "typeof", "value", "===", "'undefined'", ")", "{", "return", "[", "]", ";", "}", "else", "{", "var", "values", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "Math", ".", "max", "(", "1", ",", "ct", ")", ";", "i", "++", ")", "{", "values", ".", "push", "(", "cloneJSON", "(", "value", ")", ")", ";", "}", "return", "values", ";", "}", "}", "}" ]
returns a object that built with default values from json schema @param {Object} schema @param {Object} definitions @return {Object}
[ "returns", "a", "object", "that", "built", "with", "default", "values", "from", "json", "schema" ]
0c448d7939c9021dd66f54e5f9f1697153bbc570
https://github.com/trilogy-group/ignite-chute-opensource-json-schema-defaults/blob/0c448d7939c9021dd66f54e5f9f1697153bbc570/lib/defaults.js#L133-L201
18,531
wooorm/lowlight
lib/core.js
highlight
function highlight(language, value, options) { var settings = options || {} var prefix = settings.prefix if (prefix === null || prefix === undefined) { prefix = defaultPrefix } return normalize(coreHighlight(language, value, true, prefix)) }
javascript
function highlight(language, value, options) { var settings = options || {} var prefix = settings.prefix if (prefix === null || prefix === undefined) { prefix = defaultPrefix } return normalize(coreHighlight(language, value, true, prefix)) }
[ "function", "highlight", "(", "language", ",", "value", ",", "options", ")", "{", "var", "settings", "=", "options", "||", "{", "}", "var", "prefix", "=", "settings", ".", "prefix", "if", "(", "prefix", "===", "null", "||", "prefix", "===", "undefined", ")", "{", "prefix", "=", "defaultPrefix", "}", "return", "normalize", "(", "coreHighlight", "(", "language", ",", "value", ",", "true", ",", "prefix", ")", ")", "}" ]
Highlighting `value` in the language `language`.
[ "Highlighting", "value", "in", "the", "language", "language", "." ]
2eea3acec5882038908d37d6abd5ad9ca351b65c
https://github.com/wooorm/lowlight/blob/2eea3acec5882038908d37d6abd5ad9ca351b65c/lib/core.js#L100-L109
18,532
wooorm/lowlight
lib/core.js
registerLanguage
function registerLanguage(name, syntax) { var lang = syntax(low) languages[name] = lang languageNames.push(name) if (lang.aliases) { registerAlias(name, lang.aliases) } }
javascript
function registerLanguage(name, syntax) { var lang = syntax(low) languages[name] = lang languageNames.push(name) if (lang.aliases) { registerAlias(name, lang.aliases) } }
[ "function", "registerLanguage", "(", "name", ",", "syntax", ")", "{", "var", "lang", "=", "syntax", "(", "low", ")", "languages", "[", "name", "]", "=", "lang", "languageNames", ".", "push", "(", "name", ")", "if", "(", "lang", ".", "aliases", ")", "{", "registerAlias", "(", "name", ",", "lang", ".", "aliases", ")", "}", "}" ]
Register a language.
[ "Register", "a", "language", "." ]
2eea3acec5882038908d37d6abd5ad9ca351b65c
https://github.com/wooorm/lowlight/blob/2eea3acec5882038908d37d6abd5ad9ca351b65c/lib/core.js#L112-L122
18,533
wooorm/lowlight
lib/core.js
registerAlias
function registerAlias(name, alias) { var map = name var key var list var length var index if (alias) { map = {} map[name] = alias } for (key in map) { list = map[key] list = typeof list === 'string' ? [list] : list length = list.length index = -1 while (++index < length) { aliases[list[index]] = key } } }
javascript
function registerAlias(name, alias) { var map = name var key var list var length var index if (alias) { map = {} map[name] = alias } for (key in map) { list = map[key] list = typeof list === 'string' ? [list] : list length = list.length index = -1 while (++index < length) { aliases[list[index]] = key } } }
[ "function", "registerAlias", "(", "name", ",", "alias", ")", "{", "var", "map", "=", "name", "var", "key", "var", "list", "var", "length", "var", "index", "if", "(", "alias", ")", "{", "map", "=", "{", "}", "map", "[", "name", "]", "=", "alias", "}", "for", "(", "key", "in", "map", ")", "{", "list", "=", "map", "[", "key", "]", "list", "=", "typeof", "list", "===", "'string'", "?", "[", "list", "]", ":", "list", "length", "=", "list", ".", "length", "index", "=", "-", "1", "while", "(", "++", "index", "<", "length", ")", "{", "aliases", "[", "list", "[", "index", "]", "]", "=", "key", "}", "}", "}" ]
Register more aliases for an already registered language.
[ "Register", "more", "aliases", "for", "an", "already", "registered", "language", "." ]
2eea3acec5882038908d37d6abd5ad9ca351b65c
https://github.com/wooorm/lowlight/blob/2eea3acec5882038908d37d6abd5ad9ca351b65c/lib/core.js#L130-L152
18,534
wooorm/lowlight
lib/core.js
processLexeme
function processLexeme(buffer, lexeme) { var newMode var endMode var origin modeBuffer += buffer if (lexeme === undefined) { addSiblings(processBuffer(), currentChildren) return 0 } newMode = subMode(lexeme, top) if (newMode) { addSiblings(processBuffer(), currentChildren) startNewMode(newMode, lexeme) return newMode.returnBegin ? 0 : lexeme.length } endMode = endOfMode(top, lexeme) if (endMode) { origin = top if (!(origin.returnEnd || origin.excludeEnd)) { modeBuffer += lexeme } addSiblings(processBuffer(), currentChildren) // Close open modes. do { if (top.className) { pop() } relevance += top.relevance top = top.parent } while (top !== endMode.parent) if (origin.excludeEnd) { addText(lexeme, currentChildren) } modeBuffer = '' if (endMode.starts) { startNewMode(endMode.starts, '') } return origin.returnEnd ? 0 : lexeme.length } if (isIllegal(lexeme, top)) { throw fault( 'Illegal lexeme "%s" for mode "%s"', lexeme, top.className || '<unnamed>' ) } // Parser should not reach this point as all types of lexemes should be // caught earlier, but if it does due to some bug make sure it advances // at least one character forward to prevent infinite looping. modeBuffer += lexeme return lexeme.length || /* istanbul ignore next */ 1 }
javascript
function processLexeme(buffer, lexeme) { var newMode var endMode var origin modeBuffer += buffer if (lexeme === undefined) { addSiblings(processBuffer(), currentChildren) return 0 } newMode = subMode(lexeme, top) if (newMode) { addSiblings(processBuffer(), currentChildren) startNewMode(newMode, lexeme) return newMode.returnBegin ? 0 : lexeme.length } endMode = endOfMode(top, lexeme) if (endMode) { origin = top if (!(origin.returnEnd || origin.excludeEnd)) { modeBuffer += lexeme } addSiblings(processBuffer(), currentChildren) // Close open modes. do { if (top.className) { pop() } relevance += top.relevance top = top.parent } while (top !== endMode.parent) if (origin.excludeEnd) { addText(lexeme, currentChildren) } modeBuffer = '' if (endMode.starts) { startNewMode(endMode.starts, '') } return origin.returnEnd ? 0 : lexeme.length } if (isIllegal(lexeme, top)) { throw fault( 'Illegal lexeme "%s" for mode "%s"', lexeme, top.className || '<unnamed>' ) } // Parser should not reach this point as all types of lexemes should be // caught earlier, but if it does due to some bug make sure it advances // at least one character forward to prevent infinite looping. modeBuffer += lexeme return lexeme.length || /* istanbul ignore next */ 1 }
[ "function", "processLexeme", "(", "buffer", ",", "lexeme", ")", "{", "var", "newMode", "var", "endMode", "var", "origin", "modeBuffer", "+=", "buffer", "if", "(", "lexeme", "===", "undefined", ")", "{", "addSiblings", "(", "processBuffer", "(", ")", ",", "currentChildren", ")", "return", "0", "}", "newMode", "=", "subMode", "(", "lexeme", ",", "top", ")", "if", "(", "newMode", ")", "{", "addSiblings", "(", "processBuffer", "(", ")", ",", "currentChildren", ")", "startNewMode", "(", "newMode", ",", "lexeme", ")", "return", "newMode", ".", "returnBegin", "?", "0", ":", "lexeme", ".", "length", "}", "endMode", "=", "endOfMode", "(", "top", ",", "lexeme", ")", "if", "(", "endMode", ")", "{", "origin", "=", "top", "if", "(", "!", "(", "origin", ".", "returnEnd", "||", "origin", ".", "excludeEnd", ")", ")", "{", "modeBuffer", "+=", "lexeme", "}", "addSiblings", "(", "processBuffer", "(", ")", ",", "currentChildren", ")", "// Close open modes.", "do", "{", "if", "(", "top", ".", "className", ")", "{", "pop", "(", ")", "}", "relevance", "+=", "top", ".", "relevance", "top", "=", "top", ".", "parent", "}", "while", "(", "top", "!==", "endMode", ".", "parent", ")", "if", "(", "origin", ".", "excludeEnd", ")", "{", "addText", "(", "lexeme", ",", "currentChildren", ")", "}", "modeBuffer", "=", "''", "if", "(", "endMode", ".", "starts", ")", "{", "startNewMode", "(", "endMode", ".", "starts", ",", "''", ")", "}", "return", "origin", ".", "returnEnd", "?", "0", ":", "lexeme", ".", "length", "}", "if", "(", "isIllegal", "(", "lexeme", ",", "top", ")", ")", "{", "throw", "fault", "(", "'Illegal lexeme \"%s\" for mode \"%s\"'", ",", "lexeme", ",", "top", ".", "className", "||", "'<unnamed>'", ")", "}", "// Parser should not reach this point as all types of lexemes should be", "// caught earlier, but if it does due to some bug make sure it advances", "// at least one character forward to prevent infinite looping.", "modeBuffer", "+=", "lexeme", "return", "lexeme", ".", "length", "||", "/* istanbul ignore next */", "1", "}" ]
Process a lexeme. Returns next position.
[ "Process", "a", "lexeme", ".", "Returns", "next", "position", "." ]
2eea3acec5882038908d37d6abd5ad9ca351b65c
https://github.com/wooorm/lowlight/blob/2eea3acec5882038908d37d6abd5ad9ca351b65c/lib/core.js#L231-L302
18,535
wooorm/lowlight
lib/core.js
startNewMode
function startNewMode(mode, lexeme) { var node if (mode.className) { node = build(mode.className, []) } if (mode.returnBegin) { modeBuffer = '' } else if (mode.excludeBegin) { addText(lexeme, currentChildren) modeBuffer = '' } else { modeBuffer = lexeme } // Enter a new mode. if (node) { currentChildren.push(node) stack.push(currentChildren) currentChildren = node.children } top = Object.create(mode, {parent: {value: top}}) }
javascript
function startNewMode(mode, lexeme) { var node if (mode.className) { node = build(mode.className, []) } if (mode.returnBegin) { modeBuffer = '' } else if (mode.excludeBegin) { addText(lexeme, currentChildren) modeBuffer = '' } else { modeBuffer = lexeme } // Enter a new mode. if (node) { currentChildren.push(node) stack.push(currentChildren) currentChildren = node.children } top = Object.create(mode, {parent: {value: top}}) }
[ "function", "startNewMode", "(", "mode", ",", "lexeme", ")", "{", "var", "node", "if", "(", "mode", ".", "className", ")", "{", "node", "=", "build", "(", "mode", ".", "className", ",", "[", "]", ")", "}", "if", "(", "mode", ".", "returnBegin", ")", "{", "modeBuffer", "=", "''", "}", "else", "if", "(", "mode", ".", "excludeBegin", ")", "{", "addText", "(", "lexeme", ",", "currentChildren", ")", "modeBuffer", "=", "''", "}", "else", "{", "modeBuffer", "=", "lexeme", "}", "// Enter a new mode.", "if", "(", "node", ")", "{", "currentChildren", ".", "push", "(", "node", ")", "stack", ".", "push", "(", "currentChildren", ")", "currentChildren", "=", "node", ".", "children", "}", "top", "=", "Object", ".", "create", "(", "mode", ",", "{", "parent", ":", "{", "value", ":", "top", "}", "}", ")", "}" ]
Start a new mode with a `lexeme` to process.
[ "Start", "a", "new", "mode", "with", "a", "lexeme", "to", "process", "." ]
2eea3acec5882038908d37d6abd5ad9ca351b65c
https://github.com/wooorm/lowlight/blob/2eea3acec5882038908d37d6abd5ad9ca351b65c/lib/core.js#L305-L330
18,536
wooorm/lowlight
lib/core.js
processKeywords
function processKeywords() { var nodes = [] var lastIndex var keyword var node var submatch if (!top.keywords) { return addText(modeBuffer, nodes) } lastIndex = 0 top.lexemesRe.lastIndex = 0 keyword = top.lexemesRe.exec(modeBuffer) while (keyword) { addText(modeBuffer.substring(lastIndex, keyword.index), nodes) submatch = keywordMatch(top, keyword) if (submatch) { relevance += submatch[1] node = build(submatch[0], []) nodes.push(node) addText(keyword[0], node.children) } else { addText(keyword[0], nodes) } lastIndex = top.lexemesRe.lastIndex keyword = top.lexemesRe.exec(modeBuffer) } addText(modeBuffer.substr(lastIndex), nodes) return nodes }
javascript
function processKeywords() { var nodes = [] var lastIndex var keyword var node var submatch if (!top.keywords) { return addText(modeBuffer, nodes) } lastIndex = 0 top.lexemesRe.lastIndex = 0 keyword = top.lexemesRe.exec(modeBuffer) while (keyword) { addText(modeBuffer.substring(lastIndex, keyword.index), nodes) submatch = keywordMatch(top, keyword) if (submatch) { relevance += submatch[1] node = build(submatch[0], []) nodes.push(node) addText(keyword[0], node.children) } else { addText(keyword[0], nodes) } lastIndex = top.lexemesRe.lastIndex keyword = top.lexemesRe.exec(modeBuffer) } addText(modeBuffer.substr(lastIndex), nodes) return nodes }
[ "function", "processKeywords", "(", ")", "{", "var", "nodes", "=", "[", "]", "var", "lastIndex", "var", "keyword", "var", "node", "var", "submatch", "if", "(", "!", "top", ".", "keywords", ")", "{", "return", "addText", "(", "modeBuffer", ",", "nodes", ")", "}", "lastIndex", "=", "0", "top", ".", "lexemesRe", ".", "lastIndex", "=", "0", "keyword", "=", "top", ".", "lexemesRe", ".", "exec", "(", "modeBuffer", ")", "while", "(", "keyword", ")", "{", "addText", "(", "modeBuffer", ".", "substring", "(", "lastIndex", ",", "keyword", ".", "index", ")", ",", "nodes", ")", "submatch", "=", "keywordMatch", "(", "top", ",", "keyword", ")", "if", "(", "submatch", ")", "{", "relevance", "+=", "submatch", "[", "1", "]", "node", "=", "build", "(", "submatch", "[", "0", "]", ",", "[", "]", ")", "nodes", ".", "push", "(", "node", ")", "addText", "(", "keyword", "[", "0", "]", ",", "node", ".", "children", ")", "}", "else", "{", "addText", "(", "keyword", "[", "0", "]", ",", "nodes", ")", "}", "lastIndex", "=", "top", ".", "lexemesRe", ".", "lastIndex", "keyword", "=", "top", ".", "lexemesRe", ".", "exec", "(", "modeBuffer", ")", "}", "addText", "(", "modeBuffer", ".", "substr", "(", "lastIndex", ")", ",", "nodes", ")", "return", "nodes", "}" ]
Process keywords. Returns nodes.
[ "Process", "keywords", ".", "Returns", "nodes", "." ]
2eea3acec5882038908d37d6abd5ad9ca351b65c
https://github.com/wooorm/lowlight/blob/2eea3acec5882038908d37d6abd5ad9ca351b65c/lib/core.js#L380-L421
18,537
wooorm/lowlight
lib/core.js
addSiblings
function addSiblings(siblings, nodes) { var length = siblings.length var index = -1 var sibling while (++index < length) { sibling = siblings[index] if (sibling.type === 'text') { addText(sibling.value, nodes) } else { nodes.push(sibling) } } }
javascript
function addSiblings(siblings, nodes) { var length = siblings.length var index = -1 var sibling while (++index < length) { sibling = siblings[index] if (sibling.type === 'text') { addText(sibling.value, nodes) } else { nodes.push(sibling) } } }
[ "function", "addSiblings", "(", "siblings", ",", "nodes", ")", "{", "var", "length", "=", "siblings", ".", "length", "var", "index", "=", "-", "1", "var", "sibling", "while", "(", "++", "index", "<", "length", ")", "{", "sibling", "=", "siblings", "[", "index", "]", "if", "(", "sibling", ".", "type", "===", "'text'", ")", "{", "addText", "(", "sibling", ".", "value", ",", "nodes", ")", "}", "else", "{", "nodes", ".", "push", "(", "sibling", ")", "}", "}", "}" ]
Add siblings.
[ "Add", "siblings", "." ]
2eea3acec5882038908d37d6abd5ad9ca351b65c
https://github.com/wooorm/lowlight/blob/2eea3acec5882038908d37d6abd5ad9ca351b65c/lib/core.js#L424-L438
18,538
wooorm/lowlight
lib/core.js
addText
function addText(value, nodes) { var tail if (value) { tail = nodes[nodes.length - 1] if (tail && tail.type === 'text') { tail.value += value } else { nodes.push(buildText(value)) } } return nodes }
javascript
function addText(value, nodes) { var tail if (value) { tail = nodes[nodes.length - 1] if (tail && tail.type === 'text') { tail.value += value } else { nodes.push(buildText(value)) } } return nodes }
[ "function", "addText", "(", "value", ",", "nodes", ")", "{", "var", "tail", "if", "(", "value", ")", "{", "tail", "=", "nodes", "[", "nodes", ".", "length", "-", "1", "]", "if", "(", "tail", "&&", "tail", ".", "type", "===", "'text'", ")", "{", "tail", ".", "value", "+=", "value", "}", "else", "{", "nodes", ".", "push", "(", "buildText", "(", "value", ")", ")", "}", "}", "return", "nodes", "}" ]
Add a text.
[ "Add", "a", "text", "." ]
2eea3acec5882038908d37d6abd5ad9ca351b65c
https://github.com/wooorm/lowlight/blob/2eea3acec5882038908d37d6abd5ad9ca351b65c/lib/core.js#L441-L455
18,539
wooorm/lowlight
lib/core.js
build
function build(name, contents, noPrefix) { return { type: 'element', tagName: 'span', properties: { className: [(noPrefix ? '' : prefix) + name] }, children: contents } }
javascript
function build(name, contents, noPrefix) { return { type: 'element', tagName: 'span', properties: { className: [(noPrefix ? '' : prefix) + name] }, children: contents } }
[ "function", "build", "(", "name", ",", "contents", ",", "noPrefix", ")", "{", "return", "{", "type", ":", "'element'", ",", "tagName", ":", "'span'", ",", "properties", ":", "{", "className", ":", "[", "(", "noPrefix", "?", "''", ":", "prefix", ")", "+", "name", "]", "}", ",", "children", ":", "contents", "}", "}" ]
Build a span.
[ "Build", "a", "span", "." ]
2eea3acec5882038908d37d6abd5ad9ca351b65c
https://github.com/wooorm/lowlight/blob/2eea3acec5882038908d37d6abd5ad9ca351b65c/lib/core.js#L463-L472
18,540
wooorm/lowlight
lib/core.js
keywordMatch
function keywordMatch(mode, keywords) { var keyword = keywords[0] if (language[keyInsensitive]) { keyword = keyword.toLowerCase() } return own.call(mode.keywords, keyword) && mode.keywords[keyword] }
javascript
function keywordMatch(mode, keywords) { var keyword = keywords[0] if (language[keyInsensitive]) { keyword = keyword.toLowerCase() } return own.call(mode.keywords, keyword) && mode.keywords[keyword] }
[ "function", "keywordMatch", "(", "mode", ",", "keywords", ")", "{", "var", "keyword", "=", "keywords", "[", "0", "]", "if", "(", "language", "[", "keyInsensitive", "]", ")", "{", "keyword", "=", "keyword", ".", "toLowerCase", "(", ")", "}", "return", "own", ".", "call", "(", "mode", ".", "keywords", ",", "keyword", ")", "&&", "mode", ".", "keywords", "[", "keyword", "]", "}" ]
Check if the first word in `keywords` is a keyword.
[ "Check", "if", "the", "first", "word", "in", "keywords", "is", "a", "keyword", "." ]
2eea3acec5882038908d37d6abd5ad9ca351b65c
https://github.com/wooorm/lowlight/blob/2eea3acec5882038908d37d6abd5ad9ca351b65c/lib/core.js#L475-L483
18,541
wooorm/lowlight
lib/core.js
endOfMode
function endOfMode(mode, lexeme) { if (test(mode.endRe, lexeme)) { while (mode.endsParent && mode.parent) { mode = mode.parent } return mode } if (mode.endsWithParent) { return endOfMode(mode.parent, lexeme) } }
javascript
function endOfMode(mode, lexeme) { if (test(mode.endRe, lexeme)) { while (mode.endsParent && mode.parent) { mode = mode.parent } return mode } if (mode.endsWithParent) { return endOfMode(mode.parent, lexeme) } }
[ "function", "endOfMode", "(", "mode", ",", "lexeme", ")", "{", "if", "(", "test", "(", "mode", ".", "endRe", ",", "lexeme", ")", ")", "{", "while", "(", "mode", ".", "endsParent", "&&", "mode", ".", "parent", ")", "{", "mode", "=", "mode", ".", "parent", "}", "return", "mode", "}", "if", "(", "mode", ".", "endsWithParent", ")", "{", "return", "endOfMode", "(", "mode", ".", "parent", ",", "lexeme", ")", "}", "}" ]
Check if `lexeme` ends `mode`.
[ "Check", "if", "lexeme", "ends", "mode", "." ]
2eea3acec5882038908d37d6abd5ad9ca351b65c
https://github.com/wooorm/lowlight/blob/2eea3acec5882038908d37d6abd5ad9ca351b65c/lib/core.js#L491-L503
18,542
wooorm/lowlight
lib/core.js
subMode
function subMode(lexeme, mode) { var values = mode.contains var length = values.length var index = -1 while (++index < length) { if (test(values[index].beginRe, lexeme)) { return values[index] } } }
javascript
function subMode(lexeme, mode) { var values = mode.contains var length = values.length var index = -1 while (++index < length) { if (test(values[index].beginRe, lexeme)) { return values[index] } } }
[ "function", "subMode", "(", "lexeme", ",", "mode", ")", "{", "var", "values", "=", "mode", ".", "contains", "var", "length", "=", "values", ".", "length", "var", "index", "=", "-", "1", "while", "(", "++", "index", "<", "length", ")", "{", "if", "(", "test", "(", "values", "[", "index", "]", ".", "beginRe", ",", "lexeme", ")", ")", "{", "return", "values", "[", "index", "]", "}", "}", "}" ]
Check a sub-mode.
[ "Check", "a", "sub", "-", "mode", "." ]
2eea3acec5882038908d37d6abd5ad9ca351b65c
https://github.com/wooorm/lowlight/blob/2eea3acec5882038908d37d6abd5ad9ca351b65c/lib/core.js#L506-L516
18,543
wooorm/lowlight
lib/core.js
compileLanguage
function compileLanguage(language) { compileMode(language) // Compile a language mode, optionally with a parent. function compileMode(mode, parent) { var compiledKeywords = {} var terminators if (mode.compiled) { return } mode.compiled = true mode.keywords = mode.keywords || mode.beginKeywords if (mode.keywords) { if (typeof mode.keywords === 'string') { flatten('keyword', mode.keywords) } else { Object.keys(mode.keywords).forEach(function(className) { flatten(className, mode.keywords[className]) }) } mode.keywords = compiledKeywords } mode.lexemesRe = langRe(mode.lexemes || /\w+/, true) if (parent) { if (mode.beginKeywords) { mode.begin = '\\b(' + mode.beginKeywords.split(space).join(verticalBar) + ')\\b' } if (!mode.begin) { mode.begin = /\B|\b/ } mode.beginRe = langRe(mode.begin) if (!mode.end && !mode.endsWithParent) { mode.end = /\B|\b/ } if (mode.end) { mode.endRe = langRe(mode.end) } mode.terminatorEnd = source(mode.end) || '' if (mode.endsWithParent && parent.terminatorEnd) { mode.terminatorEnd += (mode.end ? verticalBar : '') + parent.terminatorEnd } } if (mode.illegal) { mode.illegalRe = langRe(mode.illegal) } if (mode.relevance === undefined) { mode.relevance = 1 } if (!mode.contains) { mode.contains = [] } mode.contains = concat.apply( [], mode.contains.map(function(c) { return expandMode(c === 'self' ? mode : c) }) ) mode.contains.forEach(function(c) { compileMode(c, mode) }) if (mode.starts) { compileMode(mode.starts, parent) } terminators = mode.contains .map(map) .concat([mode.terminatorEnd, mode.illegal]) .map(source) .filter(Boolean) mode.terminators = terminators.length === 0 ? {exec: execNoop} : langRe(terminators.join(verticalBar), true) function map(c) { return c.beginKeywords ? '\\.?(' + c.begin + ')\\.?' : c.begin } // Flatten a classname. function flatten(className, value) { var pairs var pair var index var length if (language[keyInsensitive]) { value = value.toLowerCase() } pairs = value.split(space) length = pairs.length index = -1 while (++index < length) { pair = pairs[index].split(verticalBar) compiledKeywords[pair[0]] = [className, pair[1] ? Number(pair[1]) : 1] } } } // Create a regex for `value`. function langRe(value, global) { return new RegExp( source(value), 'm' + (language[keyInsensitive] ? 'i' : '') + (global ? 'g' : '') ) } // Get the source of an expression or string. function source(re) { return (re && re.source) || re } }
javascript
function compileLanguage(language) { compileMode(language) // Compile a language mode, optionally with a parent. function compileMode(mode, parent) { var compiledKeywords = {} var terminators if (mode.compiled) { return } mode.compiled = true mode.keywords = mode.keywords || mode.beginKeywords if (mode.keywords) { if (typeof mode.keywords === 'string') { flatten('keyword', mode.keywords) } else { Object.keys(mode.keywords).forEach(function(className) { flatten(className, mode.keywords[className]) }) } mode.keywords = compiledKeywords } mode.lexemesRe = langRe(mode.lexemes || /\w+/, true) if (parent) { if (mode.beginKeywords) { mode.begin = '\\b(' + mode.beginKeywords.split(space).join(verticalBar) + ')\\b' } if (!mode.begin) { mode.begin = /\B|\b/ } mode.beginRe = langRe(mode.begin) if (!mode.end && !mode.endsWithParent) { mode.end = /\B|\b/ } if (mode.end) { mode.endRe = langRe(mode.end) } mode.terminatorEnd = source(mode.end) || '' if (mode.endsWithParent && parent.terminatorEnd) { mode.terminatorEnd += (mode.end ? verticalBar : '') + parent.terminatorEnd } } if (mode.illegal) { mode.illegalRe = langRe(mode.illegal) } if (mode.relevance === undefined) { mode.relevance = 1 } if (!mode.contains) { mode.contains = [] } mode.contains = concat.apply( [], mode.contains.map(function(c) { return expandMode(c === 'self' ? mode : c) }) ) mode.contains.forEach(function(c) { compileMode(c, mode) }) if (mode.starts) { compileMode(mode.starts, parent) } terminators = mode.contains .map(map) .concat([mode.terminatorEnd, mode.illegal]) .map(source) .filter(Boolean) mode.terminators = terminators.length === 0 ? {exec: execNoop} : langRe(terminators.join(verticalBar), true) function map(c) { return c.beginKeywords ? '\\.?(' + c.begin + ')\\.?' : c.begin } // Flatten a classname. function flatten(className, value) { var pairs var pair var index var length if (language[keyInsensitive]) { value = value.toLowerCase() } pairs = value.split(space) length = pairs.length index = -1 while (++index < length) { pair = pairs[index].split(verticalBar) compiledKeywords[pair[0]] = [className, pair[1] ? Number(pair[1]) : 1] } } } // Create a regex for `value`. function langRe(value, global) { return new RegExp( source(value), 'm' + (language[keyInsensitive] ? 'i' : '') + (global ? 'g' : '') ) } // Get the source of an expression or string. function source(re) { return (re && re.source) || re } }
[ "function", "compileLanguage", "(", "language", ")", "{", "compileMode", "(", "language", ")", "// Compile a language mode, optionally with a parent.", "function", "compileMode", "(", "mode", ",", "parent", ")", "{", "var", "compiledKeywords", "=", "{", "}", "var", "terminators", "if", "(", "mode", ".", "compiled", ")", "{", "return", "}", "mode", ".", "compiled", "=", "true", "mode", ".", "keywords", "=", "mode", ".", "keywords", "||", "mode", ".", "beginKeywords", "if", "(", "mode", ".", "keywords", ")", "{", "if", "(", "typeof", "mode", ".", "keywords", "===", "'string'", ")", "{", "flatten", "(", "'keyword'", ",", "mode", ".", "keywords", ")", "}", "else", "{", "Object", ".", "keys", "(", "mode", ".", "keywords", ")", ".", "forEach", "(", "function", "(", "className", ")", "{", "flatten", "(", "className", ",", "mode", ".", "keywords", "[", "className", "]", ")", "}", ")", "}", "mode", ".", "keywords", "=", "compiledKeywords", "}", "mode", ".", "lexemesRe", "=", "langRe", "(", "mode", ".", "lexemes", "||", "/", "\\w+", "/", ",", "true", ")", "if", "(", "parent", ")", "{", "if", "(", "mode", ".", "beginKeywords", ")", "{", "mode", ".", "begin", "=", "'\\\\b('", "+", "mode", ".", "beginKeywords", ".", "split", "(", "space", ")", ".", "join", "(", "verticalBar", ")", "+", "')\\\\b'", "}", "if", "(", "!", "mode", ".", "begin", ")", "{", "mode", ".", "begin", "=", "/", "\\B|\\b", "/", "}", "mode", ".", "beginRe", "=", "langRe", "(", "mode", ".", "begin", ")", "if", "(", "!", "mode", ".", "end", "&&", "!", "mode", ".", "endsWithParent", ")", "{", "mode", ".", "end", "=", "/", "\\B|\\b", "/", "}", "if", "(", "mode", ".", "end", ")", "{", "mode", ".", "endRe", "=", "langRe", "(", "mode", ".", "end", ")", "}", "mode", ".", "terminatorEnd", "=", "source", "(", "mode", ".", "end", ")", "||", "''", "if", "(", "mode", ".", "endsWithParent", "&&", "parent", ".", "terminatorEnd", ")", "{", "mode", ".", "terminatorEnd", "+=", "(", "mode", ".", "end", "?", "verticalBar", ":", "''", ")", "+", "parent", ".", "terminatorEnd", "}", "}", "if", "(", "mode", ".", "illegal", ")", "{", "mode", ".", "illegalRe", "=", "langRe", "(", "mode", ".", "illegal", ")", "}", "if", "(", "mode", ".", "relevance", "===", "undefined", ")", "{", "mode", ".", "relevance", "=", "1", "}", "if", "(", "!", "mode", ".", "contains", ")", "{", "mode", ".", "contains", "=", "[", "]", "}", "mode", ".", "contains", "=", "concat", ".", "apply", "(", "[", "]", ",", "mode", ".", "contains", ".", "map", "(", "function", "(", "c", ")", "{", "return", "expandMode", "(", "c", "===", "'self'", "?", "mode", ":", "c", ")", "}", ")", ")", "mode", ".", "contains", ".", "forEach", "(", "function", "(", "c", ")", "{", "compileMode", "(", "c", ",", "mode", ")", "}", ")", "if", "(", "mode", ".", "starts", ")", "{", "compileMode", "(", "mode", ".", "starts", ",", "parent", ")", "}", "terminators", "=", "mode", ".", "contains", ".", "map", "(", "map", ")", ".", "concat", "(", "[", "mode", ".", "terminatorEnd", ",", "mode", ".", "illegal", "]", ")", ".", "map", "(", "source", ")", ".", "filter", "(", "Boolean", ")", "mode", ".", "terminators", "=", "terminators", ".", "length", "===", "0", "?", "{", "exec", ":", "execNoop", "}", ":", "langRe", "(", "terminators", ".", "join", "(", "verticalBar", ")", ",", "true", ")", "function", "map", "(", "c", ")", "{", "return", "c", ".", "beginKeywords", "?", "'\\\\.?('", "+", "c", ".", "begin", "+", "')\\\\.?'", ":", "c", ".", "begin", "}", "// Flatten a classname.", "function", "flatten", "(", "className", ",", "value", ")", "{", "var", "pairs", "var", "pair", "var", "index", "var", "length", "if", "(", "language", "[", "keyInsensitive", "]", ")", "{", "value", "=", "value", ".", "toLowerCase", "(", ")", "}", "pairs", "=", "value", ".", "split", "(", "space", ")", "length", "=", "pairs", ".", "length", "index", "=", "-", "1", "while", "(", "++", "index", "<", "length", ")", "{", "pair", "=", "pairs", "[", "index", "]", ".", "split", "(", "verticalBar", ")", "compiledKeywords", "[", "pair", "[", "0", "]", "]", "=", "[", "className", ",", "pair", "[", "1", "]", "?", "Number", "(", "pair", "[", "1", "]", ")", ":", "1", "]", "}", "}", "}", "// Create a regex for `value`.", "function", "langRe", "(", "value", ",", "global", ")", "{", "return", "new", "RegExp", "(", "source", "(", "value", ")", ",", "'m'", "+", "(", "language", "[", "keyInsensitive", "]", "?", "'i'", ":", "''", ")", "+", "(", "global", "?", "'g'", ":", "''", ")", ")", "}", "// Get the source of an expression or string.", "function", "source", "(", "re", ")", "{", "return", "(", "re", "&&", "re", ".", "source", ")", "||", "re", "}", "}" ]
Compile a language.
[ "Compile", "a", "language", "." ]
2eea3acec5882038908d37d6abd5ad9ca351b65c
https://github.com/wooorm/lowlight/blob/2eea3acec5882038908d37d6abd5ad9ca351b65c/lib/core.js#L550-L685
18,544
wooorm/lowlight
lib/core.js
flatten
function flatten(className, value) { var pairs var pair var index var length if (language[keyInsensitive]) { value = value.toLowerCase() } pairs = value.split(space) length = pairs.length index = -1 while (++index < length) { pair = pairs[index].split(verticalBar) compiledKeywords[pair[0]] = [className, pair[1] ? Number(pair[1]) : 1] } }
javascript
function flatten(className, value) { var pairs var pair var index var length if (language[keyInsensitive]) { value = value.toLowerCase() } pairs = value.split(space) length = pairs.length index = -1 while (++index < length) { pair = pairs[index].split(verticalBar) compiledKeywords[pair[0]] = [className, pair[1] ? Number(pair[1]) : 1] } }
[ "function", "flatten", "(", "className", ",", "value", ")", "{", "var", "pairs", "var", "pair", "var", "index", "var", "length", "if", "(", "language", "[", "keyInsensitive", "]", ")", "{", "value", "=", "value", ".", "toLowerCase", "(", ")", "}", "pairs", "=", "value", ".", "split", "(", "space", ")", "length", "=", "pairs", ".", "length", "index", "=", "-", "1", "while", "(", "++", "index", "<", "length", ")", "{", "pair", "=", "pairs", "[", "index", "]", ".", "split", "(", "verticalBar", ")", "compiledKeywords", "[", "pair", "[", "0", "]", "]", "=", "[", "className", ",", "pair", "[", "1", "]", "?", "Number", "(", "pair", "[", "1", "]", ")", ":", "1", "]", "}", "}" ]
Flatten a classname.
[ "Flatten", "a", "classname", "." ]
2eea3acec5882038908d37d6abd5ad9ca351b65c
https://github.com/wooorm/lowlight/blob/2eea3acec5882038908d37d6abd5ad9ca351b65c/lib/core.js#L651-L670
18,545
wooorm/lowlight
lib/core.js
normalize
function normalize(result) { return { relevance: result.relevance || 0, language: result.language || null, value: result.value || [] } }
javascript
function normalize(result) { return { relevance: result.relevance || 0, language: result.language || null, value: result.value || [] } }
[ "function", "normalize", "(", "result", ")", "{", "return", "{", "relevance", ":", "result", ".", "relevance", "||", "0", ",", "language", ":", "result", ".", "language", "||", "null", ",", "value", ":", "result", ".", "value", "||", "[", "]", "}", "}" ]
Normalize a syntax result.
[ "Normalize", "a", "syntax", "result", "." ]
2eea3acec5882038908d37d6abd5ad9ca351b65c
https://github.com/wooorm/lowlight/blob/2eea3acec5882038908d37d6abd5ad9ca351b65c/lib/core.js#L688-L694
18,546
rxaviers/cldrjs
build/compare-size.js
function(cache) { var tips = cache[""].tips; // Sort labels: metadata, then branch tips by first add, // then user entries by first add, then last run // Then return without metadata return Object.keys(cache) .sort(function(a, b) { var keys = Object.keys(cache); return ( (a ? 1 : 0) - (b ? 1 : 0) || (a in tips ? 0 : 1) - (b in tips ? 0 : 1) || (a.charAt(0) === " " ? 1 : 0) - (b.charAt(0) === " " ? 1 : 0) || keys.indexOf(a) - keys.indexOf(b) ); }) .slice(1); }
javascript
function(cache) { var tips = cache[""].tips; // Sort labels: metadata, then branch tips by first add, // then user entries by first add, then last run // Then return without metadata return Object.keys(cache) .sort(function(a, b) { var keys = Object.keys(cache); return ( (a ? 1 : 0) - (b ? 1 : 0) || (a in tips ? 0 : 1) - (b in tips ? 0 : 1) || (a.charAt(0) === " " ? 1 : 0) - (b.charAt(0) === " " ? 1 : 0) || keys.indexOf(a) - keys.indexOf(b) ); }) .slice(1); }
[ "function", "(", "cache", ")", "{", "var", "tips", "=", "cache", "[", "\"\"", "]", ".", "tips", ";", "// Sort labels: metadata, then branch tips by first add,\r", "// then user entries by first add, then last run\r", "// Then return without metadata\r", "return", "Object", ".", "keys", "(", "cache", ")", ".", "sort", "(", "function", "(", "a", ",", "b", ")", "{", "var", "keys", "=", "Object", ".", "keys", "(", "cache", ")", ";", "return", "(", "(", "a", "?", "1", ":", "0", ")", "-", "(", "b", "?", "1", ":", "0", ")", "||", "(", "a", "in", "tips", "?", "0", ":", "1", ")", "-", "(", "b", "in", "tips", "?", "0", ":", "1", ")", "||", "(", "a", ".", "charAt", "(", "0", ")", "===", "\" \"", "?", "1", ":", "0", ")", "-", "(", "b", ".", "charAt", "(", "0", ")", "===", "\" \"", "?", "1", ":", "0", ")", "||", "keys", ".", "indexOf", "(", "a", ")", "-", "keys", ".", "indexOf", "(", "b", ")", ")", ";", "}", ")", ".", "slice", "(", "1", ")", ";", "}" ]
Label sequence helper
[ "Label", "sequence", "helper" ]
9efaa3c9902f0a740057af40a976ec0258feaf33
https://github.com/rxaviers/cldrjs/blob/9efaa3c9902f0a740057af40a976ec0258feaf33/build/compare-size.js#L103-L121
18,547
rxaviers/cldrjs
build/compare-size.js
function(delta) { var color = "green"; if (delta > 0) { delta = "+" + delta; color = "red"; } else if (!delta) { delta = delta === 0 ? "=" : "?"; color = "grey"; } return chalk[color](delta); }
javascript
function(delta) { var color = "green"; if (delta > 0) { delta = "+" + delta; color = "red"; } else if (!delta) { delta = delta === 0 ? "=" : "?"; color = "grey"; } return chalk[color](delta); }
[ "function", "(", "delta", ")", "{", "var", "color", "=", "\"green\"", ";", "if", "(", "delta", ">", "0", ")", "{", "delta", "=", "\"+\"", "+", "delta", ";", "color", "=", "\"red\"", ";", "}", "else", "if", "(", "!", "delta", ")", "{", "delta", "=", "delta", "===", "0", "?", "\"=\"", ":", "\"?\"", ";", "color", "=", "\"grey\"", ";", "}", "return", "chalk", "[", "color", "]", "(", "delta", ")", ";", "}" ]
Color-coded size difference
[ "Color", "-", "coded", "size", "difference" ]
9efaa3c9902f0a740057af40a976ec0258feaf33
https://github.com/rxaviers/cldrjs/blob/9efaa3c9902f0a740057af40a976ec0258feaf33/build/compare-size.js#L131-L143
18,548
rxaviers/cldrjs
build/compare-size.js
function(src) { var cache; try { cache = fs.existsSync(src) ? file.readJSON(src) : undefined; } catch (e) { debug(e); } // Progressively upgrade `cache`, which is one of: // empty // {} // { file: size [,...] } // { "": { tips: { label: SHA1, ... } }, label: { file: size, ... }, ... } // { "": { version: 0.4, tips: { label: SHA1, ... } }, // label: { file: { "": size, compressor: size, ... }, ... }, ... } if (typeof cache !== "object") { cache = undefined; } if (!cache || !cache[""]) { // If promoting cache to dictionary, assume that data are for last run cache = _.zipObject(["", lastrun], [{ version: 0, tips: {} }, cache]); } if (!cache[""].version) { cache[""].version = 0.4; _.forEach(cache, function(sizes, label) { if (!label || !sizes) { return; } // If promoting sizes to dictionary, assume that compressed size data are indicated by suffixes Object.keys(sizes) .sort() .forEach(function(file) { var parts = file.split("."), prefix = parts.shift(); // Append compressed size data to a matching prefix while (parts.length) { if (typeof sizes[prefix] === "object") { sizes[prefix][parts.join(".")] = sizes[file]; delete sizes[file]; return; } prefix += "." + parts.shift(); } // Store uncompressed size data sizes[file] = { "": sizes[file] }; }); }); } return cache; }
javascript
function(src) { var cache; try { cache = fs.existsSync(src) ? file.readJSON(src) : undefined; } catch (e) { debug(e); } // Progressively upgrade `cache`, which is one of: // empty // {} // { file: size [,...] } // { "": { tips: { label: SHA1, ... } }, label: { file: size, ... }, ... } // { "": { version: 0.4, tips: { label: SHA1, ... } }, // label: { file: { "": size, compressor: size, ... }, ... }, ... } if (typeof cache !== "object") { cache = undefined; } if (!cache || !cache[""]) { // If promoting cache to dictionary, assume that data are for last run cache = _.zipObject(["", lastrun], [{ version: 0, tips: {} }, cache]); } if (!cache[""].version) { cache[""].version = 0.4; _.forEach(cache, function(sizes, label) { if (!label || !sizes) { return; } // If promoting sizes to dictionary, assume that compressed size data are indicated by suffixes Object.keys(sizes) .sort() .forEach(function(file) { var parts = file.split("."), prefix = parts.shift(); // Append compressed size data to a matching prefix while (parts.length) { if (typeof sizes[prefix] === "object") { sizes[prefix][parts.join(".")] = sizes[file]; delete sizes[file]; return; } prefix += "." + parts.shift(); } // Store uncompressed size data sizes[file] = { "": sizes[file] }; }); }); } return cache; }
[ "function", "(", "src", ")", "{", "var", "cache", ";", "try", "{", "cache", "=", "fs", ".", "existsSync", "(", "src", ")", "?", "file", ".", "readJSON", "(", "src", ")", ":", "undefined", ";", "}", "catch", "(", "e", ")", "{", "debug", "(", "e", ")", ";", "}", "// Progressively upgrade `cache`, which is one of:\r", "// empty\r", "// {}\r", "// { file: size [,...] }\r", "// { \"\": { tips: { label: SHA1, ... } }, label: { file: size, ... }, ... }\r", "// { \"\": { version: 0.4, tips: { label: SHA1, ... } },\r", "// label: { file: { \"\": size, compressor: size, ... }, ... }, ... }\r", "if", "(", "typeof", "cache", "!==", "\"object\"", ")", "{", "cache", "=", "undefined", ";", "}", "if", "(", "!", "cache", "||", "!", "cache", "[", "\"\"", "]", ")", "{", "// If promoting cache to dictionary, assume that data are for last run\r", "cache", "=", "_", ".", "zipObject", "(", "[", "\"\"", ",", "lastrun", "]", ",", "[", "{", "version", ":", "0", ",", "tips", ":", "{", "}", "}", ",", "cache", "]", ")", ";", "}", "if", "(", "!", "cache", "[", "\"\"", "]", ".", "version", ")", "{", "cache", "[", "\"\"", "]", ".", "version", "=", "0.4", ";", "_", ".", "forEach", "(", "cache", ",", "function", "(", "sizes", ",", "label", ")", "{", "if", "(", "!", "label", "||", "!", "sizes", ")", "{", "return", ";", "}", "// If promoting sizes to dictionary, assume that compressed size data are indicated by suffixes\r", "Object", ".", "keys", "(", "sizes", ")", ".", "sort", "(", ")", ".", "forEach", "(", "function", "(", "file", ")", "{", "var", "parts", "=", "file", ".", "split", "(", "\".\"", ")", ",", "prefix", "=", "parts", ".", "shift", "(", ")", ";", "// Append compressed size data to a matching prefix\r", "while", "(", "parts", ".", "length", ")", "{", "if", "(", "typeof", "sizes", "[", "prefix", "]", "===", "\"object\"", ")", "{", "sizes", "[", "prefix", "]", "[", "parts", ".", "join", "(", "\".\"", ")", "]", "=", "sizes", "[", "file", "]", ";", "delete", "sizes", "[", "file", "]", ";", "return", ";", "}", "prefix", "+=", "\".\"", "+", "parts", ".", "shift", "(", ")", ";", "}", "// Store uncompressed size data\r", "sizes", "[", "file", "]", "=", "{", "\"\"", ":", "sizes", "[", "file", "]", "}", ";", "}", ")", ";", "}", ")", ";", "}", "return", "cache", ";", "}" ]
Size cache helper
[ "Size", "cache", "helper" ]
9efaa3c9902f0a740057af40a976ec0258feaf33
https://github.com/rxaviers/cldrjs/blob/9efaa3c9902f0a740057af40a976ec0258feaf33/build/compare-size.js#L146-L200
18,549
rxaviers/cldrjs
build/compare-size.js
function(task, compressors) { var sizes = {}, files = processPatterns(task.files, function(pattern) { // Find all matching files for this pattern. return glob.sync(pattern, { filter: "isFile" }); }); files.forEach(function(src) { var contents = file.read(src), fileSizes = (sizes[src] = { "": contents.length }); if (compressors) { Object.keys(compressors).forEach(function(compressor) { fileSizes[compressor] = compressors[compressor](contents); }); } }); return sizes; }
javascript
function(task, compressors) { var sizes = {}, files = processPatterns(task.files, function(pattern) { // Find all matching files for this pattern. return glob.sync(pattern, { filter: "isFile" }); }); files.forEach(function(src) { var contents = file.read(src), fileSizes = (sizes[src] = { "": contents.length }); if (compressors) { Object.keys(compressors).forEach(function(compressor) { fileSizes[compressor] = compressors[compressor](contents); }); } }); return sizes; }
[ "function", "(", "task", ",", "compressors", ")", "{", "var", "sizes", "=", "{", "}", ",", "files", "=", "processPatterns", "(", "task", ".", "files", ",", "function", "(", "pattern", ")", "{", "// Find all matching files for this pattern.\r", "return", "glob", ".", "sync", "(", "pattern", ",", "{", "filter", ":", "\"isFile\"", "}", ")", ";", "}", ")", ";", "files", ".", "forEach", "(", "function", "(", "src", ")", "{", "var", "contents", "=", "file", ".", "read", "(", "src", ")", ",", "fileSizes", "=", "(", "sizes", "[", "src", "]", "=", "{", "\"\"", ":", "contents", ".", "length", "}", ")", ";", "if", "(", "compressors", ")", "{", "Object", ".", "keys", "(", "compressors", ")", ".", "forEach", "(", "function", "(", "compressor", ")", "{", "fileSizes", "[", "compressor", "]", "=", "compressors", "[", "compressor", "]", "(", "contents", ")", ";", "}", ")", ";", "}", "}", ")", ";", "return", "sizes", ";", "}" ]
Files helper.
[ "Files", "helper", "." ]
9efaa3c9902f0a740057af40a976ec0258feaf33
https://github.com/rxaviers/cldrjs/blob/9efaa3c9902f0a740057af40a976ec0258feaf33/build/compare-size.js#L203-L221
18,550
rxaviers/cldrjs
build/compare-size.js
function(done) { debug("Running `git branch` command..."); exec( "git branch --no-color --verbose --no-abbrev --contains HEAD", function(err, stdout) { var status = {}, matches = /^\* (.+?)\s+([0-9a-f]{8,})/im.exec(stdout); if (err || !matches) { done(err || "branch not found"); } else if (matches[1].indexOf(" ") >= 0) { done("not a branch tip: " + matches[2]); } else { status.branch = matches[1]; status.head = matches[2]; exec("git diff --quiet HEAD", function(err) { status.changed = !!err; done(null, status); }); } } ); }
javascript
function(done) { debug("Running `git branch` command..."); exec( "git branch --no-color --verbose --no-abbrev --contains HEAD", function(err, stdout) { var status = {}, matches = /^\* (.+?)\s+([0-9a-f]{8,})/im.exec(stdout); if (err || !matches) { done(err || "branch not found"); } else if (matches[1].indexOf(" ") >= 0) { done("not a branch tip: " + matches[2]); } else { status.branch = matches[1]; status.head = matches[2]; exec("git diff --quiet HEAD", function(err) { status.changed = !!err; done(null, status); }); } } ); }
[ "function", "(", "done", ")", "{", "debug", "(", "\"Running `git branch` command...\"", ")", ";", "exec", "(", "\"git branch --no-color --verbose --no-abbrev --contains HEAD\"", ",", "function", "(", "err", ",", "stdout", ")", "{", "var", "status", "=", "{", "}", ",", "matches", "=", "/", "^\\* (.+?)\\s+([0-9a-f]{8,})", "/", "im", ".", "exec", "(", "stdout", ")", ";", "if", "(", "err", "||", "!", "matches", ")", "{", "done", "(", "err", "||", "\"branch not found\"", ")", ";", "}", "else", "if", "(", "matches", "[", "1", "]", ".", "indexOf", "(", "\" \"", ")", ">=", "0", ")", "{", "done", "(", "\"not a branch tip: \"", "+", "matches", "[", "2", "]", ")", ";", "}", "else", "{", "status", ".", "branch", "=", "matches", "[", "1", "]", ";", "status", ".", "head", "=", "matches", "[", "2", "]", ";", "exec", "(", "\"git diff --quiet HEAD\"", ",", "function", "(", "err", ")", "{", "status", ".", "changed", "=", "!", "!", "err", ";", "done", "(", "null", ",", "status", ")", ";", "}", ")", ";", "}", "}", ")", ";", "}" ]
git helper.
[ "git", "helper", "." ]
9efaa3c9902f0a740057af40a976ec0258feaf33
https://github.com/rxaviers/cldrjs/blob/9efaa3c9902f0a740057af40a976ec0258feaf33/build/compare-size.js#L224-L246
18,551
rxaviers/cldrjs
build/compare-size.js
compareSizes
function compareSizes(task) { var compressors = task.options.compress, newsizes = helpers.sizes(task, compressors), files = Object.keys(newsizes), sizecache = defaultCache, cache = helpers.get_cache(sizecache), tips = cache[""].tips, labels = helpers.sorted_labels(cache); // Obtain the current branch and continue... helpers.git_status(function(err, status) { var prefixes = compressors ? [""].concat(Object.keys(compressors)) : [""], commonHeader = prefixes.map( (label, i) => (i === 0 && compressors ? "raw" : label) ); const tableOptions = { align: prefixes.map(() => "r").concat("l"), // eslint-disable-next-line no-control-regex stringLength: s => s.replace(/\x1B\[\d+m/g, "").length // Return a string, uncolored (suitable for testing .length, etc). }; if (err) { console.warn(err); status = {}; } let rows = []; rows.push(commonHeader.concat("Sizes")); // Raw sizes files.forEach(function(key) { rows.push(prefixes.map(prefix => newsizes[key][prefix]).concat(key + "")); }); console.log(table(rows, tableOptions)); // Comparisons labels.forEach(function(label) { var oldsizes = cache[label]; // Skip metadata key and empty cache entries if (label === "" || !cache[label]) { return; } rows = []; // Header rows.push( commonHeader.concat("Compared to " + helpers.label(label, tips[label])) ); // Data files.forEach(function(key) { var old = oldsizes && oldsizes[key]; rows.push( prefixes .map(function(prefix) { return helpers.delta(old && newsizes[key][prefix] - old[prefix]); }) .concat(key + "") ); }); console.log(); console.log(table(rows, tableOptions)); }); // Update "last run" sizes cache[lastrun] = newsizes; // Remember if we're at a branch tip and the branch name is an available key if ( status.branch && !status.changed && (status.branch in tips || !cache[status.branch]) ) { tips[status.branch] = status.head; cache[status.branch] = newsizes; console.log("\nSaved as: " + status.branch); } // Write to file file.write(sizecache, JSON.stringify(cache)); }); }
javascript
function compareSizes(task) { var compressors = task.options.compress, newsizes = helpers.sizes(task, compressors), files = Object.keys(newsizes), sizecache = defaultCache, cache = helpers.get_cache(sizecache), tips = cache[""].tips, labels = helpers.sorted_labels(cache); // Obtain the current branch and continue... helpers.git_status(function(err, status) { var prefixes = compressors ? [""].concat(Object.keys(compressors)) : [""], commonHeader = prefixes.map( (label, i) => (i === 0 && compressors ? "raw" : label) ); const tableOptions = { align: prefixes.map(() => "r").concat("l"), // eslint-disable-next-line no-control-regex stringLength: s => s.replace(/\x1B\[\d+m/g, "").length // Return a string, uncolored (suitable for testing .length, etc). }; if (err) { console.warn(err); status = {}; } let rows = []; rows.push(commonHeader.concat("Sizes")); // Raw sizes files.forEach(function(key) { rows.push(prefixes.map(prefix => newsizes[key][prefix]).concat(key + "")); }); console.log(table(rows, tableOptions)); // Comparisons labels.forEach(function(label) { var oldsizes = cache[label]; // Skip metadata key and empty cache entries if (label === "" || !cache[label]) { return; } rows = []; // Header rows.push( commonHeader.concat("Compared to " + helpers.label(label, tips[label])) ); // Data files.forEach(function(key) { var old = oldsizes && oldsizes[key]; rows.push( prefixes .map(function(prefix) { return helpers.delta(old && newsizes[key][prefix] - old[prefix]); }) .concat(key + "") ); }); console.log(); console.log(table(rows, tableOptions)); }); // Update "last run" sizes cache[lastrun] = newsizes; // Remember if we're at a branch tip and the branch name is an available key if ( status.branch && !status.changed && (status.branch in tips || !cache[status.branch]) ) { tips[status.branch] = status.head; cache[status.branch] = newsizes; console.log("\nSaved as: " + status.branch); } // Write to file file.write(sizecache, JSON.stringify(cache)); }); }
[ "function", "compareSizes", "(", "task", ")", "{", "var", "compressors", "=", "task", ".", "options", ".", "compress", ",", "newsizes", "=", "helpers", ".", "sizes", "(", "task", ",", "compressors", ")", ",", "files", "=", "Object", ".", "keys", "(", "newsizes", ")", ",", "sizecache", "=", "defaultCache", ",", "cache", "=", "helpers", ".", "get_cache", "(", "sizecache", ")", ",", "tips", "=", "cache", "[", "\"\"", "]", ".", "tips", ",", "labels", "=", "helpers", ".", "sorted_labels", "(", "cache", ")", ";", "// Obtain the current branch and continue...\r", "helpers", ".", "git_status", "(", "function", "(", "err", ",", "status", ")", "{", "var", "prefixes", "=", "compressors", "?", "[", "\"\"", "]", ".", "concat", "(", "Object", ".", "keys", "(", "compressors", ")", ")", ":", "[", "\"\"", "]", ",", "commonHeader", "=", "prefixes", ".", "map", "(", "(", "label", ",", "i", ")", "=>", "(", "i", "===", "0", "&&", "compressors", "?", "\"raw\"", ":", "label", ")", ")", ";", "const", "tableOptions", "=", "{", "align", ":", "prefixes", ".", "map", "(", "(", ")", "=>", "\"r\"", ")", ".", "concat", "(", "\"l\"", ")", ",", "// eslint-disable-next-line no-control-regex\r", "stringLength", ":", "s", "=>", "s", ".", "replace", "(", "/", "\\x1B\\[\\d+m", "/", "g", ",", "\"\"", ")", ".", "length", "// Return a string, uncolored (suitable for testing .length, etc).\r", "}", ";", "if", "(", "err", ")", "{", "console", ".", "warn", "(", "err", ")", ";", "status", "=", "{", "}", ";", "}", "let", "rows", "=", "[", "]", ";", "rows", ".", "push", "(", "commonHeader", ".", "concat", "(", "\"Sizes\"", ")", ")", ";", "// Raw sizes\r", "files", ".", "forEach", "(", "function", "(", "key", ")", "{", "rows", ".", "push", "(", "prefixes", ".", "map", "(", "prefix", "=>", "newsizes", "[", "key", "]", "[", "prefix", "]", ")", ".", "concat", "(", "key", "+", "\"\"", ")", ")", ";", "}", ")", ";", "console", ".", "log", "(", "table", "(", "rows", ",", "tableOptions", ")", ")", ";", "// Comparisons\r", "labels", ".", "forEach", "(", "function", "(", "label", ")", "{", "var", "oldsizes", "=", "cache", "[", "label", "]", ";", "// Skip metadata key and empty cache entries\r", "if", "(", "label", "===", "\"\"", "||", "!", "cache", "[", "label", "]", ")", "{", "return", ";", "}", "rows", "=", "[", "]", ";", "// Header\r", "rows", ".", "push", "(", "commonHeader", ".", "concat", "(", "\"Compared to \"", "+", "helpers", ".", "label", "(", "label", ",", "tips", "[", "label", "]", ")", ")", ")", ";", "// Data\r", "files", ".", "forEach", "(", "function", "(", "key", ")", "{", "var", "old", "=", "oldsizes", "&&", "oldsizes", "[", "key", "]", ";", "rows", ".", "push", "(", "prefixes", ".", "map", "(", "function", "(", "prefix", ")", "{", "return", "helpers", ".", "delta", "(", "old", "&&", "newsizes", "[", "key", "]", "[", "prefix", "]", "-", "old", "[", "prefix", "]", ")", ";", "}", ")", ".", "concat", "(", "key", "+", "\"\"", ")", ")", ";", "}", ")", ";", "console", ".", "log", "(", ")", ";", "console", ".", "log", "(", "table", "(", "rows", ",", "tableOptions", ")", ")", ";", "}", ")", ";", "// Update \"last run\" sizes\r", "cache", "[", "lastrun", "]", "=", "newsizes", ";", "// Remember if we're at a branch tip and the branch name is an available key\r", "if", "(", "status", ".", "branch", "&&", "!", "status", ".", "changed", "&&", "(", "status", ".", "branch", "in", "tips", "||", "!", "cache", "[", "status", ".", "branch", "]", ")", ")", "{", "tips", "[", "status", ".", "branch", "]", "=", "status", ".", "head", ";", "cache", "[", "status", ".", "branch", "]", "=", "newsizes", ";", "console", ".", "log", "(", "\"\\nSaved as: \"", "+", "status", ".", "branch", ")", ";", "}", "// Write to file\r", "file", ".", "write", "(", "sizecache", ",", "JSON", ".", "stringify", "(", "cache", ")", ")", ";", "}", ")", ";", "}" ]
Compare size to saved sizes Derived and adapted from Corey Frang's original `sizer`
[ "Compare", "size", "to", "saved", "sizes", "Derived", "and", "adapted", "from", "Corey", "Frang", "s", "original", "sizer" ]
9efaa3c9902f0a740057af40a976ec0258feaf33
https://github.com/rxaviers/cldrjs/blob/9efaa3c9902f0a740057af40a976ec0258feaf33/build/compare-size.js#L251-L337
18,552
kaisalmen/WWOBJLoader
src/loaders/support/LoaderWorkerSupport.js
function ( functionCodeBuilder, parserName, libLocations, libPath, runnerImpl ) { if ( THREE.LoaderSupport.Validator.isValid( this.loaderWorker.worker ) ) return; if ( this.logging.enabled ) { console.info( 'WorkerSupport: Building worker code...' ); console.time( 'buildWebWorkerCode' ); } if ( THREE.LoaderSupport.Validator.isValid( runnerImpl ) ) { if ( this.logging.enabled ) console.info( 'WorkerSupport: Using "' + runnerImpl.runnerName + '" as Runner class for worker.' ); // Browser implementation } else if ( typeof window !== "undefined" ) { runnerImpl = THREE.LoaderSupport.WorkerRunnerRefImpl; if ( this.logging.enabled ) console.info( 'WorkerSupport: Using DEFAULT "THREE.LoaderSupport.WorkerRunnerRefImpl" as Runner class for worker.' ); // NodeJS implementation } else { runnerImpl = THREE.LoaderSupport.NodeWorkerRunnerRefImpl; if ( this.logging.enabled ) console.info( 'WorkerSupport: Using DEFAULT "THREE.LoaderSupport.NodeWorkerRunnerRefImpl" as Runner class for worker.' ); } var userWorkerCode = functionCodeBuilder( THREE.LoaderSupport.WorkerSupport.CodeSerializer ); userWorkerCode += 'var Parser = '+ parserName + ';\n\n'; userWorkerCode += THREE.LoaderSupport.WorkerSupport.CodeSerializer.serializeClass( runnerImpl.runnerName, runnerImpl ); userWorkerCode += 'new ' + runnerImpl.runnerName + '();\n\n'; var scope = this; if ( THREE.LoaderSupport.Validator.isValid( libLocations ) && libLocations.length > 0 ) { var libsContent = ''; var loadAllLibraries = function ( path, locations ) { if ( locations.length === 0 ) { scope.loaderWorker.initWorker( libsContent + userWorkerCode, runnerImpl.runnerName ); if ( scope.logging.enabled ) console.timeEnd( 'buildWebWorkerCode' ); } else { var loadedLib = function ( contentAsString ) { libsContent += contentAsString; loadAllLibraries( path, locations ); }; var fileLoader = new THREE.FileLoader(); fileLoader.setPath( path ); fileLoader.setResponseType( 'text' ); fileLoader.load( locations[ 0 ], loadedLib ); locations.shift(); } }; loadAllLibraries( libPath, libLocations ); } else { this.loaderWorker.initWorker( userWorkerCode, runnerImpl.runnerName ); if ( this.logging.enabled ) console.timeEnd( 'buildWebWorkerCode' ); } }
javascript
function ( functionCodeBuilder, parserName, libLocations, libPath, runnerImpl ) { if ( THREE.LoaderSupport.Validator.isValid( this.loaderWorker.worker ) ) return; if ( this.logging.enabled ) { console.info( 'WorkerSupport: Building worker code...' ); console.time( 'buildWebWorkerCode' ); } if ( THREE.LoaderSupport.Validator.isValid( runnerImpl ) ) { if ( this.logging.enabled ) console.info( 'WorkerSupport: Using "' + runnerImpl.runnerName + '" as Runner class for worker.' ); // Browser implementation } else if ( typeof window !== "undefined" ) { runnerImpl = THREE.LoaderSupport.WorkerRunnerRefImpl; if ( this.logging.enabled ) console.info( 'WorkerSupport: Using DEFAULT "THREE.LoaderSupport.WorkerRunnerRefImpl" as Runner class for worker.' ); // NodeJS implementation } else { runnerImpl = THREE.LoaderSupport.NodeWorkerRunnerRefImpl; if ( this.logging.enabled ) console.info( 'WorkerSupport: Using DEFAULT "THREE.LoaderSupport.NodeWorkerRunnerRefImpl" as Runner class for worker.' ); } var userWorkerCode = functionCodeBuilder( THREE.LoaderSupport.WorkerSupport.CodeSerializer ); userWorkerCode += 'var Parser = '+ parserName + ';\n\n'; userWorkerCode += THREE.LoaderSupport.WorkerSupport.CodeSerializer.serializeClass( runnerImpl.runnerName, runnerImpl ); userWorkerCode += 'new ' + runnerImpl.runnerName + '();\n\n'; var scope = this; if ( THREE.LoaderSupport.Validator.isValid( libLocations ) && libLocations.length > 0 ) { var libsContent = ''; var loadAllLibraries = function ( path, locations ) { if ( locations.length === 0 ) { scope.loaderWorker.initWorker( libsContent + userWorkerCode, runnerImpl.runnerName ); if ( scope.logging.enabled ) console.timeEnd( 'buildWebWorkerCode' ); } else { var loadedLib = function ( contentAsString ) { libsContent += contentAsString; loadAllLibraries( path, locations ); }; var fileLoader = new THREE.FileLoader(); fileLoader.setPath( path ); fileLoader.setResponseType( 'text' ); fileLoader.load( locations[ 0 ], loadedLib ); locations.shift(); } }; loadAllLibraries( libPath, libLocations ); } else { this.loaderWorker.initWorker( userWorkerCode, runnerImpl.runnerName ); if ( this.logging.enabled ) console.timeEnd( 'buildWebWorkerCode' ); } }
[ "function", "(", "functionCodeBuilder", ",", "parserName", ",", "libLocations", ",", "libPath", ",", "runnerImpl", ")", "{", "if", "(", "THREE", ".", "LoaderSupport", ".", "Validator", ".", "isValid", "(", "this", ".", "loaderWorker", ".", "worker", ")", ")", "return", ";", "if", "(", "this", ".", "logging", ".", "enabled", ")", "{", "console", ".", "info", "(", "'WorkerSupport: Building worker code...'", ")", ";", "console", ".", "time", "(", "'buildWebWorkerCode'", ")", ";", "}", "if", "(", "THREE", ".", "LoaderSupport", ".", "Validator", ".", "isValid", "(", "runnerImpl", ")", ")", "{", "if", "(", "this", ".", "logging", ".", "enabled", ")", "console", ".", "info", "(", "'WorkerSupport: Using \"'", "+", "runnerImpl", ".", "runnerName", "+", "'\" as Runner class for worker.'", ")", ";", "// Browser implementation", "}", "else", "if", "(", "typeof", "window", "!==", "\"undefined\"", ")", "{", "runnerImpl", "=", "THREE", ".", "LoaderSupport", ".", "WorkerRunnerRefImpl", ";", "if", "(", "this", ".", "logging", ".", "enabled", ")", "console", ".", "info", "(", "'WorkerSupport: Using DEFAULT \"THREE.LoaderSupport.WorkerRunnerRefImpl\" as Runner class for worker.'", ")", ";", "// NodeJS implementation", "}", "else", "{", "runnerImpl", "=", "THREE", ".", "LoaderSupport", ".", "NodeWorkerRunnerRefImpl", ";", "if", "(", "this", ".", "logging", ".", "enabled", ")", "console", ".", "info", "(", "'WorkerSupport: Using DEFAULT \"THREE.LoaderSupport.NodeWorkerRunnerRefImpl\" as Runner class for worker.'", ")", ";", "}", "var", "userWorkerCode", "=", "functionCodeBuilder", "(", "THREE", ".", "LoaderSupport", ".", "WorkerSupport", ".", "CodeSerializer", ")", ";", "userWorkerCode", "+=", "'var Parser = '", "+", "parserName", "+", "';\\n\\n'", ";", "userWorkerCode", "+=", "THREE", ".", "LoaderSupport", ".", "WorkerSupport", ".", "CodeSerializer", ".", "serializeClass", "(", "runnerImpl", ".", "runnerName", ",", "runnerImpl", ")", ";", "userWorkerCode", "+=", "'new '", "+", "runnerImpl", ".", "runnerName", "+", "'();\\n\\n'", ";", "var", "scope", "=", "this", ";", "if", "(", "THREE", ".", "LoaderSupport", ".", "Validator", ".", "isValid", "(", "libLocations", ")", "&&", "libLocations", ".", "length", ">", "0", ")", "{", "var", "libsContent", "=", "''", ";", "var", "loadAllLibraries", "=", "function", "(", "path", ",", "locations", ")", "{", "if", "(", "locations", ".", "length", "===", "0", ")", "{", "scope", ".", "loaderWorker", ".", "initWorker", "(", "libsContent", "+", "userWorkerCode", ",", "runnerImpl", ".", "runnerName", ")", ";", "if", "(", "scope", ".", "logging", ".", "enabled", ")", "console", ".", "timeEnd", "(", "'buildWebWorkerCode'", ")", ";", "}", "else", "{", "var", "loadedLib", "=", "function", "(", "contentAsString", ")", "{", "libsContent", "+=", "contentAsString", ";", "loadAllLibraries", "(", "path", ",", "locations", ")", ";", "}", ";", "var", "fileLoader", "=", "new", "THREE", ".", "FileLoader", "(", ")", ";", "fileLoader", ".", "setPath", "(", "path", ")", ";", "fileLoader", ".", "setResponseType", "(", "'text'", ")", ";", "fileLoader", ".", "load", "(", "locations", "[", "0", "]", ",", "loadedLib", ")", ";", "locations", ".", "shift", "(", ")", ";", "}", "}", ";", "loadAllLibraries", "(", "libPath", ",", "libLocations", ")", ";", "}", "else", "{", "this", ".", "loaderWorker", ".", "initWorker", "(", "userWorkerCode", ",", "runnerImpl", ".", "runnerName", ")", ";", "if", "(", "this", ".", "logging", ".", "enabled", ")", "console", ".", "timeEnd", "(", "'buildWebWorkerCode'", ")", ";", "}", "}" ]
Validate the status of worker code and the derived worker. @param {Function} functionCodeBuilder Function that is invoked with funcBuildObject and funcBuildSingleton that allows stringification of objects and singletons. @param {String} parserName Name of the Parser object @param {String[]} libLocations URL of libraries that shall be added to worker code relative to libPath @param {String} libPath Base path used for loading libraries @param {THREE.LoaderSupport.WorkerRunnerRefImpl} runnerImpl The default worker parser wrapper implementation (communication and execution). An extended class could be passed here.
[ "Validate", "the", "status", "of", "worker", "code", "and", "the", "derived", "worker", "." ]
729c1f1549db24c22c0bc202d7295edbc655c7bc
https://github.com/kaisalmen/WWOBJLoader/blob/729c1f1549db24c22c0bc202d7295edbc655c7bc/src/loaders/support/LoaderWorkerSupport.js#L54-L118
18,553
kaisalmen/WWOBJLoader
src/loaders/support/LoaderWorkerSupport.js
function ( e ) { var payload = e.data; switch ( payload.cmd ) { case 'meshData': case 'materialData': case 'imageData': this.runtimeRef.callbacks.meshBuilder( payload ); break; case 'complete': this.runtimeRef.queuedMessage = null; this.started = false; this.runtimeRef.callbacks.onLoad( payload.msg ); if ( this.runtimeRef.terminateRequested ) { if ( this.runtimeRef.logging.enabled ) console.info( 'WorkerSupport [' + this.runtimeRef.runnerImplName + ']: Run is complete. Terminating application on request!' ); this.runtimeRef._terminate(); } break; case 'error': console.error( 'WorkerSupport [' + this.runtimeRef.runnerImplName + ']: Reported error: ' + payload.msg ); this.runtimeRef.queuedMessage = null; this.started = false; this.runtimeRef.callbacks.onLoad( payload.msg ); if ( this.runtimeRef.terminateRequested ) { if ( this.runtimeRef.logging.enabled ) console.info( 'WorkerSupport [' + this.runtimeRef.runnerImplName + ']: Run reported error. Terminating application on request!' ); this.runtimeRef._terminate(); } break; default: console.error( 'WorkerSupport [' + this.runtimeRef.runnerImplName + ']: Received unknown command: ' + payload.cmd ); break; } }
javascript
function ( e ) { var payload = e.data; switch ( payload.cmd ) { case 'meshData': case 'materialData': case 'imageData': this.runtimeRef.callbacks.meshBuilder( payload ); break; case 'complete': this.runtimeRef.queuedMessage = null; this.started = false; this.runtimeRef.callbacks.onLoad( payload.msg ); if ( this.runtimeRef.terminateRequested ) { if ( this.runtimeRef.logging.enabled ) console.info( 'WorkerSupport [' + this.runtimeRef.runnerImplName + ']: Run is complete. Terminating application on request!' ); this.runtimeRef._terminate(); } break; case 'error': console.error( 'WorkerSupport [' + this.runtimeRef.runnerImplName + ']: Reported error: ' + payload.msg ); this.runtimeRef.queuedMessage = null; this.started = false; this.runtimeRef.callbacks.onLoad( payload.msg ); if ( this.runtimeRef.terminateRequested ) { if ( this.runtimeRef.logging.enabled ) console.info( 'WorkerSupport [' + this.runtimeRef.runnerImplName + ']: Run reported error. Terminating application on request!' ); this.runtimeRef._terminate(); } break; default: console.error( 'WorkerSupport [' + this.runtimeRef.runnerImplName + ']: Received unknown command: ' + payload.cmd ); break; } }
[ "function", "(", "e", ")", "{", "var", "payload", "=", "e", ".", "data", ";", "switch", "(", "payload", ".", "cmd", ")", "{", "case", "'meshData'", ":", "case", "'materialData'", ":", "case", "'imageData'", ":", "this", ".", "runtimeRef", ".", "callbacks", ".", "meshBuilder", "(", "payload", ")", ";", "break", ";", "case", "'complete'", ":", "this", ".", "runtimeRef", ".", "queuedMessage", "=", "null", ";", "this", ".", "started", "=", "false", ";", "this", ".", "runtimeRef", ".", "callbacks", ".", "onLoad", "(", "payload", ".", "msg", ")", ";", "if", "(", "this", ".", "runtimeRef", ".", "terminateRequested", ")", "{", "if", "(", "this", ".", "runtimeRef", ".", "logging", ".", "enabled", ")", "console", ".", "info", "(", "'WorkerSupport ['", "+", "this", ".", "runtimeRef", ".", "runnerImplName", "+", "']: Run is complete. Terminating application on request!'", ")", ";", "this", ".", "runtimeRef", ".", "_terminate", "(", ")", ";", "}", "break", ";", "case", "'error'", ":", "console", ".", "error", "(", "'WorkerSupport ['", "+", "this", ".", "runtimeRef", ".", "runnerImplName", "+", "']: Reported error: '", "+", "payload", ".", "msg", ")", ";", "this", ".", "runtimeRef", ".", "queuedMessage", "=", "null", ";", "this", ".", "started", "=", "false", ";", "this", ".", "runtimeRef", ".", "callbacks", ".", "onLoad", "(", "payload", ".", "msg", ")", ";", "if", "(", "this", ".", "runtimeRef", ".", "terminateRequested", ")", "{", "if", "(", "this", ".", "runtimeRef", ".", "logging", ".", "enabled", ")", "console", ".", "info", "(", "'WorkerSupport ['", "+", "this", ".", "runtimeRef", ".", "runnerImplName", "+", "']: Run reported error. Terminating application on request!'", ")", ";", "this", ".", "runtimeRef", ".", "_terminate", "(", ")", ";", "}", "break", ";", "default", ":", "console", ".", "error", "(", "'WorkerSupport ['", "+", "this", ".", "runtimeRef", ".", "runnerImplName", "+", "']: Received unknown command: '", "+", "payload", ".", "cmd", ")", ";", "break", ";", "}", "}" ]
Executed in worker scope
[ "Executed", "in", "worker", "scope" ]
729c1f1549db24c22c0bc202d7295edbc655c7bc
https://github.com/kaisalmen/WWOBJLoader/blob/729c1f1549db24c22c0bc202d7295edbc655c7bc/src/loaders/support/LoaderWorkerSupport.js#L222-L263
18,554
kaisalmen/WWOBJLoader
src/loaders/support/LoaderWorkerSupport.js
function ( parser, params ) { var property, funcName, values; for ( property in params ) { funcName = 'set' + property.substring( 0, 1 ).toLocaleUpperCase() + property.substring( 1 ); values = params[ property ]; if ( typeof parser[ funcName ] === 'function' ) { parser[ funcName ]( values ); } else if ( parser.hasOwnProperty( property ) ) { parser[ property ] = values; } } }
javascript
function ( parser, params ) { var property, funcName, values; for ( property in params ) { funcName = 'set' + property.substring( 0, 1 ).toLocaleUpperCase() + property.substring( 1 ); values = params[ property ]; if ( typeof parser[ funcName ] === 'function' ) { parser[ funcName ]( values ); } else if ( parser.hasOwnProperty( property ) ) { parser[ property ] = values; } } }
[ "function", "(", "parser", ",", "params", ")", "{", "var", "property", ",", "funcName", ",", "values", ";", "for", "(", "property", "in", "params", ")", "{", "funcName", "=", "'set'", "+", "property", ".", "substring", "(", "0", ",", "1", ")", ".", "toLocaleUpperCase", "(", ")", "+", "property", ".", "substring", "(", "1", ")", ";", "values", "=", "params", "[", "property", "]", ";", "if", "(", "typeof", "parser", "[", "funcName", "]", "===", "'function'", ")", "{", "parser", "[", "funcName", "]", "(", "values", ")", ";", "}", "else", "if", "(", "parser", ".", "hasOwnProperty", "(", "property", ")", ")", "{", "parser", "[", "property", "]", "=", "values", ";", "}", "}", "}" ]
Applies values from parameter object via set functions or via direct assignment. @param {Object} parser The parser instance @param {Object} params The parameter object
[ "Applies", "values", "from", "parameter", "object", "via", "set", "functions", "or", "via", "direct", "assignment", "." ]
729c1f1549db24c22c0bc202d7295edbc655c7bc
https://github.com/kaisalmen/WWOBJLoader/blob/729c1f1549db24c22c0bc202d7295edbc655c7bc/src/loaders/support/LoaderWorkerSupport.js#L550-L566
18,555
kaisalmen/WWOBJLoader
src/loaders/support/LoaderWorkerSupport.js
function ( payload ) { if ( payload.cmd === 'run' ) { var self = this.getParentScope(); var callbacks = { callbackOnAssetAvailable: function ( payload ) { self.postMessage( payload ); }, callbackOnProgress: function ( text ) { if ( payload.logging.enabled && payload.logging.debug ) console.debug( 'WorkerRunner: progress: ' + text ); } }; // Parser is expected to be named as such var parser = new Parser(); if ( typeof parser[ 'setLogging' ] === 'function' ) parser.setLogging( payload.logging.enabled, payload.logging.debug ); this.applyProperties( parser, payload.params ); this.applyProperties( parser, payload.materials ); this.applyProperties( parser, callbacks ); parser.workerScope = self; parser.parse( payload.data.input, payload.data.options ); if ( payload.logging.enabled ) console.log( 'WorkerRunner: Run complete!' ); callbacks.callbackOnAssetAvailable( { cmd: 'complete', msg: 'WorkerRunner completed run.' } ); } else { console.error( 'WorkerRunner: Received unknown command: ' + payload.cmd ); } }
javascript
function ( payload ) { if ( payload.cmd === 'run' ) { var self = this.getParentScope(); var callbacks = { callbackOnAssetAvailable: function ( payload ) { self.postMessage( payload ); }, callbackOnProgress: function ( text ) { if ( payload.logging.enabled && payload.logging.debug ) console.debug( 'WorkerRunner: progress: ' + text ); } }; // Parser is expected to be named as such var parser = new Parser(); if ( typeof parser[ 'setLogging' ] === 'function' ) parser.setLogging( payload.logging.enabled, payload.logging.debug ); this.applyProperties( parser, payload.params ); this.applyProperties( parser, payload.materials ); this.applyProperties( parser, callbacks ); parser.workerScope = self; parser.parse( payload.data.input, payload.data.options ); if ( payload.logging.enabled ) console.log( 'WorkerRunner: Run complete!' ); callbacks.callbackOnAssetAvailable( { cmd: 'complete', msg: 'WorkerRunner completed run.' } ); } else { console.error( 'WorkerRunner: Received unknown command: ' + payload.cmd ); } }
[ "function", "(", "payload", ")", "{", "if", "(", "payload", ".", "cmd", "===", "'run'", ")", "{", "var", "self", "=", "this", ".", "getParentScope", "(", ")", ";", "var", "callbacks", "=", "{", "callbackOnAssetAvailable", ":", "function", "(", "payload", ")", "{", "self", ".", "postMessage", "(", "payload", ")", ";", "}", ",", "callbackOnProgress", ":", "function", "(", "text", ")", "{", "if", "(", "payload", ".", "logging", ".", "enabled", "&&", "payload", ".", "logging", ".", "debug", ")", "console", ".", "debug", "(", "'WorkerRunner: progress: '", "+", "text", ")", ";", "}", "}", ";", "// Parser is expected to be named as such", "var", "parser", "=", "new", "Parser", "(", ")", ";", "if", "(", "typeof", "parser", "[", "'setLogging'", "]", "===", "'function'", ")", "parser", ".", "setLogging", "(", "payload", ".", "logging", ".", "enabled", ",", "payload", ".", "logging", ".", "debug", ")", ";", "this", ".", "applyProperties", "(", "parser", ",", "payload", ".", "params", ")", ";", "this", ".", "applyProperties", "(", "parser", ",", "payload", ".", "materials", ")", ";", "this", ".", "applyProperties", "(", "parser", ",", "callbacks", ")", ";", "parser", ".", "workerScope", "=", "self", ";", "parser", ".", "parse", "(", "payload", ".", "data", ".", "input", ",", "payload", ".", "data", ".", "options", ")", ";", "if", "(", "payload", ".", "logging", ".", "enabled", ")", "console", ".", "log", "(", "'WorkerRunner: Run complete!'", ")", ";", "callbacks", ".", "callbackOnAssetAvailable", "(", "{", "cmd", ":", "'complete'", ",", "msg", ":", "'WorkerRunner completed run.'", "}", ")", ";", "}", "else", "{", "console", ".", "error", "(", "'WorkerRunner: Received unknown command: '", "+", "payload", ".", "cmd", ")", ";", "}", "}" ]
Configures the Parser implementation according the supplied configuration object. @param {Object} payload Raw mesh description (buffers, params, materials) used to build one to many meshes.
[ "Configures", "the", "Parser", "implementation", "according", "the", "supplied", "configuration", "object", "." ]
729c1f1549db24c22c0bc202d7295edbc655c7bc
https://github.com/kaisalmen/WWOBJLoader/blob/729c1f1549db24c22c0bc202d7295edbc655c7bc/src/loaders/support/LoaderWorkerSupport.js#L573-L607
18,556
kaisalmen/WWOBJLoader
src/loaders/OBJLoader2.js
function ( url, onLoad, onProgress, onError, onMeshAlter, useAsync ) { var resource = new THREE.LoaderSupport.ResourceDescriptor( url, 'OBJ' ); this._loadObj( resource, onLoad, onProgress, onError, onMeshAlter, useAsync ); }
javascript
function ( url, onLoad, onProgress, onError, onMeshAlter, useAsync ) { var resource = new THREE.LoaderSupport.ResourceDescriptor( url, 'OBJ' ); this._loadObj( resource, onLoad, onProgress, onError, onMeshAlter, useAsync ); }
[ "function", "(", "url", ",", "onLoad", ",", "onProgress", ",", "onError", ",", "onMeshAlter", ",", "useAsync", ")", "{", "var", "resource", "=", "new", "THREE", ".", "LoaderSupport", ".", "ResourceDescriptor", "(", "url", ",", "'OBJ'", ")", ";", "this", ".", "_loadObj", "(", "resource", ",", "onLoad", ",", "onProgress", ",", "onError", ",", "onMeshAlter", ",", "useAsync", ")", ";", "}" ]
Use this convenient method to load a file at the given URL. By default the fileLoader uses an ArrayBuffer. @param {string} url A string containing the path/URL of the file to be loaded. @param {callback} onLoad A function to be called after loading is successfully completed. The function receives loaded Object3D as an argument. @param {callback} [onProgress] A function to be called while the loading is in progress. The argument will be the XMLHttpRequest instance, which contains total and Integer bytes. @param {callback} [onError] A function to be called if an error occurs during loading. The function receives the error as an argument. @param {callback} [onMeshAlter] A function to be called after a new mesh raw data becomes available for alteration. @param {boolean} [useAsync] If true, uses async loading with worker, if false loads data synchronously.
[ "Use", "this", "convenient", "method", "to", "load", "a", "file", "at", "the", "given", "URL", ".", "By", "default", "the", "fileLoader", "uses", "an", "ArrayBuffer", "." ]
729c1f1549db24c22c0bc202d7295edbc655c7bc
https://github.com/kaisalmen/WWOBJLoader/blob/729c1f1549db24c22c0bc202d7295edbc655c7bc/src/loaders/OBJLoader2.js#L196-L199
18,557
kaisalmen/WWOBJLoader
src/loaders/OBJLoader2.js
function ( prepData, workerSupportExternal ) { this._applyPrepData( prepData ); var available = prepData.checkResourceDescriptorFiles( prepData.resources, [ { ext: "obj", type: "ArrayBuffer", ignore: false }, { ext: "mtl", type: "String", ignore: false }, { ext: "zip", type: "String", ignore: true } ] ); if ( THREE.LoaderSupport.Validator.isValid( workerSupportExternal ) ) { this.terminateWorkerOnLoad = false; this.workerSupport = workerSupportExternal; this.logging.enabled = this.workerSupport.logging.enabled; this.logging.debug = this.workerSupport.logging.debug; } var scope = this; var onMaterialsLoaded = function ( materials ) { if ( materials !== null ) scope.meshBuilder.setMaterials( materials ); scope._loadObj( available.obj, scope.callbacks.onLoad, null, null, scope.callbacks.onMeshAlter, prepData.useAsync ); }; this._loadMtl( available.mtl, onMaterialsLoaded, null, null, prepData.crossOrigin, prepData.materialOptions ); }
javascript
function ( prepData, workerSupportExternal ) { this._applyPrepData( prepData ); var available = prepData.checkResourceDescriptorFiles( prepData.resources, [ { ext: "obj", type: "ArrayBuffer", ignore: false }, { ext: "mtl", type: "String", ignore: false }, { ext: "zip", type: "String", ignore: true } ] ); if ( THREE.LoaderSupport.Validator.isValid( workerSupportExternal ) ) { this.terminateWorkerOnLoad = false; this.workerSupport = workerSupportExternal; this.logging.enabled = this.workerSupport.logging.enabled; this.logging.debug = this.workerSupport.logging.debug; } var scope = this; var onMaterialsLoaded = function ( materials ) { if ( materials !== null ) scope.meshBuilder.setMaterials( materials ); scope._loadObj( available.obj, scope.callbacks.onLoad, null, null, scope.callbacks.onMeshAlter, prepData.useAsync ); }; this._loadMtl( available.mtl, onMaterialsLoaded, null, null, prepData.crossOrigin, prepData.materialOptions ); }
[ "function", "(", "prepData", ",", "workerSupportExternal", ")", "{", "this", ".", "_applyPrepData", "(", "prepData", ")", ";", "var", "available", "=", "prepData", ".", "checkResourceDescriptorFiles", "(", "prepData", ".", "resources", ",", "[", "{", "ext", ":", "\"obj\"", ",", "type", ":", "\"ArrayBuffer\"", ",", "ignore", ":", "false", "}", ",", "{", "ext", ":", "\"mtl\"", ",", "type", ":", "\"String\"", ",", "ignore", ":", "false", "}", ",", "{", "ext", ":", "\"zip\"", ",", "type", ":", "\"String\"", ",", "ignore", ":", "true", "}", "]", ")", ";", "if", "(", "THREE", ".", "LoaderSupport", ".", "Validator", ".", "isValid", "(", "workerSupportExternal", ")", ")", "{", "this", ".", "terminateWorkerOnLoad", "=", "false", ";", "this", ".", "workerSupport", "=", "workerSupportExternal", ";", "this", ".", "logging", ".", "enabled", "=", "this", ".", "workerSupport", ".", "logging", ".", "enabled", ";", "this", ".", "logging", ".", "debug", "=", "this", ".", "workerSupport", ".", "logging", ".", "debug", ";", "}", "var", "scope", "=", "this", ";", "var", "onMaterialsLoaded", "=", "function", "(", "materials", ")", "{", "if", "(", "materials", "!==", "null", ")", "scope", ".", "meshBuilder", ".", "setMaterials", "(", "materials", ")", ";", "scope", ".", "_loadObj", "(", "available", ".", "obj", ",", "scope", ".", "callbacks", ".", "onLoad", ",", "null", ",", "null", ",", "scope", ".", "callbacks", ".", "onMeshAlter", ",", "prepData", ".", "useAsync", ")", ";", "}", ";", "this", ".", "_loadMtl", "(", "available", ".", "mtl", ",", "onMaterialsLoaded", ",", "null", ",", "null", ",", "prepData", ".", "crossOrigin", ",", "prepData", ".", "materialOptions", ")", ";", "}" ]
Run the loader according the provided instructions. @param {THREE.LoaderSupport.PrepData} prepData All parameters and resources required for execution @param {THREE.LoaderSupport.WorkerSupport} [workerSupportExternal] Use pre-existing WorkerSupport
[ "Run", "the", "loader", "according", "the", "provided", "instructions", "." ]
729c1f1549db24c22c0bc202d7295edbc655c7bc
https://github.com/kaisalmen/WWOBJLoader/blob/729c1f1549db24c22c0bc202d7295edbc655c7bc/src/loaders/OBJLoader2.js#L286-L310
18,558
kaisalmen/WWOBJLoader
src/loaders/OBJLoader2.js
function ( content ) { // fast-fail in case of illegal data if ( content === null || content === undefined ) { throw 'Provided content is not a valid ArrayBuffer or String. Unable to continue parsing'; } if ( this.logging.enabled ) console.time( 'OBJLoader2 parse: ' + this.modelName ); this.meshBuilder.init(); var parser = new THREE.OBJLoader2.Parser(); parser.setLogging( this.logging.enabled, this.logging.debug ); parser.setMaterialPerSmoothingGroup( this.materialPerSmoothingGroup ); parser.setUseOAsMesh( this.useOAsMesh ); parser.setUseIndices( this.useIndices ); parser.setDisregardNormals( this.disregardNormals ); // sync code works directly on the material references parser.setMaterials( this.meshBuilder.getMaterials() ); var scope = this; var onMeshLoaded = function ( payload ) { var meshes = scope.meshBuilder.processPayload( payload ); var mesh; for ( var i in meshes ) { mesh = meshes[ i ]; scope.loaderRootNode.add( mesh ); } }; parser.setCallbackOnAssetAvailable( onMeshLoaded ); var onProgressScoped = function ( text, numericalValue ) { scope.onProgress( 'progressParse', text, numericalValue ); }; parser.setCallbackOnProgress( onProgressScoped ); var onErrorScoped = function ( message ) { scope._onError( message ); }; parser.setCallbackOnError( onErrorScoped ); if ( content instanceof ArrayBuffer || content instanceof Uint8Array ) { if ( this.logging.enabled ) console.info( 'Parsing arrayBuffer...' ); parser.parse( content ); } else if ( typeof( content ) === 'string' || content instanceof String ) { if ( this.logging.enabled ) console.info( 'Parsing text...' ); parser.parseText( content ); } else { this._onError( 'Provided content was neither of type String nor Uint8Array! Aborting...' ); } if ( this.logging.enabled ) console.timeEnd( 'OBJLoader2 parse: ' + this.modelName ); return this.loaderRootNode; }
javascript
function ( content ) { // fast-fail in case of illegal data if ( content === null || content === undefined ) { throw 'Provided content is not a valid ArrayBuffer or String. Unable to continue parsing'; } if ( this.logging.enabled ) console.time( 'OBJLoader2 parse: ' + this.modelName ); this.meshBuilder.init(); var parser = new THREE.OBJLoader2.Parser(); parser.setLogging( this.logging.enabled, this.logging.debug ); parser.setMaterialPerSmoothingGroup( this.materialPerSmoothingGroup ); parser.setUseOAsMesh( this.useOAsMesh ); parser.setUseIndices( this.useIndices ); parser.setDisregardNormals( this.disregardNormals ); // sync code works directly on the material references parser.setMaterials( this.meshBuilder.getMaterials() ); var scope = this; var onMeshLoaded = function ( payload ) { var meshes = scope.meshBuilder.processPayload( payload ); var mesh; for ( var i in meshes ) { mesh = meshes[ i ]; scope.loaderRootNode.add( mesh ); } }; parser.setCallbackOnAssetAvailable( onMeshLoaded ); var onProgressScoped = function ( text, numericalValue ) { scope.onProgress( 'progressParse', text, numericalValue ); }; parser.setCallbackOnProgress( onProgressScoped ); var onErrorScoped = function ( message ) { scope._onError( message ); }; parser.setCallbackOnError( onErrorScoped ); if ( content instanceof ArrayBuffer || content instanceof Uint8Array ) { if ( this.logging.enabled ) console.info( 'Parsing arrayBuffer...' ); parser.parse( content ); } else if ( typeof( content ) === 'string' || content instanceof String ) { if ( this.logging.enabled ) console.info( 'Parsing text...' ); parser.parseText( content ); } else { this._onError( 'Provided content was neither of type String nor Uint8Array! Aborting...' ); } if ( this.logging.enabled ) console.timeEnd( 'OBJLoader2 parse: ' + this.modelName ); return this.loaderRootNode; }
[ "function", "(", "content", ")", "{", "// fast-fail in case of illegal data", "if", "(", "content", "===", "null", "||", "content", "===", "undefined", ")", "{", "throw", "'Provided content is not a valid ArrayBuffer or String. Unable to continue parsing'", ";", "}", "if", "(", "this", ".", "logging", ".", "enabled", ")", "console", ".", "time", "(", "'OBJLoader2 parse: '", "+", "this", ".", "modelName", ")", ";", "this", ".", "meshBuilder", ".", "init", "(", ")", ";", "var", "parser", "=", "new", "THREE", ".", "OBJLoader2", ".", "Parser", "(", ")", ";", "parser", ".", "setLogging", "(", "this", ".", "logging", ".", "enabled", ",", "this", ".", "logging", ".", "debug", ")", ";", "parser", ".", "setMaterialPerSmoothingGroup", "(", "this", ".", "materialPerSmoothingGroup", ")", ";", "parser", ".", "setUseOAsMesh", "(", "this", ".", "useOAsMesh", ")", ";", "parser", ".", "setUseIndices", "(", "this", ".", "useIndices", ")", ";", "parser", ".", "setDisregardNormals", "(", "this", ".", "disregardNormals", ")", ";", "// sync code works directly on the material references", "parser", ".", "setMaterials", "(", "this", ".", "meshBuilder", ".", "getMaterials", "(", ")", ")", ";", "var", "scope", "=", "this", ";", "var", "onMeshLoaded", "=", "function", "(", "payload", ")", "{", "var", "meshes", "=", "scope", ".", "meshBuilder", ".", "processPayload", "(", "payload", ")", ";", "var", "mesh", ";", "for", "(", "var", "i", "in", "meshes", ")", "{", "mesh", "=", "meshes", "[", "i", "]", ";", "scope", ".", "loaderRootNode", ".", "add", "(", "mesh", ")", ";", "}", "}", ";", "parser", ".", "setCallbackOnAssetAvailable", "(", "onMeshLoaded", ")", ";", "var", "onProgressScoped", "=", "function", "(", "text", ",", "numericalValue", ")", "{", "scope", ".", "onProgress", "(", "'progressParse'", ",", "text", ",", "numericalValue", ")", ";", "}", ";", "parser", ".", "setCallbackOnProgress", "(", "onProgressScoped", ")", ";", "var", "onErrorScoped", "=", "function", "(", "message", ")", "{", "scope", ".", "_onError", "(", "message", ")", ";", "}", ";", "parser", ".", "setCallbackOnError", "(", "onErrorScoped", ")", ";", "if", "(", "content", "instanceof", "ArrayBuffer", "||", "content", "instanceof", "Uint8Array", ")", "{", "if", "(", "this", ".", "logging", ".", "enabled", ")", "console", ".", "info", "(", "'Parsing arrayBuffer...'", ")", ";", "parser", ".", "parse", "(", "content", ")", ";", "}", "else", "if", "(", "typeof", "(", "content", ")", "===", "'string'", "||", "content", "instanceof", "String", ")", "{", "if", "(", "this", ".", "logging", ".", "enabled", ")", "console", ".", "info", "(", "'Parsing text...'", ")", ";", "parser", ".", "parseText", "(", "content", ")", ";", "}", "else", "{", "this", ".", "_onError", "(", "'Provided content was neither of type String nor Uint8Array! Aborting...'", ")", ";", "}", "if", "(", "this", ".", "logging", ".", "enabled", ")", "console", ".", "timeEnd", "(", "'OBJLoader2 parse: '", "+", "this", ".", "modelName", ")", ";", "return", "this", ".", "loaderRootNode", ";", "}" ]
Parses OBJ data synchronously from arraybuffer or string. @param {arraybuffer|string} content OBJ data as Uint8Array or String
[ "Parses", "OBJ", "data", "synchronously", "from", "arraybuffer", "or", "string", "." ]
729c1f1549db24c22c0bc202d7295edbc655c7bc
https://github.com/kaisalmen/WWOBJLoader/blob/729c1f1549db24c22c0bc202d7295edbc655c7bc/src/loaders/OBJLoader2.js#L334-L390
18,559
kaisalmen/WWOBJLoader
src/loaders/OBJLoader2.js
function ( content, onLoad ) { var scope = this; var measureTime = false; var scopedOnLoad = function () { onLoad( { detail: { loaderRootNode: scope.loaderRootNode, modelName: scope.modelName, instanceNo: scope.instanceNo } } ); if ( measureTime && scope.logging.enabled ) console.timeEnd( 'OBJLoader2 parseAsync: ' + scope.modelName ); }; // fast-fail in case of illegal data if ( content === null || content === undefined ) { throw 'Provided content is not a valid ArrayBuffer or String. Unable to continue parsing'; } else { measureTime = true; } if ( measureTime && this.logging.enabled ) console.time( 'OBJLoader2 parseAsync: ' + this.modelName ); this.meshBuilder.init(); var scopedOnMeshLoaded = function ( payload ) { var meshes = scope.meshBuilder.processPayload( payload ); var mesh; for ( var i in meshes ) { mesh = meshes[ i ]; scope.loaderRootNode.add( mesh ); } }; var buildCode = function ( codeSerializer ) { var workerCode = ''; workerCode += '/**\n'; workerCode += ' * This code was constructed by OBJLoader2 buildCode.\n'; workerCode += ' */\n\n'; workerCode += 'THREE = { LoaderSupport: {}, OBJLoader2: {} };\n\n'; workerCode += codeSerializer.serializeClass( 'THREE.OBJLoader2.Parser', THREE.OBJLoader2.Parser ); return workerCode; }; this.workerSupport.validate( buildCode, 'THREE.OBJLoader2.Parser' ); this.workerSupport.setCallbacks( scopedOnMeshLoaded, scopedOnLoad ); if ( scope.terminateWorkerOnLoad ) this.workerSupport.setTerminateRequested( true ); var materialNames = {}; var materials = this.meshBuilder.getMaterials(); for ( var materialName in materials ) { materialNames[ materialName ] = materialName; } this.workerSupport.run( { params: { useAsync: true, materialPerSmoothingGroup: this.materialPerSmoothingGroup, useOAsMesh: this.useOAsMesh, useIndices: this.useIndices, disregardNormals: this.disregardNormals }, logging: { enabled: this.logging.enabled, debug: this.logging.debug }, materials: { // in async case only material names are supplied to parser materials: materialNames }, data: { input: content, options: null } } ); }
javascript
function ( content, onLoad ) { var scope = this; var measureTime = false; var scopedOnLoad = function () { onLoad( { detail: { loaderRootNode: scope.loaderRootNode, modelName: scope.modelName, instanceNo: scope.instanceNo } } ); if ( measureTime && scope.logging.enabled ) console.timeEnd( 'OBJLoader2 parseAsync: ' + scope.modelName ); }; // fast-fail in case of illegal data if ( content === null || content === undefined ) { throw 'Provided content is not a valid ArrayBuffer or String. Unable to continue parsing'; } else { measureTime = true; } if ( measureTime && this.logging.enabled ) console.time( 'OBJLoader2 parseAsync: ' + this.modelName ); this.meshBuilder.init(); var scopedOnMeshLoaded = function ( payload ) { var meshes = scope.meshBuilder.processPayload( payload ); var mesh; for ( var i in meshes ) { mesh = meshes[ i ]; scope.loaderRootNode.add( mesh ); } }; var buildCode = function ( codeSerializer ) { var workerCode = ''; workerCode += '/**\n'; workerCode += ' * This code was constructed by OBJLoader2 buildCode.\n'; workerCode += ' */\n\n'; workerCode += 'THREE = { LoaderSupport: {}, OBJLoader2: {} };\n\n'; workerCode += codeSerializer.serializeClass( 'THREE.OBJLoader2.Parser', THREE.OBJLoader2.Parser ); return workerCode; }; this.workerSupport.validate( buildCode, 'THREE.OBJLoader2.Parser' ); this.workerSupport.setCallbacks( scopedOnMeshLoaded, scopedOnLoad ); if ( scope.terminateWorkerOnLoad ) this.workerSupport.setTerminateRequested( true ); var materialNames = {}; var materials = this.meshBuilder.getMaterials(); for ( var materialName in materials ) { materialNames[ materialName ] = materialName; } this.workerSupport.run( { params: { useAsync: true, materialPerSmoothingGroup: this.materialPerSmoothingGroup, useOAsMesh: this.useOAsMesh, useIndices: this.useIndices, disregardNormals: this.disregardNormals }, logging: { enabled: this.logging.enabled, debug: this.logging.debug }, materials: { // in async case only material names are supplied to parser materials: materialNames }, data: { input: content, options: null } } ); }
[ "function", "(", "content", ",", "onLoad", ")", "{", "var", "scope", "=", "this", ";", "var", "measureTime", "=", "false", ";", "var", "scopedOnLoad", "=", "function", "(", ")", "{", "onLoad", "(", "{", "detail", ":", "{", "loaderRootNode", ":", "scope", ".", "loaderRootNode", ",", "modelName", ":", "scope", ".", "modelName", ",", "instanceNo", ":", "scope", ".", "instanceNo", "}", "}", ")", ";", "if", "(", "measureTime", "&&", "scope", ".", "logging", ".", "enabled", ")", "console", ".", "timeEnd", "(", "'OBJLoader2 parseAsync: '", "+", "scope", ".", "modelName", ")", ";", "}", ";", "// fast-fail in case of illegal data", "if", "(", "content", "===", "null", "||", "content", "===", "undefined", ")", "{", "throw", "'Provided content is not a valid ArrayBuffer or String. Unable to continue parsing'", ";", "}", "else", "{", "measureTime", "=", "true", ";", "}", "if", "(", "measureTime", "&&", "this", ".", "logging", ".", "enabled", ")", "console", ".", "time", "(", "'OBJLoader2 parseAsync: '", "+", "this", ".", "modelName", ")", ";", "this", ".", "meshBuilder", ".", "init", "(", ")", ";", "var", "scopedOnMeshLoaded", "=", "function", "(", "payload", ")", "{", "var", "meshes", "=", "scope", ".", "meshBuilder", ".", "processPayload", "(", "payload", ")", ";", "var", "mesh", ";", "for", "(", "var", "i", "in", "meshes", ")", "{", "mesh", "=", "meshes", "[", "i", "]", ";", "scope", ".", "loaderRootNode", ".", "add", "(", "mesh", ")", ";", "}", "}", ";", "var", "buildCode", "=", "function", "(", "codeSerializer", ")", "{", "var", "workerCode", "=", "''", ";", "workerCode", "+=", "'/**\\n'", ";", "workerCode", "+=", "' * This code was constructed by OBJLoader2 buildCode.\\n'", ";", "workerCode", "+=", "' */\\n\\n'", ";", "workerCode", "+=", "'THREE = { LoaderSupport: {}, OBJLoader2: {} };\\n\\n'", ";", "workerCode", "+=", "codeSerializer", ".", "serializeClass", "(", "'THREE.OBJLoader2.Parser'", ",", "THREE", ".", "OBJLoader2", ".", "Parser", ")", ";", "return", "workerCode", ";", "}", ";", "this", ".", "workerSupport", ".", "validate", "(", "buildCode", ",", "'THREE.OBJLoader2.Parser'", ")", ";", "this", ".", "workerSupport", ".", "setCallbacks", "(", "scopedOnMeshLoaded", ",", "scopedOnLoad", ")", ";", "if", "(", "scope", ".", "terminateWorkerOnLoad", ")", "this", ".", "workerSupport", ".", "setTerminateRequested", "(", "true", ")", ";", "var", "materialNames", "=", "{", "}", ";", "var", "materials", "=", "this", ".", "meshBuilder", ".", "getMaterials", "(", ")", ";", "for", "(", "var", "materialName", "in", "materials", ")", "{", "materialNames", "[", "materialName", "]", "=", "materialName", ";", "}", "this", ".", "workerSupport", ".", "run", "(", "{", "params", ":", "{", "useAsync", ":", "true", ",", "materialPerSmoothingGroup", ":", "this", ".", "materialPerSmoothingGroup", ",", "useOAsMesh", ":", "this", ".", "useOAsMesh", ",", "useIndices", ":", "this", ".", "useIndices", ",", "disregardNormals", ":", "this", ".", "disregardNormals", "}", ",", "logging", ":", "{", "enabled", ":", "this", ".", "logging", ".", "enabled", ",", "debug", ":", "this", ".", "logging", ".", "debug", "}", ",", "materials", ":", "{", "// in async case only material names are supplied to parser", "materials", ":", "materialNames", "}", ",", "data", ":", "{", "input", ":", "content", ",", "options", ":", "null", "}", "}", ")", ";", "}" ]
Parses OBJ content asynchronously from arraybuffer. @param {arraybuffer} content OBJ data as Uint8Array @param {callback} onLoad Called after worker successfully completed loading
[ "Parses", "OBJ", "content", "asynchronously", "from", "arraybuffer", "." ]
729c1f1549db24c22c0bc202d7295edbc655c7bc
https://github.com/kaisalmen/WWOBJLoader/blob/729c1f1549db24c22c0bc202d7295edbc655c7bc/src/loaders/OBJLoader2.js#L398-L478
18,560
kaisalmen/WWOBJLoader
src/loaders/OBJLoader2.js
function ( url, content, onLoad, onProgress, onError, crossOrigin, materialOptions ) { var resource = new THREE.LoaderSupport.ResourceDescriptor( url, 'MTL' ); resource.setContent( content ); this._loadMtl( resource, onLoad, onProgress, onError, crossOrigin, materialOptions ); }
javascript
function ( url, content, onLoad, onProgress, onError, crossOrigin, materialOptions ) { var resource = new THREE.LoaderSupport.ResourceDescriptor( url, 'MTL' ); resource.setContent( content ); this._loadMtl( resource, onLoad, onProgress, onError, crossOrigin, materialOptions ); }
[ "function", "(", "url", ",", "content", ",", "onLoad", ",", "onProgress", ",", "onError", ",", "crossOrigin", ",", "materialOptions", ")", "{", "var", "resource", "=", "new", "THREE", ".", "LoaderSupport", ".", "ResourceDescriptor", "(", "url", ",", "'MTL'", ")", ";", "resource", ".", "setContent", "(", "content", ")", ";", "this", ".", "_loadMtl", "(", "resource", ",", "onLoad", ",", "onProgress", ",", "onError", ",", "crossOrigin", ",", "materialOptions", ")", ";", "}" ]
Utility method for loading an mtl file according resource description. Provide url or content. @param {string} url URL to the file @param {Object} content The file content as arraybuffer or text @param {function} onLoad Callback to be called after successful load @param {callback} [onProgress] A function to be called while the loading is in progress. The argument will be the XMLHttpRequest instance, which contains total and Integer bytes. @param {callback} [onError] A function to be called if an error occurs during loading. The function receives the error as an argument. @param {string} [crossOrigin] CORS value @param {Object} [materialOptions] Set material loading options for MTLLoader
[ "Utility", "method", "for", "loading", "an", "mtl", "file", "according", "resource", "description", ".", "Provide", "url", "or", "content", "." ]
729c1f1549db24c22c0bc202d7295edbc655c7bc
https://github.com/kaisalmen/WWOBJLoader/blob/729c1f1549db24c22c0bc202d7295edbc655c7bc/src/loaders/OBJLoader2.js#L491-L495
18,561
kaisalmen/WWOBJLoader
src/loaders/OBJLoader2.js
function ( arrayBuffer ) { if ( this.logging.enabled ) console.time( 'OBJLoader2.Parser.parse' ); this.configure(); var arrayBufferView = new Uint8Array( arrayBuffer ); this.contentRef = arrayBufferView; var length = arrayBufferView.byteLength; this.globalCounts.totalBytes = length; var buffer = new Array( 128 ); for ( var code, word = '', bufferPointer = 0, slashesCount = 0, i = 0; i < length; i++ ) { code = arrayBufferView[ i ]; switch ( code ) { // space case 32: if ( word.length > 0 ) buffer[ bufferPointer++ ] = word; word = ''; break; // slash case 47: if ( word.length > 0 ) buffer[ bufferPointer++ ] = word; slashesCount++; word = ''; break; // LF case 10: if ( word.length > 0 ) buffer[ bufferPointer++ ] = word; word = ''; this.globalCounts.lineByte = this.globalCounts.currentByte; this.globalCounts.currentByte = i; this.processLine( buffer, bufferPointer, slashesCount ); bufferPointer = 0; slashesCount = 0; break; // CR case 13: break; default: word += String.fromCharCode( code ); break; } } this.finalizeParsing(); if ( this.logging.enabled ) console.timeEnd( 'OBJLoader2.Parser.parse' ); }
javascript
function ( arrayBuffer ) { if ( this.logging.enabled ) console.time( 'OBJLoader2.Parser.parse' ); this.configure(); var arrayBufferView = new Uint8Array( arrayBuffer ); this.contentRef = arrayBufferView; var length = arrayBufferView.byteLength; this.globalCounts.totalBytes = length; var buffer = new Array( 128 ); for ( var code, word = '', bufferPointer = 0, slashesCount = 0, i = 0; i < length; i++ ) { code = arrayBufferView[ i ]; switch ( code ) { // space case 32: if ( word.length > 0 ) buffer[ bufferPointer++ ] = word; word = ''; break; // slash case 47: if ( word.length > 0 ) buffer[ bufferPointer++ ] = word; slashesCount++; word = ''; break; // LF case 10: if ( word.length > 0 ) buffer[ bufferPointer++ ] = word; word = ''; this.globalCounts.lineByte = this.globalCounts.currentByte; this.globalCounts.currentByte = i; this.processLine( buffer, bufferPointer, slashesCount ); bufferPointer = 0; slashesCount = 0; break; // CR case 13: break; default: word += String.fromCharCode( code ); break; } } this.finalizeParsing(); if ( this.logging.enabled ) console.timeEnd( 'OBJLoader2.Parser.parse' ); }
[ "function", "(", "arrayBuffer", ")", "{", "if", "(", "this", ".", "logging", ".", "enabled", ")", "console", ".", "time", "(", "'OBJLoader2.Parser.parse'", ")", ";", "this", ".", "configure", "(", ")", ";", "var", "arrayBufferView", "=", "new", "Uint8Array", "(", "arrayBuffer", ")", ";", "this", ".", "contentRef", "=", "arrayBufferView", ";", "var", "length", "=", "arrayBufferView", ".", "byteLength", ";", "this", ".", "globalCounts", ".", "totalBytes", "=", "length", ";", "var", "buffer", "=", "new", "Array", "(", "128", ")", ";", "for", "(", "var", "code", ",", "word", "=", "''", ",", "bufferPointer", "=", "0", ",", "slashesCount", "=", "0", ",", "i", "=", "0", ";", "i", "<", "length", ";", "i", "++", ")", "{", "code", "=", "arrayBufferView", "[", "i", "]", ";", "switch", "(", "code", ")", "{", "// space", "case", "32", ":", "if", "(", "word", ".", "length", ">", "0", ")", "buffer", "[", "bufferPointer", "++", "]", "=", "word", ";", "word", "=", "''", ";", "break", ";", "// slash", "case", "47", ":", "if", "(", "word", ".", "length", ">", "0", ")", "buffer", "[", "bufferPointer", "++", "]", "=", "word", ";", "slashesCount", "++", ";", "word", "=", "''", ";", "break", ";", "// LF", "case", "10", ":", "if", "(", "word", ".", "length", ">", "0", ")", "buffer", "[", "bufferPointer", "++", "]", "=", "word", ";", "word", "=", "''", ";", "this", ".", "globalCounts", ".", "lineByte", "=", "this", ".", "globalCounts", ".", "currentByte", ";", "this", ".", "globalCounts", ".", "currentByte", "=", "i", ";", "this", ".", "processLine", "(", "buffer", ",", "bufferPointer", ",", "slashesCount", ")", ";", "bufferPointer", "=", "0", ";", "slashesCount", "=", "0", ";", "break", ";", "// CR", "case", "13", ":", "break", ";", "default", ":", "word", "+=", "String", ".", "fromCharCode", "(", "code", ")", ";", "break", ";", "}", "}", "this", ".", "finalizeParsing", "(", ")", ";", "if", "(", "this", ".", "logging", ".", "enabled", ")", "console", ".", "timeEnd", "(", "'OBJLoader2.Parser.parse'", ")", ";", "}" ]
Parse the provided arraybuffer @param {Uint8Array} arrayBuffer OBJ data as Uint8Array
[ "Parse", "the", "provided", "arraybuffer" ]
729c1f1549db24c22c0bc202d7295edbc655c7bc
https://github.com/kaisalmen/WWOBJLoader/blob/729c1f1549db24c22c0bc202d7295edbc655c7bc/src/loaders/OBJLoader2.js#L783-L831
18,562
kaisalmen/WWOBJLoader
src/loaders/OBJLoader2.js
function ( text ) { if ( this.logging.enabled ) console.time( 'OBJLoader2.Parser.parseText' ); this.configure(); this.legacyMode = true; this.contentRef = text; var length = text.length; this.globalCounts.totalBytes = length; var buffer = new Array( 128 ); for ( var char, word = '', bufferPointer = 0, slashesCount = 0, i = 0; i < length; i++ ) { char = text[ i ]; switch ( char ) { case ' ': if ( word.length > 0 ) buffer[ bufferPointer++ ] = word; word = ''; break; case '/': if ( word.length > 0 ) buffer[ bufferPointer++ ] = word; slashesCount++; word = ''; break; case '\n': if ( word.length > 0 ) buffer[ bufferPointer++ ] = word; word = ''; this.globalCounts.lineByte = this.globalCounts.currentByte; this.globalCounts.currentByte = i; this.processLine( buffer, bufferPointer, slashesCount ); bufferPointer = 0; slashesCount = 0; break; case '\r': break; default: word += char; } } this.finalizeParsing(); if ( this.logging.enabled ) console.timeEnd( 'OBJLoader2.Parser.parseText' ); }
javascript
function ( text ) { if ( this.logging.enabled ) console.time( 'OBJLoader2.Parser.parseText' ); this.configure(); this.legacyMode = true; this.contentRef = text; var length = text.length; this.globalCounts.totalBytes = length; var buffer = new Array( 128 ); for ( var char, word = '', bufferPointer = 0, slashesCount = 0, i = 0; i < length; i++ ) { char = text[ i ]; switch ( char ) { case ' ': if ( word.length > 0 ) buffer[ bufferPointer++ ] = word; word = ''; break; case '/': if ( word.length > 0 ) buffer[ bufferPointer++ ] = word; slashesCount++; word = ''; break; case '\n': if ( word.length > 0 ) buffer[ bufferPointer++ ] = word; word = ''; this.globalCounts.lineByte = this.globalCounts.currentByte; this.globalCounts.currentByte = i; this.processLine( buffer, bufferPointer, slashesCount ); bufferPointer = 0; slashesCount = 0; break; case '\r': break; default: word += char; } } this.finalizeParsing(); if ( this.logging.enabled ) console.timeEnd( 'OBJLoader2.Parser.parseText' ); }
[ "function", "(", "text", ")", "{", "if", "(", "this", ".", "logging", ".", "enabled", ")", "console", ".", "time", "(", "'OBJLoader2.Parser.parseText'", ")", ";", "this", ".", "configure", "(", ")", ";", "this", ".", "legacyMode", "=", "true", ";", "this", ".", "contentRef", "=", "text", ";", "var", "length", "=", "text", ".", "length", ";", "this", ".", "globalCounts", ".", "totalBytes", "=", "length", ";", "var", "buffer", "=", "new", "Array", "(", "128", ")", ";", "for", "(", "var", "char", ",", "word", "=", "''", ",", "bufferPointer", "=", "0", ",", "slashesCount", "=", "0", ",", "i", "=", "0", ";", "i", "<", "length", ";", "i", "++", ")", "{", "char", "=", "text", "[", "i", "]", ";", "switch", "(", "char", ")", "{", "case", "' '", ":", "if", "(", "word", ".", "length", ">", "0", ")", "buffer", "[", "bufferPointer", "++", "]", "=", "word", ";", "word", "=", "''", ";", "break", ";", "case", "'/'", ":", "if", "(", "word", ".", "length", ">", "0", ")", "buffer", "[", "bufferPointer", "++", "]", "=", "word", ";", "slashesCount", "++", ";", "word", "=", "''", ";", "break", ";", "case", "'\\n'", ":", "if", "(", "word", ".", "length", ">", "0", ")", "buffer", "[", "bufferPointer", "++", "]", "=", "word", ";", "word", "=", "''", ";", "this", ".", "globalCounts", ".", "lineByte", "=", "this", ".", "globalCounts", ".", "currentByte", ";", "this", ".", "globalCounts", ".", "currentByte", "=", "i", ";", "this", ".", "processLine", "(", "buffer", ",", "bufferPointer", ",", "slashesCount", ")", ";", "bufferPointer", "=", "0", ";", "slashesCount", "=", "0", ";", "break", ";", "case", "'\\r'", ":", "break", ";", "default", ":", "word", "+=", "char", ";", "}", "}", "this", ".", "finalizeParsing", "(", ")", ";", "if", "(", "this", ".", "logging", ".", "enabled", ")", "console", ".", "timeEnd", "(", "'OBJLoader2.Parser.parseText'", ")", ";", "}" ]
Parse the provided text @param {string} text OBJ data as string
[ "Parse", "the", "provided", "text" ]
729c1f1549db24c22c0bc202d7295edbc655c7bc
https://github.com/kaisalmen/WWOBJLoader/blob/729c1f1549db24c22c0bc202d7295edbc655c7bc/src/loaders/OBJLoader2.js#L838-L881
18,563
kaisalmen/WWOBJLoader
src/loaders/OBJLoader2.js
function () { var meshOutputGroupTemp = []; var meshOutputGroup; var absoluteVertexCount = 0; var absoluteIndexMappingsCount = 0; var absoluteIndexCount = 0; var absoluteColorCount = 0; var absoluteNormalCount = 0; var absoluteUvCount = 0; var indices; for ( var name in this.rawMesh.subGroups ) { meshOutputGroup = this.rawMesh.subGroups[ name ]; if ( meshOutputGroup.vertices.length > 0 ) { indices = meshOutputGroup.indices; if ( indices.length > 0 && absoluteIndexMappingsCount > 0 ) { for ( var i in indices ) indices[ i ] = indices[ i ] + absoluteIndexMappingsCount; } meshOutputGroupTemp.push( meshOutputGroup ); absoluteVertexCount += meshOutputGroup.vertices.length; absoluteIndexMappingsCount += meshOutputGroup.indexMappingsCount; absoluteIndexCount += meshOutputGroup.indices.length; absoluteColorCount += meshOutputGroup.colors.length; absoluteUvCount += meshOutputGroup.uvs.length; absoluteNormalCount += meshOutputGroup.normals.length; } } // do not continue if no result var result = null; if ( meshOutputGroupTemp.length > 0 ) { result = { name: this.rawMesh.groupName !== '' ? this.rawMesh.groupName : this.rawMesh.objectName, subGroups: meshOutputGroupTemp, absoluteVertexCount: absoluteVertexCount, absoluteIndexCount: absoluteIndexCount, absoluteColorCount: absoluteColorCount, absoluteNormalCount: absoluteNormalCount, absoluteUvCount: absoluteUvCount, faceCount: this.rawMesh.counts.faceCount, doubleIndicesCount: this.rawMesh.counts.doubleIndicesCount }; } return result; }
javascript
function () { var meshOutputGroupTemp = []; var meshOutputGroup; var absoluteVertexCount = 0; var absoluteIndexMappingsCount = 0; var absoluteIndexCount = 0; var absoluteColorCount = 0; var absoluteNormalCount = 0; var absoluteUvCount = 0; var indices; for ( var name in this.rawMesh.subGroups ) { meshOutputGroup = this.rawMesh.subGroups[ name ]; if ( meshOutputGroup.vertices.length > 0 ) { indices = meshOutputGroup.indices; if ( indices.length > 0 && absoluteIndexMappingsCount > 0 ) { for ( var i in indices ) indices[ i ] = indices[ i ] + absoluteIndexMappingsCount; } meshOutputGroupTemp.push( meshOutputGroup ); absoluteVertexCount += meshOutputGroup.vertices.length; absoluteIndexMappingsCount += meshOutputGroup.indexMappingsCount; absoluteIndexCount += meshOutputGroup.indices.length; absoluteColorCount += meshOutputGroup.colors.length; absoluteUvCount += meshOutputGroup.uvs.length; absoluteNormalCount += meshOutputGroup.normals.length; } } // do not continue if no result var result = null; if ( meshOutputGroupTemp.length > 0 ) { result = { name: this.rawMesh.groupName !== '' ? this.rawMesh.groupName : this.rawMesh.objectName, subGroups: meshOutputGroupTemp, absoluteVertexCount: absoluteVertexCount, absoluteIndexCount: absoluteIndexCount, absoluteColorCount: absoluteColorCount, absoluteNormalCount: absoluteNormalCount, absoluteUvCount: absoluteUvCount, faceCount: this.rawMesh.counts.faceCount, doubleIndicesCount: this.rawMesh.counts.doubleIndicesCount }; } return result; }
[ "function", "(", ")", "{", "var", "meshOutputGroupTemp", "=", "[", "]", ";", "var", "meshOutputGroup", ";", "var", "absoluteVertexCount", "=", "0", ";", "var", "absoluteIndexMappingsCount", "=", "0", ";", "var", "absoluteIndexCount", "=", "0", ";", "var", "absoluteColorCount", "=", "0", ";", "var", "absoluteNormalCount", "=", "0", ";", "var", "absoluteUvCount", "=", "0", ";", "var", "indices", ";", "for", "(", "var", "name", "in", "this", ".", "rawMesh", ".", "subGroups", ")", "{", "meshOutputGroup", "=", "this", ".", "rawMesh", ".", "subGroups", "[", "name", "]", ";", "if", "(", "meshOutputGroup", ".", "vertices", ".", "length", ">", "0", ")", "{", "indices", "=", "meshOutputGroup", ".", "indices", ";", "if", "(", "indices", ".", "length", ">", "0", "&&", "absoluteIndexMappingsCount", ">", "0", ")", "{", "for", "(", "var", "i", "in", "indices", ")", "indices", "[", "i", "]", "=", "indices", "[", "i", "]", "+", "absoluteIndexMappingsCount", ";", "}", "meshOutputGroupTemp", ".", "push", "(", "meshOutputGroup", ")", ";", "absoluteVertexCount", "+=", "meshOutputGroup", ".", "vertices", ".", "length", ";", "absoluteIndexMappingsCount", "+=", "meshOutputGroup", ".", "indexMappingsCount", ";", "absoluteIndexCount", "+=", "meshOutputGroup", ".", "indices", ".", "length", ";", "absoluteColorCount", "+=", "meshOutputGroup", ".", "colors", ".", "length", ";", "absoluteUvCount", "+=", "meshOutputGroup", ".", "uvs", ".", "length", ";", "absoluteNormalCount", "+=", "meshOutputGroup", ".", "normals", ".", "length", ";", "}", "}", "// do not continue if no result", "var", "result", "=", "null", ";", "if", "(", "meshOutputGroupTemp", ".", "length", ">", "0", ")", "{", "result", "=", "{", "name", ":", "this", ".", "rawMesh", ".", "groupName", "!==", "''", "?", "this", ".", "rawMesh", ".", "groupName", ":", "this", ".", "rawMesh", ".", "objectName", ",", "subGroups", ":", "meshOutputGroupTemp", ",", "absoluteVertexCount", ":", "absoluteVertexCount", ",", "absoluteIndexCount", ":", "absoluteIndexCount", ",", "absoluteColorCount", ":", "absoluteColorCount", ",", "absoluteNormalCount", ":", "absoluteNormalCount", ",", "absoluteUvCount", ":", "absoluteUvCount", ",", "faceCount", ":", "this", ".", "rawMesh", ".", "counts", ".", "faceCount", ",", "doubleIndicesCount", ":", "this", ".", "rawMesh", ".", "counts", ".", "doubleIndicesCount", "}", ";", "}", "return", "result", ";", "}" ]
Clear any empty subGroup and calculate absolute vertex, normal and uv counts
[ "Clear", "any", "empty", "subGroup", "and", "calculate", "absolute", "vertex", "normal", "and", "uv", "counts" ]
729c1f1549db24c22c0bc202d7295edbc655c7bc
https://github.com/kaisalmen/WWOBJLoader/blob/729c1f1549db24c22c0bc202d7295edbc655c7bc/src/loaders/OBJLoader2.js#L1188-L1238
18,564
kaisalmen/WWOBJLoader
src/loaders/support/LoaderBuilder.js
function () { var materialsJSON = {}; var material; for ( var materialName in this.materials ) { material = this.materials[ materialName ]; materialsJSON[ materialName ] = material.toJSON(); } return materialsJSON; }
javascript
function () { var materialsJSON = {}; var material; for ( var materialName in this.materials ) { material = this.materials[ materialName ]; materialsJSON[ materialName ] = material.toJSON(); } return materialsJSON; }
[ "function", "(", ")", "{", "var", "materialsJSON", "=", "{", "}", ";", "var", "material", ";", "for", "(", "var", "materialName", "in", "this", ".", "materials", ")", "{", "material", "=", "this", ".", "materials", "[", "materialName", "]", ";", "materialsJSON", "[", "materialName", "]", "=", "material", ".", "toJSON", "(", ")", ";", "}", "return", "materialsJSON", ";", "}" ]
Returns the mapping object of material name and corresponding jsonified material. @returns {Object} Map of Materials in JSON representation
[ "Returns", "the", "mapping", "object", "of", "material", "name", "and", "corresponding", "jsonified", "material", "." ]
729c1f1549db24c22c0bc202d7295edbc655c7bc
https://github.com/kaisalmen/WWOBJLoader/blob/729c1f1549db24c22c0bc202d7295edbc655c7bc/src/loaders/support/LoaderBuilder.js#L347-L357
18,565
kaisalmen/WWOBJLoader
src/loaders/support/LoaderWorkerDirector.js
function ( globalCallbacks, maxQueueSize, maxWebWorkers ) { if ( THREE.LoaderSupport.Validator.isValid( globalCallbacks ) ) this.workerDescription.globalCallbacks = globalCallbacks; this.maxQueueSize = Math.min( maxQueueSize, THREE.LoaderSupport.WorkerDirector.MAX_QUEUE_SIZE ); this.maxWebWorkers = Math.min( maxWebWorkers, THREE.LoaderSupport.WorkerDirector.MAX_WEB_WORKER ); this.maxWebWorkers = Math.min( this.maxWebWorkers, this.maxQueueSize ); this.objectsCompleted = 0; this.instructionQueue = []; this.instructionQueuePointer = 0; for ( var instanceNo = 0; instanceNo < this.maxWebWorkers; instanceNo++ ) { var workerSupport = new THREE.LoaderSupport.WorkerSupport(); workerSupport.setLogging( this.logging.enabled, this.logging.debug ); workerSupport.setForceWorkerDataCopy( this.workerDescription.forceWorkerDataCopy ); this.workerDescription.workerSupports[ instanceNo ] = { instanceNo: instanceNo, inUse: false, terminateRequested: false, workerSupport: workerSupport, loader: null }; } }
javascript
function ( globalCallbacks, maxQueueSize, maxWebWorkers ) { if ( THREE.LoaderSupport.Validator.isValid( globalCallbacks ) ) this.workerDescription.globalCallbacks = globalCallbacks; this.maxQueueSize = Math.min( maxQueueSize, THREE.LoaderSupport.WorkerDirector.MAX_QUEUE_SIZE ); this.maxWebWorkers = Math.min( maxWebWorkers, THREE.LoaderSupport.WorkerDirector.MAX_WEB_WORKER ); this.maxWebWorkers = Math.min( this.maxWebWorkers, this.maxQueueSize ); this.objectsCompleted = 0; this.instructionQueue = []; this.instructionQueuePointer = 0; for ( var instanceNo = 0; instanceNo < this.maxWebWorkers; instanceNo++ ) { var workerSupport = new THREE.LoaderSupport.WorkerSupport(); workerSupport.setLogging( this.logging.enabled, this.logging.debug ); workerSupport.setForceWorkerDataCopy( this.workerDescription.forceWorkerDataCopy ); this.workerDescription.workerSupports[ instanceNo ] = { instanceNo: instanceNo, inUse: false, terminateRequested: false, workerSupport: workerSupport, loader: null }; } }
[ "function", "(", "globalCallbacks", ",", "maxQueueSize", ",", "maxWebWorkers", ")", "{", "if", "(", "THREE", ".", "LoaderSupport", ".", "Validator", ".", "isValid", "(", "globalCallbacks", ")", ")", "this", ".", "workerDescription", ".", "globalCallbacks", "=", "globalCallbacks", ";", "this", ".", "maxQueueSize", "=", "Math", ".", "min", "(", "maxQueueSize", ",", "THREE", ".", "LoaderSupport", ".", "WorkerDirector", ".", "MAX_QUEUE_SIZE", ")", ";", "this", ".", "maxWebWorkers", "=", "Math", ".", "min", "(", "maxWebWorkers", ",", "THREE", ".", "LoaderSupport", ".", "WorkerDirector", ".", "MAX_WEB_WORKER", ")", ";", "this", ".", "maxWebWorkers", "=", "Math", ".", "min", "(", "this", ".", "maxWebWorkers", ",", "this", ".", "maxQueueSize", ")", ";", "this", ".", "objectsCompleted", "=", "0", ";", "this", ".", "instructionQueue", "=", "[", "]", ";", "this", ".", "instructionQueuePointer", "=", "0", ";", "for", "(", "var", "instanceNo", "=", "0", ";", "instanceNo", "<", "this", ".", "maxWebWorkers", ";", "instanceNo", "++", ")", "{", "var", "workerSupport", "=", "new", "THREE", ".", "LoaderSupport", ".", "WorkerSupport", "(", ")", ";", "workerSupport", ".", "setLogging", "(", "this", ".", "logging", ".", "enabled", ",", "this", ".", "logging", ".", "debug", ")", ";", "workerSupport", ".", "setForceWorkerDataCopy", "(", "this", ".", "workerDescription", ".", "forceWorkerDataCopy", ")", ";", "this", ".", "workerDescription", ".", "workerSupports", "[", "instanceNo", "]", "=", "{", "instanceNo", ":", "instanceNo", ",", "inUse", ":", "false", ",", "terminateRequested", ":", "false", ",", "workerSupport", ":", "workerSupport", ",", "loader", ":", "null", "}", ";", "}", "}" ]
Create or destroy workers according limits. Set the name and register callbacks for dynamically created web workers. @param {THREE.OBJLoader2.WWOBJLoader2.PrepDataCallbacks} globalCallbacks Register global callbacks used by all web workers @param {number} maxQueueSize Set the maximum size of the instruction queue (1-1024) @param {number} maxWebWorkers Set the maximum amount of workers (1-16)
[ "Create", "or", "destroy", "workers", "according", "limits", ".", "Set", "the", "name", "and", "register", "callbacks", "for", "dynamically", "created", "web", "workers", "." ]
729c1f1549db24c22c0bc202d7295edbc655c7bc
https://github.com/kaisalmen/WWOBJLoader/blob/729c1f1549db24c22c0bc202d7295edbc655c7bc/src/loaders/support/LoaderWorkerDirector.js#L102-L125
18,566
kaisalmen/WWOBJLoader
src/loaders/support/LoaderWorkerDirector.js
function () { var wsKeys = Object.keys( this.workerDescription.workerSupports ); return ( ( this.instructionQueue.length > 0 && this.instructionQueuePointer < this.instructionQueue.length ) || wsKeys.length > 0 ); }
javascript
function () { var wsKeys = Object.keys( this.workerDescription.workerSupports ); return ( ( this.instructionQueue.length > 0 && this.instructionQueuePointer < this.instructionQueue.length ) || wsKeys.length > 0 ); }
[ "function", "(", ")", "{", "var", "wsKeys", "=", "Object", ".", "keys", "(", "this", ".", "workerDescription", ".", "workerSupports", ")", ";", "return", "(", "(", "this", ".", "instructionQueue", ".", "length", ">", "0", "&&", "this", ".", "instructionQueuePointer", "<", "this", ".", "instructionQueue", ".", "length", ")", "||", "wsKeys", ".", "length", ">", "0", ")", ";", "}" ]
Returns if any workers are running. @returns {boolean}
[ "Returns", "if", "any", "workers", "are", "running", "." ]
729c1f1549db24c22c0bc202d7295edbc655c7bc
https://github.com/kaisalmen/WWOBJLoader/blob/729c1f1549db24c22c0bc202d7295edbc655c7bc/src/loaders/support/LoaderWorkerDirector.js#L143-L146
18,567
kaisalmen/WWOBJLoader
src/loaders/support/LoaderWorkerDirector.js
function () { var prepData, supportDesc; for ( var instanceNo in this.workerDescription.workerSupports ) { supportDesc = this.workerDescription.workerSupports[ instanceNo ]; if ( ! supportDesc.inUse ) { if ( this.instructionQueuePointer < this.instructionQueue.length ) { prepData = this.instructionQueue[ this.instructionQueuePointer ]; this._kickWorkerRun( prepData, supportDesc ); this.instructionQueuePointer++; } else { this._deregister( supportDesc ); } } } if ( ! this.isRunning() && this.callbackOnFinishedProcessing !== null ) { this.callbackOnFinishedProcessing(); this.callbackOnFinishedProcessing = null; } }
javascript
function () { var prepData, supportDesc; for ( var instanceNo in this.workerDescription.workerSupports ) { supportDesc = this.workerDescription.workerSupports[ instanceNo ]; if ( ! supportDesc.inUse ) { if ( this.instructionQueuePointer < this.instructionQueue.length ) { prepData = this.instructionQueue[ this.instructionQueuePointer ]; this._kickWorkerRun( prepData, supportDesc ); this.instructionQueuePointer++; } else { this._deregister( supportDesc ); } } } if ( ! this.isRunning() && this.callbackOnFinishedProcessing !== null ) { this.callbackOnFinishedProcessing(); this.callbackOnFinishedProcessing = null; } }
[ "function", "(", ")", "{", "var", "prepData", ",", "supportDesc", ";", "for", "(", "var", "instanceNo", "in", "this", ".", "workerDescription", ".", "workerSupports", ")", "{", "supportDesc", "=", "this", ".", "workerDescription", ".", "workerSupports", "[", "instanceNo", "]", ";", "if", "(", "!", "supportDesc", ".", "inUse", ")", "{", "if", "(", "this", ".", "instructionQueuePointer", "<", "this", ".", "instructionQueue", ".", "length", ")", "{", "prepData", "=", "this", ".", "instructionQueue", "[", "this", ".", "instructionQueuePointer", "]", ";", "this", ".", "_kickWorkerRun", "(", "prepData", ",", "supportDesc", ")", ";", "this", ".", "instructionQueuePointer", "++", ";", "}", "else", "{", "this", ".", "_deregister", "(", "supportDesc", ")", ";", "}", "}", "}", "if", "(", "!", "this", ".", "isRunning", "(", ")", "&&", "this", ".", "callbackOnFinishedProcessing", "!==", "null", ")", "{", "this", ".", "callbackOnFinishedProcessing", "(", ")", ";", "this", ".", "callbackOnFinishedProcessing", "=", "null", ";", "}", "}" ]
Process the instructionQueue until it is depleted.
[ "Process", "the", "instructionQueue", "until", "it", "is", "depleted", "." ]
729c1f1549db24c22c0bc202d7295edbc655c7bc
https://github.com/kaisalmen/WWOBJLoader/blob/729c1f1549db24c22c0bc202d7295edbc655c7bc/src/loaders/support/LoaderWorkerDirector.js#L151-L180
18,568
kaisalmen/WWOBJLoader
src/loaders/support/LoaderWorkerDirector.js
function ( callbackOnFinishedProcessing ) { if ( this.logging.enabled ) console.info( 'WorkerDirector received the deregister call. Terminating all workers!' ); this.instructionQueuePointer = this.instructionQueue.length; this.callbackOnFinishedProcessing = THREE.LoaderSupport.Validator.verifyInput( callbackOnFinishedProcessing, null ); for ( var name in this.workerDescription.workerSupports ) { this.workerDescription.workerSupports[ name ].terminateRequested = true; } }
javascript
function ( callbackOnFinishedProcessing ) { if ( this.logging.enabled ) console.info( 'WorkerDirector received the deregister call. Terminating all workers!' ); this.instructionQueuePointer = this.instructionQueue.length; this.callbackOnFinishedProcessing = THREE.LoaderSupport.Validator.verifyInput( callbackOnFinishedProcessing, null ); for ( var name in this.workerDescription.workerSupports ) { this.workerDescription.workerSupports[ name ].terminateRequested = true; } }
[ "function", "(", "callbackOnFinishedProcessing", ")", "{", "if", "(", "this", ".", "logging", ".", "enabled", ")", "console", ".", "info", "(", "'WorkerDirector received the deregister call. Terminating all workers!'", ")", ";", "this", ".", "instructionQueuePointer", "=", "this", ".", "instructionQueue", ".", "length", ";", "this", ".", "callbackOnFinishedProcessing", "=", "THREE", ".", "LoaderSupport", ".", "Validator", ".", "verifyInput", "(", "callbackOnFinishedProcessing", ",", "null", ")", ";", "for", "(", "var", "name", "in", "this", ".", "workerDescription", ".", "workerSupports", ")", "{", "this", ".", "workerDescription", ".", "workerSupports", "[", "name", "]", ".", "terminateRequested", "=", "true", ";", "}", "}" ]
Terminate all workers. @param {callback} callbackOnFinishedProcessing Function called once all workers finished processing.
[ "Terminate", "all", "workers", "." ]
729c1f1549db24c22c0bc202d7295edbc655c7bc
https://github.com/kaisalmen/WWOBJLoader/blob/729c1f1549db24c22c0bc202d7295edbc655c7bc/src/loaders/support/LoaderWorkerDirector.js#L293-L304
18,569
blankapp/ui
docs/themes/landscape/source/fancybox/helpers/jquery.fancybox-thumbs.js
function ( item ) { // function to obtain the URL of the thumbnail image var href; if (item.element) { href = $(item.element).find('img').attr('src'); } if (!href && item.type === 'image' && item.href) { href = item.href; } return href; }
javascript
function ( item ) { // function to obtain the URL of the thumbnail image var href; if (item.element) { href = $(item.element).find('img').attr('src'); } if (!href && item.type === 'image' && item.href) { href = item.href; } return href; }
[ "function", "(", "item", ")", "{", "// function to obtain the URL of the thumbnail image", "var", "href", ";", "if", "(", "item", ".", "element", ")", "{", "href", "=", "$", "(", "item", ".", "element", ")", ".", "find", "(", "'img'", ")", ".", "attr", "(", "'src'", ")", ";", "}", "if", "(", "!", "href", "&&", "item", ".", "type", "===", "'image'", "&&", "item", ".", "href", ")", "{", "href", "=", "item", ".", "href", ";", "}", "return", "href", ";", "}" ]
'top' or 'bottom'
[ "top", "or", "bottom" ]
3e9347658754d6bc3aef4a1a7b5014e699346636
https://github.com/blankapp/ui/blob/3e9347658754d6bc3aef4a1a7b5014e699346636/docs/themes/landscape/source/fancybox/helpers/jquery.fancybox-thumbs.js#L27-L39
18,570
blankapp/ui
docs/themes/landscape/source/fancybox/helpers/jquery.fancybox-media.js
function( url, rez, params ) { params = params || ''; if ( $.type( params ) === "object" ) { params = $.param(params, true); } $.each(rez, function(key, value) { url = url.replace( '$' + key, value || '' ); }); if (params.length) { url += ( url.indexOf('?') > 0 ? '&' : '?' ) + params; } return url; }
javascript
function( url, rez, params ) { params = params || ''; if ( $.type( params ) === "object" ) { params = $.param(params, true); } $.each(rez, function(key, value) { url = url.replace( '$' + key, value || '' ); }); if (params.length) { url += ( url.indexOf('?') > 0 ? '&' : '?' ) + params; } return url; }
[ "function", "(", "url", ",", "rez", ",", "params", ")", "{", "params", "=", "params", "||", "''", ";", "if", "(", "$", ".", "type", "(", "params", ")", "===", "\"object\"", ")", "{", "params", "=", "$", ".", "param", "(", "params", ",", "true", ")", ";", "}", "$", ".", "each", "(", "rez", ",", "function", "(", "key", ",", "value", ")", "{", "url", "=", "url", ".", "replace", "(", "'$'", "+", "key", ",", "value", "||", "''", ")", ";", "}", ")", ";", "if", "(", "params", ".", "length", ")", "{", "url", "+=", "(", "url", ".", "indexOf", "(", "'?'", ")", ">", "0", "?", "'&'", ":", "'?'", ")", "+", "params", ";", "}", "return", "url", ";", "}" ]
Shortcut for fancyBox object
[ "Shortcut", "for", "fancyBox", "object" ]
3e9347658754d6bc3aef4a1a7b5014e699346636
https://github.com/blankapp/ui/blob/3e9347658754d6bc3aef4a1a7b5014e699346636/docs/themes/landscape/source/fancybox/helpers/jquery.fancybox-media.js#L70-L86
18,571
buunguyen/mongoose-deep-populate
lib/plugin.js
createMongoosePromise
function createMongoosePromise(resolver) { var promise // mongoose 5 and up if (parseInt(mongoose.version) >= 5) { promise = new mongoose.Promise(resolver) } // mongoose 4.1 and up else if (mongoose.Promise.ES6) { promise = new mongoose.Promise.ES6(resolver) } // backward compatibility else { promise = new mongoose.Promise resolver(promise.resolve.bind(promise, null), promise.reject.bind(promise)) } return promise }
javascript
function createMongoosePromise(resolver) { var promise // mongoose 5 and up if (parseInt(mongoose.version) >= 5) { promise = new mongoose.Promise(resolver) } // mongoose 4.1 and up else if (mongoose.Promise.ES6) { promise = new mongoose.Promise.ES6(resolver) } // backward compatibility else { promise = new mongoose.Promise resolver(promise.resolve.bind(promise, null), promise.reject.bind(promise)) } return promise }
[ "function", "createMongoosePromise", "(", "resolver", ")", "{", "var", "promise", "// mongoose 5 and up", "if", "(", "parseInt", "(", "mongoose", ".", "version", ")", ">=", "5", ")", "{", "promise", "=", "new", "mongoose", ".", "Promise", "(", "resolver", ")", "}", "// mongoose 4.1 and up", "else", "if", "(", "mongoose", ".", "Promise", ".", "ES6", ")", "{", "promise", "=", "new", "mongoose", ".", "Promise", ".", "ES6", "(", "resolver", ")", "}", "// backward compatibility", "else", "{", "promise", "=", "new", "mongoose", ".", "Promise", "resolver", "(", "promise", ".", "resolve", ".", "bind", "(", "promise", ",", "null", ")", ",", "promise", ".", "reject", ".", "bind", "(", "promise", ")", ")", "}", "return", "promise", "}" ]
Creates a Mongoose promise.
[ "Creates", "a", "Mongoose", "promise", "." ]
4f7ee2f47743b00eb6431512660d067bc481144c
https://github.com/buunguyen/mongoose-deep-populate/blob/4f7ee2f47743b00eb6431512660d067bc481144c/lib/plugin.js#L89-L107
18,572
buunguyen/mongoose-deep-populate
lib/plugin.js
deepPopulatePlugin
function deepPopulatePlugin(schema, defaultOptions) { schema._defaultDeepPopulateOptions = defaultOptions = defaultOptions || {} /** * Populates this document with the specified paths. * @param paths the paths to be populated. * @param options (optional) the population options. * @param cb (optional) the callback. * @return {MongoosePromise} */ schema.methods.deepPopulate = function (paths, options, cb) { return deepPopulate(this.constructor, this, paths, options, cb) } /** * Populates provided documents with the specified paths. * @param docs the documents to be populated. * @param paths the paths to be populated. * @param options (optional) the population options. * @param cb (optional) the callback. * @return {MongoosePromise} */ schema.statics.deepPopulate = function (docs, paths, options, cb) { return deepPopulate(this, docs, paths, options, cb) } function deepPopulate(model, docs, paths, options, cb) { if (isFunction(options)) { cb = options options = null } else { cb = cb || noop } return createMongoosePromise(function (resolve, reject) { if (docs == null || docs.length === 0) { return resolve(docs), cb(null, docs) } execute(model, docs, paths, options, defaultOptions, false, function (err, docs) { if (err) reject(err), cb(err) else resolve(docs), cb(null, docs) }) }) } }
javascript
function deepPopulatePlugin(schema, defaultOptions) { schema._defaultDeepPopulateOptions = defaultOptions = defaultOptions || {} /** * Populates this document with the specified paths. * @param paths the paths to be populated. * @param options (optional) the population options. * @param cb (optional) the callback. * @return {MongoosePromise} */ schema.methods.deepPopulate = function (paths, options, cb) { return deepPopulate(this.constructor, this, paths, options, cb) } /** * Populates provided documents with the specified paths. * @param docs the documents to be populated. * @param paths the paths to be populated. * @param options (optional) the population options. * @param cb (optional) the callback. * @return {MongoosePromise} */ schema.statics.deepPopulate = function (docs, paths, options, cb) { return deepPopulate(this, docs, paths, options, cb) } function deepPopulate(model, docs, paths, options, cb) { if (isFunction(options)) { cb = options options = null } else { cb = cb || noop } return createMongoosePromise(function (resolve, reject) { if (docs == null || docs.length === 0) { return resolve(docs), cb(null, docs) } execute(model, docs, paths, options, defaultOptions, false, function (err, docs) { if (err) reject(err), cb(err) else resolve(docs), cb(null, docs) }) }) } }
[ "function", "deepPopulatePlugin", "(", "schema", ",", "defaultOptions", ")", "{", "schema", ".", "_defaultDeepPopulateOptions", "=", "defaultOptions", "=", "defaultOptions", "||", "{", "}", "/**\n * Populates this document with the specified paths.\n * @param paths the paths to be populated.\n * @param options (optional) the population options.\n * @param cb (optional) the callback.\n * @return {MongoosePromise}\n */", "schema", ".", "methods", ".", "deepPopulate", "=", "function", "(", "paths", ",", "options", ",", "cb", ")", "{", "return", "deepPopulate", "(", "this", ".", "constructor", ",", "this", ",", "paths", ",", "options", ",", "cb", ")", "}", "/**\n * Populates provided documents with the specified paths.\n * @param docs the documents to be populated.\n * @param paths the paths to be populated.\n * @param options (optional) the population options.\n * @param cb (optional) the callback.\n * @return {MongoosePromise}\n */", "schema", ".", "statics", ".", "deepPopulate", "=", "function", "(", "docs", ",", "paths", ",", "options", ",", "cb", ")", "{", "return", "deepPopulate", "(", "this", ",", "docs", ",", "paths", ",", "options", ",", "cb", ")", "}", "function", "deepPopulate", "(", "model", ",", "docs", ",", "paths", ",", "options", ",", "cb", ")", "{", "if", "(", "isFunction", "(", "options", ")", ")", "{", "cb", "=", "options", "options", "=", "null", "}", "else", "{", "cb", "=", "cb", "||", "noop", "}", "return", "createMongoosePromise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "if", "(", "docs", "==", "null", "||", "docs", ".", "length", "===", "0", ")", "{", "return", "resolve", "(", "docs", ")", ",", "cb", "(", "null", ",", "docs", ")", "}", "execute", "(", "model", ",", "docs", ",", "paths", ",", "options", ",", "defaultOptions", ",", "false", ",", "function", "(", "err", ",", "docs", ")", "{", "if", "(", "err", ")", "reject", "(", "err", ")", ",", "cb", "(", "err", ")", "else", "resolve", "(", "docs", ")", ",", "cb", "(", "null", ",", "docs", ")", "}", ")", "}", ")", "}", "}" ]
Invoked by Mongoose to executes the plugin on the specified schema.
[ "Invoked", "by", "Mongoose", "to", "executes", "the", "plugin", "on", "the", "specified", "schema", "." ]
4f7ee2f47743b00eb6431512660d067bc481144c
https://github.com/buunguyen/mongoose-deep-populate/blob/4f7ee2f47743b00eb6431512660d067bc481144c/lib/plugin.js#L112-L158
18,573
benjamn/reify
lib/utils.js
findPossibleIndexes
function findPossibleIndexes(code, identifiers, filter) { const possibleIndexes = []; if (identifiers.length === 0) { return possibleIndexes; } const pattern = new RegExp( "\\b(?:" + identifiers.join("|") + ")\\b", "g" ); let match; pattern.lastIndex = 0; while ((match = pattern.exec(code))) { if (typeof filter !== "function" || filter(match)) { possibleIndexes.push(match.index); } } return possibleIndexes; }
javascript
function findPossibleIndexes(code, identifiers, filter) { const possibleIndexes = []; if (identifiers.length === 0) { return possibleIndexes; } const pattern = new RegExp( "\\b(?:" + identifiers.join("|") + ")\\b", "g" ); let match; pattern.lastIndex = 0; while ((match = pattern.exec(code))) { if (typeof filter !== "function" || filter(match)) { possibleIndexes.push(match.index); } } return possibleIndexes; }
[ "function", "findPossibleIndexes", "(", "code", ",", "identifiers", ",", "filter", ")", "{", "const", "possibleIndexes", "=", "[", "]", ";", "if", "(", "identifiers", ".", "length", "===", "0", ")", "{", "return", "possibleIndexes", ";", "}", "const", "pattern", "=", "new", "RegExp", "(", "\"\\\\b(?:\"", "+", "identifiers", ".", "join", "(", "\"|\"", ")", "+", "\")\\\\b\"", ",", "\"g\"", ")", ";", "let", "match", ";", "pattern", ".", "lastIndex", "=", "0", ";", "while", "(", "(", "match", "=", "pattern", ".", "exec", "(", "code", ")", ")", ")", "{", "if", "(", "typeof", "filter", "!==", "\"function\"", "||", "filter", "(", "match", ")", ")", "{", "possibleIndexes", ".", "push", "(", "match", ".", "index", ")", ";", "}", "}", "return", "possibleIndexes", ";", "}" ]
Returns a sorted array of possible indexes within the code string where any identifier in the identifiers array might appear. This information can be used to optimize AST traversal by allowing subtrees to be ignored if they don't contain any possible indexes.
[ "Returns", "a", "sorted", "array", "of", "possible", "indexes", "within", "the", "code", "string", "where", "any", "identifier", "in", "the", "identifiers", "array", "might", "appear", ".", "This", "information", "can", "be", "used", "to", "optimize", "AST", "traversal", "by", "allowing", "subtrees", "to", "be", "ignored", "if", "they", "don", "t", "contain", "any", "possible", "indexes", "." ]
9b7321db373a8e5cba3309c10fc42a63856d51c1
https://github.com/benjamn/reify/blob/9b7321db373a8e5cba3309c10fc42a63856d51c1/lib/utils.js#L98-L119
18,574
benjamn/reify
lib/runtime/index.js
moduleExport
function moduleExport(getters, constant) { utils.setESModule(this.exports); var entry = Entry.getOrCreate(this.id, this); entry.addGetters(getters, constant); if (this.loaded) { // If the module has already been evaluated, then we need to trigger // another round of entry.runSetters calls, which begins by calling // entry.runModuleGetters(module). entry.runSetters(); } }
javascript
function moduleExport(getters, constant) { utils.setESModule(this.exports); var entry = Entry.getOrCreate(this.id, this); entry.addGetters(getters, constant); if (this.loaded) { // If the module has already been evaluated, then we need to trigger // another round of entry.runSetters calls, which begins by calling // entry.runModuleGetters(module). entry.runSetters(); } }
[ "function", "moduleExport", "(", "getters", ",", "constant", ")", "{", "utils", ".", "setESModule", "(", "this", ".", "exports", ")", ";", "var", "entry", "=", "Entry", ".", "getOrCreate", "(", "this", ".", "id", ",", "this", ")", ";", "entry", ".", "addGetters", "(", "getters", ",", "constant", ")", ";", "if", "(", "this", ".", "loaded", ")", "{", "// If the module has already been evaluated, then we need to trigger", "// another round of entry.runSetters calls, which begins by calling", "// entry.runModuleGetters(module).", "entry", ".", "runSetters", "(", ")", ";", "}", "}" ]
Register getter functions for local variables in the scope of an export statement. Pass true as the second argument to indicate that the getter functions always return the same values.
[ "Register", "getter", "functions", "for", "local", "variables", "in", "the", "scope", "of", "an", "export", "statement", ".", "Pass", "true", "as", "the", "second", "argument", "to", "indicate", "that", "the", "getter", "functions", "always", "return", "the", "same", "values", "." ]
9b7321db373a8e5cba3309c10fc42a63856d51c1
https://github.com/benjamn/reify/blob/9b7321db373a8e5cba3309c10fc42a63856d51c1/lib/runtime/index.js#L67-L77
18,575
zalando-incubator/tessellate
packages/tessellate-request/webpack.config.js
nodeModules
function nodeModules() { return fs.readdirSync('node_modules') .filter(dir => ['.bin'].indexOf(dir) === -1) .reduce((modules, m) => { modules[m] = 'commonjs2 ' + m return modules }, {}) }
javascript
function nodeModules() { return fs.readdirSync('node_modules') .filter(dir => ['.bin'].indexOf(dir) === -1) .reduce((modules, m) => { modules[m] = 'commonjs2 ' + m return modules }, {}) }
[ "function", "nodeModules", "(", ")", "{", "return", "fs", ".", "readdirSync", "(", "'node_modules'", ")", ".", "filter", "(", "dir", "=>", "[", "'.bin'", "]", ".", "indexOf", "(", "dir", ")", "===", "-", "1", ")", ".", "reduce", "(", "(", "modules", ",", "m", ")", "=>", "{", "modules", "[", "m", "]", "=", "'commonjs2 '", "+", "m", "return", "modules", "}", ",", "{", "}", ")", "}" ]
Externalize node_modules.
[ "Externalize", "node_modules", "." ]
6f6528af24705bcb04789cc19b434a4eefe84a73
https://github.com/zalando-incubator/tessellate/blob/6f6528af24705bcb04789cc19b434a4eefe84a73/packages/tessellate-request/webpack.config.js#L8-L15
18,576
medikoo/cli-color
slice.js
function (seq, begin, end) { var sliced = seq.reduce( function (state, chunk) { var index = state.index; if (chunk instanceof Token) { var code = sgr.extractCode(chunk.token); if (index <= begin) { if (code in sgr.openers) { sgr.openStyle(state.preOpeners, code); } if (code in sgr.closers) { sgr.closeStyle(state.preOpeners, code); } } else if (index < end) { if (code in sgr.openers) { sgr.openStyle(state.inOpeners, code); state.seq.push(chunk); } else if (code in sgr.closers) { state.inClosers.push(code); state.seq.push(chunk); } } } else { var nextChunk = ""; if (isChunkInSlice(chunk, index, begin, end)) { var relBegin = Math.max(begin - index, 0) , relEnd = Math.min(end - index, chunk.length); nextChunk = chunk.slice(relBegin, relEnd); } state.seq.push(nextChunk); state.index = index + chunk.length; } return state; }, { index: 0, seq: [], // preOpeners -> [ mod ] // preOpeners must be prepended to the slice if they wasn't closed til the end of it // preOpeners must be closed if they wasn't closed til the end of the slice preOpeners: [], // inOpeners -> [ mod ] // inOpeners already in the slice and must not be prepended to the slice // inOpeners must be closed if they wasn't closed til the end of the slice inOpeners: [], // opener CSI inside slice // inClosers -> [ code ] // closer CSIs for determining which pre/in-Openers must be closed inClosers: [] } ); sliced.seq = [].concat( sgr.prepend(sliced.preOpeners), sliced.seq, sgr.complete([].concat(sliced.preOpeners, sliced.inOpeners), sliced.inClosers) ); return sliced.seq; }
javascript
function (seq, begin, end) { var sliced = seq.reduce( function (state, chunk) { var index = state.index; if (chunk instanceof Token) { var code = sgr.extractCode(chunk.token); if (index <= begin) { if (code in sgr.openers) { sgr.openStyle(state.preOpeners, code); } if (code in sgr.closers) { sgr.closeStyle(state.preOpeners, code); } } else if (index < end) { if (code in sgr.openers) { sgr.openStyle(state.inOpeners, code); state.seq.push(chunk); } else if (code in sgr.closers) { state.inClosers.push(code); state.seq.push(chunk); } } } else { var nextChunk = ""; if (isChunkInSlice(chunk, index, begin, end)) { var relBegin = Math.max(begin - index, 0) , relEnd = Math.min(end - index, chunk.length); nextChunk = chunk.slice(relBegin, relEnd); } state.seq.push(nextChunk); state.index = index + chunk.length; } return state; }, { index: 0, seq: [], // preOpeners -> [ mod ] // preOpeners must be prepended to the slice if they wasn't closed til the end of it // preOpeners must be closed if they wasn't closed til the end of the slice preOpeners: [], // inOpeners -> [ mod ] // inOpeners already in the slice and must not be prepended to the slice // inOpeners must be closed if they wasn't closed til the end of the slice inOpeners: [], // opener CSI inside slice // inClosers -> [ code ] // closer CSIs for determining which pre/in-Openers must be closed inClosers: [] } ); sliced.seq = [].concat( sgr.prepend(sliced.preOpeners), sliced.seq, sgr.complete([].concat(sliced.preOpeners, sliced.inOpeners), sliced.inClosers) ); return sliced.seq; }
[ "function", "(", "seq", ",", "begin", ",", "end", ")", "{", "var", "sliced", "=", "seq", ".", "reduce", "(", "function", "(", "state", ",", "chunk", ")", "{", "var", "index", "=", "state", ".", "index", ";", "if", "(", "chunk", "instanceof", "Token", ")", "{", "var", "code", "=", "sgr", ".", "extractCode", "(", "chunk", ".", "token", ")", ";", "if", "(", "index", "<=", "begin", ")", "{", "if", "(", "code", "in", "sgr", ".", "openers", ")", "{", "sgr", ".", "openStyle", "(", "state", ".", "preOpeners", ",", "code", ")", ";", "}", "if", "(", "code", "in", "sgr", ".", "closers", ")", "{", "sgr", ".", "closeStyle", "(", "state", ".", "preOpeners", ",", "code", ")", ";", "}", "}", "else", "if", "(", "index", "<", "end", ")", "{", "if", "(", "code", "in", "sgr", ".", "openers", ")", "{", "sgr", ".", "openStyle", "(", "state", ".", "inOpeners", ",", "code", ")", ";", "state", ".", "seq", ".", "push", "(", "chunk", ")", ";", "}", "else", "if", "(", "code", "in", "sgr", ".", "closers", ")", "{", "state", ".", "inClosers", ".", "push", "(", "code", ")", ";", "state", ".", "seq", ".", "push", "(", "chunk", ")", ";", "}", "}", "}", "else", "{", "var", "nextChunk", "=", "\"\"", ";", "if", "(", "isChunkInSlice", "(", "chunk", ",", "index", ",", "begin", ",", "end", ")", ")", "{", "var", "relBegin", "=", "Math", ".", "max", "(", "begin", "-", "index", ",", "0", ")", ",", "relEnd", "=", "Math", ".", "min", "(", "end", "-", "index", ",", "chunk", ".", "length", ")", ";", "nextChunk", "=", "chunk", ".", "slice", "(", "relBegin", ",", "relEnd", ")", ";", "}", "state", ".", "seq", ".", "push", "(", "nextChunk", ")", ";", "state", ".", "index", "=", "index", "+", "chunk", ".", "length", ";", "}", "return", "state", ";", "}", ",", "{", "index", ":", "0", ",", "seq", ":", "[", "]", ",", "// preOpeners -> [ mod ]", "// preOpeners must be prepended to the slice if they wasn't closed til the end of it", "// preOpeners must be closed if they wasn't closed til the end of the slice", "preOpeners", ":", "[", "]", ",", "// inOpeners -> [ mod ]", "// inOpeners already in the slice and must not be prepended to the slice", "// inOpeners must be closed if they wasn't closed til the end of the slice", "inOpeners", ":", "[", "]", ",", "// opener CSI inside slice", "// inClosers -> [ code ]", "// closer CSIs for determining which pre/in-Openers must be closed", "inClosers", ":", "[", "]", "}", ")", ";", "sliced", ".", "seq", "=", "[", "]", ".", "concat", "(", "sgr", ".", "prepend", "(", "sliced", ".", "preOpeners", ")", ",", "sliced", ".", "seq", ",", "sgr", ".", "complete", "(", "[", "]", ".", "concat", "(", "sliced", ".", "preOpeners", ",", "sliced", ".", "inOpeners", ")", ",", "sliced", ".", "inClosers", ")", ")", ";", "return", "sliced", ".", "seq", ";", "}" ]
eslint-disable-next-line max-lines-per-function
[ "eslint", "-", "disable", "-", "next", "-", "line", "max", "-", "lines", "-", "per", "-", "function" ]
930da00833a387d7817564bb00c48966792d2896
https://github.com/medikoo/cli-color/blob/930da00833a387d7817564bb00c48966792d2896/slice.js#L43-L109
18,577
frontarm/mdx-util
packages/mdx.macro/mdx.macro.js
transform
function transform({ babel, filename, documentFilename }) { if (!filename) { throw new Error( `You must pass a filename to importMDX(). Please see the mdx.macro documentation`, ) } let documentPath = path.join(filename, '..', documentFilename); let imports = `import React from 'react'\nimport { MDXTag } from '@mdx-js/tag'\n` // In development mode, we want to import the original document so that // changes will be picked up and cause a re-build. // Note: this relies on files with macros *not* being cached by babel. if (process.env.NODE_ENV === "development") { imports += `import '${documentPath}'\n` } let source = fs.readFileSync(documentPath, 'utf8'); let transformedSource = babel.transformSync( imports+mdx.sync(source), { presets: [babelPresetReactApp], filename: documentPath, }, ).code return writeTempFile(documentPath, transformedSource) }
javascript
function transform({ babel, filename, documentFilename }) { if (!filename) { throw new Error( `You must pass a filename to importMDX(). Please see the mdx.macro documentation`, ) } let documentPath = path.join(filename, '..', documentFilename); let imports = `import React from 'react'\nimport { MDXTag } from '@mdx-js/tag'\n` // In development mode, we want to import the original document so that // changes will be picked up and cause a re-build. // Note: this relies on files with macros *not* being cached by babel. if (process.env.NODE_ENV === "development") { imports += `import '${documentPath}'\n` } let source = fs.readFileSync(documentPath, 'utf8'); let transformedSource = babel.transformSync( imports+mdx.sync(source), { presets: [babelPresetReactApp], filename: documentPath, }, ).code return writeTempFile(documentPath, transformedSource) }
[ "function", "transform", "(", "{", "babel", ",", "filename", ",", "documentFilename", "}", ")", "{", "if", "(", "!", "filename", ")", "{", "throw", "new", "Error", "(", "`", "`", ",", ")", "}", "let", "documentPath", "=", "path", ".", "join", "(", "filename", ",", "'..'", ",", "documentFilename", ")", ";", "let", "imports", "=", "`", "\\n", "\\n", "`", "// In development mode, we want to import the original document so that", "// changes will be picked up and cause a re-build.", "// Note: this relies on files with macros *not* being cached by babel.", "if", "(", "process", ".", "env", ".", "NODE_ENV", "===", "\"development\"", ")", "{", "imports", "+=", "`", "${", "documentPath", "}", "\\n", "`", "}", "let", "source", "=", "fs", ".", "readFileSync", "(", "documentPath", ",", "'utf8'", ")", ";", "let", "transformedSource", "=", "babel", ".", "transformSync", "(", "imports", "+", "mdx", ".", "sync", "(", "source", ")", ",", "{", "presets", ":", "[", "babelPresetReactApp", "]", ",", "filename", ":", "documentPath", ",", "}", ",", ")", ".", "code", "return", "writeTempFile", "(", "documentPath", ",", "transformedSource", ")", "}" ]
Find the import filename,
[ "Find", "the", "import", "filename" ]
319228aa2bfd0e6ebf6bff38f7d73b8412933161
https://github.com/frontarm/mdx-util/blob/319228aa2bfd0e6ebf6bff38f7d73b8412933161/packages/mdx.macro/mdx.macro.js#L110-L137
18,578
frontarm/mdx-util
deprecated-packages/mdxc/src/jsx_inline.js
parseJSXContent
function parseJSXContent(state, start, type) { var text, result, max = state.posMax, prevPos, oldPos = state.pos; state.pos = start; while (state.pos < max) { text = state.src.slice(state.pos) result = JSX_INLINE_CLOSE_TAG_PARSER.parse(text) prevPos = state.pos; state.md.inline.skipToken(state); if (result.status && result.value.value === type && prevPos === state.pos - 1) { // restore old state state.pos = oldPos; return { contentEnd: prevPos, closeEnd: prevPos + result.value.end.offset } } } // restore old state state.pos = oldPos; }
javascript
function parseJSXContent(state, start, type) { var text, result, max = state.posMax, prevPos, oldPos = state.pos; state.pos = start; while (state.pos < max) { text = state.src.slice(state.pos) result = JSX_INLINE_CLOSE_TAG_PARSER.parse(text) prevPos = state.pos; state.md.inline.skipToken(state); if (result.status && result.value.value === type && prevPos === state.pos - 1) { // restore old state state.pos = oldPos; return { contentEnd: prevPos, closeEnd: prevPos + result.value.end.offset } } } // restore old state state.pos = oldPos; }
[ "function", "parseJSXContent", "(", "state", ",", "start", ",", "type", ")", "{", "var", "text", ",", "result", ",", "max", "=", "state", ".", "posMax", ",", "prevPos", ",", "oldPos", "=", "state", ".", "pos", ";", "state", ".", "pos", "=", "start", ";", "while", "(", "state", ".", "pos", "<", "max", ")", "{", "text", "=", "state", ".", "src", ".", "slice", "(", "state", ".", "pos", ")", "result", "=", "JSX_INLINE_CLOSE_TAG_PARSER", ".", "parse", "(", "text", ")", "prevPos", "=", "state", ".", "pos", ";", "state", ".", "md", ".", "inline", ".", "skipToken", "(", "state", ")", ";", "if", "(", "result", ".", "status", "&&", "result", ".", "value", ".", "value", "===", "type", "&&", "prevPos", "===", "state", ".", "pos", "-", "1", ")", "{", "// restore old state", "state", ".", "pos", "=", "oldPos", ";", "return", "{", "contentEnd", ":", "prevPos", ",", "closeEnd", ":", "prevPos", "+", "result", ".", "value", ".", "end", ".", "offset", "}", "}", "}", "// restore old state", "state", ".", "pos", "=", "oldPos", ";", "}" ]
Iterate through a JSX tag's content until the closing tag is found, making sure to skip nested JSX and to not match closing tags in code blocks.
[ "Iterate", "through", "a", "JSX", "tag", "s", "content", "until", "the", "closing", "tag", "is", "found", "making", "sure", "to", "skip", "nested", "JSX", "and", "to", "not", "match", "closing", "tags", "in", "code", "blocks", "." ]
319228aa2bfd0e6ebf6bff38f7d73b8412933161
https://github.com/frontarm/mdx-util/blob/319228aa2bfd0e6ebf6bff38f7d73b8412933161/deprecated-packages/mdxc/src/jsx_inline.js#L10-L35
18,579
fortunejs/fortune
lib/request/check_links.js
checkLinks
function checkLinks (transaction, record, fields, links, meta) { var Promise = promise.Promise var enforceLinks = this.options.settings.enforceLinks return Promise.all(map(links, function (field) { var ids = Array.isArray(record[field]) ? record[field] : !record.hasOwnProperty(field) || record[field] === null ? [] : [ record[field] ] var fieldLink = fields[field][linkKey] var fieldInverse = fields[field][inverseKey] var findOptions = { fields: {} } // Don't need the entire records. findOptions.fields[fieldInverse] = true return new Promise(function (resolve, reject) { if (!ids.length) return resolve() return transaction.find(fieldLink, ids, findOptions, meta) .then(function (records) { var recordIds, i, j if (enforceLinks) { recordIds = unique(map(records, function (record) { return record[primaryKey] })) for (i = 0, j = ids.length; i < j; i++) if (!includes(recordIds, ids[i])) return reject(new BadRequestError( message('RelatedRecordNotFound', meta.language, { field: field }) )) } return resolve(records) }) }) })) .then(function (partialRecords) { var object = {}, records, i, j for (i = 0, j = partialRecords.length; i < j; i++) { records = partialRecords[i] if (records) object[links[i]] = fields[links[i]][isArrayKey] ? records : records[0] } return object }) }
javascript
function checkLinks (transaction, record, fields, links, meta) { var Promise = promise.Promise var enforceLinks = this.options.settings.enforceLinks return Promise.all(map(links, function (field) { var ids = Array.isArray(record[field]) ? record[field] : !record.hasOwnProperty(field) || record[field] === null ? [] : [ record[field] ] var fieldLink = fields[field][linkKey] var fieldInverse = fields[field][inverseKey] var findOptions = { fields: {} } // Don't need the entire records. findOptions.fields[fieldInverse] = true return new Promise(function (resolve, reject) { if (!ids.length) return resolve() return transaction.find(fieldLink, ids, findOptions, meta) .then(function (records) { var recordIds, i, j if (enforceLinks) { recordIds = unique(map(records, function (record) { return record[primaryKey] })) for (i = 0, j = ids.length; i < j; i++) if (!includes(recordIds, ids[i])) return reject(new BadRequestError( message('RelatedRecordNotFound', meta.language, { field: field }) )) } return resolve(records) }) }) })) .then(function (partialRecords) { var object = {}, records, i, j for (i = 0, j = partialRecords.length; i < j; i++) { records = partialRecords[i] if (records) object[links[i]] = fields[links[i]][isArrayKey] ? records : records[0] } return object }) }
[ "function", "checkLinks", "(", "transaction", ",", "record", ",", "fields", ",", "links", ",", "meta", ")", "{", "var", "Promise", "=", "promise", ".", "Promise", "var", "enforceLinks", "=", "this", ".", "options", ".", "settings", ".", "enforceLinks", "return", "Promise", ".", "all", "(", "map", "(", "links", ",", "function", "(", "field", ")", "{", "var", "ids", "=", "Array", ".", "isArray", "(", "record", "[", "field", "]", ")", "?", "record", "[", "field", "]", ":", "!", "record", ".", "hasOwnProperty", "(", "field", ")", "||", "record", "[", "field", "]", "===", "null", "?", "[", "]", ":", "[", "record", "[", "field", "]", "]", "var", "fieldLink", "=", "fields", "[", "field", "]", "[", "linkKey", "]", "var", "fieldInverse", "=", "fields", "[", "field", "]", "[", "inverseKey", "]", "var", "findOptions", "=", "{", "fields", ":", "{", "}", "}", "// Don't need the entire records.", "findOptions", ".", "fields", "[", "fieldInverse", "]", "=", "true", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "if", "(", "!", "ids", ".", "length", ")", "return", "resolve", "(", ")", "return", "transaction", ".", "find", "(", "fieldLink", ",", "ids", ",", "findOptions", ",", "meta", ")", ".", "then", "(", "function", "(", "records", ")", "{", "var", "recordIds", ",", "i", ",", "j", "if", "(", "enforceLinks", ")", "{", "recordIds", "=", "unique", "(", "map", "(", "records", ",", "function", "(", "record", ")", "{", "return", "record", "[", "primaryKey", "]", "}", ")", ")", "for", "(", "i", "=", "0", ",", "j", "=", "ids", ".", "length", ";", "i", "<", "j", ";", "i", "++", ")", "if", "(", "!", "includes", "(", "recordIds", ",", "ids", "[", "i", "]", ")", ")", "return", "reject", "(", "new", "BadRequestError", "(", "message", "(", "'RelatedRecordNotFound'", ",", "meta", ".", "language", ",", "{", "field", ":", "field", "}", ")", ")", ")", "}", "return", "resolve", "(", "records", ")", "}", ")", "}", ")", "}", ")", ")", ".", "then", "(", "function", "(", "partialRecords", ")", "{", "var", "object", "=", "{", "}", ",", "records", ",", "i", ",", "j", "for", "(", "i", "=", "0", ",", "j", "=", "partialRecords", ".", "length", ";", "i", "<", "j", ";", "i", "++", ")", "{", "records", "=", "partialRecords", "[", "i", "]", "if", "(", "records", ")", "object", "[", "links", "[", "i", "]", "]", "=", "fields", "[", "links", "[", "i", "]", "]", "[", "isArrayKey", "]", "?", "records", ":", "records", "[", "0", "]", "}", "return", "object", "}", ")", "}" ]
Ensure referential integrity by checking if related records exist. @param {Object} transaction @param {Object} record @param {Object} fields @param {String[]} links - An array of strings indicating which fields are links. Need to pass this so that it doesn't get computed each time. @param {Object} [meta] @return {Promise}
[ "Ensure", "referential", "integrity", "by", "checking", "if", "related", "records", "exist", "." ]
cccc0d1ba67916a97c3905dd30d3478265ba9ced
https://github.com/fortunejs/fortune/blob/cccc0d1ba67916a97c3905dd30d3478265ba9ced/lib/request/check_links.js#L32-L85
18,580
fortunejs/fortune
lib/request/update.js
validateUpdates
function validateUpdates (updates, meta) { var language = meta.language var i, j, update if (!updates || !updates.length) throw new BadRequestError( message('UpdateRecordsInvalid', language)) for (i = 0, j = updates.length; i < j; i++) { update = updates[i] if (!update[primaryKey]) throw new BadRequestError( message('UpdateRecordMissingID', language)) } }
javascript
function validateUpdates (updates, meta) { var language = meta.language var i, j, update if (!updates || !updates.length) throw new BadRequestError( message('UpdateRecordsInvalid', language)) for (i = 0, j = updates.length; i < j; i++) { update = updates[i] if (!update[primaryKey]) throw new BadRequestError( message('UpdateRecordMissingID', language)) } }
[ "function", "validateUpdates", "(", "updates", ",", "meta", ")", "{", "var", "language", "=", "meta", ".", "language", "var", "i", ",", "j", ",", "update", "if", "(", "!", "updates", "||", "!", "updates", ".", "length", ")", "throw", "new", "BadRequestError", "(", "message", "(", "'UpdateRecordsInvalid'", ",", "language", ")", ")", "for", "(", "i", "=", "0", ",", "j", "=", "updates", ".", "length", ";", "i", "<", "j", ";", "i", "++", ")", "{", "update", "=", "updates", "[", "i", "]", "if", "(", "!", "update", "[", "primaryKey", "]", ")", "throw", "new", "BadRequestError", "(", "message", "(", "'UpdateRecordMissingID'", ",", "language", ")", ")", "}", "}" ]
Validate updates.
[ "Validate", "updates", "." ]
cccc0d1ba67916a97c3905dd30d3478265ba9ced
https://github.com/fortunejs/fortune/blob/cccc0d1ba67916a97c3905dd30d3478265ba9ced/lib/request/update.js#L363-L377
18,581
fortunejs/fortune
lib/adapter/singleton.js
AdapterSingleton
function AdapterSingleton (properties) { var CustomAdapter, input input = Array.isArray(properties.adapter) ? properties.adapter : [ properties.adapter ] if (typeof input[0] !== 'function') throw new TypeError('The adapter must be a function.') CustomAdapter = Adapter.prototype .isPrototypeOf(input[0].prototype) ? input[0] : input[0](Adapter) if (!Adapter.prototype.isPrototypeOf(CustomAdapter.prototype)) throw new TypeError('The adapter must inherit the Adapter class.') return new CustomAdapter({ options: input[1] || {}, recordTypes: properties.recordTypes, features: CustomAdapter.features, common: common, errors: errors, keys: keys, message: properties.message, Promise: promise.Promise }) }
javascript
function AdapterSingleton (properties) { var CustomAdapter, input input = Array.isArray(properties.adapter) ? properties.adapter : [ properties.adapter ] if (typeof input[0] !== 'function') throw new TypeError('The adapter must be a function.') CustomAdapter = Adapter.prototype .isPrototypeOf(input[0].prototype) ? input[0] : input[0](Adapter) if (!Adapter.prototype.isPrototypeOf(CustomAdapter.prototype)) throw new TypeError('The adapter must inherit the Adapter class.') return new CustomAdapter({ options: input[1] || {}, recordTypes: properties.recordTypes, features: CustomAdapter.features, common: common, errors: errors, keys: keys, message: properties.message, Promise: promise.Promise }) }
[ "function", "AdapterSingleton", "(", "properties", ")", "{", "var", "CustomAdapter", ",", "input", "input", "=", "Array", ".", "isArray", "(", "properties", ".", "adapter", ")", "?", "properties", ".", "adapter", ":", "[", "properties", ".", "adapter", "]", "if", "(", "typeof", "input", "[", "0", "]", "!==", "'function'", ")", "throw", "new", "TypeError", "(", "'The adapter must be a function.'", ")", "CustomAdapter", "=", "Adapter", ".", "prototype", ".", "isPrototypeOf", "(", "input", "[", "0", "]", ".", "prototype", ")", "?", "input", "[", "0", "]", ":", "input", "[", "0", "]", "(", "Adapter", ")", "if", "(", "!", "Adapter", ".", "prototype", ".", "isPrototypeOf", "(", "CustomAdapter", ".", "prototype", ")", ")", "throw", "new", "TypeError", "(", "'The adapter must inherit the Adapter class.'", ")", "return", "new", "CustomAdapter", "(", "{", "options", ":", "input", "[", "1", "]", "||", "{", "}", ",", "recordTypes", ":", "properties", ".", "recordTypes", ",", "features", ":", "CustomAdapter", ".", "features", ",", "common", ":", "common", ",", "errors", ":", "errors", ",", "keys", ":", "keys", ",", "message", ":", "properties", ".", "message", ",", "Promise", ":", "promise", ".", "Promise", "}", ")", "}" ]
A singleton for the adapter. For internal use.
[ "A", "singleton", "for", "the", "adapter", ".", "For", "internal", "use", "." ]
cccc0d1ba67916a97c3905dd30d3478265ba9ced
https://github.com/fortunejs/fortune/blob/cccc0d1ba67916a97c3905dd30d3478265ba9ced/lib/adapter/singleton.js#L13-L38
18,582
fortunejs/fortune
lib/record_type/validate.js
validateField
function validateField (fields, key) { var value = fields[key] = castShorthand(fields[key]) if (typeof value !== 'object') throw new TypeError('The definition of "' + key + '" must be an object.') if (key === primaryKey) throw new Error('Can not define primary key "' + primaryKey + '".') if (key in plainObject) throw new Error('Can not define field name "' + key + '" which is in Object.prototype.') if (!value[typeKey] && !value[linkKey]) throw new Error('The definition of "' + key + '" must contain either ' + 'the "' + typeKey + '" or "' + linkKey + '" property.') if (value[typeKey] && value[linkKey]) throw new Error('Can not define both "' + typeKey + '" and "' + linkKey + '" on "' + key + '".') if (value[typeKey]) { if (typeof value[typeKey] === 'string') value[typeKey] = nativeTypes[ stringifiedTypes.indexOf(value[typeKey].toLowerCase())] if (typeof value[typeKey] !== 'function') throw new Error('The "' + typeKey + '" on "' + key + '" must be a function.') if (!find(nativeTypes, function (type) { var hasMatch = type === value[typeKey] || type.name === value[typeKey].name // In case this errors due to security sandboxing, just skip this check. if (!hasMatch) try { hasMatch = Object.create(value[typeKey]) instanceof type } catch (e) { hasMatch = true } return hasMatch })) throw new Error('The "' + typeKey + '" on "' + key + '" must be or ' + 'inherit from a valid native type.') if (value[inverseKey]) throw new Error('The field "' + inverseKey + '" may not be defined ' + 'on "' + key + '".') } if (value[linkKey]) { if (typeof value[linkKey] !== 'string') throw new TypeError('The "' + linkKey + '" on "' + key + '" must be a string.') if (value[inverseKey] && typeof value[inverseKey] !== 'string') throw new TypeError('The "' + inverseKey + '" on "' + key + '" ' + 'must be a string.') } if (value[isArrayKey] && typeof value[isArrayKey] !== 'boolean') throw new TypeError('The key "' + isArrayKey + '" on "' + key + '" ' + 'must be a boolean.') }
javascript
function validateField (fields, key) { var value = fields[key] = castShorthand(fields[key]) if (typeof value !== 'object') throw new TypeError('The definition of "' + key + '" must be an object.') if (key === primaryKey) throw new Error('Can not define primary key "' + primaryKey + '".') if (key in plainObject) throw new Error('Can not define field name "' + key + '" which is in Object.prototype.') if (!value[typeKey] && !value[linkKey]) throw new Error('The definition of "' + key + '" must contain either ' + 'the "' + typeKey + '" or "' + linkKey + '" property.') if (value[typeKey] && value[linkKey]) throw new Error('Can not define both "' + typeKey + '" and "' + linkKey + '" on "' + key + '".') if (value[typeKey]) { if (typeof value[typeKey] === 'string') value[typeKey] = nativeTypes[ stringifiedTypes.indexOf(value[typeKey].toLowerCase())] if (typeof value[typeKey] !== 'function') throw new Error('The "' + typeKey + '" on "' + key + '" must be a function.') if (!find(nativeTypes, function (type) { var hasMatch = type === value[typeKey] || type.name === value[typeKey].name // In case this errors due to security sandboxing, just skip this check. if (!hasMatch) try { hasMatch = Object.create(value[typeKey]) instanceof type } catch (e) { hasMatch = true } return hasMatch })) throw new Error('The "' + typeKey + '" on "' + key + '" must be or ' + 'inherit from a valid native type.') if (value[inverseKey]) throw new Error('The field "' + inverseKey + '" may not be defined ' + 'on "' + key + '".') } if (value[linkKey]) { if (typeof value[linkKey] !== 'string') throw new TypeError('The "' + linkKey + '" on "' + key + '" must be a string.') if (value[inverseKey] && typeof value[inverseKey] !== 'string') throw new TypeError('The "' + inverseKey + '" on "' + key + '" ' + 'must be a string.') } if (value[isArrayKey] && typeof value[isArrayKey] !== 'boolean') throw new TypeError('The key "' + isArrayKey + '" on "' + key + '" ' + 'must be a boolean.') }
[ "function", "validateField", "(", "fields", ",", "key", ")", "{", "var", "value", "=", "fields", "[", "key", "]", "=", "castShorthand", "(", "fields", "[", "key", "]", ")", "if", "(", "typeof", "value", "!==", "'object'", ")", "throw", "new", "TypeError", "(", "'The definition of \"'", "+", "key", "+", "'\" must be an object.'", ")", "if", "(", "key", "===", "primaryKey", ")", "throw", "new", "Error", "(", "'Can not define primary key \"'", "+", "primaryKey", "+", "'\".'", ")", "if", "(", "key", "in", "plainObject", ")", "throw", "new", "Error", "(", "'Can not define field name \"'", "+", "key", "+", "'\" which is in Object.prototype.'", ")", "if", "(", "!", "value", "[", "typeKey", "]", "&&", "!", "value", "[", "linkKey", "]", ")", "throw", "new", "Error", "(", "'The definition of \"'", "+", "key", "+", "'\" must contain either '", "+", "'the \"'", "+", "typeKey", "+", "'\" or \"'", "+", "linkKey", "+", "'\" property.'", ")", "if", "(", "value", "[", "typeKey", "]", "&&", "value", "[", "linkKey", "]", ")", "throw", "new", "Error", "(", "'Can not define both \"'", "+", "typeKey", "+", "'\" and \"'", "+", "linkKey", "+", "'\" on \"'", "+", "key", "+", "'\".'", ")", "if", "(", "value", "[", "typeKey", "]", ")", "{", "if", "(", "typeof", "value", "[", "typeKey", "]", "===", "'string'", ")", "value", "[", "typeKey", "]", "=", "nativeTypes", "[", "stringifiedTypes", ".", "indexOf", "(", "value", "[", "typeKey", "]", ".", "toLowerCase", "(", ")", ")", "]", "if", "(", "typeof", "value", "[", "typeKey", "]", "!==", "'function'", ")", "throw", "new", "Error", "(", "'The \"'", "+", "typeKey", "+", "'\" on \"'", "+", "key", "+", "'\" must be a function.'", ")", "if", "(", "!", "find", "(", "nativeTypes", ",", "function", "(", "type", ")", "{", "var", "hasMatch", "=", "type", "===", "value", "[", "typeKey", "]", "||", "type", ".", "name", "===", "value", "[", "typeKey", "]", ".", "name", "// In case this errors due to security sandboxing, just skip this check.", "if", "(", "!", "hasMatch", ")", "try", "{", "hasMatch", "=", "Object", ".", "create", "(", "value", "[", "typeKey", "]", ")", "instanceof", "type", "}", "catch", "(", "e", ")", "{", "hasMatch", "=", "true", "}", "return", "hasMatch", "}", ")", ")", "throw", "new", "Error", "(", "'The \"'", "+", "typeKey", "+", "'\" on \"'", "+", "key", "+", "'\" must be or '", "+", "'inherit from a valid native type.'", ")", "if", "(", "value", "[", "inverseKey", "]", ")", "throw", "new", "Error", "(", "'The field \"'", "+", "inverseKey", "+", "'\" may not be defined '", "+", "'on \"'", "+", "key", "+", "'\".'", ")", "}", "if", "(", "value", "[", "linkKey", "]", ")", "{", "if", "(", "typeof", "value", "[", "linkKey", "]", "!==", "'string'", ")", "throw", "new", "TypeError", "(", "'The \"'", "+", "linkKey", "+", "'\" on \"'", "+", "key", "+", "'\" must be a string.'", ")", "if", "(", "value", "[", "inverseKey", "]", "&&", "typeof", "value", "[", "inverseKey", "]", "!==", "'string'", ")", "throw", "new", "TypeError", "(", "'The \"'", "+", "inverseKey", "+", "'\" on \"'", "+", "key", "+", "'\" '", "+", "'must be a string.'", ")", "}", "if", "(", "value", "[", "isArrayKey", "]", "&&", "typeof", "value", "[", "isArrayKey", "]", "!==", "'boolean'", ")", "throw", "new", "TypeError", "(", "'The key \"'", "+", "isArrayKey", "+", "'\" on \"'", "+", "key", "+", "'\" '", "+", "'must be a boolean.'", ")", "}" ]
Parse a field definition. @param {Object} fields @param {String} key
[ "Parse", "a", "field", "definition", "." ]
cccc0d1ba67916a97c3905dd30d3478265ba9ced
https://github.com/fortunejs/fortune/blob/cccc0d1ba67916a97c3905dd30d3478265ba9ced/lib/record_type/validate.js#L45-L111
18,583
fortunejs/fortune
lib/record_type/validate.js
castShorthand
function castShorthand (value) { var obj if (typeof value === 'string') obj = { link: value } else if (typeof value === 'function') obj = { type: value } else if (Array.isArray(value)) { obj = {} if (value[1]) obj.inverse = value[1] else obj.isArray = true // Extract type or link. if (Array.isArray(value[0])) { obj.isArray = true value = value[0][0] } else value = value[0] if (typeof value === 'string') obj.link = value else if (typeof value === 'function') obj.type = value } else return value return obj }
javascript
function castShorthand (value) { var obj if (typeof value === 'string') obj = { link: value } else if (typeof value === 'function') obj = { type: value } else if (Array.isArray(value)) { obj = {} if (value[1]) obj.inverse = value[1] else obj.isArray = true // Extract type or link. if (Array.isArray(value[0])) { obj.isArray = true value = value[0][0] } else value = value[0] if (typeof value === 'string') obj.link = value else if (typeof value === 'function') obj.type = value } else return value return obj }
[ "function", "castShorthand", "(", "value", ")", "{", "var", "obj", "if", "(", "typeof", "value", "===", "'string'", ")", "obj", "=", "{", "link", ":", "value", "}", "else", "if", "(", "typeof", "value", "===", "'function'", ")", "obj", "=", "{", "type", ":", "value", "}", "else", "if", "(", "Array", ".", "isArray", "(", "value", ")", ")", "{", "obj", "=", "{", "}", "if", "(", "value", "[", "1", "]", ")", "obj", ".", "inverse", "=", "value", "[", "1", "]", "else", "obj", ".", "isArray", "=", "true", "// Extract type or link.", "if", "(", "Array", ".", "isArray", "(", "value", "[", "0", "]", ")", ")", "{", "obj", ".", "isArray", "=", "true", "value", "=", "value", "[", "0", "]", "[", "0", "]", "}", "else", "value", "=", "value", "[", "0", "]", "if", "(", "typeof", "value", "===", "'string'", ")", "obj", ".", "link", "=", "value", "else", "if", "(", "typeof", "value", "===", "'function'", ")", "obj", ".", "type", "=", "value", "}", "else", "return", "value", "return", "obj", "}" ]
Cast shorthand definition to standard definition. @param {*} value @return {Object}
[ "Cast", "shorthand", "definition", "to", "standard", "definition", "." ]
cccc0d1ba67916a97c3905dd30d3478265ba9ced
https://github.com/fortunejs/fortune/blob/cccc0d1ba67916a97c3905dd30d3478265ba9ced/lib/record_type/validate.js#L120-L144
18,584
fortunejs/fortune
lib/common/message.js
message
function message (id, language, data) { var genericMessage = 'GenericError' var self = this || message var str, key, subtag if (!self.hasOwnProperty(language)) { subtag = language && language.match(/.+?(?=-)/) if (subtag) subtag = subtag[0] if (self.hasOwnProperty(subtag)) language = subtag else language = self.defaultLanguage } str = self[language].hasOwnProperty(id) ? self[language][id] : self[language][genericMessage] || self.en[genericMessage] if (typeof str === 'string') for (key in data) str = str.replace('{' + key + '}', data[key]) if (typeof str === 'function') str = str(data) return str }
javascript
function message (id, language, data) { var genericMessage = 'GenericError' var self = this || message var str, key, subtag if (!self.hasOwnProperty(language)) { subtag = language && language.match(/.+?(?=-)/) if (subtag) subtag = subtag[0] if (self.hasOwnProperty(subtag)) language = subtag else language = self.defaultLanguage } str = self[language].hasOwnProperty(id) ? self[language][id] : self[language][genericMessage] || self.en[genericMessage] if (typeof str === 'string') for (key in data) str = str.replace('{' + key + '}', data[key]) if (typeof str === 'function') str = str(data) return str }
[ "function", "message", "(", "id", ",", "language", ",", "data", ")", "{", "var", "genericMessage", "=", "'GenericError'", "var", "self", "=", "this", "||", "message", "var", "str", ",", "key", ",", "subtag", "if", "(", "!", "self", ".", "hasOwnProperty", "(", "language", ")", ")", "{", "subtag", "=", "language", "&&", "language", ".", "match", "(", "/", ".+?(?=-)", "/", ")", "if", "(", "subtag", ")", "subtag", "=", "subtag", "[", "0", "]", "if", "(", "self", ".", "hasOwnProperty", "(", "subtag", ")", ")", "language", "=", "subtag", "else", "language", "=", "self", ".", "defaultLanguage", "}", "str", "=", "self", "[", "language", "]", ".", "hasOwnProperty", "(", "id", ")", "?", "self", "[", "language", "]", "[", "id", "]", ":", "self", "[", "language", "]", "[", "genericMessage", "]", "||", "self", ".", "en", "[", "genericMessage", "]", "if", "(", "typeof", "str", "===", "'string'", ")", "for", "(", "key", "in", "data", ")", "str", "=", "str", ".", "replace", "(", "'{'", "+", "key", "+", "'}'", ",", "data", "[", "key", "]", ")", "if", "(", "typeof", "str", "===", "'function'", ")", "str", "=", "str", "(", "data", ")", "return", "str", "}" ]
Message function for i18n. @param {String} id @param {String} language @param {Object} [data] @return {String}
[ "Message", "function", "for", "i18n", "." ]
cccc0d1ba67916a97c3905dd30d3478265ba9ced
https://github.com/fortunejs/fortune/blob/cccc0d1ba67916a97c3905dd30d3478265ba9ced/lib/common/message.js#L22-L46
18,585
fortunejs/fortune
lib/common/deep_equal.js
deepEqual
function deepEqual (a, b) { var key, value, compare, aLength = 0, bLength = 0 // If they are the same object, don't need to go further. if (a === b) return true // Both objects must be defined. if (!a || !b) return false // Objects must be of the same type. if (a.prototype !== b.prototype) return false for (key in a) { aLength++ value = a[key] compare = b[key] if (typeof value === 'object') { if (typeof compare !== 'object' || !deepEqual(value, compare)) return false continue } if (Buffer.isBuffer(value)) { if (!Buffer.isBuffer(compare) || !value.equals(compare)) return false continue } if (value && typeof value.getTime === 'function') { if (!compare || typeof compare.getTime !== 'function' || value.getTime() !== compare.getTime()) return false continue } if (value !== compare) return false } for (key in b) bLength++ // Keys must be of same length. return aLength === bLength }
javascript
function deepEqual (a, b) { var key, value, compare, aLength = 0, bLength = 0 // If they are the same object, don't need to go further. if (a === b) return true // Both objects must be defined. if (!a || !b) return false // Objects must be of the same type. if (a.prototype !== b.prototype) return false for (key in a) { aLength++ value = a[key] compare = b[key] if (typeof value === 'object') { if (typeof compare !== 'object' || !deepEqual(value, compare)) return false continue } if (Buffer.isBuffer(value)) { if (!Buffer.isBuffer(compare) || !value.equals(compare)) return false continue } if (value && typeof value.getTime === 'function') { if (!compare || typeof compare.getTime !== 'function' || value.getTime() !== compare.getTime()) return false continue } if (value !== compare) return false } for (key in b) bLength++ // Keys must be of same length. return aLength === bLength }
[ "function", "deepEqual", "(", "a", ",", "b", ")", "{", "var", "key", ",", "value", ",", "compare", ",", "aLength", "=", "0", ",", "bLength", "=", "0", "// If they are the same object, don't need to go further.", "if", "(", "a", "===", "b", ")", "return", "true", "// Both objects must be defined.", "if", "(", "!", "a", "||", "!", "b", ")", "return", "false", "// Objects must be of the same type.", "if", "(", "a", ".", "prototype", "!==", "b", ".", "prototype", ")", "return", "false", "for", "(", "key", "in", "a", ")", "{", "aLength", "++", "value", "=", "a", "[", "key", "]", "compare", "=", "b", "[", "key", "]", "if", "(", "typeof", "value", "===", "'object'", ")", "{", "if", "(", "typeof", "compare", "!==", "'object'", "||", "!", "deepEqual", "(", "value", ",", "compare", ")", ")", "return", "false", "continue", "}", "if", "(", "Buffer", ".", "isBuffer", "(", "value", ")", ")", "{", "if", "(", "!", "Buffer", ".", "isBuffer", "(", "compare", ")", "||", "!", "value", ".", "equals", "(", "compare", ")", ")", "return", "false", "continue", "}", "if", "(", "value", "&&", "typeof", "value", ".", "getTime", "===", "'function'", ")", "{", "if", "(", "!", "compare", "||", "typeof", "compare", ".", "getTime", "!==", "'function'", "||", "value", ".", "getTime", "(", ")", "!==", "compare", ".", "getTime", "(", ")", ")", "return", "false", "continue", "}", "if", "(", "value", "!==", "compare", ")", "return", "false", "}", "for", "(", "key", "in", "b", ")", "bLength", "++", "// Keys must be of same length.", "return", "aLength", "===", "bLength", "}" ]
A fast recursive equality check, which covers limited use cases. @param {Object} @param {Object} @return {Boolean}
[ "A", "fast", "recursive", "equality", "check", "which", "covers", "limited", "use", "cases", "." ]
cccc0d1ba67916a97c3905dd30d3478265ba9ced
https://github.com/fortunejs/fortune/blob/cccc0d1ba67916a97c3905dd30d3478265ba9ced/lib/common/deep_equal.js#L10-L53
18,586
mapbox/preprocessorcerer
preprocessors/togeojson-gpx.preprocessor.js
createIndices
function createIndices(callback) { const q = queue(); geojson_files.forEach((gj) => { q.defer(createIndex, gj); }); q.awaitAll((err) => { if (err) return callback(err); return callback(); }); }
javascript
function createIndices(callback) { const q = queue(); geojson_files.forEach((gj) => { q.defer(createIndex, gj); }); q.awaitAll((err) => { if (err) return callback(err); return callback(); }); }
[ "function", "createIndices", "(", "callback", ")", "{", "const", "q", "=", "queue", "(", ")", ";", "geojson_files", ".", "forEach", "(", "(", "gj", ")", "=>", "{", "q", ".", "defer", "(", "createIndex", ",", "gj", ")", ";", "}", ")", ";", "q", ".", "awaitAll", "(", "(", "err", ")", "=>", "{", "if", "(", "err", ")", "return", "callback", "(", "err", ")", ";", "return", "callback", "(", ")", ";", "}", ")", ";", "}" ]
create mapnik index for each geojson layer
[ "create", "mapnik", "index", "for", "each", "geojson", "layer" ]
9c0c3f6e8e33692792bd66ff1d4596f91aba1fa3
https://github.com/mapbox/preprocessorcerer/blob/9c0c3f6e8e33692792bd66ff1d4596f91aba1fa3/preprocessors/togeojson-gpx.preprocessor.js#L121-L131
18,587
mapbox/preprocessorcerer
preprocessors/togeojson-kml.preprocessor.js
archiveOriginal
function archiveOriginal(callback) { const archivedOriginal = path.join(outdirectory, '/archived.kml'); const infileContents = fs.readFileSync(infile); fs.writeFile(archivedOriginal, infileContents, (err) => { if (err) return callback(err); return callback(); }); }
javascript
function archiveOriginal(callback) { const archivedOriginal = path.join(outdirectory, '/archived.kml'); const infileContents = fs.readFileSync(infile); fs.writeFile(archivedOriginal, infileContents, (err) => { if (err) return callback(err); return callback(); }); }
[ "function", "archiveOriginal", "(", "callback", ")", "{", "const", "archivedOriginal", "=", "path", ".", "join", "(", "outdirectory", ",", "'/archived.kml'", ")", ";", "const", "infileContents", "=", "fs", ".", "readFileSync", "(", "infile", ")", ";", "fs", ".", "writeFile", "(", "archivedOriginal", ",", "infileContents", ",", "(", "err", ")", "=>", "{", "if", "(", "err", ")", "return", "callback", "(", "err", ")", ";", "return", "callback", "(", ")", ";", "}", ")", ";", "}" ]
Archive original kml file
[ "Archive", "original", "kml", "file" ]
9c0c3f6e8e33692792bd66ff1d4596f91aba1fa3
https://github.com/mapbox/preprocessorcerer/blob/9c0c3f6e8e33692792bd66ff1d4596f91aba1fa3/preprocessors/togeojson-kml.preprocessor.js#L121-L129
18,588
mapbox/preprocessorcerer
preprocessors/index.js
applicable
function applicable(filepath, info, callback) { const q = queue(); preprocessors.forEach((preprocessor) => { q.defer(preprocessor.criteria, filepath, info); }); q.awaitAll((err, results) => { if (err) return callback(err); callback(null, preprocessors.filter((preprocessor, i) => { return !!results[i]; })); }); }
javascript
function applicable(filepath, info, callback) { const q = queue(); preprocessors.forEach((preprocessor) => { q.defer(preprocessor.criteria, filepath, info); }); q.awaitAll((err, results) => { if (err) return callback(err); callback(null, preprocessors.filter((preprocessor, i) => { return !!results[i]; })); }); }
[ "function", "applicable", "(", "filepath", ",", "info", ",", "callback", ")", "{", "const", "q", "=", "queue", "(", ")", ";", "preprocessors", ".", "forEach", "(", "(", "preprocessor", ")", "=>", "{", "q", ".", "defer", "(", "preprocessor", ".", "criteria", ",", "filepath", ",", "info", ")", ";", "}", ")", ";", "q", ".", "awaitAll", "(", "(", "err", ",", "results", ")", "=>", "{", "if", "(", "err", ")", "return", "callback", "(", "err", ")", ";", "callback", "(", "null", ",", "preprocessors", ".", "filter", "(", "(", "preprocessor", ",", "i", ")", "=>", "{", "return", "!", "!", "results", "[", "i", "]", ";", "}", ")", ")", ";", "}", ")", ";", "}" ]
A function that checks a file against each preprocessor's criteria callback returns only those applicable to this file
[ "A", "function", "that", "checks", "a", "file", "against", "each", "preprocessor", "s", "criteria", "callback", "returns", "only", "those", "applicable", "to", "this", "file" ]
9c0c3f6e8e33692792bd66ff1d4596f91aba1fa3
https://github.com/mapbox/preprocessorcerer/blob/9c0c3f6e8e33692792bd66ff1d4596f91aba1fa3/preprocessors/index.js#L39-L51
18,589
mapbox/preprocessorcerer
preprocessors/index.js
descriptions
function descriptions(filepath, info, callback) { applicable(filepath, info, (err, preprocessors) => { if (err) return callback(err); callback(null, preprocessors.map((preprocessor) => { return preprocessor.description; })); }); }
javascript
function descriptions(filepath, info, callback) { applicable(filepath, info, (err, preprocessors) => { if (err) return callback(err); callback(null, preprocessors.map((preprocessor) => { return preprocessor.description; })); }); }
[ "function", "descriptions", "(", "filepath", ",", "info", ",", "callback", ")", "{", "applicable", "(", "filepath", ",", "info", ",", "(", "err", ",", "preprocessors", ")", "=>", "{", "if", "(", "err", ")", "return", "callback", "(", "err", ")", ";", "callback", "(", "null", ",", "preprocessors", ".", "map", "(", "(", "preprocessor", ")", "=>", "{", "return", "preprocessor", ".", "description", ";", "}", ")", ")", ";", "}", ")", ";", "}" ]
Just maps applicable preprocessors into a list of descriptions
[ "Just", "maps", "applicable", "preprocessors", "into", "a", "list", "of", "descriptions" ]
9c0c3f6e8e33692792bd66ff1d4596f91aba1fa3
https://github.com/mapbox/preprocessorcerer/blob/9c0c3f6e8e33692792bd66ff1d4596f91aba1fa3/preprocessors/index.js#L54-L61
18,590
mapbox/preprocessorcerer
preprocessors/index.js
newfile
function newfile(filepath) { let dir = path.dirname(filepath); if (path.extname(filepath) === '.shp') dir = path.resolve(dir, '..'); const name = crypto.randomBytes(8).toString('hex'); return path.join(dir, name); }
javascript
function newfile(filepath) { let dir = path.dirname(filepath); if (path.extname(filepath) === '.shp') dir = path.resolve(dir, '..'); const name = crypto.randomBytes(8).toString('hex'); return path.join(dir, name); }
[ "function", "newfile", "(", "filepath", ")", "{", "let", "dir", "=", "path", ".", "dirname", "(", "filepath", ")", ";", "if", "(", "path", ".", "extname", "(", "filepath", ")", "===", "'.shp'", ")", "dir", "=", "path", ".", "resolve", "(", "dir", ",", "'..'", ")", ";", "const", "name", "=", "crypto", ".", "randomBytes", "(", "8", ")", ".", "toString", "(", "'hex'", ")", ";", "return", "path", ".", "join", "(", "dir", ",", "name", ")", ";", "}" ]
A function that hands out a new filepath in the same directory as the given file
[ "A", "function", "that", "hands", "out", "a", "new", "filepath", "in", "the", "same", "directory", "as", "the", "given", "file" ]
9c0c3f6e8e33692792bd66ff1d4596f91aba1fa3
https://github.com/mapbox/preprocessorcerer/blob/9c0c3f6e8e33692792bd66ff1d4596f91aba1fa3/preprocessors/index.js#L64-L69
18,591
mapbox/preprocessorcerer
preprocessors/index.js
preprocessorcery
function preprocessorcery(infile, info, callback) { applicable(infile, info, (err, preprocessors) => { if (err) return callback(err); const q = queue(1); preprocessors.forEach((preprocessor) => { const outfile = newfile(infile); q.defer((next) => { preprocessor(infile, outfile, (err) => { if (err) return next(err); infile = outfile; next(); }); }); }); q.await((err) => { if (err) return callback(err); // infile has been changed to the output file by this point callback(null, infile); }); }); }
javascript
function preprocessorcery(infile, info, callback) { applicable(infile, info, (err, preprocessors) => { if (err) return callback(err); const q = queue(1); preprocessors.forEach((preprocessor) => { const outfile = newfile(infile); q.defer((next) => { preprocessor(infile, outfile, (err) => { if (err) return next(err); infile = outfile; next(); }); }); }); q.await((err) => { if (err) return callback(err); // infile has been changed to the output file by this point callback(null, infile); }); }); }
[ "function", "preprocessorcery", "(", "infile", ",", "info", ",", "callback", ")", "{", "applicable", "(", "infile", ",", "info", ",", "(", "err", ",", "preprocessors", ")", "=>", "{", "if", "(", "err", ")", "return", "callback", "(", "err", ")", ";", "const", "q", "=", "queue", "(", "1", ")", ";", "preprocessors", ".", "forEach", "(", "(", "preprocessor", ")", "=>", "{", "const", "outfile", "=", "newfile", "(", "infile", ")", ";", "q", ".", "defer", "(", "(", "next", ")", "=>", "{", "preprocessor", "(", "infile", ",", "outfile", ",", "(", "err", ")", "=>", "{", "if", "(", "err", ")", "return", "next", "(", "err", ")", ";", "infile", "=", "outfile", ";", "next", "(", ")", ";", "}", ")", ";", "}", ")", ";", "}", ")", ";", "q", ".", "await", "(", "(", "err", ")", "=>", "{", "if", "(", "err", ")", "return", "callback", "(", "err", ")", ";", "// infile has been changed to the output file by this point", "callback", "(", "null", ",", "infile", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Finds applicable preprocessors and runs each `info` is expected to be an fs.Stat object + .filetype determined by mapbox-file-sniff callback returns the post-preprocessed filepath
[ "Finds", "applicable", "preprocessors", "and", "runs", "each", "info", "is", "expected", "to", "be", "an", "fs", ".", "Stat", "object", "+", ".", "filetype", "determined", "by", "mapbox", "-", "file", "-", "sniff", "callback", "returns", "the", "post", "-", "preprocessed", "filepath" ]
9c0c3f6e8e33692792bd66ff1d4596f91aba1fa3
https://github.com/mapbox/preprocessorcerer/blob/9c0c3f6e8e33692792bd66ff1d4596f91aba1fa3/preprocessors/index.js#L74-L97
18,592
mapbox/preprocessorcerer
preprocessors/spatial-index.preprocessor.js
copy
function copy(finished) { fs.createReadStream(infile) .once('error', callback) .pipe(fs.createWriteStream(outfile)) .once('error', callback) .on('finish', finished); }
javascript
function copy(finished) { fs.createReadStream(infile) .once('error', callback) .pipe(fs.createWriteStream(outfile)) .once('error', callback) .on('finish', finished); }
[ "function", "copy", "(", "finished", ")", "{", "fs", ".", "createReadStream", "(", "infile", ")", ".", "once", "(", "'error'", ",", "callback", ")", ".", "pipe", "(", "fs", ".", "createWriteStream", "(", "outfile", ")", ")", ".", "once", "(", "'error'", ",", "callback", ")", ".", "on", "(", "'finish'", ",", "finished", ")", ";", "}" ]
Create copy of original file into new dir
[ "Create", "copy", "of", "original", "file", "into", "new", "dir" ]
9c0c3f6e8e33692792bd66ff1d4596f91aba1fa3
https://github.com/mapbox/preprocessorcerer/blob/9c0c3f6e8e33692792bd66ff1d4596f91aba1fa3/preprocessors/spatial-index.preprocessor.js#L19-L25
18,593
wix/okidoc
packages/okidoc-md/src/utils/nodeAST.js
cleanUpNodeJSDoc
function cleanUpNodeJSDoc( node, JSDocCommentValue = getJSDocCommentValue(node), ) { t.removeComments(node); t.addComment(node, 'leading', createJSDocCommentValue(JSDocCommentValue)); }
javascript
function cleanUpNodeJSDoc( node, JSDocCommentValue = getJSDocCommentValue(node), ) { t.removeComments(node); t.addComment(node, 'leading', createJSDocCommentValue(JSDocCommentValue)); }
[ "function", "cleanUpNodeJSDoc", "(", "node", ",", "JSDocCommentValue", "=", "getJSDocCommentValue", "(", "node", ")", ",", ")", "{", "t", ".", "removeComments", "(", "node", ")", ";", "t", ".", "addComment", "(", "node", ",", "'leading'", ",", "createJSDocCommentValue", "(", "JSDocCommentValue", ")", ")", ";", "}" ]
Ensure node JSDoc comment is provided and in valid position
[ "Ensure", "node", "JSDoc", "comment", "is", "provided", "and", "in", "valid", "position" ]
d4f4173e46b22c636ad0ac236b6e5c2ee58163f1
https://github.com/wix/okidoc/blob/d4f4173e46b22c636ad0ac236b6e5c2ee58163f1/packages/okidoc-md/src/utils/nodeAST.js#L8-L14
18,594
wix/okidoc
packages/okidoc-site/site/src/utils/renderHtmlAst.js
renderHtmlAst
function renderHtmlAst(node, { components }) { if (node.type === 'root') { // NOTE: wrap children with React.Fragment, to avoid div wrapper from `hast-to-hyperscript` node = { type: 'element', tagName: Fragment, properties: {}, children: node.children, }; } function h(name, props, children) { return React.createElement( getReactElement(name, components), props, getReactChildren(name, children), ); } return toH(h, node); }
javascript
function renderHtmlAst(node, { components }) { if (node.type === 'root') { // NOTE: wrap children with React.Fragment, to avoid div wrapper from `hast-to-hyperscript` node = { type: 'element', tagName: Fragment, properties: {}, children: node.children, }; } function h(name, props, children) { return React.createElement( getReactElement(name, components), props, getReactChildren(name, children), ); } return toH(h, node); }
[ "function", "renderHtmlAst", "(", "node", ",", "{", "components", "}", ")", "{", "if", "(", "node", ".", "type", "===", "'root'", ")", "{", "// NOTE: wrap children with React.Fragment, to avoid div wrapper from `hast-to-hyperscript`", "node", "=", "{", "type", ":", "'element'", ",", "tagName", ":", "Fragment", ",", "properties", ":", "{", "}", ",", "children", ":", "node", ".", "children", ",", "}", ";", "}", "function", "h", "(", "name", ",", "props", ",", "children", ")", "{", "return", "React", ".", "createElement", "(", "getReactElement", "(", "name", ",", "components", ")", ",", "props", ",", "getReactChildren", "(", "name", ",", "children", ")", ",", ")", ";", "}", "return", "toH", "(", "h", ",", "node", ")", ";", "}" ]
Compile HAST to React. @param node @param components
[ "Compile", "HAST", "to", "React", "." ]
d4f4173e46b22c636ad0ac236b6e5c2ee58163f1
https://github.com/wix/okidoc/blob/d4f4173e46b22c636ad0ac236b6e5c2ee58163f1/packages/okidoc-site/site/src/utils/renderHtmlAst.js#L36-L56
18,595
gems-uff/noworkflow
capture/noworkflow/jupyter/extension.js
function(value) { if (!arguments.length) return mimeType; mimeType = value == null ? null : value + ""; return request; }
javascript
function(value) { if (!arguments.length) return mimeType; mimeType = value == null ? null : value + ""; return request; }
[ "function", "(", "value", ")", "{", "if", "(", "!", "arguments", ".", "length", ")", "return", "mimeType", ";", "mimeType", "=", "value", "==", "null", "?", "null", ":", "value", "+", "\"\"", ";", "return", "request", ";", "}" ]
If mimeType is non-null and no Accept header is set, a default is used.
[ "If", "mimeType", "is", "non", "-", "null", "and", "no", "Accept", "header", "is", "set", "a", "default", "is", "used", "." ]
3e824c5b18378872911b31db8a61222676c3fb1d
https://github.com/gems-uff/noworkflow/blob/3e824c5b18378872911b31db8a61222676c3fb1d/capture/noworkflow/jupyter/extension.js#L3497-L3501
18,596
gems-uff/noworkflow
capture/noworkflow/jupyter/extension.js
function(method, data, callback) { xhr.open(method, url, true, user, password); if (mimeType != null && !headers.has("accept")) headers.set("accept", mimeType + ",*/*"); if (xhr.setRequestHeader) headers.each(function(value, name) { xhr.setRequestHeader(name, value); }); if (mimeType != null && xhr.overrideMimeType) xhr.overrideMimeType(mimeType); if (responseType != null) xhr.responseType = responseType; if (timeout > 0) xhr.timeout = timeout; if (callback == null && typeof data === "function") callback = data, data = null; if (callback != null && callback.length === 1) callback = fixCallback(callback); if (callback != null) request.on("error", callback).on("load", function(xhr) { callback(null, xhr); }); event.call("beforesend", request, xhr); xhr.send(data == null ? null : data); return request; }
javascript
function(method, data, callback) { xhr.open(method, url, true, user, password); if (mimeType != null && !headers.has("accept")) headers.set("accept", mimeType + ",*/*"); if (xhr.setRequestHeader) headers.each(function(value, name) { xhr.setRequestHeader(name, value); }); if (mimeType != null && xhr.overrideMimeType) xhr.overrideMimeType(mimeType); if (responseType != null) xhr.responseType = responseType; if (timeout > 0) xhr.timeout = timeout; if (callback == null && typeof data === "function") callback = data, data = null; if (callback != null && callback.length === 1) callback = fixCallback(callback); if (callback != null) request.on("error", callback).on("load", function(xhr) { callback(null, xhr); }); event.call("beforesend", request, xhr); xhr.send(data == null ? null : data); return request; }
[ "function", "(", "method", ",", "data", ",", "callback", ")", "{", "xhr", ".", "open", "(", "method", ",", "url", ",", "true", ",", "user", ",", "password", ")", ";", "if", "(", "mimeType", "!=", "null", "&&", "!", "headers", ".", "has", "(", "\"accept\"", ")", ")", "headers", ".", "set", "(", "\"accept\"", ",", "mimeType", "+", "\",*/*\"", ")", ";", "if", "(", "xhr", ".", "setRequestHeader", ")", "headers", ".", "each", "(", "function", "(", "value", ",", "name", ")", "{", "xhr", ".", "setRequestHeader", "(", "name", ",", "value", ")", ";", "}", ")", ";", "if", "(", "mimeType", "!=", "null", "&&", "xhr", ".", "overrideMimeType", ")", "xhr", ".", "overrideMimeType", "(", "mimeType", ")", ";", "if", "(", "responseType", "!=", "null", ")", "xhr", ".", "responseType", "=", "responseType", ";", "if", "(", "timeout", ">", "0", ")", "xhr", ".", "timeout", "=", "timeout", ";", "if", "(", "callback", "==", "null", "&&", "typeof", "data", "===", "\"function\"", ")", "callback", "=", "data", ",", "data", "=", "null", ";", "if", "(", "callback", "!=", "null", "&&", "callback", ".", "length", "===", "1", ")", "callback", "=", "fixCallback", "(", "callback", ")", ";", "if", "(", "callback", "!=", "null", ")", "request", ".", "on", "(", "\"error\"", ",", "callback", ")", ".", "on", "(", "\"load\"", ",", "function", "(", "xhr", ")", "{", "callback", "(", "null", ",", "xhr", ")", ";", "}", ")", ";", "event", ".", "call", "(", "\"beforesend\"", ",", "request", ",", "xhr", ")", ";", "xhr", ".", "send", "(", "data", "==", "null", "?", "null", ":", "data", ")", ";", "return", "request", ";", "}" ]
If callback is non-null, it will be used for error and load events.
[ "If", "callback", "is", "non", "-", "null", "it", "will", "be", "used", "for", "error", "and", "load", "events", "." ]
3e824c5b18378872911b31db8a61222676c3fb1d
https://github.com/gems-uff/noworkflow/blob/3e824c5b18378872911b31db8a61222676c3fb1d/capture/noworkflow/jupyter/extension.js#L3543-L3556
18,597
gems-uff/noworkflow
capture/noworkflow/jupyter/extension.js
load_ipython_extension
function load_ipython_extension() { !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(181), __webpack_require__(178), __webpack_require__(179), __webpack_require__(180), __webpack_require__(560), __webpack_require__(182), __webpack_require__(216), __webpack_require__(349), __webpack_require__(504)], __WEBPACK_AMD_DEFINE_RESULT__ = (function (Extension, Jupyter, events, utils, codecell, d3_selection, trial, history, nowutils) { console.log("<<<LOAD noworkflow 2>>>"); var notebook = Jupyter.notebook; Extension.register_renderer(notebook, trial, history, nowutils, d3_selection); Extension.render_cells(notebook); }).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); }
javascript
function load_ipython_extension() { !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(181), __webpack_require__(178), __webpack_require__(179), __webpack_require__(180), __webpack_require__(560), __webpack_require__(182), __webpack_require__(216), __webpack_require__(349), __webpack_require__(504)], __WEBPACK_AMD_DEFINE_RESULT__ = (function (Extension, Jupyter, events, utils, codecell, d3_selection, trial, history, nowutils) { console.log("<<<LOAD noworkflow 2>>>"); var notebook = Jupyter.notebook; Extension.register_renderer(notebook, trial, history, nowutils, d3_selection); Extension.render_cells(notebook); }).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); }
[ "function", "load_ipython_extension", "(", ")", "{", "!", "(", "__WEBPACK_AMD_DEFINE_ARRAY__", "=", "[", "__webpack_require__", "(", "181", ")", ",", "__webpack_require__", "(", "178", ")", ",", "__webpack_require__", "(", "179", ")", ",", "__webpack_require__", "(", "180", ")", ",", "__webpack_require__", "(", "560", ")", ",", "__webpack_require__", "(", "182", ")", ",", "__webpack_require__", "(", "216", ")", ",", "__webpack_require__", "(", "349", ")", ",", "__webpack_require__", "(", "504", ")", "]", ",", "__WEBPACK_AMD_DEFINE_RESULT__", "=", "(", "function", "(", "Extension", ",", "Jupyter", ",", "events", ",", "utils", ",", "codecell", ",", "d3_selection", ",", "trial", ",", "history", ",", "nowutils", ")", "{", "console", ".", "log", "(", "\"<<<LOAD noworkflow 2>>>\"", ")", ";", "var", "notebook", "=", "Jupyter", ".", "notebook", ";", "Extension", ".", "register_renderer", "(", "notebook", ",", "trial", ",", "history", ",", "nowutils", ",", "d3_selection", ")", ";", "Extension", ".", "render_cells", "(", "notebook", ")", ";", "}", ")", ".", "apply", "(", "exports", ",", "__WEBPACK_AMD_DEFINE_ARRAY__", ")", ",", "__WEBPACK_AMD_DEFINE_RESULT__", "!==", "undefined", "&&", "(", "module", ".", "exports", "=", "__WEBPACK_AMD_DEFINE_RESULT__", ")", ")", ";", "}" ]
Export the required load_ipython_extention.
[ "Export", "the", "required", "load_ipython_extention", "." ]
3e824c5b18378872911b31db8a61222676c3fb1d
https://github.com/gems-uff/noworkflow/blob/3e824c5b18378872911b31db8a61222676c3fb1d/capture/noworkflow/jupyter/extension.js#L8905-L8913
18,598
gems-uff/noworkflow
capture/noworkflow/jupyter/extension.js
diagonal
function diagonal(s, d) { if (s.dy == undefined) { s.dy = 0; } if (d.dy == undefined) { d.dy = 0; } let path = `M ${s.x} ${(s.y + s.dy)} C ${(s.x + d.x) / 2} ${(s.y + s.dy)}, ${(s.x + d.x) / 2} ${(d.y + d.dy)}, ${d.x} ${(d.y + d.dy)}`; return path; }
javascript
function diagonal(s, d) { if (s.dy == undefined) { s.dy = 0; } if (d.dy == undefined) { d.dy = 0; } let path = `M ${s.x} ${(s.y + s.dy)} C ${(s.x + d.x) / 2} ${(s.y + s.dy)}, ${(s.x + d.x) / 2} ${(d.y + d.dy)}, ${d.x} ${(d.y + d.dy)}`; return path; }
[ "function", "diagonal", "(", "s", ",", "d", ")", "{", "if", "(", "s", ".", "dy", "==", "undefined", ")", "{", "s", ".", "dy", "=", "0", ";", "}", "if", "(", "d", ".", "dy", "==", "undefined", ")", "{", "d", ".", "dy", "=", "0", ";", "}", "let", "path", "=", "`", "${", "s", ".", "x", "}", "${", "(", "s", ".", "y", "+", "s", ".", "dy", ")", "}", "${", "(", "s", ".", "x", "+", "d", ".", "x", ")", "/", "2", "}", "${", "(", "s", ".", "y", "+", "s", ".", "dy", ")", "}", "${", "(", "s", ".", "x", "+", "d", ".", "x", ")", "/", "2", "}", "${", "(", "d", ".", "y", "+", "d", ".", "dy", ")", "}", "${", "d", ".", "x", "}", "${", "(", "d", ".", "y", "+", "d", ".", "dy", ")", "}", "`", ";", "return", "path", ";", "}" ]
Create diagonal line between two nodes
[ "Create", "diagonal", "line", "between", "two", "nodes" ]
3e824c5b18378872911b31db8a61222676c3fb1d
https://github.com/gems-uff/noworkflow/blob/3e824c5b18378872911b31db8a61222676c3fb1d/capture/noworkflow/jupyter/extension.js#L15275-L15287
18,599
gems-uff/noworkflow
capture/noworkflow/jupyter/index.js
register_renderer
function register_renderer(notebook, trial, history, utils, d3_selection) { /* Get an instance of output_area from a CodeCell instance */ var _notebook$get_cells$r = notebook.get_cells().reduce(function (result, cell) { return cell.output_area ? cell : result; }, {}), output_area = _notebook$get_cells$r.output_area; /* History mime */ var append_history = function append_history(data, metadata, element) { var div = document.createElement('div'); element.append(div); var graph = new history.HistoryGraph('history-' + utils.makeid(), div, { width: data.width, height: data.height, hintMessage: "" }); graph.load(data); return div; }; /* Trial mime */ var append_trial = function append_trial(data, metadata, element) { var div = document.createElement('div'); element.append(div); var graph = new trial.TrialGraph('trial-' + utils.makeid(), div, { width: data.width, height: data.height }); graph.load(data, data.trial1, data.trial2); return div; }; /** * Register the mime type and append_history function with output_area */ output_area.register_mime_type('application/noworkflow.history+json', append_history, { safe: true, index: 0 }); output_area.register_mime_type('application/noworkflow.trial+json', append_trial, { safe: true, index: 0 }); }
javascript
function register_renderer(notebook, trial, history, utils, d3_selection) { /* Get an instance of output_area from a CodeCell instance */ var _notebook$get_cells$r = notebook.get_cells().reduce(function (result, cell) { return cell.output_area ? cell : result; }, {}), output_area = _notebook$get_cells$r.output_area; /* History mime */ var append_history = function append_history(data, metadata, element) { var div = document.createElement('div'); element.append(div); var graph = new history.HistoryGraph('history-' + utils.makeid(), div, { width: data.width, height: data.height, hintMessage: "" }); graph.load(data); return div; }; /* Trial mime */ var append_trial = function append_trial(data, metadata, element) { var div = document.createElement('div'); element.append(div); var graph = new trial.TrialGraph('trial-' + utils.makeid(), div, { width: data.width, height: data.height }); graph.load(data, data.trial1, data.trial2); return div; }; /** * Register the mime type and append_history function with output_area */ output_area.register_mime_type('application/noworkflow.history+json', append_history, { safe: true, index: 0 }); output_area.register_mime_type('application/noworkflow.trial+json', append_trial, { safe: true, index: 0 }); }
[ "function", "register_renderer", "(", "notebook", ",", "trial", ",", "history", ",", "utils", ",", "d3_selection", ")", "{", "/* Get an instance of output_area from a CodeCell instance */", "var", "_notebook$get_cells$r", "=", "notebook", ".", "get_cells", "(", ")", ".", "reduce", "(", "function", "(", "result", ",", "cell", ")", "{", "return", "cell", ".", "output_area", "?", "cell", ":", "result", ";", "}", ",", "{", "}", ")", ",", "output_area", "=", "_notebook$get_cells$r", ".", "output_area", ";", "/* History mime */", "var", "append_history", "=", "function", "append_history", "(", "data", ",", "metadata", ",", "element", ")", "{", "var", "div", "=", "document", ".", "createElement", "(", "'div'", ")", ";", "element", ".", "append", "(", "div", ")", ";", "var", "graph", "=", "new", "history", ".", "HistoryGraph", "(", "'history-'", "+", "utils", ".", "makeid", "(", ")", ",", "div", ",", "{", "width", ":", "data", ".", "width", ",", "height", ":", "data", ".", "height", ",", "hintMessage", ":", "\"\"", "}", ")", ";", "graph", ".", "load", "(", "data", ")", ";", "return", "div", ";", "}", ";", "/* Trial mime */", "var", "append_trial", "=", "function", "append_trial", "(", "data", ",", "metadata", ",", "element", ")", "{", "var", "div", "=", "document", ".", "createElement", "(", "'div'", ")", ";", "element", ".", "append", "(", "div", ")", ";", "var", "graph", "=", "new", "trial", ".", "TrialGraph", "(", "'trial-'", "+", "utils", ".", "makeid", "(", ")", ",", "div", ",", "{", "width", ":", "data", ".", "width", ",", "height", ":", "data", ".", "height", "}", ")", ";", "graph", ".", "load", "(", "data", ",", "data", ".", "trial1", ",", "data", ".", "trial2", ")", ";", "return", "div", ";", "}", ";", "/**\n * Register the mime type and append_history function with output_area\n */", "output_area", ".", "register_mime_type", "(", "'application/noworkflow.history+json'", ",", "append_history", ",", "{", "safe", ":", "true", ",", "index", ":", "0", "}", ")", ";", "output_area", ".", "register_mime_type", "(", "'application/noworkflow.trial+json'", ",", "append_trial", ",", "{", "safe", ":", "true", ",", "index", ":", "0", "}", ")", ";", "}" ]
Register the mime type and append_mime function with the notebook's output area
[ "Register", "the", "mime", "type", "and", "append_mime", "function", "with", "the", "notebook", "s", "output", "area" ]
3e824c5b18378872911b31db8a61222676c3fb1d
https://github.com/gems-uff/noworkflow/blob/3e824c5b18378872911b31db8a61222676c3fb1d/capture/noworkflow/jupyter/index.js#L215-L261