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
22,300
josdejong/lossless-json
lib/revive.js
reviveArray
function reviveArray (array, reviver) { let revived = []; for (let i = 0; i < array.length; i++) { revived[i] = reviveValue(array, i + '', array[i], reviver); } return revived; }
javascript
function reviveArray (array, reviver) { let revived = []; for (let i = 0; i < array.length; i++) { revived[i] = reviveValue(array, i + '', array[i], reviver); } return revived; }
[ "function", "reviveArray", "(", "array", ",", "reviver", ")", "{", "let", "revived", "=", "[", "]", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "array", ".", "length", ";", "i", "++", ")", "{", "revived", "[", "i", "]", "=", "reviveValue", "(", "array", ",", "i", "+", "''", ",", "array", "[", "i", "]", ",", "reviver", ")", ";", "}", "return", "revived", ";", "}" ]
Revive the properties of an Array @param {Array} array @param {function} reviver @return {Array}
[ "Revive", "the", "properties", "of", "an", "Array" ]
ed6c201b37b5583d2c9c7a7d0b5fc1b3f01519bd
https://github.com/josdejong/lossless-json/blob/ed6c201b37b5583d2c9c7a7d0b5fc1b3f01519bd/lib/revive.js#L62-L70
22,301
mblarsen/vue-browser-acl
index.js
commentNode
function commentNode(el, vnode) { const comment = document.createComment(' ') Object.defineProperty(comment, 'setAttribute', { value: () => undefined }) vnode.text = ' ' vnode.elm = comment vnode.isComment = true vnode.tag = undefined vnode.data.directives = undefined if (vnode.componentInstance) { vnode.componentInstance.$el = comment } if (el.parentNode) { el.parentNode.replaceChild(comment, el) } }
javascript
function commentNode(el, vnode) { const comment = document.createComment(' ') Object.defineProperty(comment, 'setAttribute', { value: () => undefined }) vnode.text = ' ' vnode.elm = comment vnode.isComment = true vnode.tag = undefined vnode.data.directives = undefined if (vnode.componentInstance) { vnode.componentInstance.$el = comment } if (el.parentNode) { el.parentNode.replaceChild(comment, el) } }
[ "function", "commentNode", "(", "el", ",", "vnode", ")", "{", "const", "comment", "=", "document", ".", "createComment", "(", "' '", ")", "Object", ".", "defineProperty", "(", "comment", ",", "'setAttribute'", ",", "{", "value", ":", "(", ")", "=>", "undefined", "}", ")", "vnode", ".", "text", "=", "' '", "vnode", ".", "elm", "=", "comment", "vnode", ".", "isComment", "=", "true", "vnode", ".", "tag", "=", "undefined", "vnode", ".", "data", ".", "directives", "=", "undefined", "if", "(", "vnode", ".", "componentInstance", ")", "{", "vnode", ".", "componentInstance", ".", "$el", "=", "comment", "}", "if", "(", "el", ".", "parentNode", ")", "{", "el", ".", "parentNode", ".", "replaceChild", "(", "comment", ",", "el", ")", "}", "}" ]
Create comment node @private @author https://stackoverflow.com/questions/43003976/a-custom-directive-similar-to-v-if-in-vuejs#43543814
[ "Create", "comment", "node" ]
23323a43be269d91872bf124fa6e11488b079bb9
https://github.com/mblarsen/vue-browser-acl/blob/23323a43be269d91872bf124fa6e11488b079bb9/index.js#L175-L195
22,302
Moblox/mongo-xlsx
lib/mongo-xlsx.js
function(value, currentKeyArray) { var type = typeof value; var pushAnElement = function() { var access = currentKeyArray.reduce(buildColumnName); if (mongoModelMap[access]) { return; } mongoModelMap[access] = access; mongoModel.push({ displayName: access, access: access, type: type }); }; switch (type) { case "boolean": case "number": case "string": return pushAnElement(); case "object": if (!value) { return pushAnElement(); } switch(value.constructor) { case Array: return searchArray(value, currentKeyArray.slice()); case Object: return searchObject(value, currentKeyArray.slice()); case Date: type = 'date'; return pushAnElement(); default: if (value.constructor.name === "ObjectID") { type = "ObjectID"; return pushAnElement(); } else if (value.constructor.name === "InternalCache") { // Skip this. Internal mongoose type. // Isn't part of the document. return; } else { console.log("Unknown Object Type:", value.constructor.name); } } break; case "symbol": case "function": return; default: break; } }
javascript
function(value, currentKeyArray) { var type = typeof value; var pushAnElement = function() { var access = currentKeyArray.reduce(buildColumnName); if (mongoModelMap[access]) { return; } mongoModelMap[access] = access; mongoModel.push({ displayName: access, access: access, type: type }); }; switch (type) { case "boolean": case "number": case "string": return pushAnElement(); case "object": if (!value) { return pushAnElement(); } switch(value.constructor) { case Array: return searchArray(value, currentKeyArray.slice()); case Object: return searchObject(value, currentKeyArray.slice()); case Date: type = 'date'; return pushAnElement(); default: if (value.constructor.name === "ObjectID") { type = "ObjectID"; return pushAnElement(); } else if (value.constructor.name === "InternalCache") { // Skip this. Internal mongoose type. // Isn't part of the document. return; } else { console.log("Unknown Object Type:", value.constructor.name); } } break; case "symbol": case "function": return; default: break; } }
[ "function", "(", "value", ",", "currentKeyArray", ")", "{", "var", "type", "=", "typeof", "value", ";", "var", "pushAnElement", "=", "function", "(", ")", "{", "var", "access", "=", "currentKeyArray", ".", "reduce", "(", "buildColumnName", ")", ";", "if", "(", "mongoModelMap", "[", "access", "]", ")", "{", "return", ";", "}", "mongoModelMap", "[", "access", "]", "=", "access", ";", "mongoModel", ".", "push", "(", "{", "displayName", ":", "access", ",", "access", ":", "access", ",", "type", ":", "type", "}", ")", ";", "}", ";", "switch", "(", "type", ")", "{", "case", "\"boolean\"", ":", "case", "\"number\"", ":", "case", "\"string\"", ":", "return", "pushAnElement", "(", ")", ";", "case", "\"object\"", ":", "if", "(", "!", "value", ")", "{", "return", "pushAnElement", "(", ")", ";", "}", "switch", "(", "value", ".", "constructor", ")", "{", "case", "Array", ":", "return", "searchArray", "(", "value", ",", "currentKeyArray", ".", "slice", "(", ")", ")", ";", "case", "Object", ":", "return", "searchObject", "(", "value", ",", "currentKeyArray", ".", "slice", "(", ")", ")", ";", "case", "Date", ":", "type", "=", "'date'", ";", "return", "pushAnElement", "(", ")", ";", "default", ":", "if", "(", "value", ".", "constructor", ".", "name", "===", "\"ObjectID\"", ")", "{", "type", "=", "\"ObjectID\"", ";", "return", "pushAnElement", "(", ")", ";", "}", "else", "if", "(", "value", ".", "constructor", ".", "name", "===", "\"InternalCache\"", ")", "{", "// Skip this. Internal mongoose type.", "// Isn't part of the document.", "return", ";", "}", "else", "{", "console", ".", "log", "(", "\"Unknown Object Type:\"", ",", "value", ".", "constructor", ".", "name", ")", ";", "}", "}", "break", ";", "case", "\"symbol\"", ":", "case", "\"function\"", ":", "return", ";", "default", ":", "break", ";", "}", "}" ]
For quickly searching if value exist.
[ "For", "quickly", "searching", "if", "value", "exist", "." ]
805faae6fe4f2249ca3f9110317b8a480352480a
https://github.com/Moblox/mongo-xlsx/blob/805faae6fe4f2249ca3f9110317b8a480352480a/lib/mongo-xlsx.js#L18-L70
22,303
Inscryb/inscryb-markdown-editor
src/js/inscrybmde.js
toggleFullScreen
function toggleFullScreen(editor) { // Set fullscreen var cm = editor.codemirror; cm.setOption('fullScreen', !cm.getOption('fullScreen')); // Prevent scrolling on body during fullscreen active if (cm.getOption('fullScreen')) { saved_overflow = document.body.style.overflow; document.body.style.overflow = 'hidden'; } else { document.body.style.overflow = saved_overflow; } // Update toolbar class var wrap = cm.getWrapperElement(); if (!/fullscreen/.test(wrap.previousSibling.className)) { wrap.previousSibling.className += ' fullscreen'; } else { wrap.previousSibling.className = wrap.previousSibling.className.replace(/\s*fullscreen\b/, ''); } // Update toolbar button if (editor.toolbarElements.fullscreen) { var toolbarButton = editor.toolbarElements.fullscreen; if (!/active/.test(toolbarButton.className)) { toolbarButton.className += ' active'; } else { toolbarButton.className = toolbarButton.className.replace(/\s*active\s*/g, ''); } } // Hide side by side if needed var sidebyside = cm.getWrapperElement().nextSibling; if (/editor-preview-active-side/.test(sidebyside.className)) toggleSideBySide(editor); }
javascript
function toggleFullScreen(editor) { // Set fullscreen var cm = editor.codemirror; cm.setOption('fullScreen', !cm.getOption('fullScreen')); // Prevent scrolling on body during fullscreen active if (cm.getOption('fullScreen')) { saved_overflow = document.body.style.overflow; document.body.style.overflow = 'hidden'; } else { document.body.style.overflow = saved_overflow; } // Update toolbar class var wrap = cm.getWrapperElement(); if (!/fullscreen/.test(wrap.previousSibling.className)) { wrap.previousSibling.className += ' fullscreen'; } else { wrap.previousSibling.className = wrap.previousSibling.className.replace(/\s*fullscreen\b/, ''); } // Update toolbar button if (editor.toolbarElements.fullscreen) { var toolbarButton = editor.toolbarElements.fullscreen; if (!/active/.test(toolbarButton.className)) { toolbarButton.className += ' active'; } else { toolbarButton.className = toolbarButton.className.replace(/\s*active\s*/g, ''); } } // Hide side by side if needed var sidebyside = cm.getWrapperElement().nextSibling; if (/editor-preview-active-side/.test(sidebyside.className)) toggleSideBySide(editor); }
[ "function", "toggleFullScreen", "(", "editor", ")", "{", "// Set fullscreen", "var", "cm", "=", "editor", ".", "codemirror", ";", "cm", ".", "setOption", "(", "'fullScreen'", ",", "!", "cm", ".", "getOption", "(", "'fullScreen'", ")", ")", ";", "// Prevent scrolling on body during fullscreen active", "if", "(", "cm", ".", "getOption", "(", "'fullScreen'", ")", ")", "{", "saved_overflow", "=", "document", ".", "body", ".", "style", ".", "overflow", ";", "document", ".", "body", ".", "style", ".", "overflow", "=", "'hidden'", ";", "}", "else", "{", "document", ".", "body", ".", "style", ".", "overflow", "=", "saved_overflow", ";", "}", "// Update toolbar class", "var", "wrap", "=", "cm", ".", "getWrapperElement", "(", ")", ";", "if", "(", "!", "/", "fullscreen", "/", ".", "test", "(", "wrap", ".", "previousSibling", ".", "className", ")", ")", "{", "wrap", ".", "previousSibling", ".", "className", "+=", "' fullscreen'", ";", "}", "else", "{", "wrap", ".", "previousSibling", ".", "className", "=", "wrap", ".", "previousSibling", ".", "className", ".", "replace", "(", "/", "\\s*fullscreen\\b", "/", ",", "''", ")", ";", "}", "// Update toolbar button", "if", "(", "editor", ".", "toolbarElements", ".", "fullscreen", ")", "{", "var", "toolbarButton", "=", "editor", ".", "toolbarElements", ".", "fullscreen", ";", "if", "(", "!", "/", "active", "/", ".", "test", "(", "toolbarButton", ".", "className", ")", ")", "{", "toolbarButton", ".", "className", "+=", "' active'", ";", "}", "else", "{", "toolbarButton", ".", "className", "=", "toolbarButton", ".", "className", ".", "replace", "(", "/", "\\s*active\\s*", "/", "g", ",", "''", ")", ";", "}", "}", "// Hide side by side if needed", "var", "sidebyside", "=", "cm", ".", "getWrapperElement", "(", ")", ".", "nextSibling", ";", "if", "(", "/", "editor-preview-active-side", "/", ".", "test", "(", "sidebyside", ".", "className", ")", ")", "toggleSideBySide", "(", "editor", ")", ";", "}" ]
Toggle full screen of the editor.
[ "Toggle", "full", "screen", "of", "the", "editor", "." ]
76f1dad98625d778656fa5087313dab3f3368f8d
https://github.com/Inscryb/inscryb-markdown-editor/blob/76f1dad98625d778656fa5087313dab3f3368f8d/src/js/inscrybmde.js#L206-L247
22,304
Inscryb/inscryb-markdown-editor
src/js/inscrybmde.js
toggleSideBySide
function toggleSideBySide(editor) { var cm = editor.codemirror; var wrapper = cm.getWrapperElement(); var preview = wrapper.nextSibling; var toolbarButton = editor.toolbarElements['side-by-side']; var useSideBySideListener = false; if (/editor-preview-active-side/.test(preview.className)) { preview.className = preview.className.replace( /\s*editor-preview-active-side\s*/g, '' ); toolbarButton.className = toolbarButton.className.replace(/\s*active\s*/g, ''); wrapper.className = wrapper.className.replace(/\s*CodeMirror-sided\s*/g, ' '); } else { // When the preview button is clicked for the first time, // give some time for the transition from editor.css to fire and the view to slide from right to left, // instead of just appearing. setTimeout(function () { if (!cm.getOption('fullScreen')) toggleFullScreen(editor); preview.className += ' editor-preview-active-side'; }, 1); toolbarButton.className += ' active'; wrapper.className += ' CodeMirror-sided'; useSideBySideListener = true; } // Hide normal preview if active var previewNormal = wrapper.lastChild; if (/editor-preview-active/.test(previewNormal.className)) { previewNormal.className = previewNormal.className.replace( /\s*editor-preview-active\s*/g, '' ); var toolbar = editor.toolbarElements.preview; var toolbar_div = wrapper.previousSibling; toolbar.className = toolbar.className.replace(/\s*active\s*/g, ''); toolbar_div.className = toolbar_div.className.replace(/\s*disabled-for-preview*/g, ''); } var sideBySideRenderingFunction = function () { preview.innerHTML = editor.options.previewRender(editor.value(), preview); }; if (!cm.sideBySideRenderingFunction) { cm.sideBySideRenderingFunction = sideBySideRenderingFunction; } if (useSideBySideListener) { preview.innerHTML = editor.options.previewRender(editor.value(), preview); cm.on('update', cm.sideBySideRenderingFunction); } else { cm.off('update', cm.sideBySideRenderingFunction); } // Refresh to fix selection being off (#309) cm.refresh(); }
javascript
function toggleSideBySide(editor) { var cm = editor.codemirror; var wrapper = cm.getWrapperElement(); var preview = wrapper.nextSibling; var toolbarButton = editor.toolbarElements['side-by-side']; var useSideBySideListener = false; if (/editor-preview-active-side/.test(preview.className)) { preview.className = preview.className.replace( /\s*editor-preview-active-side\s*/g, '' ); toolbarButton.className = toolbarButton.className.replace(/\s*active\s*/g, ''); wrapper.className = wrapper.className.replace(/\s*CodeMirror-sided\s*/g, ' '); } else { // When the preview button is clicked for the first time, // give some time for the transition from editor.css to fire and the view to slide from right to left, // instead of just appearing. setTimeout(function () { if (!cm.getOption('fullScreen')) toggleFullScreen(editor); preview.className += ' editor-preview-active-side'; }, 1); toolbarButton.className += ' active'; wrapper.className += ' CodeMirror-sided'; useSideBySideListener = true; } // Hide normal preview if active var previewNormal = wrapper.lastChild; if (/editor-preview-active/.test(previewNormal.className)) { previewNormal.className = previewNormal.className.replace( /\s*editor-preview-active\s*/g, '' ); var toolbar = editor.toolbarElements.preview; var toolbar_div = wrapper.previousSibling; toolbar.className = toolbar.className.replace(/\s*active\s*/g, ''); toolbar_div.className = toolbar_div.className.replace(/\s*disabled-for-preview*/g, ''); } var sideBySideRenderingFunction = function () { preview.innerHTML = editor.options.previewRender(editor.value(), preview); }; if (!cm.sideBySideRenderingFunction) { cm.sideBySideRenderingFunction = sideBySideRenderingFunction; } if (useSideBySideListener) { preview.innerHTML = editor.options.previewRender(editor.value(), preview); cm.on('update', cm.sideBySideRenderingFunction); } else { cm.off('update', cm.sideBySideRenderingFunction); } // Refresh to fix selection being off (#309) cm.refresh(); }
[ "function", "toggleSideBySide", "(", "editor", ")", "{", "var", "cm", "=", "editor", ".", "codemirror", ";", "var", "wrapper", "=", "cm", ".", "getWrapperElement", "(", ")", ";", "var", "preview", "=", "wrapper", ".", "nextSibling", ";", "var", "toolbarButton", "=", "editor", ".", "toolbarElements", "[", "'side-by-side'", "]", ";", "var", "useSideBySideListener", "=", "false", ";", "if", "(", "/", "editor-preview-active-side", "/", ".", "test", "(", "preview", ".", "className", ")", ")", "{", "preview", ".", "className", "=", "preview", ".", "className", ".", "replace", "(", "/", "\\s*editor-preview-active-side\\s*", "/", "g", ",", "''", ")", ";", "toolbarButton", ".", "className", "=", "toolbarButton", ".", "className", ".", "replace", "(", "/", "\\s*active\\s*", "/", "g", ",", "''", ")", ";", "wrapper", ".", "className", "=", "wrapper", ".", "className", ".", "replace", "(", "/", "\\s*CodeMirror-sided\\s*", "/", "g", ",", "' '", ")", ";", "}", "else", "{", "// When the preview button is clicked for the first time,", "// give some time for the transition from editor.css to fire and the view to slide from right to left,", "// instead of just appearing.", "setTimeout", "(", "function", "(", ")", "{", "if", "(", "!", "cm", ".", "getOption", "(", "'fullScreen'", ")", ")", "toggleFullScreen", "(", "editor", ")", ";", "preview", ".", "className", "+=", "' editor-preview-active-side'", ";", "}", ",", "1", ")", ";", "toolbarButton", ".", "className", "+=", "' active'", ";", "wrapper", ".", "className", "+=", "' CodeMirror-sided'", ";", "useSideBySideListener", "=", "true", ";", "}", "// Hide normal preview if active", "var", "previewNormal", "=", "wrapper", ".", "lastChild", ";", "if", "(", "/", "editor-preview-active", "/", ".", "test", "(", "previewNormal", ".", "className", ")", ")", "{", "previewNormal", ".", "className", "=", "previewNormal", ".", "className", ".", "replace", "(", "/", "\\s*editor-preview-active\\s*", "/", "g", ",", "''", ")", ";", "var", "toolbar", "=", "editor", ".", "toolbarElements", ".", "preview", ";", "var", "toolbar_div", "=", "wrapper", ".", "previousSibling", ";", "toolbar", ".", "className", "=", "toolbar", ".", "className", ".", "replace", "(", "/", "\\s*active\\s*", "/", "g", ",", "''", ")", ";", "toolbar_div", ".", "className", "=", "toolbar_div", ".", "className", ".", "replace", "(", "/", "\\s*disabled-for-preview*", "/", "g", ",", "''", ")", ";", "}", "var", "sideBySideRenderingFunction", "=", "function", "(", ")", "{", "preview", ".", "innerHTML", "=", "editor", ".", "options", ".", "previewRender", "(", "editor", ".", "value", "(", ")", ",", "preview", ")", ";", "}", ";", "if", "(", "!", "cm", ".", "sideBySideRenderingFunction", ")", "{", "cm", ".", "sideBySideRenderingFunction", "=", "sideBySideRenderingFunction", ";", "}", "if", "(", "useSideBySideListener", ")", "{", "preview", ".", "innerHTML", "=", "editor", ".", "options", ".", "previewRender", "(", "editor", ".", "value", "(", ")", ",", "preview", ")", ";", "cm", ".", "on", "(", "'update'", ",", "cm", ".", "sideBySideRenderingFunction", ")", ";", "}", "else", "{", "cm", ".", "off", "(", "'update'", ",", "cm", ".", "sideBySideRenderingFunction", ")", ";", "}", "// Refresh to fix selection being off (#309)", "cm", ".", "refresh", "(", ")", ";", "}" ]
Toggle side by side preview
[ "Toggle", "side", "by", "side", "preview" ]
76f1dad98625d778656fa5087313dab3f3368f8d
https://github.com/Inscryb/inscryb-markdown-editor/blob/76f1dad98625d778656fa5087313dab3f3368f8d/src/js/inscrybmde.js#L711-L766
22,305
thedillonb/http-shutdown
index.js
addShutdown
function addShutdown(server) { var connections = {}; var isShuttingDown = false; var connectionCounter = 0; function destroy(socket, force) { if (force || (socket._isIdle && isShuttingDown)) { socket.destroy(); delete connections[socket._connectionId]; } }; function onConnection(socket) { var id = connectionCounter++; socket._isIdle = true; socket._connectionId = id; connections[id] = socket; socket.on('close', function() { delete connections[id]; }); }; server.on('request', function(req, res) { req.socket._isIdle = false; res.on('finish', function() { req.socket._isIdle = true; destroy(req.socket); }); }); server.on('connection', onConnection); server.on('secureConnection', onConnection); function shutdown(force, cb) { isShuttingDown = true; server.close(function(err) { if (cb) { process.nextTick(function() { cb(err); }); } }); Object.keys(connections).forEach(function(key) { destroy(connections[key], force); }); }; server.shutdown = function(cb) { shutdown(false, cb); }; server.forceShutdown = function(cb) { shutdown(true, cb); }; return server; }
javascript
function addShutdown(server) { var connections = {}; var isShuttingDown = false; var connectionCounter = 0; function destroy(socket, force) { if (force || (socket._isIdle && isShuttingDown)) { socket.destroy(); delete connections[socket._connectionId]; } }; function onConnection(socket) { var id = connectionCounter++; socket._isIdle = true; socket._connectionId = id; connections[id] = socket; socket.on('close', function() { delete connections[id]; }); }; server.on('request', function(req, res) { req.socket._isIdle = false; res.on('finish', function() { req.socket._isIdle = true; destroy(req.socket); }); }); server.on('connection', onConnection); server.on('secureConnection', onConnection); function shutdown(force, cb) { isShuttingDown = true; server.close(function(err) { if (cb) { process.nextTick(function() { cb(err); }); } }); Object.keys(connections).forEach(function(key) { destroy(connections[key], force); }); }; server.shutdown = function(cb) { shutdown(false, cb); }; server.forceShutdown = function(cb) { shutdown(true, cb); }; return server; }
[ "function", "addShutdown", "(", "server", ")", "{", "var", "connections", "=", "{", "}", ";", "var", "isShuttingDown", "=", "false", ";", "var", "connectionCounter", "=", "0", ";", "function", "destroy", "(", "socket", ",", "force", ")", "{", "if", "(", "force", "||", "(", "socket", ".", "_isIdle", "&&", "isShuttingDown", ")", ")", "{", "socket", ".", "destroy", "(", ")", ";", "delete", "connections", "[", "socket", ".", "_connectionId", "]", ";", "}", "}", ";", "function", "onConnection", "(", "socket", ")", "{", "var", "id", "=", "connectionCounter", "++", ";", "socket", ".", "_isIdle", "=", "true", ";", "socket", ".", "_connectionId", "=", "id", ";", "connections", "[", "id", "]", "=", "socket", ";", "socket", ".", "on", "(", "'close'", ",", "function", "(", ")", "{", "delete", "connections", "[", "id", "]", ";", "}", ")", ";", "}", ";", "server", ".", "on", "(", "'request'", ",", "function", "(", "req", ",", "res", ")", "{", "req", ".", "socket", ".", "_isIdle", "=", "false", ";", "res", ".", "on", "(", "'finish'", ",", "function", "(", ")", "{", "req", ".", "socket", ".", "_isIdle", "=", "true", ";", "destroy", "(", "req", ".", "socket", ")", ";", "}", ")", ";", "}", ")", ";", "server", ".", "on", "(", "'connection'", ",", "onConnection", ")", ";", "server", ".", "on", "(", "'secureConnection'", ",", "onConnection", ")", ";", "function", "shutdown", "(", "force", ",", "cb", ")", "{", "isShuttingDown", "=", "true", ";", "server", ".", "close", "(", "function", "(", "err", ")", "{", "if", "(", "cb", ")", "{", "process", ".", "nextTick", "(", "function", "(", ")", "{", "cb", "(", "err", ")", ";", "}", ")", ";", "}", "}", ")", ";", "Object", ".", "keys", "(", "connections", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "destroy", "(", "connections", "[", "key", "]", ",", "force", ")", ";", "}", ")", ";", "}", ";", "server", ".", "shutdown", "=", "function", "(", "cb", ")", "{", "shutdown", "(", "false", ",", "cb", ")", ";", "}", ";", "server", ".", "forceShutdown", "=", "function", "(", "cb", ")", "{", "shutdown", "(", "true", ",", "cb", ")", ";", "}", ";", "return", "server", ";", "}" ]
Adds shutdown functionaility to the `http.Server` object @param {http.Server} server The server to add shutdown functionaility to
[ "Adds", "shutdown", "functionaility", "to", "the", "http", ".", "Server", "object" ]
137da38b62d16a29abbfafe99b3a167cb0c192da
https://github.com/thedillonb/http-shutdown/blob/137da38b62d16a29abbfafe99b3a167cb0c192da/index.js#L14-L71
22,306
daviddias/webrtc-explorer
src/sig-server/routes-ws/index.js
join
function join (options) { if (options.peerId.length !== 12) { return this.emit('we-ready', new Error('Unvalid peerId length, must be 48 bits, received: ' + options.peerId).toString()) } if (peerTable[options.peerId]) { return this.emit('we-ready', new Error('peerId already exists').toString()) } peerTable[options.peerId] = { socket: this, notify: typeof options.notify === 'boolean' && options.notify === true, fingers: options.fingers || { '0': { ideal: idealFinger(new Id(options.peerId), '0').toHex(), current: undefined }} } log('peer joined: ' + options.peerId) this.emit('we-ready') if (Object.keys(peerTable).length === 1) { return log('This was the first peer join, do nothing') } notify() if (peerTable[options.peerId].fingers['0'].current === undefined) { if (!peerTable[options.peerId].notify) { return } updateFinger(options.peerId, '0') } // notify if to other peers if this new Peer is a best finger for them function notify () { const newId = options.peerId const peerIds = Object.keys(peerTable) // check for all the peers // if same id skip // if notify === false skip // check the first finger that matches the criteria for ideal or next to ideal peerIds.forEach((peerId) => { if (newId === peerId) { return // skip ourselves } if (!peerTable[peerId].notify) { return // skip if it doesn't want to be notified of available peers } // if it had none, notify to get a successor if (peerTable[peerId].fingers['0'].current === undefined) { peerTable[peerId].fingers['0'].current = newId peerTable[peerId].socket.emit('we-update-finger', { row: '0', id: newId }) return } const rows = Object.keys(peerTable[peerId].fingers) // find the first row that could use this finger rows.some((row) => { const finger = peerTable[peerId].fingers[row] const bestCandidate = fingerBestFit( new Id(peerId), new Id(finger.ideal), new Id(finger.current), new Id(newId)) if (bestCandidate) { peerTable[peerId].fingers[row].current = newId peerTable[peerId].socket.emit('we-update-finger', { row: row, id: newId }) return true } }) }) } }
javascript
function join (options) { if (options.peerId.length !== 12) { return this.emit('we-ready', new Error('Unvalid peerId length, must be 48 bits, received: ' + options.peerId).toString()) } if (peerTable[options.peerId]) { return this.emit('we-ready', new Error('peerId already exists').toString()) } peerTable[options.peerId] = { socket: this, notify: typeof options.notify === 'boolean' && options.notify === true, fingers: options.fingers || { '0': { ideal: idealFinger(new Id(options.peerId), '0').toHex(), current: undefined }} } log('peer joined: ' + options.peerId) this.emit('we-ready') if (Object.keys(peerTable).length === 1) { return log('This was the first peer join, do nothing') } notify() if (peerTable[options.peerId].fingers['0'].current === undefined) { if (!peerTable[options.peerId].notify) { return } updateFinger(options.peerId, '0') } // notify if to other peers if this new Peer is a best finger for them function notify () { const newId = options.peerId const peerIds = Object.keys(peerTable) // check for all the peers // if same id skip // if notify === false skip // check the first finger that matches the criteria for ideal or next to ideal peerIds.forEach((peerId) => { if (newId === peerId) { return // skip ourselves } if (!peerTable[peerId].notify) { return // skip if it doesn't want to be notified of available peers } // if it had none, notify to get a successor if (peerTable[peerId].fingers['0'].current === undefined) { peerTable[peerId].fingers['0'].current = newId peerTable[peerId].socket.emit('we-update-finger', { row: '0', id: newId }) return } const rows = Object.keys(peerTable[peerId].fingers) // find the first row that could use this finger rows.some((row) => { const finger = peerTable[peerId].fingers[row] const bestCandidate = fingerBestFit( new Id(peerId), new Id(finger.ideal), new Id(finger.current), new Id(newId)) if (bestCandidate) { peerTable[peerId].fingers[row].current = newId peerTable[peerId].socket.emit('we-update-finger', { row: row, id: newId }) return true } }) }) } }
[ "function", "join", "(", "options", ")", "{", "if", "(", "options", ".", "peerId", ".", "length", "!==", "12", ")", "{", "return", "this", ".", "emit", "(", "'we-ready'", ",", "new", "Error", "(", "'Unvalid peerId length, must be 48 bits, received: '", "+", "options", ".", "peerId", ")", ".", "toString", "(", ")", ")", "}", "if", "(", "peerTable", "[", "options", ".", "peerId", "]", ")", "{", "return", "this", ".", "emit", "(", "'we-ready'", ",", "new", "Error", "(", "'peerId already exists'", ")", ".", "toString", "(", ")", ")", "}", "peerTable", "[", "options", ".", "peerId", "]", "=", "{", "socket", ":", "this", ",", "notify", ":", "typeof", "options", ".", "notify", "===", "'boolean'", "&&", "options", ".", "notify", "===", "true", ",", "fingers", ":", "options", ".", "fingers", "||", "{", "'0'", ":", "{", "ideal", ":", "idealFinger", "(", "new", "Id", "(", "options", ".", "peerId", ")", ",", "'0'", ")", ".", "toHex", "(", ")", ",", "current", ":", "undefined", "}", "}", "}", "log", "(", "'peer joined: '", "+", "options", ".", "peerId", ")", "this", ".", "emit", "(", "'we-ready'", ")", "if", "(", "Object", ".", "keys", "(", "peerTable", ")", ".", "length", "===", "1", ")", "{", "return", "log", "(", "'This was the first peer join, do nothing'", ")", "}", "notify", "(", ")", "if", "(", "peerTable", "[", "options", ".", "peerId", "]", ".", "fingers", "[", "'0'", "]", ".", "current", "===", "undefined", ")", "{", "if", "(", "!", "peerTable", "[", "options", ".", "peerId", "]", ".", "notify", ")", "{", "return", "}", "updateFinger", "(", "options", ".", "peerId", ",", "'0'", ")", "}", "// notify if to other peers if this new Peer is a best finger for them", "function", "notify", "(", ")", "{", "const", "newId", "=", "options", ".", "peerId", "const", "peerIds", "=", "Object", ".", "keys", "(", "peerTable", ")", "// check for all the peers", "// if same id skip", "// if notify === false skip", "// check the first finger that matches the criteria for ideal or next to ideal", "peerIds", ".", "forEach", "(", "(", "peerId", ")", "=>", "{", "if", "(", "newId", "===", "peerId", ")", "{", "return", "// skip ourselves", "}", "if", "(", "!", "peerTable", "[", "peerId", "]", ".", "notify", ")", "{", "return", "// skip if it doesn't want to be notified of available peers", "}", "// if it had none, notify to get a successor", "if", "(", "peerTable", "[", "peerId", "]", ".", "fingers", "[", "'0'", "]", ".", "current", "===", "undefined", ")", "{", "peerTable", "[", "peerId", "]", ".", "fingers", "[", "'0'", "]", ".", "current", "=", "newId", "peerTable", "[", "peerId", "]", ".", "socket", ".", "emit", "(", "'we-update-finger'", ",", "{", "row", ":", "'0'", ",", "id", ":", "newId", "}", ")", "return", "}", "const", "rows", "=", "Object", ".", "keys", "(", "peerTable", "[", "peerId", "]", ".", "fingers", ")", "// find the first row that could use this finger", "rows", ".", "some", "(", "(", "row", ")", "=>", "{", "const", "finger", "=", "peerTable", "[", "peerId", "]", ".", "fingers", "[", "row", "]", "const", "bestCandidate", "=", "fingerBestFit", "(", "new", "Id", "(", "peerId", ")", ",", "new", "Id", "(", "finger", ".", "ideal", ")", ",", "new", "Id", "(", "finger", ".", "current", ")", ",", "new", "Id", "(", "newId", ")", ")", "if", "(", "bestCandidate", ")", "{", "peerTable", "[", "peerId", "]", ".", "fingers", "[", "row", "]", ".", "current", "=", "newId", "peerTable", "[", "peerId", "]", ".", "socket", ".", "emit", "(", "'we-update-finger'", ",", "{", "row", ":", "row", ",", "id", ":", "newId", "}", ")", "return", "true", "}", "}", ")", "}", ")", "}", "}" ]
join this signaling server network
[ "join", "this", "signaling", "server", "network" ]
33ea3fd72712d0f356c7f73b5f8828490aa5417d
https://github.com/daviddias/webrtc-explorer/blob/33ea3fd72712d0f356c7f73b5f8828490aa5417d/src/sig-server/routes-ws/index.js#L25-L103
22,307
daviddias/webrtc-explorer
src/sig-server/routes-ws/index.js
notify
function notify () { const newId = options.peerId const peerIds = Object.keys(peerTable) // check for all the peers // if same id skip // if notify === false skip // check the first finger that matches the criteria for ideal or next to ideal peerIds.forEach((peerId) => { if (newId === peerId) { return // skip ourselves } if (!peerTable[peerId].notify) { return // skip if it doesn't want to be notified of available peers } // if it had none, notify to get a successor if (peerTable[peerId].fingers['0'].current === undefined) { peerTable[peerId].fingers['0'].current = newId peerTable[peerId].socket.emit('we-update-finger', { row: '0', id: newId }) return } const rows = Object.keys(peerTable[peerId].fingers) // find the first row that could use this finger rows.some((row) => { const finger = peerTable[peerId].fingers[row] const bestCandidate = fingerBestFit( new Id(peerId), new Id(finger.ideal), new Id(finger.current), new Id(newId)) if (bestCandidate) { peerTable[peerId].fingers[row].current = newId peerTable[peerId].socket.emit('we-update-finger', { row: row, id: newId }) return true } }) }) }
javascript
function notify () { const newId = options.peerId const peerIds = Object.keys(peerTable) // check for all the peers // if same id skip // if notify === false skip // check the first finger that matches the criteria for ideal or next to ideal peerIds.forEach((peerId) => { if (newId === peerId) { return // skip ourselves } if (!peerTable[peerId].notify) { return // skip if it doesn't want to be notified of available peers } // if it had none, notify to get a successor if (peerTable[peerId].fingers['0'].current === undefined) { peerTable[peerId].fingers['0'].current = newId peerTable[peerId].socket.emit('we-update-finger', { row: '0', id: newId }) return } const rows = Object.keys(peerTable[peerId].fingers) // find the first row that could use this finger rows.some((row) => { const finger = peerTable[peerId].fingers[row] const bestCandidate = fingerBestFit( new Id(peerId), new Id(finger.ideal), new Id(finger.current), new Id(newId)) if (bestCandidate) { peerTable[peerId].fingers[row].current = newId peerTable[peerId].socket.emit('we-update-finger', { row: row, id: newId }) return true } }) }) }
[ "function", "notify", "(", ")", "{", "const", "newId", "=", "options", ".", "peerId", "const", "peerIds", "=", "Object", ".", "keys", "(", "peerTable", ")", "// check for all the peers", "// if same id skip", "// if notify === false skip", "// check the first finger that matches the criteria for ideal or next to ideal", "peerIds", ".", "forEach", "(", "(", "peerId", ")", "=>", "{", "if", "(", "newId", "===", "peerId", ")", "{", "return", "// skip ourselves", "}", "if", "(", "!", "peerTable", "[", "peerId", "]", ".", "notify", ")", "{", "return", "// skip if it doesn't want to be notified of available peers", "}", "// if it had none, notify to get a successor", "if", "(", "peerTable", "[", "peerId", "]", ".", "fingers", "[", "'0'", "]", ".", "current", "===", "undefined", ")", "{", "peerTable", "[", "peerId", "]", ".", "fingers", "[", "'0'", "]", ".", "current", "=", "newId", "peerTable", "[", "peerId", "]", ".", "socket", ".", "emit", "(", "'we-update-finger'", ",", "{", "row", ":", "'0'", ",", "id", ":", "newId", "}", ")", "return", "}", "const", "rows", "=", "Object", ".", "keys", "(", "peerTable", "[", "peerId", "]", ".", "fingers", ")", "// find the first row that could use this finger", "rows", ".", "some", "(", "(", "row", ")", "=>", "{", "const", "finger", "=", "peerTable", "[", "peerId", "]", ".", "fingers", "[", "row", "]", "const", "bestCandidate", "=", "fingerBestFit", "(", "new", "Id", "(", "peerId", ")", ",", "new", "Id", "(", "finger", ".", "ideal", ")", ",", "new", "Id", "(", "finger", ".", "current", ")", ",", "new", "Id", "(", "newId", ")", ")", "if", "(", "bestCandidate", ")", "{", "peerTable", "[", "peerId", "]", ".", "fingers", "[", "row", "]", ".", "current", "=", "newId", "peerTable", "[", "peerId", "]", ".", "socket", ".", "emit", "(", "'we-update-finger'", ",", "{", "row", ":", "row", ",", "id", ":", "newId", "}", ")", "return", "true", "}", "}", ")", "}", ")", "}" ]
notify if to other peers if this new Peer is a best finger for them
[ "notify", "if", "to", "other", "peers", "if", "this", "new", "Peer", "is", "a", "best", "finger", "for", "them" ]
33ea3fd72712d0f356c7f73b5f8828490aa5417d
https://github.com/daviddias/webrtc-explorer/blob/33ea3fd72712d0f356c7f73b5f8828490aa5417d/src/sig-server/routes-ws/index.js#L58-L102
22,308
daviddias/webrtc-explorer
src/sig-server/routes-ws/index.js
updateFinger
function updateFinger (peerId, row) { var availablePeers = Object.keys(peerTable) availablePeers.splice(availablePeers.indexOf(peerId), 1) // if row hasn't been checked before if (!peerTable[peerId].fingers[row]) { peerTable[peerId].fingers[row] = { ideal: idealFinger(new Id(peerId), row).toHex(), current: undefined } } var best = availablePeers.shift() availablePeers.forEach((otherId) => { const isFBT = fingerBestFit( new Id(peerId), new Id(peerTable[peerId].fingers[row].ideal), new Id(best), new Id(otherId)) if (isFBT) { best = otherId } }) if (best === peerTable[peerId].fingers[row].current) { return // nevermind then } peerTable[peerId].fingers[row].current = best peerTable[peerId].socket.emit('we-update-finger', { row: row, id: best }) }
javascript
function updateFinger (peerId, row) { var availablePeers = Object.keys(peerTable) availablePeers.splice(availablePeers.indexOf(peerId), 1) // if row hasn't been checked before if (!peerTable[peerId].fingers[row]) { peerTable[peerId].fingers[row] = { ideal: idealFinger(new Id(peerId), row).toHex(), current: undefined } } var best = availablePeers.shift() availablePeers.forEach((otherId) => { const isFBT = fingerBestFit( new Id(peerId), new Id(peerTable[peerId].fingers[row].ideal), new Id(best), new Id(otherId)) if (isFBT) { best = otherId } }) if (best === peerTable[peerId].fingers[row].current) { return // nevermind then } peerTable[peerId].fingers[row].current = best peerTable[peerId].socket.emit('we-update-finger', { row: row, id: best }) }
[ "function", "updateFinger", "(", "peerId", ",", "row", ")", "{", "var", "availablePeers", "=", "Object", ".", "keys", "(", "peerTable", ")", "availablePeers", ".", "splice", "(", "availablePeers", ".", "indexOf", "(", "peerId", ")", ",", "1", ")", "// if row hasn't been checked before", "if", "(", "!", "peerTable", "[", "peerId", "]", ".", "fingers", "[", "row", "]", ")", "{", "peerTable", "[", "peerId", "]", ".", "fingers", "[", "row", "]", "=", "{", "ideal", ":", "idealFinger", "(", "new", "Id", "(", "peerId", ")", ",", "row", ")", ".", "toHex", "(", ")", ",", "current", ":", "undefined", "}", "}", "var", "best", "=", "availablePeers", ".", "shift", "(", ")", "availablePeers", ".", "forEach", "(", "(", "otherId", ")", "=>", "{", "const", "isFBT", "=", "fingerBestFit", "(", "new", "Id", "(", "peerId", ")", ",", "new", "Id", "(", "peerTable", "[", "peerId", "]", ".", "fingers", "[", "row", "]", ".", "ideal", ")", ",", "new", "Id", "(", "best", ")", ",", "new", "Id", "(", "otherId", ")", ")", "if", "(", "isFBT", ")", "{", "best", "=", "otherId", "}", "}", ")", "if", "(", "best", "===", "peerTable", "[", "peerId", "]", ".", "fingers", "[", "row", "]", ".", "current", ")", "{", "return", "// nevermind then", "}", "peerTable", "[", "peerId", "]", ".", "fingers", "[", "row", "]", ".", "current", "=", "best", "peerTable", "[", "peerId", "]", ".", "socket", ".", "emit", "(", "'we-update-finger'", ",", "{", "row", ":", "row", ",", "id", ":", "best", "}", ")", "}" ]
finds the best new Finger for the peerId's row 'row')
[ "finds", "the", "best", "new", "Finger", "for", "the", "peerId", "s", "row", "row", ")" ]
33ea3fd72712d0f356c7f73b5f8828490aa5417d
https://github.com/daviddias/webrtc-explorer/blob/33ea3fd72712d0f356c7f73b5f8828490aa5417d/src/sig-server/routes-ws/index.js#L106-L137
22,309
daviddias/webrtc-explorer
src/sig-server/routes-ws/index.js
forward
function forward (offer) { if (offer.answer) { peerTable[offer.srcId].socket .emit('we-handshake', offer) return } peerTable[offer.dstId].socket .emit('we-handshake', offer) }
javascript
function forward (offer) { if (offer.answer) { peerTable[offer.srcId].socket .emit('we-handshake', offer) return } peerTable[offer.dstId].socket .emit('we-handshake', offer) }
[ "function", "forward", "(", "offer", ")", "{", "if", "(", "offer", ".", "answer", ")", "{", "peerTable", "[", "offer", ".", "srcId", "]", ".", "socket", ".", "emit", "(", "'we-handshake'", ",", "offer", ")", "return", "}", "peerTable", "[", "offer", ".", "dstId", "]", ".", "socket", ".", "emit", "(", "'we-handshake'", ",", "offer", ")", "}" ]
forward an WebRTC offer to another peer
[ "forward", "an", "WebRTC", "offer", "to", "another", "peer" ]
33ea3fd72712d0f356c7f73b5f8828490aa5417d
https://github.com/daviddias/webrtc-explorer/blob/33ea3fd72712d0f356c7f73b5f8828490aa5417d/src/sig-server/routes-ws/index.js#L149-L157
22,310
daviddias/webrtc-explorer
src/explorer/index.js
connect
function connect (url, callback) { io = SocketIO.connect(url) io.on('connect', callback) }
javascript
function connect (url, callback) { io = SocketIO.connect(url) io.on('connect', callback) }
[ "function", "connect", "(", "url", ",", "callback", ")", "{", "io", "=", "SocketIO", ".", "connect", "(", "url", ")", "io", ".", "on", "(", "'connect'", ",", "callback", ")", "}" ]
connect to the sig-server
[ "connect", "to", "the", "sig", "-", "server" ]
33ea3fd72712d0f356c7f73b5f8828490aa5417d
https://github.com/daviddias/webrtc-explorer/blob/33ea3fd72712d0f356c7f73b5f8828490aa5417d/src/explorer/index.js#L119-L122
22,311
daviddias/webrtc-explorer
src/explorer/index.js
join
function join (callback) { log('connected to sig-server') io.emit('ss-join', { peerId: config.peerId.toHex(), notify: true }) io.on('we-update-finger', fingerTable.updateFinger(io)) io.on('we-handshake', channel.accept(io)) io.once('we-ready', callback) }
javascript
function join (callback) { log('connected to sig-server') io.emit('ss-join', { peerId: config.peerId.toHex(), notify: true }) io.on('we-update-finger', fingerTable.updateFinger(io)) io.on('we-handshake', channel.accept(io)) io.once('we-ready', callback) }
[ "function", "join", "(", "callback", ")", "{", "log", "(", "'connected to sig-server'", ")", "io", ".", "emit", "(", "'ss-join'", ",", "{", "peerId", ":", "config", ".", "peerId", ".", "toHex", "(", ")", ",", "notify", ":", "true", "}", ")", "io", ".", "on", "(", "'we-update-finger'", ",", "fingerTable", ".", "updateFinger", "(", "io", ")", ")", "io", ".", "on", "(", "'we-handshake'", ",", "channel", ".", "accept", "(", "io", ")", ")", "io", ".", "once", "(", "'we-ready'", ",", "callback", ")", "}" ]
join the peerTable of the sig-server
[ "join", "the", "peerTable", "of", "the", "sig", "-", "server" ]
33ea3fd72712d0f356c7f73b5f8828490aa5417d
https://github.com/daviddias/webrtc-explorer/blob/33ea3fd72712d0f356c7f73b5f8828490aa5417d/src/explorer/index.js#L125-L135
22,312
zhaohaodang/vue-see
index.js
closest
function closest(el, fn) { return el && (fn(el) ? el : closest(el.parentNode, fn)); }
javascript
function closest(el, fn) { return el && (fn(el) ? el : closest(el.parentNode, fn)); }
[ "function", "closest", "(", "el", ",", "fn", ")", "{", "return", "el", "&&", "(", "fn", "(", "el", ")", "?", "el", ":", "closest", "(", "el", ".", "parentNode", ",", "fn", ")", ")", ";", "}" ]
find nearest parent element
[ "find", "nearest", "parent", "element" ]
8ba14d4c98024930cd80220daf3785be32c49781
https://github.com/zhaohaodang/vue-see/blob/8ba14d4c98024930cd80220daf3785be32c49781/index.js#L72-L74
22,313
bang88/typescript-react-intl
lib/index.js
main
function main(contents, options) { if (options === void 0) { options = { tagNames: [] }; } var sourceFile = ts.createSourceFile("file.ts", contents, ts.ScriptTarget.ES2015, /*setParentNodes */ false, ts.ScriptKind.TSX); var dm = findMethodCallsWithName(sourceFile, "defineMessages", extractMessagesForDefineMessages); // TODO formatMessage might not be the initializer for a VarDecl // eg console.log(formatMessage(...)) var fm = findMethodCallsWithName(sourceFile, "formatMessage", extractMessagesForFormatMessage); var results = []; var tagNames = ["FormattedMessage"].concat(options.tagNames); tagNames.forEach(function (tagName) { var elements = findJsxOpeningLikeElementsWithName(sourceFile, tagName); // convert JsxOpeningLikeElements to Message maps var jsxMessages = getElementsMessages(elements); results.push.apply(results, jsxMessages); }); return results.concat(dm).concat(fm); }
javascript
function main(contents, options) { if (options === void 0) { options = { tagNames: [] }; } var sourceFile = ts.createSourceFile("file.ts", contents, ts.ScriptTarget.ES2015, /*setParentNodes */ false, ts.ScriptKind.TSX); var dm = findMethodCallsWithName(sourceFile, "defineMessages", extractMessagesForDefineMessages); // TODO formatMessage might not be the initializer for a VarDecl // eg console.log(formatMessage(...)) var fm = findMethodCallsWithName(sourceFile, "formatMessage", extractMessagesForFormatMessage); var results = []; var tagNames = ["FormattedMessage"].concat(options.tagNames); tagNames.forEach(function (tagName) { var elements = findJsxOpeningLikeElementsWithName(sourceFile, tagName); // convert JsxOpeningLikeElements to Message maps var jsxMessages = getElementsMessages(elements); results.push.apply(results, jsxMessages); }); return results.concat(dm).concat(fm); }
[ "function", "main", "(", "contents", ",", "options", ")", "{", "if", "(", "options", "===", "void", "0", ")", "{", "options", "=", "{", "tagNames", ":", "[", "]", "}", ";", "}", "var", "sourceFile", "=", "ts", ".", "createSourceFile", "(", "\"file.ts\"", ",", "contents", ",", "ts", ".", "ScriptTarget", ".", "ES2015", ",", "/*setParentNodes */", "false", ",", "ts", ".", "ScriptKind", ".", "TSX", ")", ";", "var", "dm", "=", "findMethodCallsWithName", "(", "sourceFile", ",", "\"defineMessages\"", ",", "extractMessagesForDefineMessages", ")", ";", "// TODO formatMessage might not be the initializer for a VarDecl", "// eg console.log(formatMessage(...))", "var", "fm", "=", "findMethodCallsWithName", "(", "sourceFile", ",", "\"formatMessage\"", ",", "extractMessagesForFormatMessage", ")", ";", "var", "results", "=", "[", "]", ";", "var", "tagNames", "=", "[", "\"FormattedMessage\"", "]", ".", "concat", "(", "options", ".", "tagNames", ")", ";", "tagNames", ".", "forEach", "(", "function", "(", "tagName", ")", "{", "var", "elements", "=", "findJsxOpeningLikeElementsWithName", "(", "sourceFile", ",", "tagName", ")", ";", "// convert JsxOpeningLikeElements to Message maps", "var", "jsxMessages", "=", "getElementsMessages", "(", "elements", ")", ";", "results", ".", "push", ".", "apply", "(", "results", ",", "jsxMessages", ")", ";", "}", ")", ";", "return", "results", ".", "concat", "(", "dm", ")", ".", "concat", "(", "fm", ")", ";", "}" ]
Parse tsx files
[ "Parse", "tsx", "files" ]
751b3036e0b3b1925e254d228818ec1a39363297
https://github.com/bang88/typescript-react-intl/blob/751b3036e0b3b1925e254d228818ec1a39363297/lib/index.js#L120-L137
22,314
bang88/typescript-react-intl
lib/index.js
getElementsMessages
function getElementsMessages(elements) { return elements .map(function (element) { var msg = {}; if (element.attributes) { element.attributes.properties.forEach(function (attr) { if (!ts.isJsxAttribute(attr) || !attr.initializer) { // Either JsxSpreadAttribute, or JsxAttribute without initializer. return; } var key = attr.name.text; var init = attr.initializer; var text; if (ts.isStringLiteral(init)) { text = init.text; } else if (ts.isJsxExpression(init)) { if (init.expression && (ts.isStringLiteral(init.expression) || ts.isNoSubstitutionTemplateLiteral(init.expression))) { text = init.expression.text; } else { // Either the JsxExpression has no expression (?) // or a non-StringLiteral expression. return; } } else { // Should be a StringLiteral or JsxExpression, but it's not! return; } copyIfMessageKey(msg, key, text); }); } return isValidMessage(msg) ? msg : null; }) .filter(notNull); }
javascript
function getElementsMessages(elements) { return elements .map(function (element) { var msg = {}; if (element.attributes) { element.attributes.properties.forEach(function (attr) { if (!ts.isJsxAttribute(attr) || !attr.initializer) { // Either JsxSpreadAttribute, or JsxAttribute without initializer. return; } var key = attr.name.text; var init = attr.initializer; var text; if (ts.isStringLiteral(init)) { text = init.text; } else if (ts.isJsxExpression(init)) { if (init.expression && (ts.isStringLiteral(init.expression) || ts.isNoSubstitutionTemplateLiteral(init.expression))) { text = init.expression.text; } else { // Either the JsxExpression has no expression (?) // or a non-StringLiteral expression. return; } } else { // Should be a StringLiteral or JsxExpression, but it's not! return; } copyIfMessageKey(msg, key, text); }); } return isValidMessage(msg) ? msg : null; }) .filter(notNull); }
[ "function", "getElementsMessages", "(", "elements", ")", "{", "return", "elements", ".", "map", "(", "function", "(", "element", ")", "{", "var", "msg", "=", "{", "}", ";", "if", "(", "element", ".", "attributes", ")", "{", "element", ".", "attributes", ".", "properties", ".", "forEach", "(", "function", "(", "attr", ")", "{", "if", "(", "!", "ts", ".", "isJsxAttribute", "(", "attr", ")", "||", "!", "attr", ".", "initializer", ")", "{", "// Either JsxSpreadAttribute, or JsxAttribute without initializer.", "return", ";", "}", "var", "key", "=", "attr", ".", "name", ".", "text", ";", "var", "init", "=", "attr", ".", "initializer", ";", "var", "text", ";", "if", "(", "ts", ".", "isStringLiteral", "(", "init", ")", ")", "{", "text", "=", "init", ".", "text", ";", "}", "else", "if", "(", "ts", ".", "isJsxExpression", "(", "init", ")", ")", "{", "if", "(", "init", ".", "expression", "&&", "(", "ts", ".", "isStringLiteral", "(", "init", ".", "expression", ")", "||", "ts", ".", "isNoSubstitutionTemplateLiteral", "(", "init", ".", "expression", ")", ")", ")", "{", "text", "=", "init", ".", "expression", ".", "text", ";", "}", "else", "{", "// Either the JsxExpression has no expression (?)", "// or a non-StringLiteral expression.", "return", ";", "}", "}", "else", "{", "// Should be a StringLiteral or JsxExpression, but it's not!", "return", ";", "}", "copyIfMessageKey", "(", "msg", ",", "key", ",", "text", ")", ";", "}", ")", ";", "}", "return", "isValidMessage", "(", "msg", ")", "?", "msg", ":", "null", ";", "}", ")", ".", "filter", "(", "notNull", ")", ";", "}" ]
convert JsxOpeningLikeElements to Message maps @param elements
[ "convert", "JsxOpeningLikeElements", "to", "Message", "maps" ]
751b3036e0b3b1925e254d228818ec1a39363297
https://github.com/bang88/typescript-react-intl/blob/751b3036e0b3b1925e254d228818ec1a39363297/lib/index.js#L142-L180
22,315
yahoohung/loopback-graphql-server
src/schema/query/viewer.js
getRelatedModelFields
function getRelatedModelFields(User) { const fields = {}; _.forEach(User.relations, (relation) => { const model = relation.modelTo; fields[_.lowerFirst(relation.name)] = { args: Object.assign({ where: { type: getType('JSON') }, order: { type: getType('JSON') }, }, connectionArgs), type: getConnection(model.modelName), resolve: (obj, args, context) => { if (!context.req.accessToken) return null; return findUserFromAccessToken(context.req.accessToken, User) .then(user => connectionFromPromisedArray(findAllRelated(User, user, relation.name, args, context), args, model)); } }; }); return fields; }
javascript
function getRelatedModelFields(User) { const fields = {}; _.forEach(User.relations, (relation) => { const model = relation.modelTo; fields[_.lowerFirst(relation.name)] = { args: Object.assign({ where: { type: getType('JSON') }, order: { type: getType('JSON') }, }, connectionArgs), type: getConnection(model.modelName), resolve: (obj, args, context) => { if (!context.req.accessToken) return null; return findUserFromAccessToken(context.req.accessToken, User) .then(user => connectionFromPromisedArray(findAllRelated(User, user, relation.name, args, context), args, model)); } }; }); return fields; }
[ "function", "getRelatedModelFields", "(", "User", ")", "{", "const", "fields", "=", "{", "}", ";", "_", ".", "forEach", "(", "User", ".", "relations", ",", "(", "relation", ")", "=>", "{", "const", "model", "=", "relation", ".", "modelTo", ";", "fields", "[", "_", ".", "lowerFirst", "(", "relation", ".", "name", ")", "]", "=", "{", "args", ":", "Object", ".", "assign", "(", "{", "where", ":", "{", "type", ":", "getType", "(", "'JSON'", ")", "}", ",", "order", ":", "{", "type", ":", "getType", "(", "'JSON'", ")", "}", ",", "}", ",", "connectionArgs", ")", ",", "type", ":", "getConnection", "(", "model", ".", "modelName", ")", ",", "resolve", ":", "(", "obj", ",", "args", ",", "context", ")", "=>", "{", "if", "(", "!", "context", ".", "req", ".", "accessToken", ")", "return", "null", ";", "return", "findUserFromAccessToken", "(", "context", ".", "req", ".", "accessToken", ",", "User", ")", ".", "then", "(", "user", "=>", "connectionFromPromisedArray", "(", "findAllRelated", "(", "User", ",", "user", ",", "relation", ".", "name", ",", "args", ",", "context", ")", ",", "args", ",", "model", ")", ")", ";", "}", "}", ";", "}", ")", ";", "return", "fields", ";", "}" ]
Adds fields of all relationed models @param {*} models
[ "Adds", "fields", "of", "all", "relationed", "models" ]
7a624b1480f4bde10090ba744ba7a0108e393be7
https://github.com/yahoohung/loopback-graphql-server/blob/7a624b1480f4bde10090ba744ba7a0108e393be7/src/schema/query/viewer.js#L18-L46
22,316
yahoohung/loopback-graphql-server
src/schema/query/viewer.js
findUserFromAccessToken
function findUserFromAccessToken(accessToken, UserModel) { if (!accessToken) return null; return UserModel.findById(accessToken.userId).then((user) => { if (!user) return Promise.reject('No user with this access token was found.'); return Promise.resolve(user); }); }
javascript
function findUserFromAccessToken(accessToken, UserModel) { if (!accessToken) return null; return UserModel.findById(accessToken.userId).then((user) => { if (!user) return Promise.reject('No user with this access token was found.'); return Promise.resolve(user); }); }
[ "function", "findUserFromAccessToken", "(", "accessToken", ",", "UserModel", ")", "{", "if", "(", "!", "accessToken", ")", "return", "null", ";", "return", "UserModel", ".", "findById", "(", "accessToken", ".", "userId", ")", ".", "then", "(", "(", "user", ")", "=>", "{", "if", "(", "!", "user", ")", "return", "Promise", ".", "reject", "(", "'No user with this access token was found.'", ")", ";", "return", "Promise", ".", "resolve", "(", "user", ")", ";", "}", ")", ";", "}" ]
Finds a user from an access token @param {*} accessToken @param {*} UserModel
[ "Finds", "a", "user", "from", "an", "access", "token" ]
7a624b1480f4bde10090ba744ba7a0108e393be7
https://github.com/yahoohung/loopback-graphql-server/blob/7a624b1480f4bde10090ba744ba7a0108e393be7/src/schema/query/viewer.js#L53-L61
22,317
yahoohung/loopback-graphql-server
src/schema/query/viewer.js
getMeField
function getMeField(User) { return { me: { type: getType(User.modelName), resolve: (obj, args, { app, req }) => { if (!req.accessToken) return null; return findUserFromAccessToken(req.accessToken, User); } } }; }
javascript
function getMeField(User) { return { me: { type: getType(User.modelName), resolve: (obj, args, { app, req }) => { if (!req.accessToken) return null; return findUserFromAccessToken(req.accessToken, User); } } }; }
[ "function", "getMeField", "(", "User", ")", "{", "return", "{", "me", ":", "{", "type", ":", "getType", "(", "User", ".", "modelName", ")", ",", "resolve", ":", "(", "obj", ",", "args", ",", "{", "app", ",", "req", "}", ")", "=>", "{", "if", "(", "!", "req", ".", "accessToken", ")", "return", "null", ";", "return", "findUserFromAccessToken", "(", "req", ".", "accessToken", ",", "User", ")", ";", "}", "}", "}", ";", "}" ]
Create a me field for a given user model @param {*} User
[ "Create", "a", "me", "field", "for", "a", "given", "user", "model" ]
7a624b1480f4bde10090ba744ba7a0108e393be7
https://github.com/yahoohung/loopback-graphql-server/blob/7a624b1480f4bde10090ba744ba7a0108e393be7/src/schema/query/viewer.js#L67-L80
22,318
yahoohung/loopback-graphql-server
src/schema/ACLs/index.js
checkAccess
function checkAccess({ accessToken, id, model, method, options, ctx }) { return new Promise((resolve, reject) => { // ignore checking if does not enable auth if (model.app.isAuthEnabled) { if (!model.app.models.ACL) { console.log('ACL has not been setup, skipping access check.') resolve(true); } else { model.checkAccess(accessToken, id, method, ctx, ((err, allowed) => { if (err) reject(err); else if (allowed) resolve(allowed); else reject(`ACCESS_DENIED`); })); } } else { resolve(true); } }) }
javascript
function checkAccess({ accessToken, id, model, method, options, ctx }) { return new Promise((resolve, reject) => { // ignore checking if does not enable auth if (model.app.isAuthEnabled) { if (!model.app.models.ACL) { console.log('ACL has not been setup, skipping access check.') resolve(true); } else { model.checkAccess(accessToken, id, method, ctx, ((err, allowed) => { if (err) reject(err); else if (allowed) resolve(allowed); else reject(`ACCESS_DENIED`); })); } } else { resolve(true); } }) }
[ "function", "checkAccess", "(", "{", "accessToken", ",", "id", ",", "model", ",", "method", ",", "options", ",", "ctx", "}", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "// ignore checking if does not enable auth", "if", "(", "model", ".", "app", ".", "isAuthEnabled", ")", "{", "if", "(", "!", "model", ".", "app", ".", "models", ".", "ACL", ")", "{", "console", ".", "log", "(", "'ACL has not been setup, skipping access check.'", ")", "resolve", "(", "true", ")", ";", "}", "else", "{", "model", ".", "checkAccess", "(", "accessToken", ",", "id", ",", "method", ",", "ctx", ",", "(", "(", "err", ",", "allowed", ")", "=>", "{", "if", "(", "err", ")", "reject", "(", "err", ")", ";", "else", "if", "(", "allowed", ")", "resolve", "(", "allowed", ")", ";", "else", "reject", "(", "`", "`", ")", ";", "}", ")", ")", ";", "}", "}", "else", "{", "resolve", "(", "true", ")", ";", "}", "}", ")", "}" ]
calls the check the ACLS on the model and return the access permission on method.
[ "calls", "the", "check", "the", "ACLS", "on", "the", "model", "and", "return", "the", "access", "permission", "on", "method", "." ]
7a624b1480f4bde10090ba744ba7a0108e393be7
https://github.com/yahoohung/loopback-graphql-server/blob/7a624b1480f4bde10090ba744ba7a0108e393be7/src/schema/ACLs/index.js#L2-L26
22,319
yahoohung/loopback-graphql-server
src/schema/utils/index.js
isRemoteMethodAllowed
function isRemoteMethodAllowed(method, allowedVerbs) { let httpArray = method.http; if (!_.isArray(method.http)) { httpArray = [method.http]; } const results = httpArray.map((item) => { const verb = item.verb; if (allowedVerbs && !_.includes(allowedVerbs, verb)) { return false; } return true; }); const result = _.includes(results, true); return result; }
javascript
function isRemoteMethodAllowed(method, allowedVerbs) { let httpArray = method.http; if (!_.isArray(method.http)) { httpArray = [method.http]; } const results = httpArray.map((item) => { const verb = item.verb; if (allowedVerbs && !_.includes(allowedVerbs, verb)) { return false; } return true; }); const result = _.includes(results, true); return result; }
[ "function", "isRemoteMethodAllowed", "(", "method", ",", "allowedVerbs", ")", "{", "let", "httpArray", "=", "method", ".", "http", ";", "if", "(", "!", "_", ".", "isArray", "(", "method", ".", "http", ")", ")", "{", "httpArray", "=", "[", "method", ".", "http", "]", ";", "}", "const", "results", "=", "httpArray", ".", "map", "(", "(", "item", ")", "=>", "{", "const", "verb", "=", "item", ".", "verb", ";", "if", "(", "allowedVerbs", "&&", "!", "_", ".", "includes", "(", "allowedVerbs", ",", "verb", ")", ")", "{", "return", "false", ";", "}", "return", "true", ";", "}", ")", ";", "const", "result", "=", "_", ".", "includes", "(", "results", ",", "true", ")", ";", "return", "result", ";", "}" ]
Checks if a given remote method allowed based on the allowed verbs @param {*} method @param {*} allowedVerbs
[ "Checks", "if", "a", "given", "remote", "method", "allowed", "based", "on", "the", "allowed", "verbs" ]
7a624b1480f4bde10090ba744ba7a0108e393be7
https://github.com/yahoohung/loopback-graphql-server/blob/7a624b1480f4bde10090ba744ba7a0108e393be7/src/schema/utils/index.js#L25-L47
22,320
yahoohung/loopback-graphql-server
src/schema/utils/index.js
getRemoteMethodInput
function getRemoteMethodInput(method, isConnection = false) { const acceptingParams = {}; method.accepts.forEach((param) => { let paramType = ''; if (typeof param.type === 'object') { paramType = 'JSON'; } else if (!SCALARS[param.type.toLowerCase()]) { paramType = `${param.type}Input`; } else { paramType = _.upperFirst(param.type); } if (param.arg) { acceptingParams[param.arg] = { type: getType(exchangeTypes[paramType] || paramType) }; } }); return (isConnection) ? Object.assign({}, acceptingParams, connectionArgs) : acceptingParams; }
javascript
function getRemoteMethodInput(method, isConnection = false) { const acceptingParams = {}; method.accepts.forEach((param) => { let paramType = ''; if (typeof param.type === 'object') { paramType = 'JSON'; } else if (!SCALARS[param.type.toLowerCase()]) { paramType = `${param.type}Input`; } else { paramType = _.upperFirst(param.type); } if (param.arg) { acceptingParams[param.arg] = { type: getType(exchangeTypes[paramType] || paramType) }; } }); return (isConnection) ? Object.assign({}, acceptingParams, connectionArgs) : acceptingParams; }
[ "function", "getRemoteMethodInput", "(", "method", ",", "isConnection", "=", "false", ")", "{", "const", "acceptingParams", "=", "{", "}", ";", "method", ".", "accepts", ".", "forEach", "(", "(", "param", ")", "=>", "{", "let", "paramType", "=", "''", ";", "if", "(", "typeof", "param", ".", "type", "===", "'object'", ")", "{", "paramType", "=", "'JSON'", ";", "}", "else", "if", "(", "!", "SCALARS", "[", "param", ".", "type", ".", "toLowerCase", "(", ")", "]", ")", "{", "paramType", "=", "`", "${", "param", ".", "type", "}", "`", ";", "}", "else", "{", "paramType", "=", "_", ".", "upperFirst", "(", "param", ".", "type", ")", ";", "}", "if", "(", "param", ".", "arg", ")", "{", "acceptingParams", "[", "param", ".", "arg", "]", "=", "{", "type", ":", "getType", "(", "exchangeTypes", "[", "paramType", "]", "||", "paramType", ")", "}", ";", "}", "}", ")", ";", "return", "(", "isConnection", ")", "?", "Object", ".", "assign", "(", "{", "}", ",", "acceptingParams", ",", "connectionArgs", ")", ":", "acceptingParams", ";", "}" ]
Extracts query params from a remote method @param {*} method
[ "Extracts", "query", "params", "from", "a", "remote", "method" ]
7a624b1480f4bde10090ba744ba7a0108e393be7
https://github.com/yahoohung/loopback-graphql-server/blob/7a624b1480f4bde10090ba744ba7a0108e393be7/src/schema/utils/index.js#L53-L73
22,321
yahoohung/loopback-graphql-server
src/schema/utils/index.js
getRemoteMethodOutput
function getRemoteMethodOutput(method) { let returnType = 'JSON'; let list = false; if (method.returns && method.returns[0]) { if (!SCALARS[method.returns[0].type] && typeof method.returns[0].type !== 'object') { returnType = `${method.returns[0].type}`; } else { returnType = `${method.returns[0].type}`; if (_.isArray(method.returns[0].type) && _.isString(method.returns[0].type[0])) { returnType = method.returns[0].type[0]; list = true; } else if (typeof method.returns[0].type === 'object') { returnType = 'JSON'; } } } let type = exchangeTypes[returnType] || returnType; type = (list) ? getConnection(type) : getType(type); type = type || getType('JSON'); return { type, list }; }
javascript
function getRemoteMethodOutput(method) { let returnType = 'JSON'; let list = false; if (method.returns && method.returns[0]) { if (!SCALARS[method.returns[0].type] && typeof method.returns[0].type !== 'object') { returnType = `${method.returns[0].type}`; } else { returnType = `${method.returns[0].type}`; if (_.isArray(method.returns[0].type) && _.isString(method.returns[0].type[0])) { returnType = method.returns[0].type[0]; list = true; } else if (typeof method.returns[0].type === 'object') { returnType = 'JSON'; } } } let type = exchangeTypes[returnType] || returnType; type = (list) ? getConnection(type) : getType(type); type = type || getType('JSON'); return { type, list }; }
[ "function", "getRemoteMethodOutput", "(", "method", ")", "{", "let", "returnType", "=", "'JSON'", ";", "let", "list", "=", "false", ";", "if", "(", "method", ".", "returns", "&&", "method", ".", "returns", "[", "0", "]", ")", "{", "if", "(", "!", "SCALARS", "[", "method", ".", "returns", "[", "0", "]", ".", "type", "]", "&&", "typeof", "method", ".", "returns", "[", "0", "]", ".", "type", "!==", "'object'", ")", "{", "returnType", "=", "`", "${", "method", ".", "returns", "[", "0", "]", ".", "type", "}", "`", ";", "}", "else", "{", "returnType", "=", "`", "${", "method", ".", "returns", "[", "0", "]", ".", "type", "}", "`", ";", "if", "(", "_", ".", "isArray", "(", "method", ".", "returns", "[", "0", "]", ".", "type", ")", "&&", "_", ".", "isString", "(", "method", ".", "returns", "[", "0", "]", ".", "type", "[", "0", "]", ")", ")", "{", "returnType", "=", "method", ".", "returns", "[", "0", "]", ".", "type", "[", "0", "]", ";", "list", "=", "true", ";", "}", "else", "if", "(", "typeof", "method", ".", "returns", "[", "0", "]", ".", "type", "===", "'object'", ")", "{", "returnType", "=", "'JSON'", ";", "}", "}", "}", "let", "type", "=", "exchangeTypes", "[", "returnType", "]", "||", "returnType", ";", "type", "=", "(", "list", ")", "?", "getConnection", "(", "type", ")", ":", "getType", "(", "type", ")", ";", "type", "=", "type", "||", "getType", "(", "'JSON'", ")", ";", "return", "{", "type", ",", "list", "}", ";", "}" ]
Extracts query output fields from a remote method @param {*} method
[ "Extracts", "query", "output", "fields", "from", "a", "remote", "method" ]
7a624b1480f4bde10090ba744ba7a0108e393be7
https://github.com/yahoohung/loopback-graphql-server/blob/7a624b1480f4bde10090ba744ba7a0108e393be7/src/schema/utils/index.js#L79-L106
22,322
yahoohung/loopback-graphql-server
src/types/generateTypeDefs.js
mapRelation
function mapRelation(rel, modelName, relName) { let acceptingParams = Object.assign({}, { filter: { generated: false, type: 'JSON' } }, connectionArgs); types[modelName].meta.fields[relName] = { generated: true, meta: { relation: true, connection: true, relationType: rel.type, isMany: isManyRelation(rel.type), embed: rel.embed, type: rel.modelTo.modelName, args: acceptingParams, }, resolve: (obj, args, context, info) => { const ctxOptions = { accessToken: context.req.accessToken } const modelId = args && args.id; const method = rel.modelTo.sharedClass.findMethodByName('find'); // TODO: ... return new Promise((resolve, reject) => { resolve(true) }).then(() => { let params = {}; _.forEach(acceptingParams, (param, name) => { if (typeof args[name] !== 'undefined' && Object.keys(args[name]).length > 0) { _.merge(params, _.cloneDeep(args[name])); } }); if (isManyRelation(rel.type) === true) { return connectionFromPromisedArray(findRelatedMany(rel, obj, params, context), args, rel.modelTo); } else { return findRelatedOne(rel, obj, params, context); } // let wrap = promisify(model[method.name](...params, ctxOptions)); // if (typeObj.list) { // return connectionFromPromisedArray(wrap, args, model); // } else { // return wrap; // } }).catch((err) => { throw err; }); } }; }
javascript
function mapRelation(rel, modelName, relName) { let acceptingParams = Object.assign({}, { filter: { generated: false, type: 'JSON' } }, connectionArgs); types[modelName].meta.fields[relName] = { generated: true, meta: { relation: true, connection: true, relationType: rel.type, isMany: isManyRelation(rel.type), embed: rel.embed, type: rel.modelTo.modelName, args: acceptingParams, }, resolve: (obj, args, context, info) => { const ctxOptions = { accessToken: context.req.accessToken } const modelId = args && args.id; const method = rel.modelTo.sharedClass.findMethodByName('find'); // TODO: ... return new Promise((resolve, reject) => { resolve(true) }).then(() => { let params = {}; _.forEach(acceptingParams, (param, name) => { if (typeof args[name] !== 'undefined' && Object.keys(args[name]).length > 0) { _.merge(params, _.cloneDeep(args[name])); } }); if (isManyRelation(rel.type) === true) { return connectionFromPromisedArray(findRelatedMany(rel, obj, params, context), args, rel.modelTo); } else { return findRelatedOne(rel, obj, params, context); } // let wrap = promisify(model[method.name](...params, ctxOptions)); // if (typeObj.list) { // return connectionFromPromisedArray(wrap, args, model); // } else { // return wrap; // } }).catch((err) => { throw err; }); } }; }
[ "function", "mapRelation", "(", "rel", ",", "modelName", ",", "relName", ")", "{", "let", "acceptingParams", "=", "Object", ".", "assign", "(", "{", "}", ",", "{", "filter", ":", "{", "generated", ":", "false", ",", "type", ":", "'JSON'", "}", "}", ",", "connectionArgs", ")", ";", "types", "[", "modelName", "]", ".", "meta", ".", "fields", "[", "relName", "]", "=", "{", "generated", ":", "true", ",", "meta", ":", "{", "relation", ":", "true", ",", "connection", ":", "true", ",", "relationType", ":", "rel", ".", "type", ",", "isMany", ":", "isManyRelation", "(", "rel", ".", "type", ")", ",", "embed", ":", "rel", ".", "embed", ",", "type", ":", "rel", ".", "modelTo", ".", "modelName", ",", "args", ":", "acceptingParams", ",", "}", ",", "resolve", ":", "(", "obj", ",", "args", ",", "context", ",", "info", ")", "=>", "{", "const", "ctxOptions", "=", "{", "accessToken", ":", "context", ".", "req", ".", "accessToken", "}", "const", "modelId", "=", "args", "&&", "args", ".", "id", ";", "const", "method", "=", "rel", ".", "modelTo", ".", "sharedClass", ".", "findMethodByName", "(", "'find'", ")", ";", "// TODO: ...", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "resolve", "(", "true", ")", "}", ")", ".", "then", "(", "(", ")", "=>", "{", "let", "params", "=", "{", "}", ";", "_", ".", "forEach", "(", "acceptingParams", ",", "(", "param", ",", "name", ")", "=>", "{", "if", "(", "typeof", "args", "[", "name", "]", "!==", "'undefined'", "&&", "Object", ".", "keys", "(", "args", "[", "name", "]", ")", ".", "length", ">", "0", ")", "{", "_", ".", "merge", "(", "params", ",", "_", ".", "cloneDeep", "(", "args", "[", "name", "]", ")", ")", ";", "}", "}", ")", ";", "if", "(", "isManyRelation", "(", "rel", ".", "type", ")", "===", "true", ")", "{", "return", "connectionFromPromisedArray", "(", "findRelatedMany", "(", "rel", ",", "obj", ",", "params", ",", "context", ")", ",", "args", ",", "rel", ".", "modelTo", ")", ";", "}", "else", "{", "return", "findRelatedOne", "(", "rel", ",", "obj", ",", "params", ",", "context", ")", ";", "}", "// let wrap = promisify(model[method.name](...params, ctxOptions));", "// if (typeObj.list) {", "// return connectionFromPromisedArray(wrap, args, model);", "// } else {", "// return wrap;", "// }", "}", ")", ".", "catch", "(", "(", "err", ")", "=>", "{", "throw", "err", ";", "}", ")", ";", "}", "}", ";", "}" ]
Maps a relationship as a connection property to a given type @param {*} rel @param {*} modelName @param {*} relName
[ "Maps", "a", "relationship", "as", "a", "connection", "property", "to", "a", "given", "type" ]
7a624b1480f4bde10090ba744ba7a0108e393be7
https://github.com/yahoohung/loopback-graphql-server/blob/7a624b1480f4bde10090ba744ba7a0108e393be7/src/types/generateTypeDefs.js#L181-L235
22,323
yahoohung/loopback-graphql-server
src/types/generateTypeDefs.js
mapType
function mapType(model) { types[model.modelName] = { generated: false, name: model.modelName, meta: { category: 'TYPE', fields: {} } }; _.forEach(model.definition.properties, (property, key) => { mapProperty(model, property, model.modelName, key); }); _.forEach(sharedRelations(model), (rel) => { mapRelation(rel, model.modelName, rel.name); }); }
javascript
function mapType(model) { types[model.modelName] = { generated: false, name: model.modelName, meta: { category: 'TYPE', fields: {} } }; _.forEach(model.definition.properties, (property, key) => { mapProperty(model, property, model.modelName, key); }); _.forEach(sharedRelations(model), (rel) => { mapRelation(rel, model.modelName, rel.name); }); }
[ "function", "mapType", "(", "model", ")", "{", "types", "[", "model", ".", "modelName", "]", "=", "{", "generated", ":", "false", ",", "name", ":", "model", ".", "modelName", ",", "meta", ":", "{", "category", ":", "'TYPE'", ",", "fields", ":", "{", "}", "}", "}", ";", "_", ".", "forEach", "(", "model", ".", "definition", ".", "properties", ",", "(", "property", ",", "key", ")", "=>", "{", "mapProperty", "(", "model", ",", "property", ",", "model", ".", "modelName", ",", "key", ")", ";", "}", ")", ";", "_", ".", "forEach", "(", "sharedRelations", "(", "model", ")", ",", "(", "rel", ")", "=>", "{", "mapRelation", "(", "rel", ",", "model", ".", "modelName", ",", "rel", ".", "name", ")", ";", "}", ")", ";", "}" ]
Generates a definition for a single model type @param {*} model
[ "Generates", "a", "definition", "for", "a", "single", "model", "type" ]
7a624b1480f4bde10090ba744ba7a0108e393be7
https://github.com/yahoohung/loopback-graphql-server/blob/7a624b1480f4bde10090ba744ba7a0108e393be7/src/types/generateTypeDefs.js#L241-L258
22,324
yahoohung/loopback-graphql-server
src/types/generateTypeDefs.js
mapInputType
function mapInputType(model) { const modelName = `${model.modelName}Input`; types[modelName] = { generated: false, name: modelName, meta: { category: 'TYPE', input: true, fields: {} } }; _.forEach(model.definition.properties, (property, key) => { mapProperty(model, property, modelName, key, true); }); }
javascript
function mapInputType(model) { const modelName = `${model.modelName}Input`; types[modelName] = { generated: false, name: modelName, meta: { category: 'TYPE', input: true, fields: {} } }; _.forEach(model.definition.properties, (property, key) => { mapProperty(model, property, modelName, key, true); }); }
[ "function", "mapInputType", "(", "model", ")", "{", "const", "modelName", "=", "`", "${", "model", ".", "modelName", "}", "`", ";", "types", "[", "modelName", "]", "=", "{", "generated", ":", "false", ",", "name", ":", "modelName", ",", "meta", ":", "{", "category", ":", "'TYPE'", ",", "input", ":", "true", ",", "fields", ":", "{", "}", "}", "}", ";", "_", ".", "forEach", "(", "model", ".", "definition", ".", "properties", ",", "(", "property", ",", "key", ")", "=>", "{", "mapProperty", "(", "model", ",", "property", ",", "modelName", ",", "key", ",", "true", ")", ";", "}", ")", ";", "}" ]
Generates a definition for a single model input type @param {*} model
[ "Generates", "a", "definition", "for", "a", "single", "model", "input", "type" ]
7a624b1480f4bde10090ba744ba7a0108e393be7
https://github.com/yahoohung/loopback-graphql-server/blob/7a624b1480f4bde10090ba744ba7a0108e393be7/src/types/generateTypeDefs.js#L264-L280
22,325
yahoohung/loopback-graphql-server
src/types/generateTypeDefs.js
generateTypeDefs
function generateTypeDefs(models) { types = Object.assign({}, types, getCustomTypeDefs()); _.forEach(models, (model) => { mapType(model); mapInputType(model); }); return types; }
javascript
function generateTypeDefs(models) { types = Object.assign({}, types, getCustomTypeDefs()); _.forEach(models, (model) => { mapType(model); mapInputType(model); }); return types; }
[ "function", "generateTypeDefs", "(", "models", ")", "{", "types", "=", "Object", ".", "assign", "(", "{", "}", ",", "types", ",", "getCustomTypeDefs", "(", ")", ")", ";", "_", ".", "forEach", "(", "models", ",", "(", "model", ")", "=>", "{", "mapType", "(", "model", ")", ";", "mapInputType", "(", "model", ")", ";", "}", ")", ";", "return", "types", ";", "}" ]
building all models types & relationships
[ "building", "all", "models", "types", "&", "relationships" ]
7a624b1480f4bde10090ba744ba7a0108e393be7
https://github.com/yahoohung/loopback-graphql-server/blob/7a624b1480f4bde10090ba744ba7a0108e393be7/src/types/generateTypeDefs.js#L300-L310
22,326
yahoohung/loopback-graphql-server
src/types/generateType.js
generateType
function generateType(name, def) { // const def = _.find(getTypeDefs(), (o, n) => n === name); if (!name || !def) { return null; } // If def doesnt have {generated: false} prop, then it is // already a type. Hence return it as is. if (def.generated !== false) { return def; } def = _.clone(def); processIdField(name, def); if (def.meta.category === 'TYPE') { def.fields = () => generateTypeFields(def); if (def.meta.input === true) { return new GraphQLInputObjectType(def); } return new GraphQLObjectType(def); } else if (def.category === 'ENUM') { const values = {}; _.forEach(def.values, (val) => { values[val] = { value: val }; }); def.values = values; return new GraphQLEnumType(def); } }
javascript
function generateType(name, def) { // const def = _.find(getTypeDefs(), (o, n) => n === name); if (!name || !def) { return null; } // If def doesnt have {generated: false} prop, then it is // already a type. Hence return it as is. if (def.generated !== false) { return def; } def = _.clone(def); processIdField(name, def); if (def.meta.category === 'TYPE') { def.fields = () => generateTypeFields(def); if (def.meta.input === true) { return new GraphQLInputObjectType(def); } return new GraphQLObjectType(def); } else if (def.category === 'ENUM') { const values = {}; _.forEach(def.values, (val) => { values[val] = { value: val }; }); def.values = values; return new GraphQLEnumType(def); } }
[ "function", "generateType", "(", "name", ",", "def", ")", "{", "// const def = _.find(getTypeDefs(), (o, n) => n === name);", "if", "(", "!", "name", "||", "!", "def", ")", "{", "return", "null", ";", "}", "// If def doesnt have {generated: false} prop, then it is", "// already a type. Hence return it as is.", "if", "(", "def", ".", "generated", "!==", "false", ")", "{", "return", "def", ";", "}", "def", "=", "_", ".", "clone", "(", "def", ")", ";", "processIdField", "(", "name", ",", "def", ")", ";", "if", "(", "def", ".", "meta", ".", "category", "===", "'TYPE'", ")", "{", "def", ".", "fields", "=", "(", ")", "=>", "generateTypeFields", "(", "def", ")", ";", "if", "(", "def", ".", "meta", ".", "input", "===", "true", ")", "{", "return", "new", "GraphQLInputObjectType", "(", "def", ")", ";", "}", "return", "new", "GraphQLObjectType", "(", "def", ")", ";", "}", "else", "if", "(", "def", ".", "category", "===", "'ENUM'", ")", "{", "const", "values", "=", "{", "}", ";", "_", ".", "forEach", "(", "def", ".", "values", ",", "(", "val", ")", "=>", "{", "values", "[", "val", "]", "=", "{", "value", ":", "val", "}", ";", "}", ")", ";", "def", ".", "values", "=", "values", ";", "return", "new", "GraphQLEnumType", "(", "def", ")", ";", "}", "}" ]
Dynamically generate type based on the definition in typeDefs @param {*} name @param {*} def Type definition
[ "Dynamically", "generate", "type", "based", "on", "the", "definition", "in", "typeDefs" ]
7a624b1480f4bde10090ba744ba7a0108e393be7
https://github.com/yahoohung/loopback-graphql-server/blob/7a624b1480f4bde10090ba744ba7a0108e393be7/src/types/generateType.js#L146-L178
22,327
ForthHub/forth
lib/word.js
take
function take (delimeter) { var start, last, res; last = this.last; start = this.ptr; while (true) { if (this.ptr > last) { // good part res = this.buf.slice(start, this.ptr); return res; } if (this.buf[this.ptr].search(delimeter) === 0) { // good part res = this.buf.slice(start, this.ptr); this.ptr++; return res; } this.ptr++; } }
javascript
function take (delimeter) { var start, last, res; last = this.last; start = this.ptr; while (true) { if (this.ptr > last) { // good part res = this.buf.slice(start, this.ptr); return res; } if (this.buf[this.ptr].search(delimeter) === 0) { // good part res = this.buf.slice(start, this.ptr); this.ptr++; return res; } this.ptr++; } }
[ "function", "take", "(", "delimeter", ")", "{", "var", "start", ",", "last", ",", "res", ";", "last", "=", "this", ".", "last", ";", "start", "=", "this", ".", "ptr", ";", "while", "(", "true", ")", "{", "if", "(", "this", ".", "ptr", ">", "last", ")", "{", "// good part", "res", "=", "this", ".", "buf", ".", "slice", "(", "start", ",", "this", ".", "ptr", ")", ";", "return", "res", ";", "}", "if", "(", "this", ".", "buf", "[", "this", ".", "ptr", "]", ".", "search", "(", "delimeter", ")", "===", "0", ")", "{", "// good part", "res", "=", "this", ".", "buf", ".", "slice", "(", "start", ",", "this", ".", "ptr", ")", ";", "this", ".", "ptr", "++", ";", "return", "res", ";", "}", "this", ".", "ptr", "++", ";", "}", "}" ]
Parse characters ccc delimited by 'delimeter'
[ "Parse", "characters", "ccc", "delimited", "by", "delimeter" ]
5f07870d2d6a05ff3bc258192a14810cfaf84c6a
https://github.com/ForthHub/forth/blob/5f07870d2d6a05ff3bc258192a14810cfaf84c6a/lib/word.js#L86-L105
22,328
project-sunbird/sunbird-telemetry-sdk
js/dist/index.js
function () { var s = document.createElement('span') /* * We need this css as in some weird browser this * span elements shows up for a microSec which creates a * bad user experience */ s.style.position = 'absolute' s.style.left = '-9999px' s.style.fontSize = testSize // css font reset to reset external styles s.style.fontStyle = 'normal' s.style.fontWeight = 'normal' s.style.letterSpacing = 'normal' s.style.lineBreak = 'auto' s.style.lineHeight = 'normal' s.style.textTransform = 'none' s.style.textAlign = 'left' s.style.textDecoration = 'none' s.style.textShadow = 'none' s.style.whiteSpace = 'normal' s.style.wordBreak = 'normal' s.style.wordSpacing = 'normal' s.innerHTML = testString return s }
javascript
function () { var s = document.createElement('span') /* * We need this css as in some weird browser this * span elements shows up for a microSec which creates a * bad user experience */ s.style.position = 'absolute' s.style.left = '-9999px' s.style.fontSize = testSize // css font reset to reset external styles s.style.fontStyle = 'normal' s.style.fontWeight = 'normal' s.style.letterSpacing = 'normal' s.style.lineBreak = 'auto' s.style.lineHeight = 'normal' s.style.textTransform = 'none' s.style.textAlign = 'left' s.style.textDecoration = 'none' s.style.textShadow = 'none' s.style.whiteSpace = 'normal' s.style.wordBreak = 'normal' s.style.wordSpacing = 'normal' s.innerHTML = testString return s }
[ "function", "(", ")", "{", "var", "s", "=", "document", ".", "createElement", "(", "'span'", ")", "/*\n * We need this css as in some weird browser this\n * span elements shows up for a microSec which creates a\n * bad user experience\n */", "s", ".", "style", ".", "position", "=", "'absolute'", "s", ".", "style", ".", "left", "=", "'-9999px'", "s", ".", "style", ".", "fontSize", "=", "testSize", "// css font reset to reset external styles", "s", ".", "style", ".", "fontStyle", "=", "'normal'", "s", ".", "style", ".", "fontWeight", "=", "'normal'", "s", ".", "style", ".", "letterSpacing", "=", "'normal'", "s", ".", "style", ".", "lineBreak", "=", "'auto'", "s", ".", "style", ".", "lineHeight", "=", "'normal'", "s", ".", "style", ".", "textTransform", "=", "'none'", "s", ".", "style", ".", "textAlign", "=", "'left'", "s", ".", "style", ".", "textDecoration", "=", "'none'", "s", ".", "style", ".", "textShadow", "=", "'none'", "s", ".", "style", ".", "whiteSpace", "=", "'normal'", "s", ".", "style", ".", "wordBreak", "=", "'normal'", "s", ".", "style", ".", "wordSpacing", "=", "'normal'", "s", ".", "innerHTML", "=", "testString", "return", "s", "}" ]
creates a span where the fonts will be loaded
[ "creates", "a", "span", "where", "the", "fonts", "will", "be", "loaded" ]
7f77635ae1100199fa804039e6839b08722f51e0
https://github.com/project-sunbird/sunbird-telemetry-sdk/blob/7f77635ae1100199fa804039e6839b08722f51e0/js/dist/index.js#L995-L1022
22,329
project-sunbird/sunbird-telemetry-sdk
js/dist/index.js
function (fontToDetect, baseFont) { var s = createSpan() s.style.fontFamily = "'" + fontToDetect + "'," + baseFont return s }
javascript
function (fontToDetect, baseFont) { var s = createSpan() s.style.fontFamily = "'" + fontToDetect + "'," + baseFont return s }
[ "function", "(", "fontToDetect", ",", "baseFont", ")", "{", "var", "s", "=", "createSpan", "(", ")", "s", ".", "style", ".", "fontFamily", "=", "\"'\"", "+", "fontToDetect", "+", "\"',\"", "+", "baseFont", "return", "s", "}" ]
creates a span and load the font to detect and a base font for fallback
[ "creates", "a", "span", "and", "load", "the", "font", "to", "detect", "and", "a", "base", "font", "for", "fallback" ]
7f77635ae1100199fa804039e6839b08722f51e0
https://github.com/project-sunbird/sunbird-telemetry-sdk/blob/7f77635ae1100199fa804039e6839b08722f51e0/js/dist/index.js#L1025-L1029
22,330
project-sunbird/sunbird-telemetry-sdk
js/dist/index.js
function () { var spans = [] for (var index = 0, length = baseFonts.length; index < length; index++) { var s = createSpan() s.style.fontFamily = baseFonts[index] baseFontsDiv.appendChild(s) spans.push(s) } return spans }
javascript
function () { var spans = [] for (var index = 0, length = baseFonts.length; index < length; index++) { var s = createSpan() s.style.fontFamily = baseFonts[index] baseFontsDiv.appendChild(s) spans.push(s) } return spans }
[ "function", "(", ")", "{", "var", "spans", "=", "[", "]", "for", "(", "var", "index", "=", "0", ",", "length", "=", "baseFonts", ".", "length", ";", "index", "<", "length", ";", "index", "++", ")", "{", "var", "s", "=", "createSpan", "(", ")", "s", ".", "style", ".", "fontFamily", "=", "baseFonts", "[", "index", "]", "baseFontsDiv", ".", "appendChild", "(", "s", ")", "spans", ".", "push", "(", "s", ")", "}", "return", "spans", "}" ]
creates spans for the base fonts and adds them to baseFontsDiv
[ "creates", "spans", "for", "the", "base", "fonts", "and", "adds", "them", "to", "baseFontsDiv" ]
7f77635ae1100199fa804039e6839b08722f51e0
https://github.com/project-sunbird/sunbird-telemetry-sdk/blob/7f77635ae1100199fa804039e6839b08722f51e0/js/dist/index.js#L1032-L1041
22,331
project-sunbird/sunbird-telemetry-sdk
js/dist/index.js
function () { var spans = {} for (var i = 0, l = fontList.length; i < l; i++) { var fontSpans = [] for (var j = 0, numDefaultFonts = baseFonts.length; j < numDefaultFonts; j++) { var s = createSpanWithFonts(fontList[i], baseFonts[j]) fontsDiv.appendChild(s) fontSpans.push(s) } spans[fontList[i]] = fontSpans // Stores {fontName : [spans for that font]} } return spans }
javascript
function () { var spans = {} for (var i = 0, l = fontList.length; i < l; i++) { var fontSpans = [] for (var j = 0, numDefaultFonts = baseFonts.length; j < numDefaultFonts; j++) { var s = createSpanWithFonts(fontList[i], baseFonts[j]) fontsDiv.appendChild(s) fontSpans.push(s) } spans[fontList[i]] = fontSpans // Stores {fontName : [spans for that font]} } return spans }
[ "function", "(", ")", "{", "var", "spans", "=", "{", "}", "for", "(", "var", "i", "=", "0", ",", "l", "=", "fontList", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "var", "fontSpans", "=", "[", "]", "for", "(", "var", "j", "=", "0", ",", "numDefaultFonts", "=", "baseFonts", ".", "length", ";", "j", "<", "numDefaultFonts", ";", "j", "++", ")", "{", "var", "s", "=", "createSpanWithFonts", "(", "fontList", "[", "i", "]", ",", "baseFonts", "[", "j", "]", ")", "fontsDiv", ".", "appendChild", "(", "s", ")", "fontSpans", ".", "push", "(", "s", ")", "}", "spans", "[", "fontList", "[", "i", "]", "]", "=", "fontSpans", "// Stores {fontName : [spans for that font]}", "}", "return", "spans", "}" ]
creates spans for the fonts to detect and adds them to fontsDiv
[ "creates", "spans", "for", "the", "fonts", "to", "detect", "and", "adds", "them", "to", "fontsDiv" ]
7f77635ae1100199fa804039e6839b08722f51e0
https://github.com/project-sunbird/sunbird-telemetry-sdk/blob/7f77635ae1100199fa804039e6839b08722f51e0/js/dist/index.js#L1044-L1056
22,332
project-sunbird/sunbird-telemetry-sdk
js/dist/index.js
function (fontSpans) { var detected = false for (var i = 0; i < baseFonts.length; i++) { detected = (fontSpans[i].offsetWidth !== defaultWidth[baseFonts[i]] || fontSpans[i].offsetHeight !== defaultHeight[baseFonts[i]]) if (detected) { return detected } } return detected }
javascript
function (fontSpans) { var detected = false for (var i = 0; i < baseFonts.length; i++) { detected = (fontSpans[i].offsetWidth !== defaultWidth[baseFonts[i]] || fontSpans[i].offsetHeight !== defaultHeight[baseFonts[i]]) if (detected) { return detected } } return detected }
[ "function", "(", "fontSpans", ")", "{", "var", "detected", "=", "false", "for", "(", "var", "i", "=", "0", ";", "i", "<", "baseFonts", ".", "length", ";", "i", "++", ")", "{", "detected", "=", "(", "fontSpans", "[", "i", "]", ".", "offsetWidth", "!==", "defaultWidth", "[", "baseFonts", "[", "i", "]", "]", "||", "fontSpans", "[", "i", "]", ".", "offsetHeight", "!==", "defaultHeight", "[", "baseFonts", "[", "i", "]", "]", ")", "if", "(", "detected", ")", "{", "return", "detected", "}", "}", "return", "detected", "}" ]
checks if a font is available
[ "checks", "if", "a", "font", "is", "available" ]
7f77635ae1100199fa804039e6839b08722f51e0
https://github.com/project-sunbird/sunbird-telemetry-sdk/blob/7f77635ae1100199fa804039e6839b08722f51e0/js/dist/index.js#L1059-L1068
22,333
optimizely/optimizely-node
lib/services/model_factory.js
function(data) { // use the supplied constructor // This allows a user to pass in instance: function Audience() {} // and have the Audience() function return an instance of Audience var instance = new InstanceConstructor(); var instanceData = _.extend( {}, _.cloneDeep(config.fields || {}), _.cloneDeep(data || {}) ); // populate the instanceor _.extend(instance, instanceData); return instance; }
javascript
function(data) { // use the supplied constructor // This allows a user to pass in instance: function Audience() {} // and have the Audience() function return an instance of Audience var instance = new InstanceConstructor(); var instanceData = _.extend( {}, _.cloneDeep(config.fields || {}), _.cloneDeep(data || {}) ); // populate the instanceor _.extend(instance, instanceData); return instance; }
[ "function", "(", "data", ")", "{", "// use the supplied constructor", "// This allows a user to pass in instance: function Audience() {}", "// and have the Audience() function return an instance of Audience", "var", "instance", "=", "new", "InstanceConstructor", "(", ")", ";", "var", "instanceData", "=", "_", ".", "extend", "(", "{", "}", ",", "_", ".", "cloneDeep", "(", "config", ".", "fields", "||", "{", "}", ")", ",", "_", ".", "cloneDeep", "(", "data", "||", "{", "}", ")", ")", ";", "// populate the instanceor", "_", ".", "extend", "(", "instance", ",", "instanceData", ")", ";", "return", "instance", ";", "}" ]
Creates a new object with the config.fields as the default values @param {Object=} data @return {Object}
[ "Creates", "a", "new", "object", "with", "the", "config", ".", "fields", "as", "the", "default", "values" ]
36a7a1f9163b5f6e302cee3268762d056cfb1f42
https://github.com/optimizely/optimizely-node/blob/36a7a1f9163b5f6e302cee3268762d056cfb1f42/lib/services/model_factory.js#L38-L51
22,334
optimizely/optimizely-node
lib/services/model_factory.js
function(instance) { var loadData = function(data) { return _.extend(instance, data); }; if (instance.id) { // do PUT save return api .one(config.entity, instance.id) .put(instance) .then(loadData, console.error); } else { // no id is set, do a POST var endpoint = api; if (config.parent) { endpoint.one(config.parent.entity, instance[config.parent.key]); } endpoint.all(config.entity); return endpoint .post(instance) .then(loadData, console.error); } }
javascript
function(instance) { var loadData = function(data) { return _.extend(instance, data); }; if (instance.id) { // do PUT save return api .one(config.entity, instance.id) .put(instance) .then(loadData, console.error); } else { // no id is set, do a POST var endpoint = api; if (config.parent) { endpoint.one(config.parent.entity, instance[config.parent.key]); } endpoint.all(config.entity); return endpoint .post(instance) .then(loadData, console.error); } }
[ "function", "(", "instance", ")", "{", "var", "loadData", "=", "function", "(", "data", ")", "{", "return", "_", ".", "extend", "(", "instance", ",", "data", ")", ";", "}", ";", "if", "(", "instance", ".", "id", ")", "{", "// do PUT save", "return", "api", ".", "one", "(", "config", ".", "entity", ",", "instance", ".", "id", ")", ".", "put", "(", "instance", ")", ".", "then", "(", "loadData", ",", "console", ".", "error", ")", ";", "}", "else", "{", "// no id is set, do a POST", "var", "endpoint", "=", "api", ";", "if", "(", "config", ".", "parent", ")", "{", "endpoint", ".", "one", "(", "config", ".", "parent", ".", "entity", ",", "instance", "[", "config", ".", "parent", ".", "key", "]", ")", ";", "}", "endpoint", ".", "all", "(", "config", ".", "entity", ")", ";", "return", "endpoint", ".", "post", "(", "instance", ")", ".", "then", "(", "loadData", ",", "console", ".", "error", ")", ";", "}", "}" ]
Persists entity using rest API @param {Model} instance @return {Promise}
[ "Persists", "entity", "using", "rest", "API" ]
36a7a1f9163b5f6e302cee3268762d056cfb1f42
https://github.com/optimizely/optimizely-node/blob/36a7a1f9163b5f6e302cee3268762d056cfb1f42/lib/services/model_factory.js#L59-L82
22,335
optimizely/optimizely-node
lib/services/model_factory.js
function(entityId) { return api .one(config.entity, entityId) .get() .then(this.create, console.error); }
javascript
function(entityId) { return api .one(config.entity, entityId) .get() .then(this.create, console.error); }
[ "function", "(", "entityId", ")", "{", "return", "api", ".", "one", "(", "config", ".", "entity", ",", "entityId", ")", ".", "get", "(", ")", ".", "then", "(", "this", ".", "create", ",", "console", ".", "error", ")", ";", "}" ]
Fetch and return an entity @param entityId Id of Entity to fetch @returns {Deferred} Resolves to fetched Model instance
[ "Fetch", "and", "return", "an", "entity" ]
36a7a1f9163b5f6e302cee3268762d056cfb1f42
https://github.com/optimizely/optimizely-node/blob/36a7a1f9163b5f6e302cee3268762d056cfb1f42/lib/services/model_factory.js#L89-L94
22,336
optimizely/optimizely-node
lib/services/model_factory.js
function(filters) { filters = _.clone(filters || {}); var endpoint = api; if (config.parent && !filters[config.parent.key]) { throw new Error("fetchAll: must supply the parent.key as a filter to fetch all entities"); } if (config.parent) { endpoint.one(config.parent.entity, filters[config.parent.key]); // since the filtering is happening in the endpoint url we dont need filters delete filters[config.parent.key]; } return endpoint .all(config.entity) .filter(filters) .get() .then(function(results) { return results.map(this.create); // }.bind(this), console.error); }.bind(this), function(err) {console.log(err); throw new Error(err);}); }
javascript
function(filters) { filters = _.clone(filters || {}); var endpoint = api; if (config.parent && !filters[config.parent.key]) { throw new Error("fetchAll: must supply the parent.key as a filter to fetch all entities"); } if (config.parent) { endpoint.one(config.parent.entity, filters[config.parent.key]); // since the filtering is happening in the endpoint url we dont need filters delete filters[config.parent.key]; } return endpoint .all(config.entity) .filter(filters) .get() .then(function(results) { return results.map(this.create); // }.bind(this), console.error); }.bind(this), function(err) {console.log(err); throw new Error(err);}); }
[ "function", "(", "filters", ")", "{", "filters", "=", "_", ".", "clone", "(", "filters", "||", "{", "}", ")", ";", "var", "endpoint", "=", "api", ";", "if", "(", "config", ".", "parent", "&&", "!", "filters", "[", "config", ".", "parent", ".", "key", "]", ")", "{", "throw", "new", "Error", "(", "\"fetchAll: must supply the parent.key as a filter to fetch all entities\"", ")", ";", "}", "if", "(", "config", ".", "parent", ")", "{", "endpoint", ".", "one", "(", "config", ".", "parent", ".", "entity", ",", "filters", "[", "config", ".", "parent", ".", "key", "]", ")", ";", "// since the filtering is happening in the endpoint url we dont need filters", "delete", "filters", "[", "config", ".", "parent", ".", "key", "]", ";", "}", "return", "endpoint", ".", "all", "(", "config", ".", "entity", ")", ".", "filter", "(", "filters", ")", ".", "get", "(", ")", ".", "then", "(", "function", "(", "results", ")", "{", "return", "results", ".", "map", "(", "this", ".", "create", ")", ";", "// }.bind(this), console.error);", "}", ".", "bind", "(", "this", ")", ",", "function", "(", "err", ")", "{", "console", ".", "log", "(", "err", ")", ";", "throw", "new", "Error", "(", "err", ")", ";", "}", ")", ";", "}" ]
Fetches all the entities that match the supplied filters If the model has a parent association than the parent.key must be supplied. @param {Object|undefined} filters (optional) @return {Deferred}
[ "Fetches", "all", "the", "entities", "that", "match", "the", "supplied", "filters", "If", "the", "model", "has", "a", "parent", "association", "than", "the", "parent", ".", "key", "must", "be", "supplied", "." ]
36a7a1f9163b5f6e302cee3268762d056cfb1f42
https://github.com/optimizely/optimizely-node/blob/36a7a1f9163b5f6e302cee3268762d056cfb1f42/lib/services/model_factory.js#L103-L125
22,337
optimizely/optimizely-node
lib/services/model_factory.js
function(instance) { if (!instance.id) { throw new Error("delete(): `id` must be defined"); } return api .one(config.entity, instance.id) .delete(); }
javascript
function(instance) { if (!instance.id) { throw new Error("delete(): `id` must be defined"); } return api .one(config.entity, instance.id) .delete(); }
[ "function", "(", "instance", ")", "{", "if", "(", "!", "instance", ".", "id", ")", "{", "throw", "new", "Error", "(", "\"delete(): `id` must be defined\"", ")", ";", "}", "return", "api", ".", "one", "(", "config", ".", "entity", ",", "instance", ".", "id", ")", ".", "delete", "(", ")", ";", "}" ]
Makes an API request to delete the instance by id @param {Model} instance
[ "Makes", "an", "API", "request", "to", "delete", "the", "instance", "by", "id" ]
36a7a1f9163b5f6e302cee3268762d056cfb1f42
https://github.com/optimizely/optimizely-node/blob/36a7a1f9163b5f6e302cee3268762d056cfb1f42/lib/services/model_factory.js#L131-L139
22,338
tombatossals/angular-openlayers-directive
src/services/olHelpers.js
recursiveStyle
function recursiveStyle(data, styleName) { var style; if (!styleName) { styleName = 'style'; style = data; } else { style = data[styleName]; } //Instead of defining one style for the layer, we've been given a style function //to apply to each feature. if (styleName === 'style' && data instanceof Function) { return data; } if (!(style instanceof Object)) { return style; } var styleObject; if (Object.prototype.toString.call(style) === '[object Object]') { styleObject = {}; var styleConstructor = styleMap[styleName]; if (styleConstructor && style instanceof styleConstructor) { return style; } Object.getOwnPropertyNames(style).forEach(function(val, idx, array) { //Consider the case //image: { // circle: { // fill: { // color: 'red' // } // } // //An ol.style.Circle is an instance of ol.style.Image, so we do not want to construct //an Image and then construct a Circle. We assume that if we have an instanceof //relationship, that the JSON parent has exactly one child. //We check to see if an inheritance relationship exists. //If it does, then for the parent we create an instance of the child. var valConstructor = styleMap[val]; if (styleConstructor && valConstructor && valConstructor.prototype instanceof styleMap[styleName]) { console.assert(array.length === 1, 'Extra parameters for ' + styleName); styleObject = recursiveStyle(style, val); return optionalFactory(styleObject, valConstructor); } else { styleObject[val] = recursiveStyle(style, val); // if the value is 'text' and it contains a String, then it should be interpreted // as such, 'cause the text style might effectively contain a text to display if (val !== 'text' && typeof styleObject[val] !== 'string') { styleObject[val] = optionalFactory(styleObject[val], styleMap[val]); } } }); } else { styleObject = style; } return optionalFactory(styleObject, styleMap[styleName]); }
javascript
function recursiveStyle(data, styleName) { var style; if (!styleName) { styleName = 'style'; style = data; } else { style = data[styleName]; } //Instead of defining one style for the layer, we've been given a style function //to apply to each feature. if (styleName === 'style' && data instanceof Function) { return data; } if (!(style instanceof Object)) { return style; } var styleObject; if (Object.prototype.toString.call(style) === '[object Object]') { styleObject = {}; var styleConstructor = styleMap[styleName]; if (styleConstructor && style instanceof styleConstructor) { return style; } Object.getOwnPropertyNames(style).forEach(function(val, idx, array) { //Consider the case //image: { // circle: { // fill: { // color: 'red' // } // } // //An ol.style.Circle is an instance of ol.style.Image, so we do not want to construct //an Image and then construct a Circle. We assume that if we have an instanceof //relationship, that the JSON parent has exactly one child. //We check to see if an inheritance relationship exists. //If it does, then for the parent we create an instance of the child. var valConstructor = styleMap[val]; if (styleConstructor && valConstructor && valConstructor.prototype instanceof styleMap[styleName]) { console.assert(array.length === 1, 'Extra parameters for ' + styleName); styleObject = recursiveStyle(style, val); return optionalFactory(styleObject, valConstructor); } else { styleObject[val] = recursiveStyle(style, val); // if the value is 'text' and it contains a String, then it should be interpreted // as such, 'cause the text style might effectively contain a text to display if (val !== 'text' && typeof styleObject[val] !== 'string') { styleObject[val] = optionalFactory(styleObject[val], styleMap[val]); } } }); } else { styleObject = style; } return optionalFactory(styleObject, styleMap[styleName]); }
[ "function", "recursiveStyle", "(", "data", ",", "styleName", ")", "{", "var", "style", ";", "if", "(", "!", "styleName", ")", "{", "styleName", "=", "'style'", ";", "style", "=", "data", ";", "}", "else", "{", "style", "=", "data", "[", "styleName", "]", ";", "}", "//Instead of defining one style for the layer, we've been given a style function", "//to apply to each feature.", "if", "(", "styleName", "===", "'style'", "&&", "data", "instanceof", "Function", ")", "{", "return", "data", ";", "}", "if", "(", "!", "(", "style", "instanceof", "Object", ")", ")", "{", "return", "style", ";", "}", "var", "styleObject", ";", "if", "(", "Object", ".", "prototype", ".", "toString", ".", "call", "(", "style", ")", "===", "'[object Object]'", ")", "{", "styleObject", "=", "{", "}", ";", "var", "styleConstructor", "=", "styleMap", "[", "styleName", "]", ";", "if", "(", "styleConstructor", "&&", "style", "instanceof", "styleConstructor", ")", "{", "return", "style", ";", "}", "Object", ".", "getOwnPropertyNames", "(", "style", ")", ".", "forEach", "(", "function", "(", "val", ",", "idx", ",", "array", ")", "{", "//Consider the case", "//image: {", "// circle: {", "// fill: {", "// color: 'red'", "// }", "// }", "//", "//An ol.style.Circle is an instance of ol.style.Image, so we do not want to construct", "//an Image and then construct a Circle. We assume that if we have an instanceof", "//relationship, that the JSON parent has exactly one child.", "//We check to see if an inheritance relationship exists.", "//If it does, then for the parent we create an instance of the child.", "var", "valConstructor", "=", "styleMap", "[", "val", "]", ";", "if", "(", "styleConstructor", "&&", "valConstructor", "&&", "valConstructor", ".", "prototype", "instanceof", "styleMap", "[", "styleName", "]", ")", "{", "console", ".", "assert", "(", "array", ".", "length", "===", "1", ",", "'Extra parameters for '", "+", "styleName", ")", ";", "styleObject", "=", "recursiveStyle", "(", "style", ",", "val", ")", ";", "return", "optionalFactory", "(", "styleObject", ",", "valConstructor", ")", ";", "}", "else", "{", "styleObject", "[", "val", "]", "=", "recursiveStyle", "(", "style", ",", "val", ")", ";", "// if the value is 'text' and it contains a String, then it should be interpreted", "// as such, 'cause the text style might effectively contain a text to display", "if", "(", "val", "!==", "'text'", "&&", "typeof", "styleObject", "[", "val", "]", "!==", "'string'", ")", "{", "styleObject", "[", "val", "]", "=", "optionalFactory", "(", "styleObject", "[", "val", "]", ",", "styleMap", "[", "val", "]", ")", ";", "}", "}", "}", ")", ";", "}", "else", "{", "styleObject", "=", "style", ";", "}", "return", "optionalFactory", "(", "styleObject", ",", "styleMap", "[", "styleName", "]", ")", ";", "}" ]
Parse the style tree calling the appropriate constructors. The keys in styleMap can be used and the OpenLayers constructors can be used directly.
[ "Parse", "the", "style", "tree", "calling", "the", "appropriate", "constructors", ".", "The", "keys", "in", "styleMap", "can", "be", "used", "and", "the", "OpenLayers", "constructors", "can", "be", "used", "directly", "." ]
ead60778361ff86fd8c39c58cab93b1ec80873fb
https://github.com/tombatossals/angular-openlayers-directive/blob/ead60778361ff86fd8c39c58cab93b1ec80873fb/src/services/olHelpers.js#L80-L139
22,339
juttle/juttle
lib/runtime/modules/math.js
function(seed) { if (!values.isNumber(seed)) { throw errors.typeErrorFunction('Math.seed', 'number', seed); } _random = seedrandom(seed); return null; }
javascript
function(seed) { if (!values.isNumber(seed)) { throw errors.typeErrorFunction('Math.seed', 'number', seed); } _random = seedrandom(seed); return null; }
[ "function", "(", "seed", ")", "{", "if", "(", "!", "values", ".", "isNumber", "(", "seed", ")", ")", "{", "throw", "errors", ".", "typeErrorFunction", "(", "'Math.seed'", ",", "'number'", ",", "seed", ")", ";", "}", "_random", "=", "seedrandom", "(", "seed", ")", ";", "return", "null", ";", "}" ]
juttle's global RNG
[ "juttle", "s", "global", "RNG" ]
21b49f96a0e0b2098de1673c3645a6cb673ea5a8
https://github.com/juttle/juttle/blob/21b49f96a0e0b2098de1673c3645a6cb673ea5a8/lib/runtime/modules/math.js#L37-L43
22,340
juttle/juttle
lib/compiler/optimize/optimize.js
optimize
function optimize(graph, Juttle) { var reads = _.where(graph.get_roots(), {type: 'ReadProc'}); _.each(reads, function(node) {optimize_read(node, graph, Juttle);}); }
javascript
function optimize(graph, Juttle) { var reads = _.where(graph.get_roots(), {type: 'ReadProc'}); _.each(reads, function(node) {optimize_read(node, graph, Juttle);}); }
[ "function", "optimize", "(", "graph", ",", "Juttle", ")", "{", "var", "reads", "=", "_", ".", "where", "(", "graph", ".", "get_roots", "(", ")", ",", "{", "type", ":", "'ReadProc'", "}", ")", ";", "_", ".", "each", "(", "reads", ",", "function", "(", "node", ")", "{", "optimize_read", "(", "node", ",", "graph", ",", "Juttle", ")", ";", "}", ")", ";", "}" ]
The flowgraph processor that is the main entry point for optimization. For each read proc in the graph, there are various optimizations that can be performed depending on what the adapter supports and the specific program structure. To implement this support, traverse the flowgraph and check for the various patterns that are candidates for optimization. For each pattern, call into the adapter to determine whether that pattern is something the adapter can optimize, and if so, stash the relevant optimization info in the flowgraph so it will be passed to the read invocation.
[ "The", "flowgraph", "processor", "that", "is", "the", "main", "entry", "point", "for", "optimization", ".", "For", "each", "read", "proc", "in", "the", "graph", "there", "are", "various", "optimizations", "that", "can", "be", "performed", "depending", "on", "what", "the", "adapter", "supports", "and", "the", "specific", "program", "structure", ".", "To", "implement", "this", "support", "traverse", "the", "flowgraph", "and", "check", "for", "the", "various", "patterns", "that", "are", "candidates", "for", "optimization", ".", "For", "each", "pattern", "call", "into", "the", "adapter", "to", "determine", "whether", "that", "pattern", "is", "something", "the", "adapter", "can", "optimize", "and", "if", "so", "stash", "the", "relevant", "optimization", "info", "in", "the", "flowgraph", "so", "it", "will", "be", "passed", "to", "the", "read", "invocation", "." ]
21b49f96a0e0b2098de1673c3645a6cb673ea5a8
https://github.com/juttle/juttle/blob/21b49f96a0e0b2098de1673c3645a6cb673ea5a8/lib/compiler/optimize/optimize.js#L100-L103
22,341
juttle/juttle
lib/compiler/ast-visitor.js
addVisitFunction
function addVisitFunction(type) { ASTVisitor.prototype['visit' + type] = function(node) { var self = this; var extraArgs = Array.prototype.slice.call(arguments, 1); if (DEBUG) { checkNode(node); } NODE_CHILDREN[type].forEach(function(property) { var value = node[property]; if (_.isArray(value)) { value.forEach(function(item) { if (item !== null) { self.visit.apply(self, [item].concat(extraArgs)); } }); } else if (value !== null && value !== undefined) { self.visit.apply(self, [value].concat(extraArgs)); } }); }; }
javascript
function addVisitFunction(type) { ASTVisitor.prototype['visit' + type] = function(node) { var self = this; var extraArgs = Array.prototype.slice.call(arguments, 1); if (DEBUG) { checkNode(node); } NODE_CHILDREN[type].forEach(function(property) { var value = node[property]; if (_.isArray(value)) { value.forEach(function(item) { if (item !== null) { self.visit.apply(self, [item].concat(extraArgs)); } }); } else if (value !== null && value !== undefined) { self.visit.apply(self, [value].concat(extraArgs)); } }); }; }
[ "function", "addVisitFunction", "(", "type", ")", "{", "ASTVisitor", ".", "prototype", "[", "'visit'", "+", "type", "]", "=", "function", "(", "node", ")", "{", "var", "self", "=", "this", ";", "var", "extraArgs", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ",", "1", ")", ";", "if", "(", "DEBUG", ")", "{", "checkNode", "(", "node", ")", ";", "}", "NODE_CHILDREN", "[", "type", "]", ".", "forEach", "(", "function", "(", "property", ")", "{", "var", "value", "=", "node", "[", "property", "]", ";", "if", "(", "_", ".", "isArray", "(", "value", ")", ")", "{", "value", ".", "forEach", "(", "function", "(", "item", ")", "{", "if", "(", "item", "!==", "null", ")", "{", "self", ".", "visit", ".", "apply", "(", "self", ",", "[", "item", "]", ".", "concat", "(", "extraArgs", ")", ")", ";", "}", "}", ")", ";", "}", "else", "if", "(", "value", "!==", "null", "&&", "value", "!==", "undefined", ")", "{", "self", ".", "visit", ".", "apply", "(", "self", ",", "[", "value", "]", ".", "concat", "(", "extraArgs", ")", ")", ";", "}", "}", ")", ";", "}", ";", "}" ]
END DEBUGGING FUNCTIONS
[ "END", "DEBUGGING", "FUNCTIONS" ]
21b49f96a0e0b2098de1673c3645a6cb673ea5a8
https://github.com/juttle/juttle/blob/21b49f96a0e0b2098de1673c3645a6cb673ea5a8/lib/compiler/ast-visitor.js#L188-L211
22,342
juttle/juttle
lib/compiler/flowgraph/implicit_views.js
implicit_views
function implicit_views(g, options) { var default_view = options.default_view || 'table'; var leaves = g.get_leaves(); var table; _.each(leaves, function(node) { if (!is_sink(node)) { table = g.add_node('View', default_view); g.add_edge(node, table); } }); }
javascript
function implicit_views(g, options) { var default_view = options.default_view || 'table'; var leaves = g.get_leaves(); var table; _.each(leaves, function(node) { if (!is_sink(node)) { table = g.add_node('View', default_view); g.add_edge(node, table); } }); }
[ "function", "implicit_views", "(", "g", ",", "options", ")", "{", "var", "default_view", "=", "options", ".", "default_view", "||", "'table'", ";", "var", "leaves", "=", "g", ".", "get_leaves", "(", ")", ";", "var", "table", ";", "_", ".", "each", "(", "leaves", ",", "function", "(", "node", ")", "{", "if", "(", "!", "is_sink", "(", "node", ")", ")", "{", "table", "=", "g", ".", "add_node", "(", "'View'", ",", "default_view", ")", ";", "g", ".", "add_edge", "(", "node", ",", "table", ")", ";", "}", "}", ")", ";", "}" ]
Generate a graph builder that adds an implicit sink of the given type to any branches of the graph that don't already end in a sink.
[ "Generate", "a", "graph", "builder", "that", "adds", "an", "implicit", "sink", "of", "the", "given", "type", "to", "any", "branches", "of", "the", "graph", "that", "don", "t", "already", "end", "in", "a", "sink", "." ]
21b49f96a0e0b2098de1673c3645a6cb673ea5a8
https://github.com/juttle/juttle/blob/21b49f96a0e0b2098de1673c3645a6cb673ea5a8/lib/compiler/flowgraph/implicit_views.js#L8-L19
22,343
juttle/juttle
lib/errors.js
locate
function locate(fn, location) { try { return fn(); } catch (e) { if (e instanceof JuttleError && !e.info.location) { e.info.location = location; } throw e; } }
javascript
function locate(fn, location) { try { return fn(); } catch (e) { if (e instanceof JuttleError && !e.info.location) { e.info.location = location; } throw e; } }
[ "function", "locate", "(", "fn", ",", "location", ")", "{", "try", "{", "return", "fn", "(", ")", ";", "}", "catch", "(", "e", ")", "{", "if", "(", "e", "instanceof", "JuttleError", "&&", "!", "e", ".", "info", ".", "location", ")", "{", "e", ".", "info", ".", "location", "=", "location", ";", "}", "throw", "e", ";", "}", "}" ]
Adds specified location to any Juttle exception thrown when executing specified function. If the function does not throw any exception, returns its result.
[ "Adds", "specified", "location", "to", "any", "Juttle", "exception", "thrown", "when", "executing", "specified", "function", ".", "If", "the", "function", "does", "not", "throw", "any", "exception", "returns", "its", "result", "." ]
21b49f96a0e0b2098de1673c3645a6cb673ea5a8
https://github.com/juttle/juttle/blob/21b49f96a0e0b2098de1673c3645a6cb673ea5a8/lib/errors.js#L96-L106
22,344
juttle/juttle
lib/runtime/values.js
function(value) { switch (typeof value) { case 'boolean': return 'Boolean'; case 'number': return 'Number'; case 'string': return 'String'; case 'object': if (value === null) { return 'Null'; } else { switch (Object.prototype.toString.call(value)) { case '[object RegExp]': return 'RegExp'; case '[object Array]': return 'Array'; case '[object Object]': switch (value.constructor) { case JuttleMoment: if (value.moment) { return 'Date'; } if (value.duration) { return 'Duration'; } break; // silence ESLint case Filter: return 'Filter'; case Object: return 'Object'; } } } } throw new Error('Invalid Juttle value: ' + value + '.'); }
javascript
function(value) { switch (typeof value) { case 'boolean': return 'Boolean'; case 'number': return 'Number'; case 'string': return 'String'; case 'object': if (value === null) { return 'Null'; } else { switch (Object.prototype.toString.call(value)) { case '[object RegExp]': return 'RegExp'; case '[object Array]': return 'Array'; case '[object Object]': switch (value.constructor) { case JuttleMoment: if (value.moment) { return 'Date'; } if (value.duration) { return 'Duration'; } break; // silence ESLint case Filter: return 'Filter'; case Object: return 'Object'; } } } } throw new Error('Invalid Juttle value: ' + value + '.'); }
[ "function", "(", "value", ")", "{", "switch", "(", "typeof", "value", ")", "{", "case", "'boolean'", ":", "return", "'Boolean'", ";", "case", "'number'", ":", "return", "'Number'", ";", "case", "'string'", ":", "return", "'String'", ";", "case", "'object'", ":", "if", "(", "value", "===", "null", ")", "{", "return", "'Null'", ";", "}", "else", "{", "switch", "(", "Object", ".", "prototype", ".", "toString", ".", "call", "(", "value", ")", ")", "{", "case", "'[object RegExp]'", ":", "return", "'RegExp'", ";", "case", "'[object Array]'", ":", "return", "'Array'", ";", "case", "'[object Object]'", ":", "switch", "(", "value", ".", "constructor", ")", "{", "case", "JuttleMoment", ":", "if", "(", "value", ".", "moment", ")", "{", "return", "'Date'", ";", "}", "if", "(", "value", ".", "duration", ")", "{", "return", "'Duration'", ";", "}", "break", ";", "// silence ESLint", "case", "Filter", ":", "return", "'Filter'", ";", "case", "Object", ":", "return", "'Object'", ";", "}", "}", "}", "}", "throw", "new", "Error", "(", "'Invalid Juttle value: '", "+", "value", "+", "'.'", ")", ";", "}" ]
Returns a Juttle type represented by a JavaScript value. Throws an exception if the JavaScript value doesn't represent any Juttle type.
[ "Returns", "a", "Juttle", "type", "represented", "by", "a", "JavaScript", "value", ".", "Throws", "an", "exception", "if", "the", "JavaScript", "value", "doesn", "t", "represent", "any", "Juttle", "type", "." ]
21b49f96a0e0b2098de1673c3645a6cb673ea5a8
https://github.com/juttle/juttle/blob/21b49f96a0e0b2098de1673c3645a6cb673ea5a8/lib/runtime/values.js#L99-L143
22,345
juttle/juttle
lib/runtime/values.js
function(a, b) { var self = this; function equalArrays(a, b) { if (a.length !== b.length) { return false; } var length = a.length; var i; for (i = 0; i < length; i++) { if (!self.equal(a[i], b[i])) { return false; } } return true; } function equalObjects(a, b) { var keysA = Object.keys(a); var keysB = Object.keys(b); keysA.sort(); keysB.sort(); if (keysA.length !== keysB.length) { return false; } var length = keysA.length; var i; var key; for (i = 0; i < length; i++) { if (keysA[i] !== keysB[i]) { return false; } key = keysA[i]; if (!self.equal(a[key], b[key])) { return false; } } return true; } var typeA = this.typeOf(a); var typeB = this.typeOf(b); if (typeA !== typeB) { return false; } switch (typeA) { case 'Null': case 'Boolean': case 'Number': case 'String': case 'Filter': return a === b; case 'RegExp': return a.source === b.source && a.global === b.global && a.multiline === b.multiline && a.ignoreCase === b.ignoreCase; case 'Date': case 'Duration': return JuttleMoment.eq(a, b); case 'Array': return equalArrays(a, b); case 'Object': return equalObjects(a, b); } }
javascript
function(a, b) { var self = this; function equalArrays(a, b) { if (a.length !== b.length) { return false; } var length = a.length; var i; for (i = 0; i < length; i++) { if (!self.equal(a[i], b[i])) { return false; } } return true; } function equalObjects(a, b) { var keysA = Object.keys(a); var keysB = Object.keys(b); keysA.sort(); keysB.sort(); if (keysA.length !== keysB.length) { return false; } var length = keysA.length; var i; var key; for (i = 0; i < length; i++) { if (keysA[i] !== keysB[i]) { return false; } key = keysA[i]; if (!self.equal(a[key], b[key])) { return false; } } return true; } var typeA = this.typeOf(a); var typeB = this.typeOf(b); if (typeA !== typeB) { return false; } switch (typeA) { case 'Null': case 'Boolean': case 'Number': case 'String': case 'Filter': return a === b; case 'RegExp': return a.source === b.source && a.global === b.global && a.multiline === b.multiline && a.ignoreCase === b.ignoreCase; case 'Date': case 'Duration': return JuttleMoment.eq(a, b); case 'Array': return equalArrays(a, b); case 'Object': return equalObjects(a, b); } }
[ "function", "(", "a", ",", "b", ")", "{", "var", "self", "=", "this", ";", "function", "equalArrays", "(", "a", ",", "b", ")", "{", "if", "(", "a", ".", "length", "!==", "b", ".", "length", ")", "{", "return", "false", ";", "}", "var", "length", "=", "a", ".", "length", ";", "var", "i", ";", "for", "(", "i", "=", "0", ";", "i", "<", "length", ";", "i", "++", ")", "{", "if", "(", "!", "self", ".", "equal", "(", "a", "[", "i", "]", ",", "b", "[", "i", "]", ")", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}", "function", "equalObjects", "(", "a", ",", "b", ")", "{", "var", "keysA", "=", "Object", ".", "keys", "(", "a", ")", ";", "var", "keysB", "=", "Object", ".", "keys", "(", "b", ")", ";", "keysA", ".", "sort", "(", ")", ";", "keysB", ".", "sort", "(", ")", ";", "if", "(", "keysA", ".", "length", "!==", "keysB", ".", "length", ")", "{", "return", "false", ";", "}", "var", "length", "=", "keysA", ".", "length", ";", "var", "i", ";", "var", "key", ";", "for", "(", "i", "=", "0", ";", "i", "<", "length", ";", "i", "++", ")", "{", "if", "(", "keysA", "[", "i", "]", "!==", "keysB", "[", "i", "]", ")", "{", "return", "false", ";", "}", "key", "=", "keysA", "[", "i", "]", ";", "if", "(", "!", "self", ".", "equal", "(", "a", "[", "key", "]", ",", "b", "[", "key", "]", ")", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}", "var", "typeA", "=", "this", ".", "typeOf", "(", "a", ")", ";", "var", "typeB", "=", "this", ".", "typeOf", "(", "b", ")", ";", "if", "(", "typeA", "!==", "typeB", ")", "{", "return", "false", ";", "}", "switch", "(", "typeA", ")", "{", "case", "'Null'", ":", "case", "'Boolean'", ":", "case", "'Number'", ":", "case", "'String'", ":", "case", "'Filter'", ":", "return", "a", "===", "b", ";", "case", "'RegExp'", ":", "return", "a", ".", "source", "===", "b", ".", "source", "&&", "a", ".", "global", "===", "b", ".", "global", "&&", "a", ".", "multiline", "===", "b", ".", "multiline", "&&", "a", ".", "ignoreCase", "===", "b", ".", "ignoreCase", ";", "case", "'Date'", ":", "case", "'Duration'", ":", "return", "JuttleMoment", ".", "eq", "(", "a", ",", "b", ")", ";", "case", "'Array'", ":", "return", "equalArrays", "(", "a", ",", "b", ")", ";", "case", "'Object'", ":", "return", "equalObjects", "(", "a", ",", "b", ")", ";", "}", "}" ]
Determines whether two Juttle values are equal.
[ "Determines", "whether", "two", "Juttle", "values", "are", "equal", "." ]
21b49f96a0e0b2098de1673c3645a6cb673ea5a8
https://github.com/juttle/juttle/blob/21b49f96a0e0b2098de1673c3645a6cb673ea5a8/lib/runtime/values.js#L290-L368
22,346
juttle/juttle
lib/runtime/values.js
function(value) { switch (values.typeOf(value)) { case 'Null': case 'Boolean': case 'String': case 'Number': return value; case 'RegExp': return String(value); case 'Date': case 'Duration': return value.valueOf(); case 'Filter': return value.source; case 'Array': return _.map(value, this.toJSONCompatible, this); case 'Object': return _.mapObject(value, this.toJSONCompatible, this); } }
javascript
function(value) { switch (values.typeOf(value)) { case 'Null': case 'Boolean': case 'String': case 'Number': return value; case 'RegExp': return String(value); case 'Date': case 'Duration': return value.valueOf(); case 'Filter': return value.source; case 'Array': return _.map(value, this.toJSONCompatible, this); case 'Object': return _.mapObject(value, this.toJSONCompatible, this); } }
[ "function", "(", "value", ")", "{", "switch", "(", "values", ".", "typeOf", "(", "value", ")", ")", "{", "case", "'Null'", ":", "case", "'Boolean'", ":", "case", "'String'", ":", "case", "'Number'", ":", "return", "value", ";", "case", "'RegExp'", ":", "return", "String", "(", "value", ")", ";", "case", "'Date'", ":", "case", "'Duration'", ":", "return", "value", ".", "valueOf", "(", ")", ";", "case", "'Filter'", ":", "return", "value", ".", "source", ";", "case", "'Array'", ":", "return", "_", ".", "map", "(", "value", ",", "this", ".", "toJSONCompatible", ",", "this", ")", ";", "case", "'Object'", ":", "return", "_", ".", "mapObject", "(", "value", ",", "this", ".", "toJSONCompatible", ",", "this", ")", ";", "}", "}" ]
Returns a value that can be serialized to JSON.
[ "Returns", "a", "value", "that", "can", "be", "serialized", "to", "JSON", "." ]
21b49f96a0e0b2098de1673c3645a6cb673ea5a8
https://github.com/juttle/juttle/blob/21b49f96a0e0b2098de1673c3645a6cb673ea5a8/lib/runtime/values.js#L371-L395
22,347
juttle/juttle
lib/runtime/values.js
function(value) { switch (values.typeOf(value)) { case 'Null': return { type: 'NullLiteral' }; case 'Boolean': return { type: 'BooleanLiteral', value: value }; case 'Number': if (value !== value) { return { type: 'NaNLiteral' }; } else if (value === Infinity) { return { type: 'InfinityLiteral', negative: false }; } else if (value === -Infinity) { return { type: 'InfinityLiteral', negative: true }; } else { return { type: 'NumberLiteral', value: value }; } break; // silence ESLint case 'String': return { type: 'StringLiteral', value: value }; case 'RegExp': return { type: 'RegExpLiteral', pattern: value.source, flags: value.toString().match(/\/(\w*)$/)[1] }; case 'Date': return { type: 'MomentLiteral', value: value.valueOf() }; case 'Duration': return { type: 'DurationLiteral', value: value.valueOf() }; case 'Filter': return { type: 'FilterLiteral', ast: value.ast, source: value.source }; case 'Array': return { type: 'ArrayLiteral', elements: _.map(value, values.toAST) }; case 'Object': return { type: 'ObjectLiteral', properties: _.map(value, function(value, key) { return { type: 'ObjectProperty', key: values.toAST(key), value: values.toAST(value) }; }) }; } }
javascript
function(value) { switch (values.typeOf(value)) { case 'Null': return { type: 'NullLiteral' }; case 'Boolean': return { type: 'BooleanLiteral', value: value }; case 'Number': if (value !== value) { return { type: 'NaNLiteral' }; } else if (value === Infinity) { return { type: 'InfinityLiteral', negative: false }; } else if (value === -Infinity) { return { type: 'InfinityLiteral', negative: true }; } else { return { type: 'NumberLiteral', value: value }; } break; // silence ESLint case 'String': return { type: 'StringLiteral', value: value }; case 'RegExp': return { type: 'RegExpLiteral', pattern: value.source, flags: value.toString().match(/\/(\w*)$/)[1] }; case 'Date': return { type: 'MomentLiteral', value: value.valueOf() }; case 'Duration': return { type: 'DurationLiteral', value: value.valueOf() }; case 'Filter': return { type: 'FilterLiteral', ast: value.ast, source: value.source }; case 'Array': return { type: 'ArrayLiteral', elements: _.map(value, values.toAST) }; case 'Object': return { type: 'ObjectLiteral', properties: _.map(value, function(value, key) { return { type: 'ObjectProperty', key: values.toAST(key), value: values.toAST(value) }; }) }; } }
[ "function", "(", "value", ")", "{", "switch", "(", "values", ".", "typeOf", "(", "value", ")", ")", "{", "case", "'Null'", ":", "return", "{", "type", ":", "'NullLiteral'", "}", ";", "case", "'Boolean'", ":", "return", "{", "type", ":", "'BooleanLiteral'", ",", "value", ":", "value", "}", ";", "case", "'Number'", ":", "if", "(", "value", "!==", "value", ")", "{", "return", "{", "type", ":", "'NaNLiteral'", "}", ";", "}", "else", "if", "(", "value", "===", "Infinity", ")", "{", "return", "{", "type", ":", "'InfinityLiteral'", ",", "negative", ":", "false", "}", ";", "}", "else", "if", "(", "value", "===", "-", "Infinity", ")", "{", "return", "{", "type", ":", "'InfinityLiteral'", ",", "negative", ":", "true", "}", ";", "}", "else", "{", "return", "{", "type", ":", "'NumberLiteral'", ",", "value", ":", "value", "}", ";", "}", "break", ";", "// silence ESLint", "case", "'String'", ":", "return", "{", "type", ":", "'StringLiteral'", ",", "value", ":", "value", "}", ";", "case", "'RegExp'", ":", "return", "{", "type", ":", "'RegExpLiteral'", ",", "pattern", ":", "value", ".", "source", ",", "flags", ":", "value", ".", "toString", "(", ")", ".", "match", "(", "/", "\\/(\\w*)$", "/", ")", "[", "1", "]", "}", ";", "case", "'Date'", ":", "return", "{", "type", ":", "'MomentLiteral'", ",", "value", ":", "value", ".", "valueOf", "(", ")", "}", ";", "case", "'Duration'", ":", "return", "{", "type", ":", "'DurationLiteral'", ",", "value", ":", "value", ".", "valueOf", "(", ")", "}", ";", "case", "'Filter'", ":", "return", "{", "type", ":", "'FilterLiteral'", ",", "ast", ":", "value", ".", "ast", ",", "source", ":", "value", ".", "source", "}", ";", "case", "'Array'", ":", "return", "{", "type", ":", "'ArrayLiteral'", ",", "elements", ":", "_", ".", "map", "(", "value", ",", "values", ".", "toAST", ")", "}", ";", "case", "'Object'", ":", "return", "{", "type", ":", "'ObjectLiteral'", ",", "properties", ":", "_", ".", "map", "(", "value", ",", "function", "(", "value", ",", "key", ")", "{", "return", "{", "type", ":", "'ObjectProperty'", ",", "key", ":", "values", ".", "toAST", "(", "key", ")", ",", "value", ":", "values", ".", "toAST", "(", "value", ")", "}", ";", "}", ")", "}", ";", "}", "}" ]
Returns an AST corresponding to a Juttle value.
[ "Returns", "an", "AST", "corresponding", "to", "a", "Juttle", "value", "." ]
21b49f96a0e0b2098de1673c3645a6cb673ea5a8
https://github.com/juttle/juttle/blob/21b49f96a0e0b2098de1673c3645a6cb673ea5a8/lib/runtime/values.js#L483-L537
22,348
juttle/juttle
lib/compiler/flowgraph/program_stats.js
extract_program_stats
function extract_program_stats(prog) { var stats = {}; var sources_array = source_stats(prog); stats.inputs = input_stats(prog); stats.input_total = count_procs(stats.inputs); stats.sources = sources_array; stats.source_total = sources_array.length; stats.reducers = reducer_stats(prog); stats.reducer_total = count_procs(stats.reducers); stats.functions = function_stats(prog); stats.procs = proc_stats(prog); stats.proc_total = count_procs(stats.procs); stats.views = view_stats(prog); stats.view_total = count_procs(stats.views); stats.subs = sub_stats(prog); stats.imports = import_stats(prog); return stats; }
javascript
function extract_program_stats(prog) { var stats = {}; var sources_array = source_stats(prog); stats.inputs = input_stats(prog); stats.input_total = count_procs(stats.inputs); stats.sources = sources_array; stats.source_total = sources_array.length; stats.reducers = reducer_stats(prog); stats.reducer_total = count_procs(stats.reducers); stats.functions = function_stats(prog); stats.procs = proc_stats(prog); stats.proc_total = count_procs(stats.procs); stats.views = view_stats(prog); stats.view_total = count_procs(stats.views); stats.subs = sub_stats(prog); stats.imports = import_stats(prog); return stats; }
[ "function", "extract_program_stats", "(", "prog", ")", "{", "var", "stats", "=", "{", "}", ";", "var", "sources_array", "=", "source_stats", "(", "prog", ")", ";", "stats", ".", "inputs", "=", "input_stats", "(", "prog", ")", ";", "stats", ".", "input_total", "=", "count_procs", "(", "stats", ".", "inputs", ")", ";", "stats", ".", "sources", "=", "sources_array", ";", "stats", ".", "source_total", "=", "sources_array", ".", "length", ";", "stats", ".", "reducers", "=", "reducer_stats", "(", "prog", ")", ";", "stats", ".", "reducer_total", "=", "count_procs", "(", "stats", ".", "reducers", ")", ";", "stats", ".", "functions", "=", "function_stats", "(", "prog", ")", ";", "stats", ".", "procs", "=", "proc_stats", "(", "prog", ")", ";", "stats", ".", "proc_total", "=", "count_procs", "(", "stats", ".", "procs", ")", ";", "stats", ".", "views", "=", "view_stats", "(", "prog", ")", ";", "stats", ".", "view_total", "=", "count_procs", "(", "stats", ".", "views", ")", ";", "stats", ".", "subs", "=", "sub_stats", "(", "prog", ")", ";", "stats", ".", "imports", "=", "import_stats", "(", "prog", ")", ";", "return", "stats", ";", "}" ]
Call this with a Program object
[ "Call", "this", "with", "a", "Program", "object" ]
21b49f96a0e0b2098de1673c3645a6cb673ea5a8
https://github.com/juttle/juttle/blob/21b49f96a0e0b2098de1673c3645a6cb673ea5a8/lib/compiler/flowgraph/program_stats.js#L161-L179
22,349
juttle/juttle
lib/runtime/adapters.js
loadAdapter
function loadAdapter(type, location) { var options = adapterConfig[type]; try { var modulePath = adapterModulePath(type, options); global.JuttleAdapterAPI = JuttleAdapterAPI; var start = new Date(); if (!options.builtin) { checkCompatible(type, modulePath, location); } var init = require(modulePath); var loaded = new Date(); var adapter = init(options); global.JuttleAdapterAPI = undefined; if (adapter.name !== type) { throw new Error('adapter name ', adapter.name, ' != type ', type); } var initialized = new Date(); logger.debug(adapter.name, 'adapter loaded in', (loaded - start), 'ms,', 'initialized in', (initialized - loaded), 'ms'); register(adapter.name, adapter); return adapter; } catch (err) { logger.error('error loading adapter ' + type + ': ' + err.message); throw err; } }
javascript
function loadAdapter(type, location) { var options = adapterConfig[type]; try { var modulePath = adapterModulePath(type, options); global.JuttleAdapterAPI = JuttleAdapterAPI; var start = new Date(); if (!options.builtin) { checkCompatible(type, modulePath, location); } var init = require(modulePath); var loaded = new Date(); var adapter = init(options); global.JuttleAdapterAPI = undefined; if (adapter.name !== type) { throw new Error('adapter name ', adapter.name, ' != type ', type); } var initialized = new Date(); logger.debug(adapter.name, 'adapter loaded in', (loaded - start), 'ms,', 'initialized in', (initialized - loaded), 'ms'); register(adapter.name, adapter); return adapter; } catch (err) { logger.error('error loading adapter ' + type + ': ' + err.message); throw err; } }
[ "function", "loadAdapter", "(", "type", ",", "location", ")", "{", "var", "options", "=", "adapterConfig", "[", "type", "]", ";", "try", "{", "var", "modulePath", "=", "adapterModulePath", "(", "type", ",", "options", ")", ";", "global", ".", "JuttleAdapterAPI", "=", "JuttleAdapterAPI", ";", "var", "start", "=", "new", "Date", "(", ")", ";", "if", "(", "!", "options", ".", "builtin", ")", "{", "checkCompatible", "(", "type", ",", "modulePath", ",", "location", ")", ";", "}", "var", "init", "=", "require", "(", "modulePath", ")", ";", "var", "loaded", "=", "new", "Date", "(", ")", ";", "var", "adapter", "=", "init", "(", "options", ")", ";", "global", ".", "JuttleAdapterAPI", "=", "undefined", ";", "if", "(", "adapter", ".", "name", "!==", "type", ")", "{", "throw", "new", "Error", "(", "'adapter name '", ",", "adapter", ".", "name", ",", "' != type '", ",", "type", ")", ";", "}", "var", "initialized", "=", "new", "Date", "(", ")", ";", "logger", ".", "debug", "(", "adapter", ".", "name", ",", "'adapter loaded in'", ",", "(", "loaded", "-", "start", ")", ",", "'ms,'", ",", "'initialized in'", ",", "(", "initialized", "-", "loaded", ")", ",", "'ms'", ")", ";", "register", "(", "adapter", ".", "name", ",", "adapter", ")", ";", "return", "adapter", ";", "}", "catch", "(", "err", ")", "{", "logger", ".", "error", "(", "'error loading adapter '", "+", "type", "+", "': '", "+", "err", ".", "message", ")", ";", "throw", "err", ";", "}", "}" ]
Load the adapter of the given type.
[ "Load", "the", "adapter", "of", "the", "given", "type", "." ]
21b49f96a0e0b2098de1673c3645a6cb673ea5a8
https://github.com/juttle/juttle/blob/21b49f96a0e0b2098de1673c3645a6cb673ea5a8/lib/runtime/adapters.js#L62-L97
22,350
juttle/juttle
lib/runtime/adapters.js
checkCompatible
function checkCompatible(type, modulePath, location) { var adapterPackage = require(path.join(modulePath, 'package.json')); var adapterJuttleVersion = adapterPackage.juttleAdapterAPI; if (!adapterJuttleVersion) { throw errors.compileError('INCOMPATIBLE-ADAPTER', { type, adapterJuttleVersion: '(unknown)', apiVersion: JuttleAdapterAPI.version, location }); } if (!semver.satisfies(JuttleAdapterAPI.version, adapterJuttleVersion)) { throw errors.compileError('INCOMPATIBLE-ADAPTER', { type, adapterJuttleVersion, apiVersion: JuttleAdapterAPI.version, location }); } }
javascript
function checkCompatible(type, modulePath, location) { var adapterPackage = require(path.join(modulePath, 'package.json')); var adapterJuttleVersion = adapterPackage.juttleAdapterAPI; if (!adapterJuttleVersion) { throw errors.compileError('INCOMPATIBLE-ADAPTER', { type, adapterJuttleVersion: '(unknown)', apiVersion: JuttleAdapterAPI.version, location }); } if (!semver.satisfies(JuttleAdapterAPI.version, adapterJuttleVersion)) { throw errors.compileError('INCOMPATIBLE-ADAPTER', { type, adapterJuttleVersion, apiVersion: JuttleAdapterAPI.version, location }); } }
[ "function", "checkCompatible", "(", "type", ",", "modulePath", ",", "location", ")", "{", "var", "adapterPackage", "=", "require", "(", "path", ".", "join", "(", "modulePath", ",", "'package.json'", ")", ")", ";", "var", "adapterJuttleVersion", "=", "adapterPackage", ".", "juttleAdapterAPI", ";", "if", "(", "!", "adapterJuttleVersion", ")", "{", "throw", "errors", ".", "compileError", "(", "'INCOMPATIBLE-ADAPTER'", ",", "{", "type", ",", "adapterJuttleVersion", ":", "'(unknown)'", ",", "apiVersion", ":", "JuttleAdapterAPI", ".", "version", ",", "location", "}", ")", ";", "}", "if", "(", "!", "semver", ".", "satisfies", "(", "JuttleAdapterAPI", ".", "version", ",", "adapterJuttleVersion", ")", ")", "{", "throw", "errors", ".", "compileError", "(", "'INCOMPATIBLE-ADAPTER'", ",", "{", "type", ",", "adapterJuttleVersion", ",", "apiVersion", ":", "JuttleAdapterAPI", ".", "version", ",", "location", "}", ")", ";", "}", "}" ]
Check whether the given adapter is compatible with this version of the juttle runtime by extracting the juttleAdapterAPI entry from the adapter's package.json and comparing it to the declared version of the API.
[ "Check", "whether", "the", "given", "adapter", "is", "compatible", "with", "this", "version", "of", "the", "juttle", "runtime", "by", "extracting", "the", "juttleAdapterAPI", "entry", "from", "the", "adapter", "s", "package", ".", "json", "and", "comparing", "it", "to", "the", "declared", "version", "of", "the", "API", "." ]
21b49f96a0e0b2098de1673c3645a6cb673ea5a8
https://github.com/juttle/juttle/blob/21b49f96a0e0b2098de1673c3645a6cb673ea5a8/lib/runtime/adapters.js#L102-L122
22,351
juttle/juttle
lib/runtime/adapters.js
configure
function configure(config) { config = config || {}; logger.debug('configuring adapters', _.keys(config).join(',')); _.extend(adapterConfig, _.clone(config)); logger.debug('configuring builtin adapters'); _.each(BUILTIN_ADAPTERS, function(adapter) { adapterConfig[adapter] = { path: path.resolve(__dirname, '../adapters/' + adapter), builtin: true }; }); }
javascript
function configure(config) { config = config || {}; logger.debug('configuring adapters', _.keys(config).join(',')); _.extend(adapterConfig, _.clone(config)); logger.debug('configuring builtin adapters'); _.each(BUILTIN_ADAPTERS, function(adapter) { adapterConfig[adapter] = { path: path.resolve(__dirname, '../adapters/' + adapter), builtin: true }; }); }
[ "function", "configure", "(", "config", ")", "{", "config", "=", "config", "||", "{", "}", ";", "logger", ".", "debug", "(", "'configuring adapters'", ",", "_", ".", "keys", "(", "config", ")", ".", "join", "(", "','", ")", ")", ";", "_", ".", "extend", "(", "adapterConfig", ",", "_", ".", "clone", "(", "config", ")", ")", ";", "logger", ".", "debug", "(", "'configuring builtin adapters'", ")", ";", "_", ".", "each", "(", "BUILTIN_ADAPTERS", ",", "function", "(", "adapter", ")", "{", "adapterConfig", "[", "adapter", "]", "=", "{", "path", ":", "path", ".", "resolve", "(", "__dirname", ",", "'../adapters/'", "+", "adapter", ")", ",", "builtin", ":", "true", "}", ";", "}", ")", ";", "}" ]
Add configuration for the specified adapters but don't initialize them until they are actually used.
[ "Add", "configuration", "for", "the", "specified", "adapters", "but", "don", "t", "initialize", "them", "until", "they", "are", "actually", "used", "." ]
21b49f96a0e0b2098de1673c3645a6cb673ea5a8
https://github.com/juttle/juttle/blob/21b49f96a0e0b2098de1673c3645a6cb673ea5a8/lib/runtime/adapters.js#L126-L138
22,352
juttle/juttle
lib/runtime/adapters.js
list
function list() { var adapters = []; _.each(adapterConfig, function(config, adapter) { var modulePath = adapterModulePath(adapter, config); var version, installPath, moduleName; var isBuiltin = BUILTIN_ADAPTERS.indexOf(adapter) !== -1; var loaded = true; if (isBuiltin) { version = juttleVersion; installPath = Module._resolveFilename(modulePath, module); moduleName = '(builtin)'; } else { try { var packagePath = path.join(modulePath, 'package'); var pkg = require(packagePath); installPath = path.dirname(Module._resolveFilename(packagePath, module)); version = pkg.version || '(unknown)'; moduleName = pkg.name; } catch (err) { installPath = '(unable to load adapter)'; version = '(unknown)'; moduleName = '(unknown)'; loaded = false; } } adapters.push({adapter: adapter, builtin: isBuiltin, module: moduleName, version: version, path: installPath, loaded: loaded}); }); return adapters; }
javascript
function list() { var adapters = []; _.each(adapterConfig, function(config, adapter) { var modulePath = adapterModulePath(adapter, config); var version, installPath, moduleName; var isBuiltin = BUILTIN_ADAPTERS.indexOf(adapter) !== -1; var loaded = true; if (isBuiltin) { version = juttleVersion; installPath = Module._resolveFilename(modulePath, module); moduleName = '(builtin)'; } else { try { var packagePath = path.join(modulePath, 'package'); var pkg = require(packagePath); installPath = path.dirname(Module._resolveFilename(packagePath, module)); version = pkg.version || '(unknown)'; moduleName = pkg.name; } catch (err) { installPath = '(unable to load adapter)'; version = '(unknown)'; moduleName = '(unknown)'; loaded = false; } } adapters.push({adapter: adapter, builtin: isBuiltin, module: moduleName, version: version, path: installPath, loaded: loaded}); }); return adapters; }
[ "function", "list", "(", ")", "{", "var", "adapters", "=", "[", "]", ";", "_", ".", "each", "(", "adapterConfig", ",", "function", "(", "config", ",", "adapter", ")", "{", "var", "modulePath", "=", "adapterModulePath", "(", "adapter", ",", "config", ")", ";", "var", "version", ",", "installPath", ",", "moduleName", ";", "var", "isBuiltin", "=", "BUILTIN_ADAPTERS", ".", "indexOf", "(", "adapter", ")", "!==", "-", "1", ";", "var", "loaded", "=", "true", ";", "if", "(", "isBuiltin", ")", "{", "version", "=", "juttleVersion", ";", "installPath", "=", "Module", ".", "_resolveFilename", "(", "modulePath", ",", "module", ")", ";", "moduleName", "=", "'(builtin)'", ";", "}", "else", "{", "try", "{", "var", "packagePath", "=", "path", ".", "join", "(", "modulePath", ",", "'package'", ")", ";", "var", "pkg", "=", "require", "(", "packagePath", ")", ";", "installPath", "=", "path", ".", "dirname", "(", "Module", ".", "_resolveFilename", "(", "packagePath", ",", "module", ")", ")", ";", "version", "=", "pkg", ".", "version", "||", "'(unknown)'", ";", "moduleName", "=", "pkg", ".", "name", ";", "}", "catch", "(", "err", ")", "{", "installPath", "=", "'(unable to load adapter)'", ";", "version", "=", "'(unknown)'", ";", "moduleName", "=", "'(unknown)'", ";", "loaded", "=", "false", ";", "}", "}", "adapters", ".", "push", "(", "{", "adapter", ":", "adapter", ",", "builtin", ":", "isBuiltin", ",", "module", ":", "moduleName", ",", "version", ":", "version", ",", "path", ":", "installPath", ",", "loaded", ":", "loaded", "}", ")", ";", "}", ")", ";", "return", "adapters", ";", "}" ]
Return a list of all configured adapters and their versions.
[ "Return", "a", "list", "of", "all", "configured", "adapters", "and", "their", "versions", "." ]
21b49f96a0e0b2098de1673c3645a6cb673ea5a8
https://github.com/juttle/juttle/blob/21b49f96a0e0b2098de1673c3645a6cb673ea5a8/lib/runtime/adapters.js#L141-L170
22,353
juttle/juttle
lib/runtime/procs/stoke/util.js
bound
function bound(val, min, max) { // trim the value to be within min..max (if min..max are specified) val = (min !== undefined)? Math.max(val, min) : val; val = (max !== undefined)? Math.min(val, max) : val; return val ; }
javascript
function bound(val, min, max) { // trim the value to be within min..max (if min..max are specified) val = (min !== undefined)? Math.max(val, min) : val; val = (max !== undefined)? Math.min(val, max) : val; return val ; }
[ "function", "bound", "(", "val", ",", "min", ",", "max", ")", "{", "// trim the value to be within min..max (if min..max are specified)", "val", "=", "(", "min", "!==", "undefined", ")", "?", "Math", ".", "max", "(", "val", ",", "min", ")", ":", "val", ";", "val", "=", "(", "max", "!==", "undefined", ")", "?", "Math", ".", "min", "(", "val", ",", "max", ")", ":", "val", ";", "return", "val", ";", "}" ]
useful stuff for random timeseries.
[ "useful", "stuff", "for", "random", "timeseries", "." ]
21b49f96a0e0b2098de1673c3645a6cb673ea5a8
https://github.com/juttle/juttle/blob/21b49f96a0e0b2098de1673c3645a6cb673ea5a8/lib/runtime/procs/stoke/util.js#L16-L21
22,354
juttle/juttle
lib/runtime/procs/reduce.js
reduce
function reduce(options, params, location, program) { return options.every? new reduce_every(options, params, location, program) : new reduce_batch(options, params, location, program); }
javascript
function reduce(options, params, location, program) { return options.every? new reduce_every(options, params, location, program) : new reduce_batch(options, params, location, program); }
[ "function", "reduce", "(", "options", ",", "params", ",", "location", ",", "program", ")", "{", "return", "options", ".", "every", "?", "new", "reduce_every", "(", "options", ",", "params", ",", "location", ",", "program", ")", ":", "new", "reduce_batch", "(", "options", ",", "params", ",", "location", ",", "program", ")", ";", "}" ]
juttle reduce. Whether you get a batch-driven reducer or a data-driven reducer with its own epochs is decided by the presence of an -every option to reduce.
[ "juttle", "reduce", ".", "Whether", "you", "get", "a", "batch", "-", "driven", "reducer", "or", "a", "data", "-", "driven", "reducer", "with", "its", "own", "epochs", "is", "decided", "by", "the", "presence", "of", "an", "-", "every", "option", "to", "reduce", "." ]
21b49f96a0e0b2098de1673c3645a6cb673ea5a8
https://github.com/juttle/juttle/blob/21b49f96a0e0b2098de1673c3645a6cb673ea5a8/lib/runtime/procs/reduce.js#L353-L355
22,355
makinacorpus/Leaflet.Snap
leaflet.snap.js
function(e) { L.EditToolbar.Edit.prototype._enableLayerEdit.call(this, e); var layer = e.layer || e.target || e; if (!layer.snapediting) { if (layer.hasOwnProperty('_mRadius')) { if (layer.editing) { layer.editing._markerGroup.clearLayers(); delete layer.editing; } layer.editing = layer.snapediting = new L.Handler.CircleSnap(layer._map, layer, this.snapOptions); } else if (layer.getLatLng) { layer.snapediting = new L.Handler.MarkerSnap(layer._map, layer, this.snapOptions); } else { if (layer.editing) { if (layer.editing.hasOwnProperty('_shape')) { layer.editing._markerGroup.clearLayers(); if (layer.editing._shape instanceof L.Rectangle) { delete layer.editing; layer.editing = layer.snapediting = new L.Handler.RectangleSnap(layer._map, layer, this.snapOptions); } else if (layer.editing._shape instanceof L.FeatureGroup) { delete layer.editing; layer.editing = layer.snapediting = new L.Handler.FeatureGroupSnap(layer._map, layer, this.snapOptions); } else { delete layer.editing; layer.editing = layer.snapediting = new L.Handler.CircleSnap(layer._map, layer, this.snapOptions); } } else { layer.editing._markerGroup.clearLayers(); layer.editing._verticesHandlers[0]._markerGroup.clearLayers(); delete layer.editing; layer.editing = layer.snapediting = new L.Handler.PolylineSnap(layer._map, layer, this.snapOptions); } } else { layer.editing = layer.snapediting = new L.Handler.PolylineSnap(layer._map, layer, this.snapOptions); } } for (var i = 0, n = this._guideLayers.length; i < n; i++) { layer.snapediting.addGuideLayer(this._guideLayers[i]); } } layer.snapediting.enable(); }
javascript
function(e) { L.EditToolbar.Edit.prototype._enableLayerEdit.call(this, e); var layer = e.layer || e.target || e; if (!layer.snapediting) { if (layer.hasOwnProperty('_mRadius')) { if (layer.editing) { layer.editing._markerGroup.clearLayers(); delete layer.editing; } layer.editing = layer.snapediting = new L.Handler.CircleSnap(layer._map, layer, this.snapOptions); } else if (layer.getLatLng) { layer.snapediting = new L.Handler.MarkerSnap(layer._map, layer, this.snapOptions); } else { if (layer.editing) { if (layer.editing.hasOwnProperty('_shape')) { layer.editing._markerGroup.clearLayers(); if (layer.editing._shape instanceof L.Rectangle) { delete layer.editing; layer.editing = layer.snapediting = new L.Handler.RectangleSnap(layer._map, layer, this.snapOptions); } else if (layer.editing._shape instanceof L.FeatureGroup) { delete layer.editing; layer.editing = layer.snapediting = new L.Handler.FeatureGroupSnap(layer._map, layer, this.snapOptions); } else { delete layer.editing; layer.editing = layer.snapediting = new L.Handler.CircleSnap(layer._map, layer, this.snapOptions); } } else { layer.editing._markerGroup.clearLayers(); layer.editing._verticesHandlers[0]._markerGroup.clearLayers(); delete layer.editing; layer.editing = layer.snapediting = new L.Handler.PolylineSnap(layer._map, layer, this.snapOptions); } } else { layer.editing = layer.snapediting = new L.Handler.PolylineSnap(layer._map, layer, this.snapOptions); } } for (var i = 0, n = this._guideLayers.length; i < n; i++) { layer.snapediting.addGuideLayer(this._guideLayers[i]); } } layer.snapediting.enable(); }
[ "function", "(", "e", ")", "{", "L", ".", "EditToolbar", ".", "Edit", ".", "prototype", ".", "_enableLayerEdit", ".", "call", "(", "this", ",", "e", ")", ";", "var", "layer", "=", "e", ".", "layer", "||", "e", ".", "target", "||", "e", ";", "if", "(", "!", "layer", ".", "snapediting", ")", "{", "if", "(", "layer", ".", "hasOwnProperty", "(", "'_mRadius'", ")", ")", "{", "if", "(", "layer", ".", "editing", ")", "{", "layer", ".", "editing", ".", "_markerGroup", ".", "clearLayers", "(", ")", ";", "delete", "layer", ".", "editing", ";", "}", "layer", ".", "editing", "=", "layer", ".", "snapediting", "=", "new", "L", ".", "Handler", ".", "CircleSnap", "(", "layer", ".", "_map", ",", "layer", ",", "this", ".", "snapOptions", ")", ";", "}", "else", "if", "(", "layer", ".", "getLatLng", ")", "{", "layer", ".", "snapediting", "=", "new", "L", ".", "Handler", ".", "MarkerSnap", "(", "layer", ".", "_map", ",", "layer", ",", "this", ".", "snapOptions", ")", ";", "}", "else", "{", "if", "(", "layer", ".", "editing", ")", "{", "if", "(", "layer", ".", "editing", ".", "hasOwnProperty", "(", "'_shape'", ")", ")", "{", "layer", ".", "editing", ".", "_markerGroup", ".", "clearLayers", "(", ")", ";", "if", "(", "layer", ".", "editing", ".", "_shape", "instanceof", "L", ".", "Rectangle", ")", "{", "delete", "layer", ".", "editing", ";", "layer", ".", "editing", "=", "layer", ".", "snapediting", "=", "new", "L", ".", "Handler", ".", "RectangleSnap", "(", "layer", ".", "_map", ",", "layer", ",", "this", ".", "snapOptions", ")", ";", "}", "else", "if", "(", "layer", ".", "editing", ".", "_shape", "instanceof", "L", ".", "FeatureGroup", ")", "{", "delete", "layer", ".", "editing", ";", "layer", ".", "editing", "=", "layer", ".", "snapediting", "=", "new", "L", ".", "Handler", ".", "FeatureGroupSnap", "(", "layer", ".", "_map", ",", "layer", ",", "this", ".", "snapOptions", ")", ";", "}", "else", "{", "delete", "layer", ".", "editing", ";", "layer", ".", "editing", "=", "layer", ".", "snapediting", "=", "new", "L", ".", "Handler", ".", "CircleSnap", "(", "layer", ".", "_map", ",", "layer", ",", "this", ".", "snapOptions", ")", ";", "}", "}", "else", "{", "layer", ".", "editing", ".", "_markerGroup", ".", "clearLayers", "(", ")", ";", "layer", ".", "editing", ".", "_verticesHandlers", "[", "0", "]", ".", "_markerGroup", ".", "clearLayers", "(", ")", ";", "delete", "layer", ".", "editing", ";", "layer", ".", "editing", "=", "layer", ".", "snapediting", "=", "new", "L", ".", "Handler", ".", "PolylineSnap", "(", "layer", ".", "_map", ",", "layer", ",", "this", ".", "snapOptions", ")", ";", "}", "}", "else", "{", "layer", ".", "editing", "=", "layer", ".", "snapediting", "=", "new", "L", ".", "Handler", ".", "PolylineSnap", "(", "layer", ".", "_map", ",", "layer", ",", "this", ".", "snapOptions", ")", ";", "}", "}", "for", "(", "var", "i", "=", "0", ",", "n", "=", "this", ".", "_guideLayers", ".", "length", ";", "i", "<", "n", ";", "i", "++", ")", "{", "layer", ".", "snapediting", ".", "addGuideLayer", "(", "this", ".", "_guideLayers", "[", "i", "]", ")", ";", "}", "}", "layer", ".", "snapediting", ".", "enable", "(", ")", ";", "}" ]
essentially, the idea here is that we're gonna find the currently instantiated L.Edit handler, figure out its type, get rid of it, and then replace it with a snapedit instead
[ "essentially", "the", "idea", "here", "is", "that", "we", "re", "gonna", "find", "the", "currently", "instantiated", "L", ".", "Edit", "handler", "figure", "out", "its", "type", "get", "rid", "of", "it", "and", "then", "replace", "it", "with", "a", "snapedit", "instead" ]
bdcc9a3554dd11c0f5bc22ede813db1e6e122327
https://github.com/makinacorpus/Leaflet.Snap/blob/bdcc9a3554dd11c0f5bc22ede813db1e6e122327/leaflet.snap.js#L467-L520
22,356
RReverser/mpegts
browser.js
nextFrame
function nextFrame() { if (currentVideo.paused || currentVideo.ended) { return; } context.drawImage(currentVideo, 0, 0); requestAnimationFrame(nextFrame); }
javascript
function nextFrame() { if (currentVideo.paused || currentVideo.ended) { return; } context.drawImage(currentVideo, 0, 0); requestAnimationFrame(nextFrame); }
[ "function", "nextFrame", "(", ")", "{", "if", "(", "currentVideo", ".", "paused", "||", "currentVideo", ".", "ended", ")", "{", "return", ";", "}", "context", ".", "drawImage", "(", "currentVideo", ",", "0", ",", "0", ")", ";", "requestAnimationFrame", "(", "nextFrame", ")", ";", "}" ]
drawing new frame
[ "drawing", "new", "frame" ]
013ff8a03395b2404d3021d4b84be437ce683f56
https://github.com/RReverser/mpegts/blob/013ff8a03395b2404d3021d4b84be437ce683f56/browser.js#L21-L27
22,357
RReverser/mpegts
browser.js
getMore
function getMore() { var ajax = new XMLHttpRequest(); ajax.addEventListener('load', function () { var originals = this.responseText .split(/\r?\n/) .filter(RegExp.prototype.test.bind(/\.ts$/)) .map(resolveURL.bind(null, manifest)); originals = originals.slice(originals.lastIndexOf(lastOriginal) + 1); lastOriginal = originals[originals.length - 1]; worker.postMessage(originals.map(function (url, index) { return {url: url, index: sentVideos + index}; })); sentVideos += originals.length; console.log('asked for ' + originals.length + ' more videos'); }); ajax.open('GET', manifest, true); ajax.send(); }
javascript
function getMore() { var ajax = new XMLHttpRequest(); ajax.addEventListener('load', function () { var originals = this.responseText .split(/\r?\n/) .filter(RegExp.prototype.test.bind(/\.ts$/)) .map(resolveURL.bind(null, manifest)); originals = originals.slice(originals.lastIndexOf(lastOriginal) + 1); lastOriginal = originals[originals.length - 1]; worker.postMessage(originals.map(function (url, index) { return {url: url, index: sentVideos + index}; })); sentVideos += originals.length; console.log('asked for ' + originals.length + ' more videos'); }); ajax.open('GET', manifest, true); ajax.send(); }
[ "function", "getMore", "(", ")", "{", "var", "ajax", "=", "new", "XMLHttpRequest", "(", ")", ";", "ajax", ".", "addEventListener", "(", "'load'", ",", "function", "(", ")", "{", "var", "originals", "=", "this", ".", "responseText", ".", "split", "(", "/", "\\r?\\n", "/", ")", ".", "filter", "(", "RegExp", ".", "prototype", ".", "test", ".", "bind", "(", "/", "\\.ts$", "/", ")", ")", ".", "map", "(", "resolveURL", ".", "bind", "(", "null", ",", "manifest", ")", ")", ";", "originals", "=", "originals", ".", "slice", "(", "originals", ".", "lastIndexOf", "(", "lastOriginal", ")", "+", "1", ")", ";", "lastOriginal", "=", "originals", "[", "originals", ".", "length", "-", "1", "]", ";", "worker", ".", "postMessage", "(", "originals", ".", "map", "(", "function", "(", "url", ",", "index", ")", "{", "return", "{", "url", ":", "url", ",", "index", ":", "sentVideos", "+", "index", "}", ";", "}", ")", ")", ";", "sentVideos", "+=", "originals", ".", "length", ";", "console", ".", "log", "(", "'asked for '", "+", "originals", ".", "length", "+", "' more videos'", ")", ";", "}", ")", ";", "ajax", ".", "open", "(", "'GET'", ",", "manifest", ",", "true", ")", ";", "ajax", ".", "send", "(", ")", ";", "}" ]
loading more videos from manifest
[ "loading", "more", "videos", "from", "manifest" ]
013ff8a03395b2404d3021d4b84be437ce683f56
https://github.com/RReverser/mpegts/blob/013ff8a03395b2404d3021d4b84be437ce683f56/browser.js#L127-L149
22,358
akottr/dragtable
jquery.dragtable.js
function() { var i, j, col1, col2; var from = this.originalTable.startIndex; var to = this.originalTable.endIndex; /* Find children thead and tbody. * Only to process the immediate tr-children. Bugfix for inner tables */ var thtb = this.originalTable.el.children(); if (this.options.excludeFooter) { thtb = thtb.not('tfoot'); } if (from < to) { for (i = from; i < to; i++) { col1 = thtb.find('> tr > td:nth-child(' + i + ')') .add(thtb.find('> tr > th:nth-child(' + i + ')')); col2 = thtb.find('> tr > td:nth-child(' + (i + 1) + ')') .add(thtb.find('> tr > th:nth-child(' + (i + 1) + ')')); for (j = 0; j < col1.length; j++) { swapNodes(col1[j], col2[j]); } } } else { for (i = from; i > to; i--) { col1 = thtb.find('> tr > td:nth-child(' + i + ')') .add(thtb.find('> tr > th:nth-child(' + i + ')')); col2 = thtb.find('> tr > td:nth-child(' + (i - 1) + ')') .add(thtb.find('> tr > th:nth-child(' + (i - 1) + ')')); for (j = 0; j < col1.length; j++) { swapNodes(col1[j], col2[j]); } } } }
javascript
function() { var i, j, col1, col2; var from = this.originalTable.startIndex; var to = this.originalTable.endIndex; /* Find children thead and tbody. * Only to process the immediate tr-children. Bugfix for inner tables */ var thtb = this.originalTable.el.children(); if (this.options.excludeFooter) { thtb = thtb.not('tfoot'); } if (from < to) { for (i = from; i < to; i++) { col1 = thtb.find('> tr > td:nth-child(' + i + ')') .add(thtb.find('> tr > th:nth-child(' + i + ')')); col2 = thtb.find('> tr > td:nth-child(' + (i + 1) + ')') .add(thtb.find('> tr > th:nth-child(' + (i + 1) + ')')); for (j = 0; j < col1.length; j++) { swapNodes(col1[j], col2[j]); } } } else { for (i = from; i > to; i--) { col1 = thtb.find('> tr > td:nth-child(' + i + ')') .add(thtb.find('> tr > th:nth-child(' + i + ')')); col2 = thtb.find('> tr > td:nth-child(' + (i - 1) + ')') .add(thtb.find('> tr > th:nth-child(' + (i - 1) + ')')); for (j = 0; j < col1.length; j++) { swapNodes(col1[j], col2[j]); } } } }
[ "function", "(", ")", "{", "var", "i", ",", "j", ",", "col1", ",", "col2", ";", "var", "from", "=", "this", ".", "originalTable", ".", "startIndex", ";", "var", "to", "=", "this", ".", "originalTable", ".", "endIndex", ";", "/* Find children thead and tbody.\n * Only to process the immediate tr-children. Bugfix for inner tables\n */", "var", "thtb", "=", "this", ".", "originalTable", ".", "el", ".", "children", "(", ")", ";", "if", "(", "this", ".", "options", ".", "excludeFooter", ")", "{", "thtb", "=", "thtb", ".", "not", "(", "'tfoot'", ")", ";", "}", "if", "(", "from", "<", "to", ")", "{", "for", "(", "i", "=", "from", ";", "i", "<", "to", ";", "i", "++", ")", "{", "col1", "=", "thtb", ".", "find", "(", "'> tr > td:nth-child('", "+", "i", "+", "')'", ")", ".", "add", "(", "thtb", ".", "find", "(", "'> tr > th:nth-child('", "+", "i", "+", "')'", ")", ")", ";", "col2", "=", "thtb", ".", "find", "(", "'> tr > td:nth-child('", "+", "(", "i", "+", "1", ")", "+", "')'", ")", ".", "add", "(", "thtb", ".", "find", "(", "'> tr > th:nth-child('", "+", "(", "i", "+", "1", ")", "+", "')'", ")", ")", ";", "for", "(", "j", "=", "0", ";", "j", "<", "col1", ".", "length", ";", "j", "++", ")", "{", "swapNodes", "(", "col1", "[", "j", "]", ",", "col2", "[", "j", "]", ")", ";", "}", "}", "}", "else", "{", "for", "(", "i", "=", "from", ";", "i", ">", "to", ";", "i", "--", ")", "{", "col1", "=", "thtb", ".", "find", "(", "'> tr > td:nth-child('", "+", "i", "+", "')'", ")", ".", "add", "(", "thtb", ".", "find", "(", "'> tr > th:nth-child('", "+", "i", "+", "')'", ")", ")", ";", "col2", "=", "thtb", ".", "find", "(", "'> tr > td:nth-child('", "+", "(", "i", "-", "1", ")", "+", "')'", ")", ".", "add", "(", "thtb", ".", "find", "(", "'> tr > th:nth-child('", "+", "(", "i", "-", "1", ")", "+", "')'", ")", ")", ";", "for", "(", "j", "=", "0", ";", "j", "<", "col1", ".", "length", ";", "j", "++", ")", "{", "swapNodes", "(", "col1", "[", "j", "]", ",", "col2", "[", "j", "]", ")", ";", "}", "}", "}", "}" ]
bubble the moved col left or right
[ "bubble", "the", "moved", "col", "left", "or", "right" ]
e916264057bd495a6870bd576e756a179aec5c90
https://github.com/akottr/dragtable/blob/e916264057bd495a6870bd576e756a179aec5c90/jquery.dragtable.js#L117-L149
22,359
OpusCapita/react-markdown
src/client/components/PlainMarkdownInput/slate/tokenizer.js
getTokensLength
function getTokensLength(tokens) { if (typeof tokens === 'string') { return tokens.length; } return tokens.reduce((acc, token) => { return acc + (token.length ? token.length : 0); }, 0); }
javascript
function getTokensLength(tokens) { if (typeof tokens === 'string') { return tokens.length; } return tokens.reduce((acc, token) => { return acc + (token.length ? token.length : 0); }, 0); }
[ "function", "getTokensLength", "(", "tokens", ")", "{", "if", "(", "typeof", "tokens", "===", "'string'", ")", "{", "return", "tokens", ".", "length", ";", "}", "return", "tokens", ".", "reduce", "(", "(", "acc", ",", "token", ")", "=>", "{", "return", "acc", "+", "(", "token", ".", "length", "?", "token", ".", "length", ":", "0", ")", ";", "}", ",", "0", ")", ";", "}" ]
getTokensLength - Function calculate tokens' length @param tokens @returns {Number}
[ "getTokensLength", "-", "Function", "calculate", "tokens", "length" ]
77f977bd839bdf9c90b8f064179e44464860ae11
https://github.com/OpusCapita/react-markdown/blob/77f977bd839bdf9c90b8f064179e44464860ae11/src/client/components/PlainMarkdownInput/slate/tokenizer.js#L69-L76
22,360
OpusCapita/react-markdown
src/client/components/PlainMarkdownInput/slate/tokenizer.js
getHeaderContent
function getHeaderContent(tokens, type, markup) { if (tokens[1].children.length === 0) { tokens[1].children.push(getEmptyText()); } else if (tokens[1].children[0].type !== 'text') { tokens[1].children.unshift(getEmptyText()); } const content = changeText(tokens[1].children, markup); return { type, content, length: getTokensLength(content) }; }
javascript
function getHeaderContent(tokens, type, markup) { if (tokens[1].children.length === 0) { tokens[1].children.push(getEmptyText()); } else if (tokens[1].children[0].type !== 'text') { tokens[1].children.unshift(getEmptyText()); } const content = changeText(tokens[1].children, markup); return { type, content, length: getTokensLength(content) }; }
[ "function", "getHeaderContent", "(", "tokens", ",", "type", ",", "markup", ")", "{", "if", "(", "tokens", "[", "1", "]", ".", "children", ".", "length", "===", "0", ")", "{", "tokens", "[", "1", "]", ".", "children", ".", "push", "(", "getEmptyText", "(", ")", ")", ";", "}", "else", "if", "(", "tokens", "[", "1", "]", ".", "children", "[", "0", "]", ".", "type", "!==", "'text'", ")", "{", "tokens", "[", "1", "]", ".", "children", ".", "unshift", "(", "getEmptyText", "(", ")", ")", ";", "}", "const", "content", "=", "changeText", "(", "tokens", "[", "1", "]", ".", "children", ",", "markup", ")", ";", "return", "{", "type", ",", "content", ",", "length", ":", "getTokensLength", "(", "content", ")", "}", ";", "}" ]
getHeaderContent - Function create content for header-token @param tokens @param type @param markup @returns {{type: *, content}}
[ "getHeaderContent", "-", "Function", "create", "content", "for", "header", "-", "token" ]
77f977bd839bdf9c90b8f064179e44464860ae11
https://github.com/OpusCapita/react-markdown/blob/77f977bd839bdf9c90b8f064179e44464860ae11/src/client/components/PlainMarkdownInput/slate/tokenizer.js#L105-L117
22,361
OpusCapita/react-markdown
src/client/components/PlainMarkdownInput/slate/tokenizer.js
getBlockContent
function getBlockContent(tokens, type, markup, start = false) { const content = { type, content: processBlockTokens(tokens.slice(1, -1)), // eslint-disable-line markup }; if (start) { content.start = start; } return content; }
javascript
function getBlockContent(tokens, type, markup, start = false) { const content = { type, content: processBlockTokens(tokens.slice(1, -1)), // eslint-disable-line markup }; if (start) { content.start = start; } return content; }
[ "function", "getBlockContent", "(", "tokens", ",", "type", ",", "markup", ",", "start", "=", "false", ")", "{", "const", "content", "=", "{", "type", ",", "content", ":", "processBlockTokens", "(", "tokens", ".", "slice", "(", "1", ",", "-", "1", ")", ")", ",", "// eslint-disable-line", "markup", "}", ";", "if", "(", "start", ")", "{", "content", ".", "start", "=", "start", ";", "}", "return", "content", ";", "}" ]
getBlockContent - Function returns block content @param tokens @param type @param markup @param start @returns {{type: *, content, markup: *}}
[ "getBlockContent", "-", "Function", "returns", "block", "content" ]
77f977bd839bdf9c90b8f064179e44464860ae11
https://github.com/OpusCapita/react-markdown/blob/77f977bd839bdf9c90b8f064179e44464860ae11/src/client/components/PlainMarkdownInput/slate/tokenizer.js#L129-L139
22,362
OpusCapita/react-markdown
src/client/components/PlainMarkdownInput/slate/tokenizer.js
getUrlToken
function getUrlToken({ tokens, intEmphasis, num }) { const urlContent = `(${getAttr(tokens[num].attrs, 'href')})`; const urlLength = urlContent.length; const punctuation1 = { type: "punctuation", content: "[", length: 1 }; const punctuation2 = { type: "punctuation", content: "]", length: 1 }; const urlContentObj = { type: "punctuation", content: urlContent, length: urlLength }; const content = Array.isArray(intEmphasis) ? [punctuation1, ...intEmphasis, punctuation2, urlContentObj] : [punctuation1, intEmphasis, punctuation2, urlContentObj]; return { type: "url", content, length: Array.isArray(intEmphasis) ? getTokensLength(content) : 1 + intEmphasis.length + 1 + urlLength }; }
javascript
function getUrlToken({ tokens, intEmphasis, num }) { const urlContent = `(${getAttr(tokens[num].attrs, 'href')})`; const urlLength = urlContent.length; const punctuation1 = { type: "punctuation", content: "[", length: 1 }; const punctuation2 = { type: "punctuation", content: "]", length: 1 }; const urlContentObj = { type: "punctuation", content: urlContent, length: urlLength }; const content = Array.isArray(intEmphasis) ? [punctuation1, ...intEmphasis, punctuation2, urlContentObj] : [punctuation1, intEmphasis, punctuation2, urlContentObj]; return { type: "url", content, length: Array.isArray(intEmphasis) ? getTokensLength(content) : 1 + intEmphasis.length + 1 + urlLength }; }
[ "function", "getUrlToken", "(", "{", "tokens", ",", "intEmphasis", ",", "num", "}", ")", "{", "const", "urlContent", "=", "`", "${", "getAttr", "(", "tokens", "[", "num", "]", ".", "attrs", ",", "'href'", ")", "}", "`", ";", "const", "urlLength", "=", "urlContent", ".", "length", ";", "const", "punctuation1", "=", "{", "type", ":", "\"punctuation\"", ",", "content", ":", "\"[\"", ",", "length", ":", "1", "}", ";", "const", "punctuation2", "=", "{", "type", ":", "\"punctuation\"", ",", "content", ":", "\"]\"", ",", "length", ":", "1", "}", ";", "const", "urlContentObj", "=", "{", "type", ":", "\"punctuation\"", ",", "content", ":", "urlContent", ",", "length", ":", "urlLength", "}", ";", "const", "content", "=", "Array", ".", "isArray", "(", "intEmphasis", ")", "?", "[", "punctuation1", ",", "...", "intEmphasis", ",", "punctuation2", ",", "urlContentObj", "]", ":", "[", "punctuation1", ",", "intEmphasis", ",", "punctuation2", ",", "urlContentObj", "]", ";", "return", "{", "type", ":", "\"url\"", ",", "content", ",", "length", ":", "Array", ".", "isArray", "(", "intEmphasis", ")", "?", "getTokensLength", "(", "content", ")", ":", "1", "+", "intEmphasis", ".", "length", "+", "1", "+", "urlLength", "}", ";", "}" ]
getUrlToken - Function create url-token @param tokens @param intEmphasis @param num @returns {{type: string, content: [null,null,null,null], length: *}}
[ "getUrlToken", "-", "Function", "create", "url", "-", "token" ]
77f977bd839bdf9c90b8f064179e44464860ae11
https://github.com/OpusCapita/react-markdown/blob/77f977bd839bdf9c90b8f064179e44464860ae11/src/client/components/PlainMarkdownInput/slate/tokenizer.js#L246-L272
22,363
OpusCapita/react-markdown
src/client/components/PlainMarkdownInput/slate/tokenizer.js
getEmphasisToken
function getEmphasisToken({ tokens, intEmphasis, currTag, num }) { const rawContent = joinArrString(_.flattenDeep([ tokens[num].markup, intEmphasis, tokens[num].markup ])); const contentLength = getTokensLength(rawContent); return { type: getEmphasisType(currTag), content: rawContent, length: contentLength }; }
javascript
function getEmphasisToken({ tokens, intEmphasis, currTag, num }) { const rawContent = joinArrString(_.flattenDeep([ tokens[num].markup, intEmphasis, tokens[num].markup ])); const contentLength = getTokensLength(rawContent); return { type: getEmphasisType(currTag), content: rawContent, length: contentLength }; }
[ "function", "getEmphasisToken", "(", "{", "tokens", ",", "intEmphasis", ",", "currTag", ",", "num", "}", ")", "{", "const", "rawContent", "=", "joinArrString", "(", "_", ".", "flattenDeep", "(", "[", "tokens", "[", "num", "]", ".", "markup", ",", "intEmphasis", ",", "tokens", "[", "num", "]", ".", "markup", "]", ")", ")", ";", "const", "contentLength", "=", "getTokensLength", "(", "rawContent", ")", ";", "return", "{", "type", ":", "getEmphasisType", "(", "currTag", ")", ",", "content", ":", "rawContent", ",", "length", ":", "contentLength", "}", ";", "}" ]
getEmphasisToken - Function create emphasis-token @param tokens @param intEmphasis @param currTag @param num @returns {{type, content, length}}
[ "getEmphasisToken", "-", "Function", "create", "emphasis", "-", "token" ]
77f977bd839bdf9c90b8f064179e44464860ae11
https://github.com/OpusCapita/react-markdown/blob/77f977bd839bdf9c90b8f064179e44464860ae11/src/client/components/PlainMarkdownInput/slate/tokenizer.js#L284-L296
22,364
OpusCapita/react-markdown
src/client/components/PlainMarkdownInput/slate/tokenizer.js
parseEmphasis
function parseEmphasis(tokens) { const newTokens = []; let i = 0; while (i < tokens.length) { if (typeof tokens[i] === 'string') { if (tokens[i] !== '') { newTokens.push(tokens[i]); } i++; } else { const currTag = tokens[i].type; if (INLINE_OPEN.indexOf(currTag) !== -1) { const closeTag = getCloseTag(currTag); const closePos = getClosePos(tokens, i, closeTag, tokens[i].markup); if (closePos !== -1) { let intEmphasis = getOneEmphasis(tokens, i, closePos); if (Array.isArray(intEmphasis) && intEmphasis.length === 0) { intEmphasis = ''; } if (currTag === 'link_open') { newTokens.push(getUrlToken({ tokens, intEmphasis, num: i })); } else { newTokens.push(getEmphasisToken({ tokens, intEmphasis, currTag, num: i })); } i = closePos + 1; continue; } } newTokens.push(tokens[i]); i++; } } return newTokens; }
javascript
function parseEmphasis(tokens) { const newTokens = []; let i = 0; while (i < tokens.length) { if (typeof tokens[i] === 'string') { if (tokens[i] !== '') { newTokens.push(tokens[i]); } i++; } else { const currTag = tokens[i].type; if (INLINE_OPEN.indexOf(currTag) !== -1) { const closeTag = getCloseTag(currTag); const closePos = getClosePos(tokens, i, closeTag, tokens[i].markup); if (closePos !== -1) { let intEmphasis = getOneEmphasis(tokens, i, closePos); if (Array.isArray(intEmphasis) && intEmphasis.length === 0) { intEmphasis = ''; } if (currTag === 'link_open') { newTokens.push(getUrlToken({ tokens, intEmphasis, num: i })); } else { newTokens.push(getEmphasisToken({ tokens, intEmphasis, currTag, num: i })); } i = closePos + 1; continue; } } newTokens.push(tokens[i]); i++; } } return newTokens; }
[ "function", "parseEmphasis", "(", "tokens", ")", "{", "const", "newTokens", "=", "[", "]", ";", "let", "i", "=", "0", ";", "while", "(", "i", "<", "tokens", ".", "length", ")", "{", "if", "(", "typeof", "tokens", "[", "i", "]", "===", "'string'", ")", "{", "if", "(", "tokens", "[", "i", "]", "!==", "''", ")", "{", "newTokens", ".", "push", "(", "tokens", "[", "i", "]", ")", ";", "}", "i", "++", ";", "}", "else", "{", "const", "currTag", "=", "tokens", "[", "i", "]", ".", "type", ";", "if", "(", "INLINE_OPEN", ".", "indexOf", "(", "currTag", ")", "!==", "-", "1", ")", "{", "const", "closeTag", "=", "getCloseTag", "(", "currTag", ")", ";", "const", "closePos", "=", "getClosePos", "(", "tokens", ",", "i", ",", "closeTag", ",", "tokens", "[", "i", "]", ".", "markup", ")", ";", "if", "(", "closePos", "!==", "-", "1", ")", "{", "let", "intEmphasis", "=", "getOneEmphasis", "(", "tokens", ",", "i", ",", "closePos", ")", ";", "if", "(", "Array", ".", "isArray", "(", "intEmphasis", ")", "&&", "intEmphasis", ".", "length", "===", "0", ")", "{", "intEmphasis", "=", "''", ";", "}", "if", "(", "currTag", "===", "'link_open'", ")", "{", "newTokens", ".", "push", "(", "getUrlToken", "(", "{", "tokens", ",", "intEmphasis", ",", "num", ":", "i", "}", ")", ")", ";", "}", "else", "{", "newTokens", ".", "push", "(", "getEmphasisToken", "(", "{", "tokens", ",", "intEmphasis", ",", "currTag", ",", "num", ":", "i", "}", ")", ")", ";", "}", "i", "=", "closePos", "+", "1", ";", "continue", ";", "}", "}", "newTokens", ".", "push", "(", "tokens", "[", "i", "]", ")", ";", "i", "++", ";", "}", "}", "return", "newTokens", ";", "}" ]
parseEmphasis - Function parse inline and extract emphasis-tokens @param tokens @returns {Array}
[ "parseEmphasis", "-", "Function", "parse", "inline", "and", "extract", "emphasis", "-", "tokens" ]
77f977bd839bdf9c90b8f064179e44464860ae11
https://github.com/OpusCapita/react-markdown/blob/77f977bd839bdf9c90b8f064179e44464860ae11/src/client/components/PlainMarkdownInput/slate/tokenizer.js#L305-L338
22,365
OpusCapita/react-markdown
src/client/components/PlainMarkdownInput/slate/transforms.js
hasMarkOnChar
function hasMarkOnChar(character, mark) { const arrChars = character.marks.toJS(); const marksSize = arrChars.length; for (let i = 0; i < marksSize; i++) { if (arrChars[i].type === mark) { return true; } } return false; }
javascript
function hasMarkOnChar(character, mark) { const arrChars = character.marks.toJS(); const marksSize = arrChars.length; for (let i = 0; i < marksSize; i++) { if (arrChars[i].type === mark) { return true; } } return false; }
[ "function", "hasMarkOnChar", "(", "character", ",", "mark", ")", "{", "const", "arrChars", "=", "character", ".", "marks", ".", "toJS", "(", ")", ";", "const", "marksSize", "=", "arrChars", ".", "length", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "marksSize", ";", "i", "++", ")", "{", "if", "(", "arrChars", "[", "i", "]", ".", "type", "===", "mark", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Has the mark on a char @param character @param mark @returns {boolean}
[ "Has", "the", "mark", "on", "a", "char" ]
77f977bd839bdf9c90b8f064179e44464860ae11
https://github.com/OpusCapita/react-markdown/blob/77f977bd839bdf9c90b8f064179e44464860ae11/src/client/components/PlainMarkdownInput/slate/transforms.js#L61-L70
22,366
OpusCapita/react-markdown
src/client/components/PlainMarkdownInput/slate/transforms.js
hasEmphasis
function hasEmphasis(mark, state) { const { startKey, endKey, startOffset, endOffset, texts } = state; if (startKey === endKey) { const focusText = texts.get(0).text; const textLength = focusText.length; if (texts.get(0).charsData) { const characters = texts.get(0).charsData.characters; // not selection if (startOffset === endOffset) { // string's edge if (startOffset === 0 || startOffset === textLength) { return false; } else { const prevChar = characters.get(startOffset - 1); const currChar = characters.get(startOffset); const hasPrevMark = hasMarkOnChar(prevChar, mark); const hasCurrMark = hasMarkOnChar(currChar, mark); // between character's marks if (hasPrevMark && hasCurrMark) { return true; // between pairs of markers } else if ((mark === 'bold' || mark === 'strikethrough') && startOffset > 1 && startOffset < textLength - 1) { const leftPart = focusText.substr(startOffset - 2, 2); const rightPart = focusText.substr(startOffset, 2); if (leftPart === rightPart && (mark === 'bold' && (leftPart === '**' || leftPart === '__') || mark === 'strikethrough' && leftPart === '~~')) { return true; } // between italic markers and not bold's edge } else if (mark === 'italic' && prevChar.text === currChar.text && (currChar.text === '_' || currChar.text === '*') && !hasPrevMark && !hasCurrMark && (!(hasMarkOnChar(prevChar, 'bold') && hasMarkOnChar(currChar, 'bold')) && (startOffset === 1 || startOffset === focusText.length - 1 || !hasMarkOnChar(characters.get(startOffset - 2), 'bold') && !hasMarkOnChar(characters.get(startOffset + 1), 'bold')))) { return true; } } // selection } else { for (let i = startOffset; i < endOffset; i++) { if (!hasMarkOnChar(characters.get(i), mark)) { return false; } } return true; } } } return false; }
javascript
function hasEmphasis(mark, state) { const { startKey, endKey, startOffset, endOffset, texts } = state; if (startKey === endKey) { const focusText = texts.get(0).text; const textLength = focusText.length; if (texts.get(0).charsData) { const characters = texts.get(0).charsData.characters; // not selection if (startOffset === endOffset) { // string's edge if (startOffset === 0 || startOffset === textLength) { return false; } else { const prevChar = characters.get(startOffset - 1); const currChar = characters.get(startOffset); const hasPrevMark = hasMarkOnChar(prevChar, mark); const hasCurrMark = hasMarkOnChar(currChar, mark); // between character's marks if (hasPrevMark && hasCurrMark) { return true; // between pairs of markers } else if ((mark === 'bold' || mark === 'strikethrough') && startOffset > 1 && startOffset < textLength - 1) { const leftPart = focusText.substr(startOffset - 2, 2); const rightPart = focusText.substr(startOffset, 2); if (leftPart === rightPart && (mark === 'bold' && (leftPart === '**' || leftPart === '__') || mark === 'strikethrough' && leftPart === '~~')) { return true; } // between italic markers and not bold's edge } else if (mark === 'italic' && prevChar.text === currChar.text && (currChar.text === '_' || currChar.text === '*') && !hasPrevMark && !hasCurrMark && (!(hasMarkOnChar(prevChar, 'bold') && hasMarkOnChar(currChar, 'bold')) && (startOffset === 1 || startOffset === focusText.length - 1 || !hasMarkOnChar(characters.get(startOffset - 2), 'bold') && !hasMarkOnChar(characters.get(startOffset + 1), 'bold')))) { return true; } } // selection } else { for (let i = startOffset; i < endOffset; i++) { if (!hasMarkOnChar(characters.get(i), mark)) { return false; } } return true; } } } return false; }
[ "function", "hasEmphasis", "(", "mark", ",", "state", ")", "{", "const", "{", "startKey", ",", "endKey", ",", "startOffset", ",", "endOffset", ",", "texts", "}", "=", "state", ";", "if", "(", "startKey", "===", "endKey", ")", "{", "const", "focusText", "=", "texts", ".", "get", "(", "0", ")", ".", "text", ";", "const", "textLength", "=", "focusText", ".", "length", ";", "if", "(", "texts", ".", "get", "(", "0", ")", ".", "charsData", ")", "{", "const", "characters", "=", "texts", ".", "get", "(", "0", ")", ".", "charsData", ".", "characters", ";", "// not selection", "if", "(", "startOffset", "===", "endOffset", ")", "{", "// string's edge", "if", "(", "startOffset", "===", "0", "||", "startOffset", "===", "textLength", ")", "{", "return", "false", ";", "}", "else", "{", "const", "prevChar", "=", "characters", ".", "get", "(", "startOffset", "-", "1", ")", ";", "const", "currChar", "=", "characters", ".", "get", "(", "startOffset", ")", ";", "const", "hasPrevMark", "=", "hasMarkOnChar", "(", "prevChar", ",", "mark", ")", ";", "const", "hasCurrMark", "=", "hasMarkOnChar", "(", "currChar", ",", "mark", ")", ";", "// between character's marks", "if", "(", "hasPrevMark", "&&", "hasCurrMark", ")", "{", "return", "true", ";", "// between pairs of markers", "}", "else", "if", "(", "(", "mark", "===", "'bold'", "||", "mark", "===", "'strikethrough'", ")", "&&", "startOffset", ">", "1", "&&", "startOffset", "<", "textLength", "-", "1", ")", "{", "const", "leftPart", "=", "focusText", ".", "substr", "(", "startOffset", "-", "2", ",", "2", ")", ";", "const", "rightPart", "=", "focusText", ".", "substr", "(", "startOffset", ",", "2", ")", ";", "if", "(", "leftPart", "===", "rightPart", "&&", "(", "mark", "===", "'bold'", "&&", "(", "leftPart", "===", "'**'", "||", "leftPart", "===", "'__'", ")", "||", "mark", "===", "'strikethrough'", "&&", "leftPart", "===", "'~~'", ")", ")", "{", "return", "true", ";", "}", "// between italic markers and not bold's edge", "}", "else", "if", "(", "mark", "===", "'italic'", "&&", "prevChar", ".", "text", "===", "currChar", ".", "text", "&&", "(", "currChar", ".", "text", "===", "'_'", "||", "currChar", ".", "text", "===", "'*'", ")", "&&", "!", "hasPrevMark", "&&", "!", "hasCurrMark", "&&", "(", "!", "(", "hasMarkOnChar", "(", "prevChar", ",", "'bold'", ")", "&&", "hasMarkOnChar", "(", "currChar", ",", "'bold'", ")", ")", "&&", "(", "startOffset", "===", "1", "||", "startOffset", "===", "focusText", ".", "length", "-", "1", "||", "!", "hasMarkOnChar", "(", "characters", ".", "get", "(", "startOffset", "-", "2", ")", ",", "'bold'", ")", "&&", "!", "hasMarkOnChar", "(", "characters", ".", "get", "(", "startOffset", "+", "1", ")", ",", "'bold'", ")", ")", ")", ")", "{", "return", "true", ";", "}", "}", "// selection", "}", "else", "{", "for", "(", "let", "i", "=", "startOffset", ";", "i", "<", "endOffset", ";", "i", "++", ")", "{", "if", "(", "!", "hasMarkOnChar", "(", "characters", ".", "get", "(", "i", ")", ",", "mark", ")", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}", "}", "}", "return", "false", ";", "}" ]
The text has a wrapper in emphasis @param mark @param state @returns {boolean}
[ "The", "text", "has", "a", "wrapper", "in", "emphasis" ]
77f977bd839bdf9c90b8f064179e44464860ae11
https://github.com/OpusCapita/react-markdown/blob/77f977bd839bdf9c90b8f064179e44464860ae11/src/client/components/PlainMarkdownInput/slate/transforms.js#L79-L133
22,367
OpusCapita/react-markdown
src/client/components/PlainMarkdownInput/slate/transforms.js
unionEmphasis
function unionEmphasis({ change, focusKey, characters, accent, text, startOffset, endOffset, markerLength }) { const leftEmphEdge = getLeftEmphEdge(accent, characters, startOffset); const rightEmphEdge = getRightEmphEdge(accent, characters, endOffset - 1, text.length); const leftMarker = text.substr(leftEmphEdge, markerLength); let rightMarkerPos = rightEmphEdge - markerLength; const rightMarker = text.substr(rightMarkerPos, markerLength); const delCount = delInternalMarkers({ change, focusKey, characters, accent, startPos: leftEmphEdge + markerLength, endPos: rightEmphEdge - markerLength }); rightMarkerPos -= delCount * markerLength - 1; if (leftMarker !== rightMarker) { change.removeTextByKey(focusKey, rightMarkerPos, markerLength). insertTextByKey(focusKey, rightMarkerPos, leftMarker); } return change; }
javascript
function unionEmphasis({ change, focusKey, characters, accent, text, startOffset, endOffset, markerLength }) { const leftEmphEdge = getLeftEmphEdge(accent, characters, startOffset); const rightEmphEdge = getRightEmphEdge(accent, characters, endOffset - 1, text.length); const leftMarker = text.substr(leftEmphEdge, markerLength); let rightMarkerPos = rightEmphEdge - markerLength; const rightMarker = text.substr(rightMarkerPos, markerLength); const delCount = delInternalMarkers({ change, focusKey, characters, accent, startPos: leftEmphEdge + markerLength, endPos: rightEmphEdge - markerLength }); rightMarkerPos -= delCount * markerLength - 1; if (leftMarker !== rightMarker) { change.removeTextByKey(focusKey, rightMarkerPos, markerLength). insertTextByKey(focusKey, rightMarkerPos, leftMarker); } return change; }
[ "function", "unionEmphasis", "(", "{", "change", ",", "focusKey", ",", "characters", ",", "accent", ",", "text", ",", "startOffset", ",", "endOffset", ",", "markerLength", "}", ")", "{", "const", "leftEmphEdge", "=", "getLeftEmphEdge", "(", "accent", ",", "characters", ",", "startOffset", ")", ";", "const", "rightEmphEdge", "=", "getRightEmphEdge", "(", "accent", ",", "characters", ",", "endOffset", "-", "1", ",", "text", ".", "length", ")", ";", "const", "leftMarker", "=", "text", ".", "substr", "(", "leftEmphEdge", ",", "markerLength", ")", ";", "let", "rightMarkerPos", "=", "rightEmphEdge", "-", "markerLength", ";", "const", "rightMarker", "=", "text", ".", "substr", "(", "rightMarkerPos", ",", "markerLength", ")", ";", "const", "delCount", "=", "delInternalMarkers", "(", "{", "change", ",", "focusKey", ",", "characters", ",", "accent", ",", "startPos", ":", "leftEmphEdge", "+", "markerLength", ",", "endPos", ":", "rightEmphEdge", "-", "markerLength", "}", ")", ";", "rightMarkerPos", "-=", "delCount", "*", "markerLength", "-", "1", ";", "if", "(", "leftMarker", "!==", "rightMarker", ")", "{", "change", ".", "removeTextByKey", "(", "focusKey", ",", "rightMarkerPos", ",", "markerLength", ")", ".", "insertTextByKey", "(", "focusKey", ",", "rightMarkerPos", ",", "leftMarker", ")", ";", "}", "return", "change", ";", "}" ]
Both selection edges is on emphasis, delete all internal markers @param change @param focusKey @param characters @param text @param accent @param startOffset @param endOffset @param markerLength
[ "Both", "selection", "edges", "is", "on", "emphasis", "delete", "all", "internal", "markers" ]
77f977bd839bdf9c90b8f064179e44464860ae11
https://github.com/OpusCapita/react-markdown/blob/77f977bd839bdf9c90b8f064179e44464860ae11/src/client/components/PlainMarkdownInput/slate/transforms.js#L238-L258
22,368
OpusCapita/react-markdown
src/client/components/PlainMarkdownInput/slate/transforms.js
wrapEmphasis
function wrapEmphasis(accent, state) { const marker = EMPHASIS[accent]; const markerLength = marker.length; const { startOffset, endOffset, focusText, texts } = state; const { text } = focusText; const focusKey = focusText.key; let change = state.change(); // #1 no selection if (startOffset === endOffset) { change.insertText(`${marker}${marker}`). move(-markerLength); // selection (this edge is selection edge) } else { const characters = texts.get(0).charsData.characters; const delMarkers = delInternalMarkersBind({ change, focusKey, characters, accent }); const { hasLeftOnEmphasis } = getLeftSelectionEdgeData({ accent, characters, startOffset }); const { hasRightOnEmphasis } = getRightSelectionEdgeData({ accent, characters, endOffset, text }); if (hasLeftOnEmphasis) { if (hasRightOnEmphasis) { // #2 both edges on emphasis, delete all internal markers change = unionEmphasis({ change, focusKey, characters, text, accent, startOffset, endOffset, markerLength }); } else { // #3 left edge on emphasis, right edge beyond markers const leftEmphEdge = getLeftEmphEdge(accent, characters, startOffset); const leftMarker = text.substr(leftEmphEdge, markerLength); delMarkers({ startPos: leftEmphEdge, endPos: endOffset - 1 }); change.insertTextByKey(focusKey, endOffset - 1, leftMarker); } } else { if (hasRightOnEmphasis) { // #4 left edge beyond markers, right edge on emphasis const rightEmphEdge = getRightEmphEdge(accent, characters, endOffset - 1, text.length); const rightMarker = text.substr(rightEmphEdge - markerLength + 1, markerLength); delMarkers({ startPos: startOffset, endPos: rightEmphEdge }); change.insertTextByKey(focusKey, startOffset, rightMarker); } else { // #5 both edges beyond markers // delete all internal markers, wrap selection in markers delMarkers({ startPos: startOffset, endPos: endOffset }); change.wrapText(marker, marker).focus(); } } } change.focus(); return change.state; }
javascript
function wrapEmphasis(accent, state) { const marker = EMPHASIS[accent]; const markerLength = marker.length; const { startOffset, endOffset, focusText, texts } = state; const { text } = focusText; const focusKey = focusText.key; let change = state.change(); // #1 no selection if (startOffset === endOffset) { change.insertText(`${marker}${marker}`). move(-markerLength); // selection (this edge is selection edge) } else { const characters = texts.get(0).charsData.characters; const delMarkers = delInternalMarkersBind({ change, focusKey, characters, accent }); const { hasLeftOnEmphasis } = getLeftSelectionEdgeData({ accent, characters, startOffset }); const { hasRightOnEmphasis } = getRightSelectionEdgeData({ accent, characters, endOffset, text }); if (hasLeftOnEmphasis) { if (hasRightOnEmphasis) { // #2 both edges on emphasis, delete all internal markers change = unionEmphasis({ change, focusKey, characters, text, accent, startOffset, endOffset, markerLength }); } else { // #3 left edge on emphasis, right edge beyond markers const leftEmphEdge = getLeftEmphEdge(accent, characters, startOffset); const leftMarker = text.substr(leftEmphEdge, markerLength); delMarkers({ startPos: leftEmphEdge, endPos: endOffset - 1 }); change.insertTextByKey(focusKey, endOffset - 1, leftMarker); } } else { if (hasRightOnEmphasis) { // #4 left edge beyond markers, right edge on emphasis const rightEmphEdge = getRightEmphEdge(accent, characters, endOffset - 1, text.length); const rightMarker = text.substr(rightEmphEdge - markerLength + 1, markerLength); delMarkers({ startPos: startOffset, endPos: rightEmphEdge }); change.insertTextByKey(focusKey, startOffset, rightMarker); } else { // #5 both edges beyond markers // delete all internal markers, wrap selection in markers delMarkers({ startPos: startOffset, endPos: endOffset }); change.wrapText(marker, marker).focus(); } } } change.focus(); return change.state; }
[ "function", "wrapEmphasis", "(", "accent", ",", "state", ")", "{", "const", "marker", "=", "EMPHASIS", "[", "accent", "]", ";", "const", "markerLength", "=", "marker", ".", "length", ";", "const", "{", "startOffset", ",", "endOffset", ",", "focusText", ",", "texts", "}", "=", "state", ";", "const", "{", "text", "}", "=", "focusText", ";", "const", "focusKey", "=", "focusText", ".", "key", ";", "let", "change", "=", "state", ".", "change", "(", ")", ";", "// #1 no selection", "if", "(", "startOffset", "===", "endOffset", ")", "{", "change", ".", "insertText", "(", "`", "${", "marker", "}", "${", "marker", "}", "`", ")", ".", "move", "(", "-", "markerLength", ")", ";", "// selection (this edge is selection edge)", "}", "else", "{", "const", "characters", "=", "texts", ".", "get", "(", "0", ")", ".", "charsData", ".", "characters", ";", "const", "delMarkers", "=", "delInternalMarkersBind", "(", "{", "change", ",", "focusKey", ",", "characters", ",", "accent", "}", ")", ";", "const", "{", "hasLeftOnEmphasis", "}", "=", "getLeftSelectionEdgeData", "(", "{", "accent", ",", "characters", ",", "startOffset", "}", ")", ";", "const", "{", "hasRightOnEmphasis", "}", "=", "getRightSelectionEdgeData", "(", "{", "accent", ",", "characters", ",", "endOffset", ",", "text", "}", ")", ";", "if", "(", "hasLeftOnEmphasis", ")", "{", "if", "(", "hasRightOnEmphasis", ")", "{", "// #2 both edges on emphasis, delete all internal markers", "change", "=", "unionEmphasis", "(", "{", "change", ",", "focusKey", ",", "characters", ",", "text", ",", "accent", ",", "startOffset", ",", "endOffset", ",", "markerLength", "}", ")", ";", "}", "else", "{", "// #3 left edge on emphasis, right edge beyond markers", "const", "leftEmphEdge", "=", "getLeftEmphEdge", "(", "accent", ",", "characters", ",", "startOffset", ")", ";", "const", "leftMarker", "=", "text", ".", "substr", "(", "leftEmphEdge", ",", "markerLength", ")", ";", "delMarkers", "(", "{", "startPos", ":", "leftEmphEdge", ",", "endPos", ":", "endOffset", "-", "1", "}", ")", ";", "change", ".", "insertTextByKey", "(", "focusKey", ",", "endOffset", "-", "1", ",", "leftMarker", ")", ";", "}", "}", "else", "{", "if", "(", "hasRightOnEmphasis", ")", "{", "// #4 left edge beyond markers, right edge on emphasis", "const", "rightEmphEdge", "=", "getRightEmphEdge", "(", "accent", ",", "characters", ",", "endOffset", "-", "1", ",", "text", ".", "length", ")", ";", "const", "rightMarker", "=", "text", ".", "substr", "(", "rightEmphEdge", "-", "markerLength", "+", "1", ",", "markerLength", ")", ";", "delMarkers", "(", "{", "startPos", ":", "startOffset", ",", "endPos", ":", "rightEmphEdge", "}", ")", ";", "change", ".", "insertTextByKey", "(", "focusKey", ",", "startOffset", ",", "rightMarker", ")", ";", "}", "else", "{", "// #5 both edges beyond markers", "// delete all internal markers, wrap selection in markers", "delMarkers", "(", "{", "startPos", ":", "startOffset", ",", "endPos", ":", "endOffset", "}", ")", ";", "change", ".", "wrapText", "(", "marker", ",", "marker", ")", ".", "focus", "(", ")", ";", "}", "}", "}", "change", ".", "focus", "(", ")", ";", "return", "change", ".", "state", ";", "}" ]
Wrap text with accent @param accent @param state
[ "Wrap", "text", "with", "accent" ]
77f977bd839bdf9c90b8f064179e44464860ae11
https://github.com/OpusCapita/react-markdown/blob/77f977bd839bdf9c90b8f064179e44464860ae11/src/client/components/PlainMarkdownInput/slate/transforms.js#L266-L321
22,369
OpusCapita/react-markdown
src/client/components/PlainMarkdownInput/slate/transforms.js
hasBlock
function hasBlock(regExp, state) { const { focusText } = state; const focusedText = focusText.text; return regExp.test(focusedText); }
javascript
function hasBlock(regExp, state) { const { focusText } = state; const focusedText = focusText.text; return regExp.test(focusedText); }
[ "function", "hasBlock", "(", "regExp", ",", "state", ")", "{", "const", "{", "focusText", "}", "=", "state", ";", "const", "focusedText", "=", "focusText", ".", "text", ";", "return", "regExp", ".", "test", "(", "focusedText", ")", ";", "}" ]
Has block selected @param regExp - match regexp @param state - editor state
[ "Has", "block", "selected" ]
77f977bd839bdf9c90b8f064179e44464860ae11
https://github.com/OpusCapita/react-markdown/blob/77f977bd839bdf9c90b8f064179e44464860ae11/src/client/components/PlainMarkdownInput/slate/transforms.js#L418-L422
22,370
OpusCapita/react-markdown
src/client/components/PlainMarkdownInput/slate/transforms.js
function(accent, state) { let text = accent === 'ul' ? '* ' : '1. '; if (hasMultiLineSelection(state)) { const { anchorKey, anchorOffset, focusKey, focusOffset, isBackward } = state.selection; const keys = []; let firstBefore, firstAfter, lastBefore, lastAfter; for (let i = 0; i < state.texts.size; i++) { keys.push(state.texts.get(i).key); } const lineText = state.texts.get(0).text; let pref, itemNum, div; if (accent === 'ul') { const ulMarker = getUlMarker(lineText); if (ulMarker) { text = ulMarker; } else { text = '* '; } } else { ({ pref, itemNum, div } = getOlNum(lineText)); } let change = state.change(); const keysLength = keys.length; const lastNum = keysLength - 1; for (let i = 0; i < keysLength; i++) { moveSelectionToLine(change, keys[i]); // eslint-disable-line no-use-before-define if (i === 0) { firstBefore = getTextLength(change); } else if (i === lastNum) { lastBefore = getTextLength(change); } if (i === 0 && !hasBlock(MATCH_SINGLE_RULE[accent], change.state) || i > 0) { text = accent === 'ul' ? text : `${pref}${itemNum}${div} `; change = wrapBlockForChange(MATCH_RULES[accent], text, change);// eslint-disable-line if (i === 0) { firstAfter = getTextLength(change); } else if (i === lastNum) { lastAfter = getTextLength(change); } itemNum++; continue; } if (i === 0) { firstAfter = firstBefore; } else if (i === lastNum) { lastAfter = lastBefore; } itemNum++; } change.select({ anchorKey, anchorOffset: anchorOffset - firstBefore + firstAfter, focusKey, focusOffset: focusOffset - lastBefore + lastAfter, isFocused: true, isBackward }); return change.state; } else { return wrapBlock(MATCH_RULES[accent], text, state); } }
javascript
function(accent, state) { let text = accent === 'ul' ? '* ' : '1. '; if (hasMultiLineSelection(state)) { const { anchorKey, anchorOffset, focusKey, focusOffset, isBackward } = state.selection; const keys = []; let firstBefore, firstAfter, lastBefore, lastAfter; for (let i = 0; i < state.texts.size; i++) { keys.push(state.texts.get(i).key); } const lineText = state.texts.get(0).text; let pref, itemNum, div; if (accent === 'ul') { const ulMarker = getUlMarker(lineText); if (ulMarker) { text = ulMarker; } else { text = '* '; } } else { ({ pref, itemNum, div } = getOlNum(lineText)); } let change = state.change(); const keysLength = keys.length; const lastNum = keysLength - 1; for (let i = 0; i < keysLength; i++) { moveSelectionToLine(change, keys[i]); // eslint-disable-line no-use-before-define if (i === 0) { firstBefore = getTextLength(change); } else if (i === lastNum) { lastBefore = getTextLength(change); } if (i === 0 && !hasBlock(MATCH_SINGLE_RULE[accent], change.state) || i > 0) { text = accent === 'ul' ? text : `${pref}${itemNum}${div} `; change = wrapBlockForChange(MATCH_RULES[accent], text, change);// eslint-disable-line if (i === 0) { firstAfter = getTextLength(change); } else if (i === lastNum) { lastAfter = getTextLength(change); } itemNum++; continue; } if (i === 0) { firstAfter = firstBefore; } else if (i === lastNum) { lastAfter = lastBefore; } itemNum++; } change.select({ anchorKey, anchorOffset: anchorOffset - firstBefore + firstAfter, focusKey, focusOffset: focusOffset - lastBefore + lastAfter, isFocused: true, isBackward }); return change.state; } else { return wrapBlock(MATCH_RULES[accent], text, state); } }
[ "function", "(", "accent", ",", "state", ")", "{", "let", "text", "=", "accent", "===", "'ul'", "?", "'* '", ":", "'1. '", ";", "if", "(", "hasMultiLineSelection", "(", "state", ")", ")", "{", "const", "{", "anchorKey", ",", "anchorOffset", ",", "focusKey", ",", "focusOffset", ",", "isBackward", "}", "=", "state", ".", "selection", ";", "const", "keys", "=", "[", "]", ";", "let", "firstBefore", ",", "firstAfter", ",", "lastBefore", ",", "lastAfter", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "state", ".", "texts", ".", "size", ";", "i", "++", ")", "{", "keys", ".", "push", "(", "state", ".", "texts", ".", "get", "(", "i", ")", ".", "key", ")", ";", "}", "const", "lineText", "=", "state", ".", "texts", ".", "get", "(", "0", ")", ".", "text", ";", "let", "pref", ",", "itemNum", ",", "div", ";", "if", "(", "accent", "===", "'ul'", ")", "{", "const", "ulMarker", "=", "getUlMarker", "(", "lineText", ")", ";", "if", "(", "ulMarker", ")", "{", "text", "=", "ulMarker", ";", "}", "else", "{", "text", "=", "'* '", ";", "}", "}", "else", "{", "(", "{", "pref", ",", "itemNum", ",", "div", "}", "=", "getOlNum", "(", "lineText", ")", ")", ";", "}", "let", "change", "=", "state", ".", "change", "(", ")", ";", "const", "keysLength", "=", "keys", ".", "length", ";", "const", "lastNum", "=", "keysLength", "-", "1", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "keysLength", ";", "i", "++", ")", "{", "moveSelectionToLine", "(", "change", ",", "keys", "[", "i", "]", ")", ";", "// eslint-disable-line no-use-before-define", "if", "(", "i", "===", "0", ")", "{", "firstBefore", "=", "getTextLength", "(", "change", ")", ";", "}", "else", "if", "(", "i", "===", "lastNum", ")", "{", "lastBefore", "=", "getTextLength", "(", "change", ")", ";", "}", "if", "(", "i", "===", "0", "&&", "!", "hasBlock", "(", "MATCH_SINGLE_RULE", "[", "accent", "]", ",", "change", ".", "state", ")", "||", "i", ">", "0", ")", "{", "text", "=", "accent", "===", "'ul'", "?", "text", ":", "`", "${", "pref", "}", "${", "itemNum", "}", "${", "div", "}", "`", ";", "change", "=", "wrapBlockForChange", "(", "MATCH_RULES", "[", "accent", "]", ",", "text", ",", "change", ")", ";", "// eslint-disable-line", "if", "(", "i", "===", "0", ")", "{", "firstAfter", "=", "getTextLength", "(", "change", ")", ";", "}", "else", "if", "(", "i", "===", "lastNum", ")", "{", "lastAfter", "=", "getTextLength", "(", "change", ")", ";", "}", "itemNum", "++", ";", "continue", ";", "}", "if", "(", "i", "===", "0", ")", "{", "firstAfter", "=", "firstBefore", ";", "}", "else", "if", "(", "i", "===", "lastNum", ")", "{", "lastAfter", "=", "lastBefore", ";", "}", "itemNum", "++", ";", "}", "change", ".", "select", "(", "{", "anchorKey", ",", "anchorOffset", ":", "anchorOffset", "-", "firstBefore", "+", "firstAfter", ",", "focusKey", ",", "focusOffset", ":", "focusOffset", "-", "lastBefore", "+", "lastAfter", ",", "isFocused", ":", "true", ",", "isBackward", "}", ")", ";", "return", "change", ".", "state", ";", "}", "else", "{", "return", "wrapBlock", "(", "MATCH_RULES", "[", "accent", "]", ",", "text", ",", "state", ")", ";", "}", "}" ]
Wrap text with list token @param {string} accent @param state - editor state @returns {Object} - state
[ "Wrap", "text", "with", "list", "token" ]
77f977bd839bdf9c90b8f064179e44464860ae11
https://github.com/OpusCapita/react-markdown/blob/77f977bd839bdf9c90b8f064179e44464860ae11/src/client/components/PlainMarkdownInput/slate/transforms.js#L568-L638
22,371
OpusCapita/react-markdown
src/client/components/PlainMarkdownInput/slate/transforms.js
function(accent, state) { if (hasMultiLineSelection(state)) { const { anchorKey, anchorOffset, focusKey, focusOffset, isBackward } = state.selection; const keys = []; let firstBefore, firstAfter, lastBefore, lastAfter; for (let i = 0; i < state.texts.size; i++) { keys.push(state.texts.get(i).key); } let change = state.change(); const keysLength = keys.length; const lastNum = keysLength - 1; for (let i = 0; i < keysLength; i++) { moveSelectionToLine(change, keys[i]); if (i === 0) { firstBefore = getTextLength(change); } else if (i === lastNum) { lastBefore = getTextLength(change); } change = unwrapListCallbacksForChange[accent](change); if (i === 0) { firstAfter = getTextLength(change); } else if (i === lastNum) { lastAfter = getTextLength(change); } } const newAnchorOffset = anchorOffset - (isBackward ? lastBefore - lastAfter : firstBefore - firstAfter); const newFocusOffset = focusOffset - (isBackward ? firstBefore - firstAfter : lastBefore - lastAfter); change.select({ anchorKey, anchorOffset: newAnchorOffset < 0 ? 0 : newAnchorOffset, focusKey, focusOffset: newFocusOffset < 0 ? 0 : newFocusOffset, isFocused: true, isBackward }); return change.state; } else { return unwrapListCallbacks[accent](state); } }
javascript
function(accent, state) { if (hasMultiLineSelection(state)) { const { anchorKey, anchorOffset, focusKey, focusOffset, isBackward } = state.selection; const keys = []; let firstBefore, firstAfter, lastBefore, lastAfter; for (let i = 0; i < state.texts.size; i++) { keys.push(state.texts.get(i).key); } let change = state.change(); const keysLength = keys.length; const lastNum = keysLength - 1; for (let i = 0; i < keysLength; i++) { moveSelectionToLine(change, keys[i]); if (i === 0) { firstBefore = getTextLength(change); } else if (i === lastNum) { lastBefore = getTextLength(change); } change = unwrapListCallbacksForChange[accent](change); if (i === 0) { firstAfter = getTextLength(change); } else if (i === lastNum) { lastAfter = getTextLength(change); } } const newAnchorOffset = anchorOffset - (isBackward ? lastBefore - lastAfter : firstBefore - firstAfter); const newFocusOffset = focusOffset - (isBackward ? firstBefore - firstAfter : lastBefore - lastAfter); change.select({ anchorKey, anchorOffset: newAnchorOffset < 0 ? 0 : newAnchorOffset, focusKey, focusOffset: newFocusOffset < 0 ? 0 : newFocusOffset, isFocused: true, isBackward }); return change.state; } else { return unwrapListCallbacks[accent](state); } }
[ "function", "(", "accent", ",", "state", ")", "{", "if", "(", "hasMultiLineSelection", "(", "state", ")", ")", "{", "const", "{", "anchorKey", ",", "anchorOffset", ",", "focusKey", ",", "focusOffset", ",", "isBackward", "}", "=", "state", ".", "selection", ";", "const", "keys", "=", "[", "]", ";", "let", "firstBefore", ",", "firstAfter", ",", "lastBefore", ",", "lastAfter", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "state", ".", "texts", ".", "size", ";", "i", "++", ")", "{", "keys", ".", "push", "(", "state", ".", "texts", ".", "get", "(", "i", ")", ".", "key", ")", ";", "}", "let", "change", "=", "state", ".", "change", "(", ")", ";", "const", "keysLength", "=", "keys", ".", "length", ";", "const", "lastNum", "=", "keysLength", "-", "1", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "keysLength", ";", "i", "++", ")", "{", "moveSelectionToLine", "(", "change", ",", "keys", "[", "i", "]", ")", ";", "if", "(", "i", "===", "0", ")", "{", "firstBefore", "=", "getTextLength", "(", "change", ")", ";", "}", "else", "if", "(", "i", "===", "lastNum", ")", "{", "lastBefore", "=", "getTextLength", "(", "change", ")", ";", "}", "change", "=", "unwrapListCallbacksForChange", "[", "accent", "]", "(", "change", ")", ";", "if", "(", "i", "===", "0", ")", "{", "firstAfter", "=", "getTextLength", "(", "change", ")", ";", "}", "else", "if", "(", "i", "===", "lastNum", ")", "{", "lastAfter", "=", "getTextLength", "(", "change", ")", ";", "}", "}", "const", "newAnchorOffset", "=", "anchorOffset", "-", "(", "isBackward", "?", "lastBefore", "-", "lastAfter", ":", "firstBefore", "-", "firstAfter", ")", ";", "const", "newFocusOffset", "=", "focusOffset", "-", "(", "isBackward", "?", "firstBefore", "-", "firstAfter", ":", "lastBefore", "-", "lastAfter", ")", ";", "change", ".", "select", "(", "{", "anchorKey", ",", "anchorOffset", ":", "newAnchorOffset", "<", "0", "?", "0", ":", "newAnchorOffset", ",", "focusKey", ",", "focusOffset", ":", "newFocusOffset", "<", "0", "?", "0", ":", "newFocusOffset", ",", "isFocused", ":", "true", ",", "isBackward", "}", ")", ";", "return", "change", ".", "state", ";", "}", "else", "{", "return", "unwrapListCallbacks", "[", "accent", "]", "(", "state", ")", ";", "}", "}" ]
Unwrap text with list token @param {string} accent @param state - editor state @returns {Object} - state
[ "Unwrap", "text", "with", "list", "token" ]
77f977bd839bdf9c90b8f064179e44464860ae11
https://github.com/OpusCapita/react-markdown/blob/77f977bd839bdf9c90b8f064179e44464860ae11/src/client/components/PlainMarkdownInput/slate/transforms.js#L698-L744
22,372
nathanpeck/s3-upload-stream
lib/s3-upload-stream.js
Client
function Client(client) { if (this instanceof Client === false) { return new Client(client); } if (!client) { throw new Error('Must configure an S3 client before attempting to create an S3 upload stream.'); } this.cachedClient = client; }
javascript
function Client(client) { if (this instanceof Client === false) { return new Client(client); } if (!client) { throw new Error('Must configure an S3 client before attempting to create an S3 upload stream.'); } this.cachedClient = client; }
[ "function", "Client", "(", "client", ")", "{", "if", "(", "this", "instanceof", "Client", "===", "false", ")", "{", "return", "new", "Client", "(", "client", ")", ";", "}", "if", "(", "!", "client", ")", "{", "throw", "new", "Error", "(", "'Must configure an S3 client before attempting to create an S3 upload stream.'", ")", ";", "}", "this", ".", "cachedClient", "=", "client", ";", "}" ]
Set the S3 client to be used for this upload.
[ "Set", "the", "S3", "client", "to", "be", "used", "for", "this", "upload", "." ]
cf6b82d44426dfe06fb3e3de1af0db6fa7ecdfa4
https://github.com/nathanpeck/s3-upload-stream/blob/cf6b82d44426dfe06fb3e3de1af0db6fa7ecdfa4/lib/s3-upload-stream.js#L5-L15
22,373
nathanpeck/s3-upload-stream
lib/s3-upload-stream.js
function (next) { // If this is the first part, and we're just starting, // but we have a multipartUploadID, then we're beginning // a resume and can fire the 'ready' event externally. if (multipartUploadID && !started) ws.emit('ready', multipartUploadID); started = true; if (pendingParts < concurrentPartThreshold) { // Has the MPU been created yet? if (multipartUploadID) upload(); // Upload the part immediately. else { e.once('ready', upload); // Wait until multipart upload is initialized. createMultipartUpload(); } } else { // Block uploading (and receiving of more data) until we upload // some of the pending parts e.once('part', upload); } function upload() { // Pause/resume check #2 out of 2: // Block queued up parts until resumption. if (paused) e.once('resume', uploadNow); else uploadNow(); function uploadNow() { pendingParts++; flushPart(function (partDetails) { --pendingParts; e.emit('part'); // Internal event ws.emit('part', partDetails); // External event // if we're paused and this was the last outstanding part, // we can notify the caller that we're really paused now. if (paused && pendingParts === 0) notifyPaused(); }); next(); } } }
javascript
function (next) { // If this is the first part, and we're just starting, // but we have a multipartUploadID, then we're beginning // a resume and can fire the 'ready' event externally. if (multipartUploadID && !started) ws.emit('ready', multipartUploadID); started = true; if (pendingParts < concurrentPartThreshold) { // Has the MPU been created yet? if (multipartUploadID) upload(); // Upload the part immediately. else { e.once('ready', upload); // Wait until multipart upload is initialized. createMultipartUpload(); } } else { // Block uploading (and receiving of more data) until we upload // some of the pending parts e.once('part', upload); } function upload() { // Pause/resume check #2 out of 2: // Block queued up parts until resumption. if (paused) e.once('resume', uploadNow); else uploadNow(); function uploadNow() { pendingParts++; flushPart(function (partDetails) { --pendingParts; e.emit('part'); // Internal event ws.emit('part', partDetails); // External event // if we're paused and this was the last outstanding part, // we can notify the caller that we're really paused now. if (paused && pendingParts === 0) notifyPaused(); }); next(); } } }
[ "function", "(", "next", ")", "{", "// If this is the first part, and we're just starting,", "// but we have a multipartUploadID, then we're beginning", "// a resume and can fire the 'ready' event externally.", "if", "(", "multipartUploadID", "&&", "!", "started", ")", "ws", ".", "emit", "(", "'ready'", ",", "multipartUploadID", ")", ";", "started", "=", "true", ";", "if", "(", "pendingParts", "<", "concurrentPartThreshold", ")", "{", "// Has the MPU been created yet?", "if", "(", "multipartUploadID", ")", "upload", "(", ")", ";", "// Upload the part immediately.", "else", "{", "e", ".", "once", "(", "'ready'", ",", "upload", ")", ";", "// Wait until multipart upload is initialized.", "createMultipartUpload", "(", ")", ";", "}", "}", "else", "{", "// Block uploading (and receiving of more data) until we upload", "// some of the pending parts", "e", ".", "once", "(", "'part'", ",", "upload", ")", ";", "}", "function", "upload", "(", ")", "{", "// Pause/resume check #2 out of 2:", "// Block queued up parts until resumption.", "if", "(", "paused", ")", "e", ".", "once", "(", "'resume'", ",", "uploadNow", ")", ";", "else", "uploadNow", "(", ")", ";", "function", "uploadNow", "(", ")", "{", "pendingParts", "++", ";", "flushPart", "(", "function", "(", "partDetails", ")", "{", "--", "pendingParts", ";", "e", ".", "emit", "(", "'part'", ")", ";", "// Internal event", "ws", ".", "emit", "(", "'part'", ",", "partDetails", ")", ";", "// External event", "// if we're paused and this was the last outstanding part,", "// we can notify the caller that we're really paused now.", "if", "(", "paused", "&&", "pendingParts", "===", "0", ")", "notifyPaused", "(", ")", ";", "}", ")", ";", "next", "(", ")", ";", "}", "}", "}" ]
Concurrently upload parts to S3.
[ "Concurrently", "upload", "parts", "to", "S3", "." ]
cf6b82d44426dfe06fb3e3de1af0db6fa7ecdfa4
https://github.com/nathanpeck/s3-upload-stream/blob/cf6b82d44426dfe06fb3e3de1af0db6fa7ecdfa4/lib/s3-upload-stream.js#L146-L195
22,374
nathanpeck/s3-upload-stream
lib/s3-upload-stream.js
function () { // Combine the buffers we've received and reset the list of buffers. var combinedBuffer = Buffer.concat(receivedBuffers, receivedBuffersLength); receivedBuffers.length = 0; // Trick to reset the array while keeping the original reference receivedBuffersLength = 0; if (combinedBuffer.length > partSizeThreshold) { // The combined buffer is too big, so slice off the end and put it back in the array. var remainder = new Buffer(combinedBuffer.length - partSizeThreshold); combinedBuffer.copy(remainder, 0, partSizeThreshold); receivedBuffers.push(remainder); receivedBuffersLength = remainder.length; // Return the perfectly sized part. var uploadBuffer = new Buffer(partSizeThreshold); combinedBuffer.copy(uploadBuffer, 0, 0, partSizeThreshold); return uploadBuffer; } else { // It just happened to be perfectly sized, so return it. return combinedBuffer; } }
javascript
function () { // Combine the buffers we've received and reset the list of buffers. var combinedBuffer = Buffer.concat(receivedBuffers, receivedBuffersLength); receivedBuffers.length = 0; // Trick to reset the array while keeping the original reference receivedBuffersLength = 0; if (combinedBuffer.length > partSizeThreshold) { // The combined buffer is too big, so slice off the end and put it back in the array. var remainder = new Buffer(combinedBuffer.length - partSizeThreshold); combinedBuffer.copy(remainder, 0, partSizeThreshold); receivedBuffers.push(remainder); receivedBuffersLength = remainder.length; // Return the perfectly sized part. var uploadBuffer = new Buffer(partSizeThreshold); combinedBuffer.copy(uploadBuffer, 0, 0, partSizeThreshold); return uploadBuffer; } else { // It just happened to be perfectly sized, so return it. return combinedBuffer; } }
[ "function", "(", ")", "{", "// Combine the buffers we've received and reset the list of buffers.", "var", "combinedBuffer", "=", "Buffer", ".", "concat", "(", "receivedBuffers", ",", "receivedBuffersLength", ")", ";", "receivedBuffers", ".", "length", "=", "0", ";", "// Trick to reset the array while keeping the original reference", "receivedBuffersLength", "=", "0", ";", "if", "(", "combinedBuffer", ".", "length", ">", "partSizeThreshold", ")", "{", "// The combined buffer is too big, so slice off the end and put it back in the array.", "var", "remainder", "=", "new", "Buffer", "(", "combinedBuffer", ".", "length", "-", "partSizeThreshold", ")", ";", "combinedBuffer", ".", "copy", "(", "remainder", ",", "0", ",", "partSizeThreshold", ")", ";", "receivedBuffers", ".", "push", "(", "remainder", ")", ";", "receivedBuffersLength", "=", "remainder", ".", "length", ";", "// Return the perfectly sized part.", "var", "uploadBuffer", "=", "new", "Buffer", "(", "partSizeThreshold", ")", ";", "combinedBuffer", ".", "copy", "(", "uploadBuffer", ",", "0", ",", "0", ",", "partSizeThreshold", ")", ";", "return", "uploadBuffer", ";", "}", "else", "{", "// It just happened to be perfectly sized, so return it.", "return", "combinedBuffer", ";", "}", "}" ]
Take a list of received buffers and return a combined buffer that is exactly partSizeThreshold in size.
[ "Take", "a", "list", "of", "received", "buffers", "and", "return", "a", "combined", "buffer", "that", "is", "exactly", "partSizeThreshold", "in", "size", "." ]
cf6b82d44426dfe06fb3e3de1af0db6fa7ecdfa4
https://github.com/nathanpeck/s3-upload-stream/blob/cf6b82d44426dfe06fb3e3de1af0db6fa7ecdfa4/lib/s3-upload-stream.js#L205-L227
22,375
nathanpeck/s3-upload-stream
lib/s3-upload-stream.js
function (callback) { var partBuffer = preparePartBuffer(); var localPartNumber = partNumber; partNumber++; receivedSize += partBuffer.length; cachedClient.uploadPart( { Body: partBuffer, Bucket: destinationDetails.Bucket, Key: destinationDetails.Key, UploadId: multipartUploadID, PartNumber: localPartNumber }, function (err, result) { if (err) abortUpload('Failed to upload a part to S3: ' + JSON.stringify(err)); else { uploadedSize += partBuffer.length; partIds[localPartNumber - 1] = { ETag: result.ETag, PartNumber: localPartNumber }; callback({ ETag: result.ETag, PartNumber: localPartNumber, receivedSize: receivedSize, uploadedSize: uploadedSize }); } } ); }
javascript
function (callback) { var partBuffer = preparePartBuffer(); var localPartNumber = partNumber; partNumber++; receivedSize += partBuffer.length; cachedClient.uploadPart( { Body: partBuffer, Bucket: destinationDetails.Bucket, Key: destinationDetails.Key, UploadId: multipartUploadID, PartNumber: localPartNumber }, function (err, result) { if (err) abortUpload('Failed to upload a part to S3: ' + JSON.stringify(err)); else { uploadedSize += partBuffer.length; partIds[localPartNumber - 1] = { ETag: result.ETag, PartNumber: localPartNumber }; callback({ ETag: result.ETag, PartNumber: localPartNumber, receivedSize: receivedSize, uploadedSize: uploadedSize }); } } ); }
[ "function", "(", "callback", ")", "{", "var", "partBuffer", "=", "preparePartBuffer", "(", ")", ";", "var", "localPartNumber", "=", "partNumber", ";", "partNumber", "++", ";", "receivedSize", "+=", "partBuffer", ".", "length", ";", "cachedClient", ".", "uploadPart", "(", "{", "Body", ":", "partBuffer", ",", "Bucket", ":", "destinationDetails", ".", "Bucket", ",", "Key", ":", "destinationDetails", ".", "Key", ",", "UploadId", ":", "multipartUploadID", ",", "PartNumber", ":", "localPartNumber", "}", ",", "function", "(", "err", ",", "result", ")", "{", "if", "(", "err", ")", "abortUpload", "(", "'Failed to upload a part to S3: '", "+", "JSON", ".", "stringify", "(", "err", ")", ")", ";", "else", "{", "uploadedSize", "+=", "partBuffer", ".", "length", ";", "partIds", "[", "localPartNumber", "-", "1", "]", "=", "{", "ETag", ":", "result", ".", "ETag", ",", "PartNumber", ":", "localPartNumber", "}", ";", "callback", "(", "{", "ETag", ":", "result", ".", "ETag", ",", "PartNumber", ":", "localPartNumber", ",", "receivedSize", ":", "receivedSize", ",", "uploadedSize", ":", "uploadedSize", "}", ")", ";", "}", "}", ")", ";", "}" ]
Flush a part out to S3.
[ "Flush", "a", "part", "out", "to", "S3", "." ]
cf6b82d44426dfe06fb3e3de1af0db6fa7ecdfa4
https://github.com/nathanpeck/s3-upload-stream/blob/cf6b82d44426dfe06fb3e3de1af0db6fa7ecdfa4/lib/s3-upload-stream.js#L230-L263
22,376
nathanpeck/s3-upload-stream
lib/s3-upload-stream.js
function () { // There is a possibility that the incoming stream was empty, therefore the MPU never started // and cannot be finalized. if (multipartUploadID) { cachedClient.completeMultipartUpload( { Bucket: destinationDetails.Bucket, Key: destinationDetails.Key, UploadId: multipartUploadID, MultipartUpload: { Parts: partIds } }, function (err, result) { if (err) abortUpload('Failed to complete the multipart upload on S3: ' + JSON.stringify(err)); else { // Emit both events for backwards compatibility, and to follow the spec. ws.emit('uploaded', result); ws.emit('finish', result); started = false; } } ); } }
javascript
function () { // There is a possibility that the incoming stream was empty, therefore the MPU never started // and cannot be finalized. if (multipartUploadID) { cachedClient.completeMultipartUpload( { Bucket: destinationDetails.Bucket, Key: destinationDetails.Key, UploadId: multipartUploadID, MultipartUpload: { Parts: partIds } }, function (err, result) { if (err) abortUpload('Failed to complete the multipart upload on S3: ' + JSON.stringify(err)); else { // Emit both events for backwards compatibility, and to follow the spec. ws.emit('uploaded', result); ws.emit('finish', result); started = false; } } ); } }
[ "function", "(", ")", "{", "// There is a possibility that the incoming stream was empty, therefore the MPU never started", "// and cannot be finalized.", "if", "(", "multipartUploadID", ")", "{", "cachedClient", ".", "completeMultipartUpload", "(", "{", "Bucket", ":", "destinationDetails", ".", "Bucket", ",", "Key", ":", "destinationDetails", ".", "Key", ",", "UploadId", ":", "multipartUploadID", ",", "MultipartUpload", ":", "{", "Parts", ":", "partIds", "}", "}", ",", "function", "(", "err", ",", "result", ")", "{", "if", "(", "err", ")", "abortUpload", "(", "'Failed to complete the multipart upload on S3: '", "+", "JSON", ".", "stringify", "(", "err", ")", ")", ";", "else", "{", "// Emit both events for backwards compatibility, and to follow the spec.", "ws", ".", "emit", "(", "'uploaded'", ",", "result", ")", ";", "ws", ".", "emit", "(", "'finish'", ",", "result", ")", ";", "started", "=", "false", ";", "}", "}", ")", ";", "}", "}" ]
Turn all the individual parts we uploaded to S3 into a finalized upload.
[ "Turn", "all", "the", "individual", "parts", "we", "uploaded", "to", "S3", "into", "a", "finalized", "upload", "." ]
cf6b82d44426dfe06fb3e3de1af0db6fa7ecdfa4
https://github.com/nathanpeck/s3-upload-stream/blob/cf6b82d44426dfe06fb3e3de1af0db6fa7ecdfa4/lib/s3-upload-stream.js#L296-L321
22,377
nathanpeck/s3-upload-stream
lib/s3-upload-stream.js
function (rootError) { cachedClient.abortMultipartUpload( { Bucket: destinationDetails.Bucket, Key: destinationDetails.Key, UploadId: multipartUploadID }, function (abortError) { if (abortError) ws.emit('error', rootError + '\n Additionally failed to abort the multipart upload on S3: ' + abortError); else ws.emit('error', rootError); } ); }
javascript
function (rootError) { cachedClient.abortMultipartUpload( { Bucket: destinationDetails.Bucket, Key: destinationDetails.Key, UploadId: multipartUploadID }, function (abortError) { if (abortError) ws.emit('error', rootError + '\n Additionally failed to abort the multipart upload on S3: ' + abortError); else ws.emit('error', rootError); } ); }
[ "function", "(", "rootError", ")", "{", "cachedClient", ".", "abortMultipartUpload", "(", "{", "Bucket", ":", "destinationDetails", ".", "Bucket", ",", "Key", ":", "destinationDetails", ".", "Key", ",", "UploadId", ":", "multipartUploadID", "}", ",", "function", "(", "abortError", ")", "{", "if", "(", "abortError", ")", "ws", ".", "emit", "(", "'error'", ",", "rootError", "+", "'\\n Additionally failed to abort the multipart upload on S3: '", "+", "abortError", ")", ";", "else", "ws", ".", "emit", "(", "'error'", ",", "rootError", ")", ";", "}", ")", ";", "}" ]
When a fatal error occurs abort the multipart upload
[ "When", "a", "fatal", "error", "occurs", "abort", "the", "multipart", "upload" ]
cf6b82d44426dfe06fb3e3de1af0db6fa7ecdfa4
https://github.com/nathanpeck/s3-upload-stream/blob/cf6b82d44426dfe06fb3e3de1af0db6fa7ecdfa4/lib/s3-upload-stream.js#L324-L338
22,378
Wildhoney/ngRangeSlider
dist/ng-range-slider.js
_reevaluateInputs
function _reevaluateInputs() { var inputElements = element.find('input'); $angular.forEach(inputElements, function forEach(inputElement, index) { inputElement = $angular.element(inputElement); inputElement.val(''); inputElement.val(scope._model[index]); }); }
javascript
function _reevaluateInputs() { var inputElements = element.find('input'); $angular.forEach(inputElements, function forEach(inputElement, index) { inputElement = $angular.element(inputElement); inputElement.val(''); inputElement.val(scope._model[index]); }); }
[ "function", "_reevaluateInputs", "(", ")", "{", "var", "inputElements", "=", "element", ".", "find", "(", "'input'", ")", ";", "$angular", ".", "forEach", "(", "inputElements", ",", "function", "forEach", "(", "inputElement", ",", "index", ")", "{", "inputElement", "=", "$angular", ".", "element", "(", "inputElement", ")", ";", "inputElement", ".", "val", "(", "''", ")", ";", "inputElement", ".", "val", "(", "scope", ".", "_model", "[", "index", "]", ")", ";", "}", ")", ";", "}" ]
Force the re-evaluation of the input slider values. @method _reevaluateInputs @return {void} @private
[ "Force", "the", "re", "-", "evaluation", "of", "the", "input", "slider", "values", "." ]
f5eafc1dea7523f4b2f135c92e1cfded1baaa267
https://github.com/Wildhoney/ngRangeSlider/blob/f5eafc1dea7523f4b2f135c92e1cfded1baaa267/dist/ng-range-slider.js#L140-L153
22,379
julienw/dollardom
legacy/$dom.legacy.js
_sel
function _sel(selector) { var f, out = []; if (typeof selector == "string") { while (selector != "") { f = selector.match(re_selector_fragment); if (f[0] == "") return null; out.push({ rel: f[1], tag: f[2], uTag: (f[2] || "").toUpperCase(), id: f[3], classes: (f[4]) ? f[4].split(".") : _undefined }); selector = selector.substring(f[0].length); } } return out; }
javascript
function _sel(selector) { var f, out = []; if (typeof selector == "string") { while (selector != "") { f = selector.match(re_selector_fragment); if (f[0] == "") return null; out.push({ rel: f[1], tag: f[2], uTag: (f[2] || "").toUpperCase(), id: f[3], classes: (f[4]) ? f[4].split(".") : _undefined }); selector = selector.substring(f[0].length); } } return out; }
[ "function", "_sel", "(", "selector", ")", "{", "var", "f", ",", "out", "=", "[", "]", ";", "if", "(", "typeof", "selector", "==", "\"string\"", ")", "{", "while", "(", "selector", "!=", "\"\"", ")", "{", "f", "=", "selector", ".", "match", "(", "re_selector_fragment", ")", ";", "if", "(", "f", "[", "0", "]", "==", "\"\"", ")", "return", "null", ";", "out", ".", "push", "(", "{", "rel", ":", "f", "[", "1", "]", ",", "tag", ":", "f", "[", "2", "]", ",", "uTag", ":", "(", "f", "[", "2", "]", "||", "\"\"", ")", ".", "toUpperCase", "(", ")", ",", "id", ":", "f", "[", "3", "]", ",", "classes", ":", "(", "f", "[", "4", "]", ")", "?", "f", "[", "4", "]", ".", "split", "(", "\".\"", ")", ":", "_undefined", "}", ")", ";", "selector", "=", "selector", ".", "substring", "(", "f", "[", "0", "]", ".", "length", ")", ";", "}", "}", "return", "out", ";", "}" ]
_sel returns an array of simple selector fragment objects from the passed complex selector string
[ "_sel", "returns", "an", "array", "of", "simple", "selector", "fragment", "objects", "from", "the", "passed", "complex", "selector", "string" ]
59caa3e2d169e3de59dc9414f0023ceeec7ea782
https://github.com/julienw/dollardom/blob/59caa3e2d169e3de59dc9414f0023ceeec7ea782/legacy/$dom.legacy.js#L175-L189
22,380
julienw/dollardom
legacy/$dom.legacy.js
_isDescendant
function _isDescendant(elm, ancestor) { while ((elm = elm.parentNode) && elm != ancestor) { } return elm !== null; }
javascript
function _isDescendant(elm, ancestor) { while ((elm = elm.parentNode) && elm != ancestor) { } return elm !== null; }
[ "function", "_isDescendant", "(", "elm", ",", "ancestor", ")", "{", "while", "(", "(", "elm", "=", "elm", ".", "parentNode", ")", "&&", "elm", "!=", "ancestor", ")", "{", "}", "return", "elm", "!==", "null", ";", "}" ]
determines if the passed element is a descentand of anthor element
[ "determines", "if", "the", "passed", "element", "is", "a", "descentand", "of", "anthor", "element" ]
59caa3e2d169e3de59dc9414f0023ceeec7ea782
https://github.com/julienw/dollardom/blob/59caa3e2d169e3de59dc9414f0023ceeec7ea782/legacy/$dom.legacy.js#L193-L197
22,381
a1k0n/jsxm
trackview.js
drawText
function drawText(text, dx, dy, ctx) { var dx0 = dx; for (var i = 0; i < text.length; i++) { var n = text.charCodeAt(i); var sx = (n&63)*8; var sy = (n>>6)*10 + 56; var width = _fontwidths[n]; ctx.drawImage(fontimg, sx, sy, width, 10, dx, dy, width, 10); dx += width + 1; } return dx - dx0; }
javascript
function drawText(text, dx, dy, ctx) { var dx0 = dx; for (var i = 0; i < text.length; i++) { var n = text.charCodeAt(i); var sx = (n&63)*8; var sy = (n>>6)*10 + 56; var width = _fontwidths[n]; ctx.drawImage(fontimg, sx, sy, width, 10, dx, dy, width, 10); dx += width + 1; } return dx - dx0; }
[ "function", "drawText", "(", "text", ",", "dx", ",", "dy", ",", "ctx", ")", "{", "var", "dx0", "=", "dx", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "text", ".", "length", ";", "i", "++", ")", "{", "var", "n", "=", "text", ".", "charCodeAt", "(", "i", ")", ";", "var", "sx", "=", "(", "n", "&", "63", ")", "*", "8", ";", "var", "sy", "=", "(", "n", ">>", "6", ")", "*", "10", "+", "56", ";", "var", "width", "=", "_fontwidths", "[", "n", "]", ";", "ctx", ".", "drawImage", "(", "fontimg", ",", "sx", ",", "sy", ",", "width", ",", "10", ",", "dx", ",", "dy", ",", "width", ",", "10", ")", ";", "dx", "+=", "width", "+", "1", ";", "}", "return", "dx", "-", "dx0", ";", "}" ]
draw FT2 proportional font text to a drawing context returns width rendered
[ "draw", "FT2", "proportional", "font", "text", "to", "a", "drawing", "context", "returns", "width", "rendered" ]
72f3c18b25ac547a8d2c1d95318b747fac371a2a
https://github.com/a1k0n/jsxm/blob/72f3c18b25ac547a8d2c1d95318b747fac371a2a/trackview.js#L60-L71
22,382
a1k0n/jsxm
xm.js
MixSilenceIntoBuf
function MixSilenceIntoBuf(ch, start, end, dataL, dataR) { var s = ch.filterstate[1]; if (isNaN(s)) { console.log("NaN filterstate?", ch.filterstate, ch.filter); return; } for (var i = start; i < end; i++) { if (Math.abs(s) < 1.526e-5) { // == 1/65536.0 s = 0; break; } dataL[i] += s * ch.vL; dataR[i] += s * ch.vR; s *= popfilter_alpha; } ch.filterstate[1] = s; ch.filterstate[2] = s; if (isNaN(s)) { console.log("NaN filterstate after adding silence?", ch.filterstate, ch.filter, i); return; } return 0; }
javascript
function MixSilenceIntoBuf(ch, start, end, dataL, dataR) { var s = ch.filterstate[1]; if (isNaN(s)) { console.log("NaN filterstate?", ch.filterstate, ch.filter); return; } for (var i = start; i < end; i++) { if (Math.abs(s) < 1.526e-5) { // == 1/65536.0 s = 0; break; } dataL[i] += s * ch.vL; dataR[i] += s * ch.vR; s *= popfilter_alpha; } ch.filterstate[1] = s; ch.filterstate[2] = s; if (isNaN(s)) { console.log("NaN filterstate after adding silence?", ch.filterstate, ch.filter, i); return; } return 0; }
[ "function", "MixSilenceIntoBuf", "(", "ch", ",", "start", ",", "end", ",", "dataL", ",", "dataR", ")", "{", "var", "s", "=", "ch", ".", "filterstate", "[", "1", "]", ";", "if", "(", "isNaN", "(", "s", ")", ")", "{", "console", ".", "log", "(", "\"NaN filterstate?\"", ",", "ch", ".", "filterstate", ",", "ch", ".", "filter", ")", ";", "return", ";", "}", "for", "(", "var", "i", "=", "start", ";", "i", "<", "end", ";", "i", "++", ")", "{", "if", "(", "Math", ".", "abs", "(", "s", ")", "<", "1.526e-5", ")", "{", "// == 1/65536.0", "s", "=", "0", ";", "break", ";", "}", "dataL", "[", "i", "]", "+=", "s", "*", "ch", ".", "vL", ";", "dataR", "[", "i", "]", "+=", "s", "*", "ch", ".", "vR", ";", "s", "*=", "popfilter_alpha", ";", "}", "ch", ".", "filterstate", "[", "1", "]", "=", "s", ";", "ch", ".", "filterstate", "[", "2", "]", "=", "s", ";", "if", "(", "isNaN", "(", "s", ")", ")", "{", "console", ".", "log", "(", "\"NaN filterstate after adding silence?\"", ",", "ch", ".", "filterstate", ",", "ch", ".", "filter", ",", "i", ")", ";", "return", ";", "}", "return", "0", ";", "}" ]
This function gradually brings the channel back down to zero if it isn't already to avoid clicks and pops when samples end.
[ "This", "function", "gradually", "brings", "the", "channel", "back", "down", "to", "zero", "if", "it", "isn", "t", "already", "to", "avoid", "clicks", "and", "pops", "when", "samples", "end", "." ]
72f3c18b25ac547a8d2c1d95318b747fac371a2a
https://github.com/a1k0n/jsxm/blob/72f3c18b25ac547a8d2c1d95318b747fac371a2a/xm.js#L370-L392
22,383
postcss/postcss-custom-selectors
lib/transform-selectors-by-custom-selectors.js
transformSelector
function transformSelector(selector, customSelectors) { const transpiledSelectors = []; for (const index in selector.nodes) { const { value, nodes } = selector.nodes[index]; if (value in customSelectors) { for (const replacementSelector of customSelectors[value].nodes) { const selectorClone = selector.clone(); selectorClone.nodes.splice(index, 1, ...replacementSelector.clone().nodes.map(node => { // use spacing from the current usage node.spaces = { ...selector.nodes[index].spaces }; return node; })); const retranspiledSelectors = transformSelector(selectorClone, customSelectors); adjustNodesBySelectorEnds(selectorClone.nodes, Number(index)); if (retranspiledSelectors.length) { transpiledSelectors.push(...retranspiledSelectors); } else { transpiledSelectors.push(selectorClone); } } return transpiledSelectors; } else if (nodes && nodes.length) { transformSelectorList(selector.nodes[index], customSelectors); } } return transpiledSelectors; }
javascript
function transformSelector(selector, customSelectors) { const transpiledSelectors = []; for (const index in selector.nodes) { const { value, nodes } = selector.nodes[index]; if (value in customSelectors) { for (const replacementSelector of customSelectors[value].nodes) { const selectorClone = selector.clone(); selectorClone.nodes.splice(index, 1, ...replacementSelector.clone().nodes.map(node => { // use spacing from the current usage node.spaces = { ...selector.nodes[index].spaces }; return node; })); const retranspiledSelectors = transformSelector(selectorClone, customSelectors); adjustNodesBySelectorEnds(selectorClone.nodes, Number(index)); if (retranspiledSelectors.length) { transpiledSelectors.push(...retranspiledSelectors); } else { transpiledSelectors.push(selectorClone); } } return transpiledSelectors; } else if (nodes && nodes.length) { transformSelectorList(selector.nodes[index], customSelectors); } } return transpiledSelectors; }
[ "function", "transformSelector", "(", "selector", ",", "customSelectors", ")", "{", "const", "transpiledSelectors", "=", "[", "]", ";", "for", "(", "const", "index", "in", "selector", ".", "nodes", ")", "{", "const", "{", "value", ",", "nodes", "}", "=", "selector", ".", "nodes", "[", "index", "]", ";", "if", "(", "value", "in", "customSelectors", ")", "{", "for", "(", "const", "replacementSelector", "of", "customSelectors", "[", "value", "]", ".", "nodes", ")", "{", "const", "selectorClone", "=", "selector", ".", "clone", "(", ")", ";", "selectorClone", ".", "nodes", ".", "splice", "(", "index", ",", "1", ",", "...", "replacementSelector", ".", "clone", "(", ")", ".", "nodes", ".", "map", "(", "node", "=>", "{", "// use spacing from the current usage", "node", ".", "spaces", "=", "{", "...", "selector", ".", "nodes", "[", "index", "]", ".", "spaces", "}", ";", "return", "node", ";", "}", ")", ")", ";", "const", "retranspiledSelectors", "=", "transformSelector", "(", "selectorClone", ",", "customSelectors", ")", ";", "adjustNodesBySelectorEnds", "(", "selectorClone", ".", "nodes", ",", "Number", "(", "index", ")", ")", ";", "if", "(", "retranspiledSelectors", ".", "length", ")", "{", "transpiledSelectors", ".", "push", "(", "...", "retranspiledSelectors", ")", ";", "}", "else", "{", "transpiledSelectors", ".", "push", "(", "selectorClone", ")", ";", "}", "}", "return", "transpiledSelectors", ";", "}", "else", "if", "(", "nodes", "&&", "nodes", ".", "length", ")", "{", "transformSelectorList", "(", "selector", ".", "nodes", "[", "index", "]", ",", "customSelectors", ")", ";", "}", "}", "return", "transpiledSelectors", ";", "}" ]
return custom pseudo selectors replaced with custom selectors
[ "return", "custom", "pseudo", "selectors", "replaced", "with", "custom", "selectors" ]
4a422f0eaba5b47fd53abe36e92f9092ad63858f
https://github.com/postcss/postcss-custom-selectors/blob/4a422f0eaba5b47fd53abe36e92f9092ad63858f/lib/transform-selectors-by-custom-selectors.js#L19-L54
22,384
enricostara/telegram.link
lib/utility.js
callService
function callService(service, emitter, channel, callback) { var argsValue = Array.prototype.slice.call(Array.prototype.slice.call(arguments)[4]); var callerFunc = arguments.callee.caller; var eventName = service.name || service._name; var callerArgNames = _retrieveArgumentNames(callerFunc); var props = {}; for(var i = 0; i < callerArgNames.length - 1; i++) { props[callerArgNames[i]] = argsValue[i]; } if (callback) { emitter.once(eventName, callback); } if (emitter.isReady(true)) { try { service({ props: props, channel: channel, callback: createEventEmitterCallback(eventName, emitter) }); } catch (err) { emitter.emit('error', err); } } return new Promise(function (fulfill, reject) { emitter.once('error', reject); emitter.once(eventName, function (result) { emitter.removeListener('error', reject); if (typeof result !== 'boolean' && result.instanceOf('mtproto.type.Rpc_error')) { reject(new Error(result.error_message)); } else { fulfill(result); } }); }); }
javascript
function callService(service, emitter, channel, callback) { var argsValue = Array.prototype.slice.call(Array.prototype.slice.call(arguments)[4]); var callerFunc = arguments.callee.caller; var eventName = service.name || service._name; var callerArgNames = _retrieveArgumentNames(callerFunc); var props = {}; for(var i = 0; i < callerArgNames.length - 1; i++) { props[callerArgNames[i]] = argsValue[i]; } if (callback) { emitter.once(eventName, callback); } if (emitter.isReady(true)) { try { service({ props: props, channel: channel, callback: createEventEmitterCallback(eventName, emitter) }); } catch (err) { emitter.emit('error', err); } } return new Promise(function (fulfill, reject) { emitter.once('error', reject); emitter.once(eventName, function (result) { emitter.removeListener('error', reject); if (typeof result !== 'boolean' && result.instanceOf('mtproto.type.Rpc_error')) { reject(new Error(result.error_message)); } else { fulfill(result); } }); }); }
[ "function", "callService", "(", "service", ",", "emitter", ",", "channel", ",", "callback", ")", "{", "var", "argsValue", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ")", "[", "4", "]", ")", ";", "var", "callerFunc", "=", "arguments", ".", "callee", ".", "caller", ";", "var", "eventName", "=", "service", ".", "name", "||", "service", ".", "_name", ";", "var", "callerArgNames", "=", "_retrieveArgumentNames", "(", "callerFunc", ")", ";", "var", "props", "=", "{", "}", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "callerArgNames", ".", "length", "-", "1", ";", "i", "++", ")", "{", "props", "[", "callerArgNames", "[", "i", "]", "]", "=", "argsValue", "[", "i", "]", ";", "}", "if", "(", "callback", ")", "{", "emitter", ".", "once", "(", "eventName", ",", "callback", ")", ";", "}", "if", "(", "emitter", ".", "isReady", "(", "true", ")", ")", "{", "try", "{", "service", "(", "{", "props", ":", "props", ",", "channel", ":", "channel", ",", "callback", ":", "createEventEmitterCallback", "(", "eventName", ",", "emitter", ")", "}", ")", ";", "}", "catch", "(", "err", ")", "{", "emitter", ".", "emit", "(", "'error'", ",", "err", ")", ";", "}", "}", "return", "new", "Promise", "(", "function", "(", "fulfill", ",", "reject", ")", "{", "emitter", ".", "once", "(", "'error'", ",", "reject", ")", ";", "emitter", ".", "once", "(", "eventName", ",", "function", "(", "result", ")", "{", "emitter", ".", "removeListener", "(", "'error'", ",", "reject", ")", ";", "if", "(", "typeof", "result", "!==", "'boolean'", "&&", "result", ".", "instanceOf", "(", "'mtproto.type.Rpc_error'", ")", ")", "{", "reject", "(", "new", "Error", "(", "result", ".", "error_message", ")", ")", ";", "}", "else", "{", "fulfill", "(", "result", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}" ]
Calls a service and infers the arguments by the caller function.
[ "Calls", "a", "service", "and", "infers", "the", "arguments", "by", "the", "caller", "function", "." ]
37c4a98f17d2311ee4335fdd42df497ff30a1153
https://github.com/enricostara/telegram.link/blob/37c4a98f17d2311ee4335fdd42df497ff30a1153/lib/utility.js#L10-L44
22,385
enricostara/telegram.link
lib/utility.js
createEventEmitterCallback
function createEventEmitterCallback(event, emitter) { return function (ex) { if (ex) { emitter.emit('error', ex); } else { var args = Array.prototype.slice.call(arguments); args[0] = event; emitter.emit.apply(emitter, args); if (event == 'end') { emitter.removeAllListeners(); } } }; }
javascript
function createEventEmitterCallback(event, emitter) { return function (ex) { if (ex) { emitter.emit('error', ex); } else { var args = Array.prototype.slice.call(arguments); args[0] = event; emitter.emit.apply(emitter, args); if (event == 'end') { emitter.removeAllListeners(); } } }; }
[ "function", "createEventEmitterCallback", "(", "event", ",", "emitter", ")", "{", "return", "function", "(", "ex", ")", "{", "if", "(", "ex", ")", "{", "emitter", ".", "emit", "(", "'error'", ",", "ex", ")", ";", "}", "else", "{", "var", "args", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ")", ";", "args", "[", "0", "]", "=", "event", ";", "emitter", ".", "emit", ".", "apply", "(", "emitter", ",", "args", ")", ";", "if", "(", "event", "==", "'end'", ")", "{", "emitter", ".", "removeAllListeners", "(", ")", ";", "}", "}", "}", ";", "}" ]
Provides a callback function that emits the supplied event type or an error event.
[ "Provides", "a", "callback", "function", "that", "emits", "the", "supplied", "event", "type", "or", "an", "error", "event", "." ]
37c4a98f17d2311ee4335fdd42df497ff30a1153
https://github.com/enricostara/telegram.link/blob/37c4a98f17d2311ee4335fdd42df497ff30a1153/lib/utility.js#L51-L64
22,386
joewalker/gcli
gcli.js
startRepl
function startRepl() { var repl = require('repl'); var gcliEval = function(command, scope, file, callback) { // Why does node wrap the command in '(...)\n'? command = command.replace(/^\((.*)\n\)$/, function(all, part) { return part; }); if (command.length !== 0) { requisition.updateExec(command) .then(logResults) .then(function() { callback(); }) .catch(function(ex) { util.errorHandler(ex); callback(); }); } }; console.log('This is also a limited GCLI REPL. ' + 'Type \'help\' for a list of commands, CTRL+C 3 times to exit:'); repl.start(': ', process, gcliEval, false, true); }
javascript
function startRepl() { var repl = require('repl'); var gcliEval = function(command, scope, file, callback) { // Why does node wrap the command in '(...)\n'? command = command.replace(/^\((.*)\n\)$/, function(all, part) { return part; }); if (command.length !== 0) { requisition.updateExec(command) .then(logResults) .then(function() { callback(); }) .catch(function(ex) { util.errorHandler(ex); callback(); }); } }; console.log('This is also a limited GCLI REPL. ' + 'Type \'help\' for a list of commands, CTRL+C 3 times to exit:'); repl.start(': ', process, gcliEval, false, true); }
[ "function", "startRepl", "(", ")", "{", "var", "repl", "=", "require", "(", "'repl'", ")", ";", "var", "gcliEval", "=", "function", "(", "command", ",", "scope", ",", "file", ",", "callback", ")", "{", "// Why does node wrap the command in '(...)\\n'?", "command", "=", "command", ".", "replace", "(", "/", "^\\((.*)\\n\\)$", "/", ",", "function", "(", "all", ",", "part", ")", "{", "return", "part", ";", "}", ")", ";", "if", "(", "command", ".", "length", "!==", "0", ")", "{", "requisition", ".", "updateExec", "(", "command", ")", ".", "then", "(", "logResults", ")", ".", "then", "(", "function", "(", ")", "{", "callback", "(", ")", ";", "}", ")", ".", "catch", "(", "function", "(", "ex", ")", "{", "util", ".", "errorHandler", "(", "ex", ")", ";", "callback", "(", ")", ";", "}", ")", ";", "}", "}", ";", "console", ".", "log", "(", "'This is also a limited GCLI REPL. '", "+", "'Type \\'help\\' for a list of commands, CTRL+C 3 times to exit:'", ")", ";", "repl", ".", "start", "(", "': '", ",", "process", ",", "gcliEval", ",", "false", ",", "true", ")", ";", "}" ]
Start a NodeJS REPL to execute commands
[ "Start", "a", "NodeJS", "REPL", "to", "execute", "commands" ]
672ddac06402c82c44b4e45fe9336347b9c810bb
https://github.com/joewalker/gcli/blob/672ddac06402c82c44b4e45fe9336347b9c810bb/gcli.js#L85-L105
22,387
joewalker/gcli
lib/gcli/commands/server/orion.js
function(input, source) { var output = input.toString(); if (source.path.match(/\.js$/)) { output = output.replace(/(["'](do not )?use strict[\"\'];)/, 'define(function(require, exports, module) {\n\n$1'); output += '\n\n});\n'; } return output; }
javascript
function(input, source) { var output = input.toString(); if (source.path.match(/\.js$/)) { output = output.replace(/(["'](do not )?use strict[\"\'];)/, 'define(function(require, exports, module) {\n\n$1'); output += '\n\n});\n'; } return output; }
[ "function", "(", "input", ",", "source", ")", "{", "var", "output", "=", "input", ".", "toString", "(", ")", ";", "if", "(", "source", ".", "path", ".", "match", "(", "/", "\\.js$", "/", ")", ")", "{", "output", "=", "output", ".", "replace", "(", "/", "([\"'](do not )?use strict[\\\"\\'];)", "/", ",", "'define(function(require, exports, module) {\\n\\n$1'", ")", ";", "output", "+=", "'\\n\\n});\\n'", ";", "}", "return", "output", ";", "}" ]
A filter to munge CommonJS headers
[ "A", "filter", "to", "munge", "CommonJS", "headers" ]
672ddac06402c82c44b4e45fe9336347b9c810bb
https://github.com/joewalker/gcli/blob/672ddac06402c82c44b4e45fe9336347b9c810bb/lib/gcli/commands/server/orion.js#L102-L112
22,388
joewalker/gcli
lib/gcli/util/fileparser.js
function(context, typed, options) { var matches = options.matches == null ? undefined : options.matches.source; var connector = context.system.connectors.get(); return GcliFront.create(connector).then(function(front) { return front.parseFile(typed, options.filetype, options.existing, matches).then(function(reply) { reply.status = Status.fromString(reply.status); if (reply.predictions != null) { reply.predictor = function() { return Promise.resolve(reply.predictions); }; } front.connection.disconnect().catch(util.errorHandler); return reply; }); }); }
javascript
function(context, typed, options) { var matches = options.matches == null ? undefined : options.matches.source; var connector = context.system.connectors.get(); return GcliFront.create(connector).then(function(front) { return front.parseFile(typed, options.filetype, options.existing, matches).then(function(reply) { reply.status = Status.fromString(reply.status); if (reply.predictions != null) { reply.predictor = function() { return Promise.resolve(reply.predictions); }; } front.connection.disconnect().catch(util.errorHandler); return reply; }); }); }
[ "function", "(", "context", ",", "typed", ",", "options", ")", "{", "var", "matches", "=", "options", ".", "matches", "==", "null", "?", "undefined", ":", "options", ".", "matches", ".", "source", ";", "var", "connector", "=", "context", ".", "system", ".", "connectors", ".", "get", "(", ")", ";", "return", "GcliFront", ".", "create", "(", "connector", ")", ".", "then", "(", "function", "(", "front", ")", "{", "return", "front", ".", "parseFile", "(", "typed", ",", "options", ".", "filetype", ",", "options", ".", "existing", ",", "matches", ")", ".", "then", "(", "function", "(", "reply", ")", "{", "reply", ".", "status", "=", "Status", ".", "fromString", "(", "reply", ".", "status", ")", ";", "if", "(", "reply", ".", "predictions", "!=", "null", ")", "{", "reply", ".", "predictor", "=", "function", "(", ")", "{", "return", "Promise", ".", "resolve", "(", "reply", ".", "predictions", ")", ";", "}", ";", "}", "front", ".", "connection", ".", "disconnect", "(", ")", ".", "catch", "(", "util", ".", "errorHandler", ")", ";", "return", "reply", ";", "}", ")", ";", "}", ")", ";", "}" ]
Implementation of parse for the web
[ "Implementation", "of", "parse", "for", "the", "web" ]
672ddac06402c82c44b4e45fe9336347b9c810bb
https://github.com/joewalker/gcli/blob/672ddac06402c82c44b4e45fe9336347b9c810bb/lib/gcli/util/fileparser.js#L59-L76
22,389
joewalker/gcli
lib/gcli/ui/view.js
function(element, clear) { // Strict check on the off-chance that we later think of other options // and want to replace 'clear' with an 'options' parameter, but want to // support backwards compat. if (clear === true) { util.clearElement(element); } element.appendChild(this.toDom(element.ownerDocument)); }
javascript
function(element, clear) { // Strict check on the off-chance that we later think of other options // and want to replace 'clear' with an 'options' parameter, but want to // support backwards compat. if (clear === true) { util.clearElement(element); } element.appendChild(this.toDom(element.ownerDocument)); }
[ "function", "(", "element", ",", "clear", ")", "{", "// Strict check on the off-chance that we later think of other options", "// and want to replace 'clear' with an 'options' parameter, but want to", "// support backwards compat.", "if", "(", "clear", "===", "true", ")", "{", "util", ".", "clearElement", "(", "element", ")", ";", "}", "element", ".", "appendChild", "(", "this", ".", "toDom", "(", "element", ".", "ownerDocument", ")", ")", ";", "}" ]
Run the template against the document to which element belongs. @param element The element to append the result to @param clear Set clear===true to remove all children of element
[ "Run", "the", "template", "against", "the", "document", "to", "which", "element", "belongs", "." ]
672ddac06402c82c44b4e45fe9336347b9c810bb
https://github.com/joewalker/gcli/blob/672ddac06402c82c44b4e45fe9336347b9c810bb/lib/gcli/ui/view.js#L61-L70
22,390
joewalker/gcli
lib/gcli/ui/view.js
function(document) { if (options.css) { util.importCss(options.css, document, options.cssId); } var child = host.toDom(document, options.html); domtemplate.template(child, options.data || {}, options.options || {}); return child; }
javascript
function(document) { if (options.css) { util.importCss(options.css, document, options.cssId); } var child = host.toDom(document, options.html); domtemplate.template(child, options.data || {}, options.options || {}); return child; }
[ "function", "(", "document", ")", "{", "if", "(", "options", ".", "css", ")", "{", "util", ".", "importCss", "(", "options", ".", "css", ",", "document", ",", "options", ".", "cssId", ")", ";", "}", "var", "child", "=", "host", ".", "toDom", "(", "document", ",", "options", ".", "html", ")", ";", "domtemplate", ".", "template", "(", "child", ",", "options", ".", "data", "||", "{", "}", ",", "options", ".", "options", "||", "{", "}", ")", ";", "return", "child", ";", "}" ]
Actually convert the view data into a DOM suitable to be appended to an element @param document to use in realizing the template
[ "Actually", "convert", "the", "view", "data", "into", "a", "DOM", "suitable", "to", "be", "appended", "to", "an", "element" ]
672ddac06402c82c44b4e45fe9336347b9c810bb
https://github.com/joewalker/gcli/blob/672ddac06402c82c44b4e45fe9336347b9c810bb/lib/gcli/ui/view.js#L77-L85
22,391
joewalker/gcli
lib/gcli/cli.js
instanceIndex
function instanceIndex(context) { for (var i = 0; i < instances.length; i++) { var instance = instances[i]; if (instance.conversionContext === context || instance.executionContext === context) { return i; } } return -1; }
javascript
function instanceIndex(context) { for (var i = 0; i < instances.length; i++) { var instance = instances[i]; if (instance.conversionContext === context || instance.executionContext === context) { return i; } } return -1; }
[ "function", "instanceIndex", "(", "context", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "instances", ".", "length", ";", "i", "++", ")", "{", "var", "instance", "=", "instances", "[", "i", "]", ";", "if", "(", "instance", ".", "conversionContext", "===", "context", "||", "instance", ".", "executionContext", "===", "context", ")", "{", "return", "i", ";", "}", "}", "return", "-", "1", ";", "}" ]
An indexOf that looks-up both types of context
[ "An", "indexOf", "that", "looks", "-", "up", "both", "types", "of", "context" ]
672ddac06402c82c44b4e45fe9336347b9c810bb
https://github.com/joewalker/gcli/blob/672ddac06402c82c44b4e45fe9336347b9c810bb/lib/gcli/cli.js#L69-L78
22,392
joewalker/gcli
lib/gcli/cli.js
function(requisition) { if (instanceIndex(requisition.conversionContext) !== -1) { throw new Error('Remote existing mapping before adding a new one'); } instances.push({ conversionContext: requisition.conversionContext, executionContext: requisition.executionContext, mapping: { requisition: requisition } }); }
javascript
function(requisition) { if (instanceIndex(requisition.conversionContext) !== -1) { throw new Error('Remote existing mapping before adding a new one'); } instances.push({ conversionContext: requisition.conversionContext, executionContext: requisition.executionContext, mapping: { requisition: requisition } }); }
[ "function", "(", "requisition", ")", "{", "if", "(", "instanceIndex", "(", "requisition", ".", "conversionContext", ")", "!==", "-", "1", ")", "{", "throw", "new", "Error", "(", "'Remote existing mapping before adding a new one'", ")", ";", "}", "instances", ".", "push", "(", "{", "conversionContext", ":", "requisition", ".", "conversionContext", ",", "executionContext", ":", "requisition", ".", "executionContext", ",", "mapping", ":", "{", "requisition", ":", "requisition", "}", "}", ")", ";", "}" ]
Add a requisition context->terminal mapping
[ "Add", "a", "requisition", "context", "-", ">", "terminal", "mapping" ]
672ddac06402c82c44b4e45fe9336347b9c810bb
https://github.com/joewalker/gcli/blob/672ddac06402c82c44b4e45fe9336347b9c810bb/lib/gcli/cli.js#L98-L108
22,393
joewalker/gcli
lib/gcli/types/command.js
function(option) { if (arg.text.length === 0) { // If someone hasn't typed anything, we only show top level commands in // the menu. i.e. sub-commands (those with a space in their name) are // excluded. We do this to keep the list at an overview level. if (option.name.indexOf(' ') === -1) { predictions.push(option); } } else { // If someone has typed something, then we exclude parent commands // (those without an exec). We do this because the user is drilling // down and doesn't need the summary level. if (option.value.exec != null) { predictions.push(option); } } }
javascript
function(option) { if (arg.text.length === 0) { // If someone hasn't typed anything, we only show top level commands in // the menu. i.e. sub-commands (those with a space in their name) are // excluded. We do this to keep the list at an overview level. if (option.name.indexOf(' ') === -1) { predictions.push(option); } } else { // If someone has typed something, then we exclude parent commands // (those without an exec). We do this because the user is drilling // down and doesn't need the summary level. if (option.value.exec != null) { predictions.push(option); } } }
[ "function", "(", "option", ")", "{", "if", "(", "arg", ".", "text", ".", "length", "===", "0", ")", "{", "// If someone hasn't typed anything, we only show top level commands in", "// the menu. i.e. sub-commands (those with a space in their name) are", "// excluded. We do this to keep the list at an overview level.", "if", "(", "option", ".", "name", ".", "indexOf", "(", "' '", ")", "===", "-", "1", ")", "{", "predictions", ".", "push", "(", "option", ")", ";", "}", "}", "else", "{", "// If someone has typed something, then we exclude parent commands", "// (those without an exec). We do this because the user is drilling", "// down and doesn't need the summary level.", "if", "(", "option", ".", "value", ".", "exec", "!=", "null", ")", "{", "predictions", ".", "push", "(", "option", ")", ";", "}", "}", "}" ]
Add an option to our list of predicted options
[ "Add", "an", "option", "to", "our", "list", "of", "predicted", "options" ]
672ddac06402c82c44b4e45fe9336347b9c810bb
https://github.com/joewalker/gcli/blob/672ddac06402c82c44b4e45fe9336347b9c810bb/lib/gcli/types/command.js#L122-L139
22,394
joewalker/gcli
lib/gcli/commands/server/firefox.js
tweakI18nStrings
function tweakI18nStrings(data) { // Rip off the CommonJS header/footer var output = ''; data.replace(outline, function(m, inner) { // Remove the trailing spaces output += inner.replace(/ *$/, ''); }); if (output === '') { throw new Error('Mismatch in lib/gcli/nls/strings.js'); } var strings = []; // Convert each of the string definitions var reply = output.replace(singleString, function(m, note, x, name, value) { strings.push({ note: note, noteAlsoFor: [], name: name, value: value }); return ''; }); console.log('reply="' + reply + '"'); strings = strings.filter(function(string) { return ignoreStrings.indexOf(string.name) === -1; }); // All strings should have a note, but sometimes we describe several strings // with one note, so if a string has no note then we add it to noteAlsoFor // in the last string with a note var lastStringWithNote = -1; strings.forEach(function(string, i) { if (string.note === '') { strings[lastStringWithNote].noteAlsoFor.push(string.name); } else { lastStringWithNote = i; } }); // Make a single one line string from the the multi-line JS comments strings.forEach(function(string) { if (string.note !== '') { string.note = string.note.replace(/\n? *\/\/ */g, ' ') .replace(/^ /, '') .replace(/\n$/, ''); } }); // Add the 'LOCALIZATION NOTE' and word wrap strings.forEach(function(string) { if (string.note !== '') { string.noteAlsoFor.unshift(string.name); var names = ''; if (string.noteAlsoFor.length > 1) { names = ' (' + string.noteAlsoFor.join(', ') + ')'; } string.note = 'LOCALIZATION NOTE' + names + ': ' + string.note; string.note = '\n# ' + wordWrap(string.note, 77).join('\n# ') + '\n'; } }); // The values were escaped JavaScript strings to be property values they // need unescaping strings.forEach(function(string) { string.value = string.value.replace(/\\\\/g, '\\').replace(/\\'/g, '\''); }); // Join to get the output output = strings.map(function(string) { return string.note + string.name + '=' + string.value + '\n'; }).join(''); return '' + '# This Source Code Form is subject to the terms of the Mozilla Public\n' + '# License, v. 2.0. If a copy of the MPL was not distributed with this\n' + '# file, You can obtain one at http://mozilla.org/MPL/2.0/.\n' + '\n' + '# LOCALIZATION NOTE These strings are used inside the Web Console\n' + '# command line which is available from the Web Developer sub-menu\n' + '# -> \'Web Console\'.\n' + '# The correct localization of this file might be to keep it in\n' + '# English, or another language commonly spoken among web developers.\n' + '# You want to make that choice consistent across the developer tools.\n' + '# A good criteria is the language in which you\'d find the best\n' + '# documentation on web development on the web.\n' + '\n' + '# For each command there are in general two strings. As an example consider\n' + '# the \'pref\' command.\n' + '# commandDesc (e.g. prefDesc for the command \'pref\'): this string contains a\n' + '# very short description of the command. It\'s designed to be shown in a menu\n' + '# alongside the command name, which is why it should be as short as possible.\n' + '# commandManual (e.g. prefManual for the command \'pref\'): this string will\n' + '# contain a fuller description of the command. It\'s diplayed when the user\n' + '# asks for help about a specific command (e.g. \'help pref\').\n' + output; }
javascript
function tweakI18nStrings(data) { // Rip off the CommonJS header/footer var output = ''; data.replace(outline, function(m, inner) { // Remove the trailing spaces output += inner.replace(/ *$/, ''); }); if (output === '') { throw new Error('Mismatch in lib/gcli/nls/strings.js'); } var strings = []; // Convert each of the string definitions var reply = output.replace(singleString, function(m, note, x, name, value) { strings.push({ note: note, noteAlsoFor: [], name: name, value: value }); return ''; }); console.log('reply="' + reply + '"'); strings = strings.filter(function(string) { return ignoreStrings.indexOf(string.name) === -1; }); // All strings should have a note, but sometimes we describe several strings // with one note, so if a string has no note then we add it to noteAlsoFor // in the last string with a note var lastStringWithNote = -1; strings.forEach(function(string, i) { if (string.note === '') { strings[lastStringWithNote].noteAlsoFor.push(string.name); } else { lastStringWithNote = i; } }); // Make a single one line string from the the multi-line JS comments strings.forEach(function(string) { if (string.note !== '') { string.note = string.note.replace(/\n? *\/\/ */g, ' ') .replace(/^ /, '') .replace(/\n$/, ''); } }); // Add the 'LOCALIZATION NOTE' and word wrap strings.forEach(function(string) { if (string.note !== '') { string.noteAlsoFor.unshift(string.name); var names = ''; if (string.noteAlsoFor.length > 1) { names = ' (' + string.noteAlsoFor.join(', ') + ')'; } string.note = 'LOCALIZATION NOTE' + names + ': ' + string.note; string.note = '\n# ' + wordWrap(string.note, 77).join('\n# ') + '\n'; } }); // The values were escaped JavaScript strings to be property values they // need unescaping strings.forEach(function(string) { string.value = string.value.replace(/\\\\/g, '\\').replace(/\\'/g, '\''); }); // Join to get the output output = strings.map(function(string) { return string.note + string.name + '=' + string.value + '\n'; }).join(''); return '' + '# This Source Code Form is subject to the terms of the Mozilla Public\n' + '# License, v. 2.0. If a copy of the MPL was not distributed with this\n' + '# file, You can obtain one at http://mozilla.org/MPL/2.0/.\n' + '\n' + '# LOCALIZATION NOTE These strings are used inside the Web Console\n' + '# command line which is available from the Web Developer sub-menu\n' + '# -> \'Web Console\'.\n' + '# The correct localization of this file might be to keep it in\n' + '# English, or another language commonly spoken among web developers.\n' + '# You want to make that choice consistent across the developer tools.\n' + '# A good criteria is the language in which you\'d find the best\n' + '# documentation on web development on the web.\n' + '\n' + '# For each command there are in general two strings. As an example consider\n' + '# the \'pref\' command.\n' + '# commandDesc (e.g. prefDesc for the command \'pref\'): this string contains a\n' + '# very short description of the command. It\'s designed to be shown in a menu\n' + '# alongside the command name, which is why it should be as short as possible.\n' + '# commandManual (e.g. prefManual for the command \'pref\'): this string will\n' + '# contain a fuller description of the command. It\'s diplayed when the user\n' + '# asks for help about a specific command (e.g. \'help pref\').\n' + output; }
[ "function", "tweakI18nStrings", "(", "data", ")", "{", "// Rip off the CommonJS header/footer", "var", "output", "=", "''", ";", "data", ".", "replace", "(", "outline", ",", "function", "(", "m", ",", "inner", ")", "{", "// Remove the trailing spaces", "output", "+=", "inner", ".", "replace", "(", "/", " *$", "/", ",", "''", ")", ";", "}", ")", ";", "if", "(", "output", "===", "''", ")", "{", "throw", "new", "Error", "(", "'Mismatch in lib/gcli/nls/strings.js'", ")", ";", "}", "var", "strings", "=", "[", "]", ";", "// Convert each of the string definitions", "var", "reply", "=", "output", ".", "replace", "(", "singleString", ",", "function", "(", "m", ",", "note", ",", "x", ",", "name", ",", "value", ")", "{", "strings", ".", "push", "(", "{", "note", ":", "note", ",", "noteAlsoFor", ":", "[", "]", ",", "name", ":", "name", ",", "value", ":", "value", "}", ")", ";", "return", "''", ";", "}", ")", ";", "console", ".", "log", "(", "'reply=\"'", "+", "reply", "+", "'\"'", ")", ";", "strings", "=", "strings", ".", "filter", "(", "function", "(", "string", ")", "{", "return", "ignoreStrings", ".", "indexOf", "(", "string", ".", "name", ")", "===", "-", "1", ";", "}", ")", ";", "// All strings should have a note, but sometimes we describe several strings", "// with one note, so if a string has no note then we add it to noteAlsoFor", "// in the last string with a note", "var", "lastStringWithNote", "=", "-", "1", ";", "strings", ".", "forEach", "(", "function", "(", "string", ",", "i", ")", "{", "if", "(", "string", ".", "note", "===", "''", ")", "{", "strings", "[", "lastStringWithNote", "]", ".", "noteAlsoFor", ".", "push", "(", "string", ".", "name", ")", ";", "}", "else", "{", "lastStringWithNote", "=", "i", ";", "}", "}", ")", ";", "// Make a single one line string from the the multi-line JS comments", "strings", ".", "forEach", "(", "function", "(", "string", ")", "{", "if", "(", "string", ".", "note", "!==", "''", ")", "{", "string", ".", "note", "=", "string", ".", "note", ".", "replace", "(", "/", "\\n? *\\/\\/ *", "/", "g", ",", "' '", ")", ".", "replace", "(", "/", "^ ", "/", ",", "''", ")", ".", "replace", "(", "/", "\\n$", "/", ",", "''", ")", ";", "}", "}", ")", ";", "// Add the 'LOCALIZATION NOTE' and word wrap", "strings", ".", "forEach", "(", "function", "(", "string", ")", "{", "if", "(", "string", ".", "note", "!==", "''", ")", "{", "string", ".", "noteAlsoFor", ".", "unshift", "(", "string", ".", "name", ")", ";", "var", "names", "=", "''", ";", "if", "(", "string", ".", "noteAlsoFor", ".", "length", ">", "1", ")", "{", "names", "=", "' ('", "+", "string", ".", "noteAlsoFor", ".", "join", "(", "', '", ")", "+", "')'", ";", "}", "string", ".", "note", "=", "'LOCALIZATION NOTE'", "+", "names", "+", "': '", "+", "string", ".", "note", ";", "string", ".", "note", "=", "'\\n# '", "+", "wordWrap", "(", "string", ".", "note", ",", "77", ")", ".", "join", "(", "'\\n# '", ")", "+", "'\\n'", ";", "}", "}", ")", ";", "// The values were escaped JavaScript strings to be property values they", "// need unescaping", "strings", ".", "forEach", "(", "function", "(", "string", ")", "{", "string", ".", "value", "=", "string", ".", "value", ".", "replace", "(", "/", "\\\\\\\\", "/", "g", ",", "'\\\\'", ")", ".", "replace", "(", "/", "\\\\'", "/", "g", ",", "'\\''", ")", ";", "}", ")", ";", "// Join to get the output", "output", "=", "strings", ".", "map", "(", "function", "(", "string", ")", "{", "return", "string", ".", "note", "+", "string", ".", "name", "+", "'='", "+", "string", ".", "value", "+", "'\\n'", ";", "}", ")", ".", "join", "(", "''", ")", ";", "return", "''", "+", "'# This Source Code Form is subject to the terms of the Mozilla Public\\n'", "+", "'# License, v. 2.0. If a copy of the MPL was not distributed with this\\n'", "+", "'# file, You can obtain one at http://mozilla.org/MPL/2.0/.\\n'", "+", "'\\n'", "+", "'# LOCALIZATION NOTE These strings are used inside the Web Console\\n'", "+", "'# command line which is available from the Web Developer sub-menu\\n'", "+", "'# -> \\'Web Console\\'.\\n'", "+", "'# The correct localization of this file might be to keep it in\\n'", "+", "'# English, or another language commonly spoken among web developers.\\n'", "+", "'# You want to make that choice consistent across the developer tools.\\n'", "+", "'# A good criteria is the language in which you\\'d find the best\\n'", "+", "'# documentation on web development on the web.\\n'", "+", "'\\n'", "+", "'# For each command there are in general two strings. As an example consider\\n'", "+", "'# the \\'pref\\' command.\\n'", "+", "'# commandDesc (e.g. prefDesc for the command \\'pref\\'): this string contains a\\n'", "+", "'# very short description of the command. It\\'s designed to be shown in a menu\\n'", "+", "'# alongside the command name, which is why it should be as short as possible.\\n'", "+", "'# commandManual (e.g. prefManual for the command \\'pref\\'): this string will\\n'", "+", "'# contain a fuller description of the command. It\\'s diplayed when the user\\n'", "+", "'# asks for help about a specific command (e.g. \\'help pref\\').\\n'", "+", "output", ";", "}" ]
Filter to turn GCLIs l18n script file into a Firefox l10n strings file
[ "Filter", "to", "turn", "GCLIs", "l18n", "script", "file", "into", "a", "Firefox", "l10n", "strings", "file" ]
672ddac06402c82c44b4e45fe9336347b9c810bb
https://github.com/joewalker/gcli/blob/672ddac06402c82c44b4e45fe9336347b9c810bb/lib/gcli/commands/server/firefox.js#L190-L291
22,395
joewalker/gcli
lib/gcli/commands/server/firefox.js
wordWrap
function wordWrap(input, length) { // LOOK! Over there! Is it an airplane? var wrapper = new RegExp('.{0,' + (length - 1) + '}([ $|\\s$]|$)', 'g'); return input.match(wrapper).slice(0, -1).map(function(s) { return s.replace(/ $/, ''); }); // Ah, no - it's just superman, anyway, on with the code ... }
javascript
function wordWrap(input, length) { // LOOK! Over there! Is it an airplane? var wrapper = new RegExp('.{0,' + (length - 1) + '}([ $|\\s$]|$)', 'g'); return input.match(wrapper).slice(0, -1).map(function(s) { return s.replace(/ $/, ''); }); // Ah, no - it's just superman, anyway, on with the code ... }
[ "function", "wordWrap", "(", "input", ",", "length", ")", "{", "// LOOK! Over there! Is it an airplane?", "var", "wrapper", "=", "new", "RegExp", "(", "'.{0,'", "+", "(", "length", "-", "1", ")", "+", "'}([ $|\\\\s$]|$)'", ",", "'g'", ")", ";", "return", "input", ".", "match", "(", "wrapper", ")", ".", "slice", "(", "0", ",", "-", "1", ")", ".", "map", "(", "function", "(", "s", ")", "{", "return", "s", ".", "replace", "(", "/", " $", "/", ",", "''", ")", ";", "}", ")", ";", "// Ah, no - it's just superman, anyway, on with the code ...", "}" ]
Return an input string split into lines of a given length
[ "Return", "an", "input", "string", "split", "into", "lines", "of", "a", "given", "length" ]
672ddac06402c82c44b4e45fe9336347b9c810bb
https://github.com/joewalker/gcli/blob/672ddac06402c82c44b4e45fe9336347b9c810bb/lib/gcli/commands/server/firefox.js#L295-L302
22,396
joewalker/gcli
lib/gcli/converters/basic.js
nodeFromDataToString
function nodeFromDataToString(data, conversionContext) { var node = util.createElement(conversionContext.document, 'p'); node.textContent = data.toString(); return node; }
javascript
function nodeFromDataToString(data, conversionContext) { var node = util.createElement(conversionContext.document, 'p'); node.textContent = data.toString(); return node; }
[ "function", "nodeFromDataToString", "(", "data", ",", "conversionContext", ")", "{", "var", "node", "=", "util", ".", "createElement", "(", "conversionContext", ".", "document", ",", "'p'", ")", ";", "node", ".", "textContent", "=", "data", ".", "toString", "(", ")", ";", "return", "node", ";", "}" ]
Several converters are just data.toString inside a 'p' element
[ "Several", "converters", "are", "just", "data", ".", "toString", "inside", "a", "p", "element" ]
672ddac06402c82c44b4e45fe9336347b9c810bb
https://github.com/joewalker/gcli/blob/672ddac06402c82c44b4e45fe9336347b9c810bb/lib/gcli/converters/basic.js#L24-L28
22,397
joewalker/gcli
lib/gcli/util/host.js
function(javascript) { try { return Promise.resolve({ input: javascript, output: eval(javascript), exception: null }); } catch (ex) { return Promise.resolve({ input: javascript, output: null, exception: ex }); } }
javascript
function(javascript) { try { return Promise.resolve({ input: javascript, output: eval(javascript), exception: null }); } catch (ex) { return Promise.resolve({ input: javascript, output: null, exception: ex }); } }
[ "function", "(", "javascript", ")", "{", "try", "{", "return", "Promise", ".", "resolve", "(", "{", "input", ":", "javascript", ",", "output", ":", "eval", "(", "javascript", ")", ",", "exception", ":", "null", "}", ")", ";", "}", "catch", "(", "ex", ")", "{", "return", "Promise", ".", "resolve", "(", "{", "input", ":", "javascript", ",", "output", ":", "null", ",", "exception", ":", "ex", "}", ")", ";", "}", "}" ]
Execute some JavaScript
[ "Execute", "some", "JavaScript" ]
672ddac06402c82c44b4e45fe9336347b9c810bb
https://github.com/joewalker/gcli/blob/672ddac06402c82c44b4e45fe9336347b9c810bb/lib/gcli/util/host.js#L291-L306
22,398
joewalker/gcli
lib/gcli/languages/command.js
function(start) { if (!this.requisition.isUpToDate()) { return; } var newAssignment = this.requisition.getAssignmentAt(start); if (newAssignment == null) { return; } if (this.assignment !== newAssignment) { if (this.assignment.param.type.onLeave) { this.assignment.param.type.onLeave(this.assignment); } // This can be kicked off either by requisition doing an assign or by // terminal noticing a cursor movement out of a command, so we should // check that this really is a new assignment var isNew = (this.assignment !== newAssignment); this.assignment = newAssignment; this.terminal.updateCompletion().catch(util.errorHandler); if (isNew) { this.updateHints(); } if (this.assignment.param.type.onEnter) { this.assignment.param.type.onEnter(this.assignment); } } else { if (this.assignment && this.assignment.param.type.onChange) { this.assignment.param.type.onChange(this.assignment); } } // Warning: compare the logic here with the logic in fieldChanged, which // is slightly different. They should probably be the same var error = (this.assignment.status === Status.ERROR); this.focusManager.setError(error); }
javascript
function(start) { if (!this.requisition.isUpToDate()) { return; } var newAssignment = this.requisition.getAssignmentAt(start); if (newAssignment == null) { return; } if (this.assignment !== newAssignment) { if (this.assignment.param.type.onLeave) { this.assignment.param.type.onLeave(this.assignment); } // This can be kicked off either by requisition doing an assign or by // terminal noticing a cursor movement out of a command, so we should // check that this really is a new assignment var isNew = (this.assignment !== newAssignment); this.assignment = newAssignment; this.terminal.updateCompletion().catch(util.errorHandler); if (isNew) { this.updateHints(); } if (this.assignment.param.type.onEnter) { this.assignment.param.type.onEnter(this.assignment); } } else { if (this.assignment && this.assignment.param.type.onChange) { this.assignment.param.type.onChange(this.assignment); } } // Warning: compare the logic here with the logic in fieldChanged, which // is slightly different. They should probably be the same var error = (this.assignment.status === Status.ERROR); this.focusManager.setError(error); }
[ "function", "(", "start", ")", "{", "if", "(", "!", "this", ".", "requisition", ".", "isUpToDate", "(", ")", ")", "{", "return", ";", "}", "var", "newAssignment", "=", "this", ".", "requisition", ".", "getAssignmentAt", "(", "start", ")", ";", "if", "(", "newAssignment", "==", "null", ")", "{", "return", ";", "}", "if", "(", "this", ".", "assignment", "!==", "newAssignment", ")", "{", "if", "(", "this", ".", "assignment", ".", "param", ".", "type", ".", "onLeave", ")", "{", "this", ".", "assignment", ".", "param", ".", "type", ".", "onLeave", "(", "this", ".", "assignment", ")", ";", "}", "// This can be kicked off either by requisition doing an assign or by", "// terminal noticing a cursor movement out of a command, so we should", "// check that this really is a new assignment", "var", "isNew", "=", "(", "this", ".", "assignment", "!==", "newAssignment", ")", ";", "this", ".", "assignment", "=", "newAssignment", ";", "this", ".", "terminal", ".", "updateCompletion", "(", ")", ".", "catch", "(", "util", ".", "errorHandler", ")", ";", "if", "(", "isNew", ")", "{", "this", ".", "updateHints", "(", ")", ";", "}", "if", "(", "this", ".", "assignment", ".", "param", ".", "type", ".", "onEnter", ")", "{", "this", ".", "assignment", ".", "param", ".", "type", ".", "onEnter", "(", "this", ".", "assignment", ")", ";", "}", "}", "else", "{", "if", "(", "this", ".", "assignment", "&&", "this", ".", "assignment", ".", "param", ".", "type", ".", "onChange", ")", "{", "this", ".", "assignment", ".", "param", ".", "type", ".", "onChange", "(", "this", ".", "assignment", ")", ";", "}", "}", "// Warning: compare the logic here with the logic in fieldChanged, which", "// is slightly different. They should probably be the same", "var", "error", "=", "(", "this", ".", "assignment", ".", "status", "===", "Status", ".", "ERROR", ")", ";", "this", ".", "focusManager", ".", "setError", "(", "error", ")", ";", "}" ]
Called internally whenever we think that the current assignment might have changed, typically on mouse-clicks or key presses.
[ "Called", "internally", "whenever", "we", "think", "that", "the", "current", "assignment", "might", "have", "changed", "typically", "on", "mouse", "-", "clicks", "or", "key", "presses", "." ]
672ddac06402c82c44b4e45fe9336347b9c810bb
https://github.com/joewalker/gcli/blob/672ddac06402c82c44b4e45fe9336347b9c810bb/lib/gcli/languages/command.js#L165-L205
22,399
joewalker/gcli
lib/gcli/languages/command.js
function() { this.lastText = this.assignment.arg.text; var field = this.terminal.field; if (field) { field.onFieldChange.remove(this.terminal.fieldChanged, this.terminal); field.destroy(); } var fields = this.terminal.system.fields; field = this.terminal.field = fields.get(this.assignment.param.type, { document: this.terminal.document, requisition: this.requisition }); this.focusManager.setImportantFieldFlag(field.isImportant); field.onFieldChange.add(this.terminal.fieldChanged, this.terminal); field.setConversion(this.assignment.conversion); // Filled in by the template process this.terminal.errorEle = undefined; this.terminal.descriptionEle = undefined; var contents = this.terminal.tooltipTemplate.cloneNode(true); domtemplate.template(contents, this.terminal, { blankNullUndefined: true, stack: 'terminal.html#tooltip' }); util.clearElement(this.terminal.tooltipElement); this.terminal.tooltipElement.appendChild(contents); this.terminal.tooltipElement.style.display = 'block'; field.setMessageElement(this.terminal.errorEle); }
javascript
function() { this.lastText = this.assignment.arg.text; var field = this.terminal.field; if (field) { field.onFieldChange.remove(this.terminal.fieldChanged, this.terminal); field.destroy(); } var fields = this.terminal.system.fields; field = this.terminal.field = fields.get(this.assignment.param.type, { document: this.terminal.document, requisition: this.requisition }); this.focusManager.setImportantFieldFlag(field.isImportant); field.onFieldChange.add(this.terminal.fieldChanged, this.terminal); field.setConversion(this.assignment.conversion); // Filled in by the template process this.terminal.errorEle = undefined; this.terminal.descriptionEle = undefined; var contents = this.terminal.tooltipTemplate.cloneNode(true); domtemplate.template(contents, this.terminal, { blankNullUndefined: true, stack: 'terminal.html#tooltip' }); util.clearElement(this.terminal.tooltipElement); this.terminal.tooltipElement.appendChild(contents); this.terminal.tooltipElement.style.display = 'block'; field.setMessageElement(this.terminal.errorEle); }
[ "function", "(", ")", "{", "this", ".", "lastText", "=", "this", ".", "assignment", ".", "arg", ".", "text", ";", "var", "field", "=", "this", ".", "terminal", ".", "field", ";", "if", "(", "field", ")", "{", "field", ".", "onFieldChange", ".", "remove", "(", "this", ".", "terminal", ".", "fieldChanged", ",", "this", ".", "terminal", ")", ";", "field", ".", "destroy", "(", ")", ";", "}", "var", "fields", "=", "this", ".", "terminal", ".", "system", ".", "fields", ";", "field", "=", "this", ".", "terminal", ".", "field", "=", "fields", ".", "get", "(", "this", ".", "assignment", ".", "param", ".", "type", ",", "{", "document", ":", "this", ".", "terminal", ".", "document", ",", "requisition", ":", "this", ".", "requisition", "}", ")", ";", "this", ".", "focusManager", ".", "setImportantFieldFlag", "(", "field", ".", "isImportant", ")", ";", "field", ".", "onFieldChange", ".", "add", "(", "this", ".", "terminal", ".", "fieldChanged", ",", "this", ".", "terminal", ")", ";", "field", ".", "setConversion", "(", "this", ".", "assignment", ".", "conversion", ")", ";", "// Filled in by the template process", "this", ".", "terminal", ".", "errorEle", "=", "undefined", ";", "this", ".", "terminal", ".", "descriptionEle", "=", "undefined", ";", "var", "contents", "=", "this", ".", "terminal", ".", "tooltipTemplate", ".", "cloneNode", "(", "true", ")", ";", "domtemplate", ".", "template", "(", "contents", ",", "this", ".", "terminal", ",", "{", "blankNullUndefined", ":", "true", ",", "stack", ":", "'terminal.html#tooltip'", "}", ")", ";", "util", ".", "clearElement", "(", "this", ".", "terminal", ".", "tooltipElement", ")", ";", "this", ".", "terminal", ".", "tooltipElement", ".", "appendChild", "(", "contents", ")", ";", "this", ".", "terminal", ".", "tooltipElement", ".", "style", ".", "display", "=", "'block'", ";", "field", ".", "setMessageElement", "(", "this", ".", "terminal", ".", "errorEle", ")", ";", "}" ]
Called whenever the assignment that we're providing help with changes
[ "Called", "whenever", "the", "assignment", "that", "we", "re", "providing", "help", "with", "changes" ]
672ddac06402c82c44b4e45fe9336347b9c810bb
https://github.com/joewalker/gcli/blob/672ddac06402c82c44b4e45fe9336347b9c810bb/lib/gcli/languages/command.js#L208-L243