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
sequence
docstring
stringlengths
4
11.8k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
86
226
partition
stringclasses
1 value
temando/remark-mermaid
src/index.js
replaceLinkWithEmbedded
function replaceLinkWithEmbedded(node, index, parent, vFile) { const { title, url, position } = node; let newNode; // If the node isn't mermaid, ignore it. if (!isMermaid(title)) { return node; } try { const value = fs.readFileSync(`${vFile.dirname}/${url}`, { encoding: 'utf-8' }); newNode = createMermaidDiv(value); parent.children.splice(index, 1, newNode); vFile.info('mermaid link replaced with div', position, PLUGIN_NAME); } catch (error) { vFile.message(error, position, PLUGIN_NAME); return node; } return node; }
javascript
function replaceLinkWithEmbedded(node, index, parent, vFile) { const { title, url, position } = node; let newNode; // If the node isn't mermaid, ignore it. if (!isMermaid(title)) { return node; } try { const value = fs.readFileSync(`${vFile.dirname}/${url}`, { encoding: 'utf-8' }); newNode = createMermaidDiv(value); parent.children.splice(index, 1, newNode); vFile.info('mermaid link replaced with div', position, PLUGIN_NAME); } catch (error) { vFile.message(error, position, PLUGIN_NAME); return node; } return node; }
[ "function", "replaceLinkWithEmbedded", "(", "node", ",", "index", ",", "parent", ",", "vFile", ")", "{", "const", "{", "title", ",", "url", ",", "position", "}", "=", "node", ";", "let", "newNode", ";", "if", "(", "!", "isMermaid", "(", "title", ")", ")", "{", "return", "node", ";", "}", "try", "{", "const", "value", "=", "fs", ".", "readFileSync", "(", "`", "${", "vFile", ".", "dirname", "}", "${", "url", "}", "`", ",", "{", "encoding", ":", "'utf-8'", "}", ")", ";", "newNode", "=", "createMermaidDiv", "(", "value", ")", ";", "parent", ".", "children", ".", "splice", "(", "index", ",", "1", ",", "newNode", ")", ";", "vFile", ".", "info", "(", "'mermaid link replaced with div'", ",", "position", ",", "PLUGIN_NAME", ")", ";", "}", "catch", "(", "error", ")", "{", "vFile", ".", "message", "(", "error", ",", "position", ",", "PLUGIN_NAME", ")", ";", "return", "node", ";", "}", "return", "node", ";", "}" ]
Given a link to a mermaid diagram, grab the contents from the link and put it into a div that Mermaid JS can act upon. @param {object} node @param {integer} index @param {object} parent @param {vFile} vFile @return {object}
[ "Given", "a", "link", "to", "a", "mermaid", "diagram", "grab", "the", "contents", "from", "the", "link", "and", "put", "it", "into", "a", "div", "that", "Mermaid", "JS", "can", "act", "upon", "." ]
3c0aaa8e90ff8ca0d043a9648c651683c0867ae3
https://github.com/temando/remark-mermaid/blob/3c0aaa8e90ff8ca0d043a9648c651683c0867ae3/src/index.js#L60-L81
train
temando/remark-mermaid
src/index.js
visitCodeBlock
function visitCodeBlock(ast, vFile, isSimple) { return visit(ast, 'code', (node, index, parent) => { const { lang, value, position } = node; const destinationDir = getDestinationDir(vFile); let newNode; // If this codeblock is not mermaid, bail. if (lang !== 'mermaid') { return node; } // Are we just transforming to a <div>, or replacing with an image? if (isSimple) { newNode = createMermaidDiv(value); vFile.info(`${lang} code block replaced with div`, position, PLUGIN_NAME); // Otherwise, let's try and generate a graph! } else { let graphSvgFilename; try { graphSvgFilename = render(value, destinationDir); vFile.info(`${lang} code block replaced with graph`, position, PLUGIN_NAME); } catch (error) { vFile.message(error, position, PLUGIN_NAME); return node; } newNode = { type: 'image', title: '`mermaid` image', url: graphSvgFilename, }; } parent.children.splice(index, 1, newNode); return node; }); }
javascript
function visitCodeBlock(ast, vFile, isSimple) { return visit(ast, 'code', (node, index, parent) => { const { lang, value, position } = node; const destinationDir = getDestinationDir(vFile); let newNode; // If this codeblock is not mermaid, bail. if (lang !== 'mermaid') { return node; } // Are we just transforming to a <div>, or replacing with an image? if (isSimple) { newNode = createMermaidDiv(value); vFile.info(`${lang} code block replaced with div`, position, PLUGIN_NAME); // Otherwise, let's try and generate a graph! } else { let graphSvgFilename; try { graphSvgFilename = render(value, destinationDir); vFile.info(`${lang} code block replaced with graph`, position, PLUGIN_NAME); } catch (error) { vFile.message(error, position, PLUGIN_NAME); return node; } newNode = { type: 'image', title: '`mermaid` image', url: graphSvgFilename, }; } parent.children.splice(index, 1, newNode); return node; }); }
[ "function", "visitCodeBlock", "(", "ast", ",", "vFile", ",", "isSimple", ")", "{", "return", "visit", "(", "ast", ",", "'code'", ",", "(", "node", ",", "index", ",", "parent", ")", "=>", "{", "const", "{", "lang", ",", "value", ",", "position", "}", "=", "node", ";", "const", "destinationDir", "=", "getDestinationDir", "(", "vFile", ")", ";", "let", "newNode", ";", "if", "(", "lang", "!==", "'mermaid'", ")", "{", "return", "node", ";", "}", "if", "(", "isSimple", ")", "{", "newNode", "=", "createMermaidDiv", "(", "value", ")", ";", "vFile", ".", "info", "(", "`", "${", "lang", "}", "`", ",", "position", ",", "PLUGIN_NAME", ")", ";", "}", "else", "{", "let", "graphSvgFilename", ";", "try", "{", "graphSvgFilename", "=", "render", "(", "value", ",", "destinationDir", ")", ";", "vFile", ".", "info", "(", "`", "${", "lang", "}", "`", ",", "position", ",", "PLUGIN_NAME", ")", ";", "}", "catch", "(", "error", ")", "{", "vFile", ".", "message", "(", "error", ",", "position", ",", "PLUGIN_NAME", ")", ";", "return", "node", ";", "}", "newNode", "=", "{", "type", ":", "'image'", ",", "title", ":", "'`mermaid` image'", ",", "url", ":", "graphSvgFilename", ",", "}", ";", "}", "parent", ".", "children", ".", "splice", "(", "index", ",", "1", ",", "newNode", ")", ";", "return", "node", ";", "}", ")", ";", "}" ]
Given the MDAST ast, look for all fenced codeblocks that have a language of `mermaid` and pass that to mermaid.cli to render the image. Replaces the codeblocks with an image of the rendered graph. @param {object} ast @param {vFile} vFile @param {boolean} isSimple @return {function}
[ "Given", "the", "MDAST", "ast", "look", "for", "all", "fenced", "codeblocks", "that", "have", "a", "language", "of", "mermaid", "and", "pass", "that", "to", "mermaid", ".", "cli", "to", "render", "the", "image", ".", "Replaces", "the", "codeblocks", "with", "an", "image", "of", "the", "rendered", "graph", "." ]
3c0aaa8e90ff8ca0d043a9648c651683c0867ae3
https://github.com/temando/remark-mermaid/blob/3c0aaa8e90ff8ca0d043a9648c651683c0867ae3/src/index.js#L93-L133
train
temando/remark-mermaid
src/index.js
mermaid
function mermaid(options = {}) { const simpleMode = options.simple || false; /** * @param {object} ast MDAST * @param {vFile} vFile * @param {function} next * @return {object} */ return function transformer(ast, vFile, next) { visitCodeBlock(ast, vFile, simpleMode); visitLink(ast, vFile, simpleMode); visitImage(ast, vFile, simpleMode); if (typeof next === 'function') { return next(null, ast, vFile); } return ast; }; }
javascript
function mermaid(options = {}) { const simpleMode = options.simple || false; /** * @param {object} ast MDAST * @param {vFile} vFile * @param {function} next * @return {object} */ return function transformer(ast, vFile, next) { visitCodeBlock(ast, vFile, simpleMode); visitLink(ast, vFile, simpleMode); visitImage(ast, vFile, simpleMode); if (typeof next === 'function') { return next(null, ast, vFile); } return ast; }; }
[ "function", "mermaid", "(", "options", "=", "{", "}", ")", "{", "const", "simpleMode", "=", "options", ".", "simple", "||", "false", ";", "return", "function", "transformer", "(", "ast", ",", "vFile", ",", "next", ")", "{", "visitCodeBlock", "(", "ast", ",", "vFile", ",", "simpleMode", ")", ";", "visitLink", "(", "ast", ",", "vFile", ",", "simpleMode", ")", ";", "visitImage", "(", "ast", ",", "vFile", ",", "simpleMode", ")", ";", "if", "(", "typeof", "next", "===", "'function'", ")", "{", "return", "next", "(", "null", ",", "ast", ",", "vFile", ")", ";", "}", "return", "ast", ";", "}", ";", "}" ]
Returns the transformer which acts on the MDAST tree and given VFile. If `options.simple` is passed as a truthy value, the plugin will convert to `<div class="mermaid">` rather than a SVG image. @link https://github.com/unifiedjs/unified#function-transformernode-file-next @link https://github.com/syntax-tree/mdast @link https://github.com/vfile/vfile @param {object} options @return {function}
[ "Returns", "the", "transformer", "which", "acts", "on", "the", "MDAST", "tree", "and", "given", "VFile", "." ]
3c0aaa8e90ff8ca0d043a9648c651683c0867ae3
https://github.com/temando/remark-mermaid/blob/3c0aaa8e90ff8ca0d043a9648c651683c0867ae3/src/index.js#L184-L204
train
sematext/spm-agent-nodejs
lib/httpServerAgent.js
safeProcess
function safeProcess (ctx, fn) { return function processRequest (req, res) { try { fn(ctx, req, res) } catch (ex) { ctx.logger.error(ex) } } }
javascript
function safeProcess (ctx, fn) { return function processRequest (req, res) { try { fn(ctx, req, res) } catch (ex) { ctx.logger.error(ex) } } }
[ "function", "safeProcess", "(", "ctx", ",", "fn", ")", "{", "return", "function", "processRequest", "(", "req", ",", "res", ")", "{", "try", "{", "fn", "(", "ctx", ",", "req", ",", "res", ")", "}", "catch", "(", "ex", ")", "{", "ctx", ".", "logger", ".", "error", "(", "ex", ")", "}", "}", "}" ]
Make sure we deoptimize small part of fn
[ "Make", "sure", "we", "deoptimize", "small", "part", "of", "fn" ]
e4f639321568926e5c8fb6760a4afa201c54933e
https://github.com/sematext/spm-agent-nodejs/blob/e4f639321568926e5c8fb6760a4afa201c54933e/lib/httpServerAgent.js#L124-L132
train
peerigon/socket.io-session-middleware
index.js
ioSession
function ioSession(options) { var cookieParser = options.cookieParser, sessionStore = options.store, key = options.key || "connect.sid"; function findCookie(handshake) { return (handshake.secureCookies && handshake.secureCookies[key]) || (handshake.signedCookies && handshake.signedCookies[key]) || (handshake.cookies && handshake.cookies[key]); } function getSession(socketHandshake, callback) { cookieParser(socketHandshake, {}, function (parseErr) { if(parseErr) { callback(parseErr); return; } // use sessionStore.get() instead of deprecated sessionStore.load() sessionStore.get(findCookie(socketHandshake), function (storeErr, session) { if(storeErr) { callback(storeErr); return; } if(!session) { callback(new Error("could not look up session by key: " + key)); return; } callback(null, session); }); }); } return function handleSession(socket, next) { getSession(socket.request, function (err, session) { if(err) { next(err); return; } socket.session = session; next(); }); }; }
javascript
function ioSession(options) { var cookieParser = options.cookieParser, sessionStore = options.store, key = options.key || "connect.sid"; function findCookie(handshake) { return (handshake.secureCookies && handshake.secureCookies[key]) || (handshake.signedCookies && handshake.signedCookies[key]) || (handshake.cookies && handshake.cookies[key]); } function getSession(socketHandshake, callback) { cookieParser(socketHandshake, {}, function (parseErr) { if(parseErr) { callback(parseErr); return; } // use sessionStore.get() instead of deprecated sessionStore.load() sessionStore.get(findCookie(socketHandshake), function (storeErr, session) { if(storeErr) { callback(storeErr); return; } if(!session) { callback(new Error("could not look up session by key: " + key)); return; } callback(null, session); }); }); } return function handleSession(socket, next) { getSession(socket.request, function (err, session) { if(err) { next(err); return; } socket.session = session; next(); }); }; }
[ "function", "ioSession", "(", "options", ")", "{", "var", "cookieParser", "=", "options", ".", "cookieParser", ",", "sessionStore", "=", "options", ".", "store", ",", "key", "=", "options", ".", "key", "||", "\"connect.sid\"", ";", "function", "findCookie", "(", "handshake", ")", "{", "return", "(", "handshake", ".", "secureCookies", "&&", "handshake", ".", "secureCookies", "[", "key", "]", ")", "||", "(", "handshake", ".", "signedCookies", "&&", "handshake", ".", "signedCookies", "[", "key", "]", ")", "||", "(", "handshake", ".", "cookies", "&&", "handshake", ".", "cookies", "[", "key", "]", ")", ";", "}", "function", "getSession", "(", "socketHandshake", ",", "callback", ")", "{", "cookieParser", "(", "socketHandshake", ",", "{", "}", ",", "function", "(", "parseErr", ")", "{", "if", "(", "parseErr", ")", "{", "callback", "(", "parseErr", ")", ";", "return", ";", "}", "sessionStore", ".", "get", "(", "findCookie", "(", "socketHandshake", ")", ",", "function", "(", "storeErr", ",", "session", ")", "{", "if", "(", "storeErr", ")", "{", "callback", "(", "storeErr", ")", ";", "return", ";", "}", "if", "(", "!", "session", ")", "{", "callback", "(", "new", "Error", "(", "\"could not look up session by key: \"", "+", "key", ")", ")", ";", "return", ";", "}", "callback", "(", "null", ",", "session", ")", ";", "}", ")", ";", "}", ")", ";", "}", "return", "function", "handleSession", "(", "socket", ",", "next", ")", "{", "getSession", "(", "socket", ".", "request", ",", "function", "(", "err", ",", "session", ")", "{", "if", "(", "err", ")", "{", "next", "(", "err", ")", ";", "return", ";", "}", "socket", ".", "session", "=", "session", ";", "next", "(", ")", ";", "}", ")", ";", "}", ";", "}" ]
pass session... - cookieParse - store - key returns a socket.io compatible middleware (v1.+) which attaches the session to socket.session if no session could be found it nexts with an error handle the error with sockets.on("error", ...) @param {Object} options @returns {Function} handleSession
[ "pass", "session", "...", "-", "cookieParse", "-", "store", "-", "key" ]
a2ff55865021f07753634a17f28e8f7e7024ae37
https://github.com/peerigon/socket.io-session-middleware/blob/a2ff55865021f07753634a17f28e8f7e7024ae37/index.js#L19-L64
train
CrabDude/trycatch
lib/formatError.js
normalizeError
function normalizeError(err, stack) { err = coerceToError(err) if (!err.normalized) { addNonEnumerableValue(err, 'originalStack', stack || err.message) addNonEnumerableValue(err, 'normalized', true) addNonEnumerableValue(err, 'coreThrown', isCoreError(err)) addNonEnumerableValue(err, 'catchable', isCatchableError(err)) } return err }
javascript
function normalizeError(err, stack) { err = coerceToError(err) if (!err.normalized) { addNonEnumerableValue(err, 'originalStack', stack || err.message) addNonEnumerableValue(err, 'normalized', true) addNonEnumerableValue(err, 'coreThrown', isCoreError(err)) addNonEnumerableValue(err, 'catchable', isCatchableError(err)) } return err }
[ "function", "normalizeError", "(", "err", ",", "stack", ")", "{", "err", "=", "coerceToError", "(", "err", ")", "if", "(", "!", "err", ".", "normalized", ")", "{", "addNonEnumerableValue", "(", "err", ",", "'originalStack'", ",", "stack", "||", "err", ".", "message", ")", "addNonEnumerableValue", "(", "err", ",", "'normalized'", ",", "true", ")", "addNonEnumerableValue", "(", "err", ",", "'coreThrown'", ",", "isCoreError", "(", "err", ")", ")", "addNonEnumerableValue", "(", "err", ",", "'catchable'", ",", "isCatchableError", "(", "err", ")", ")", "}", "return", "err", "}" ]
Ensure error conforms to common expectations
[ "Ensure", "error", "conforms", "to", "common", "expectations" ]
66621d9410776743e677c0e481a580ef598ecc85
https://github.com/CrabDude/trycatch/blob/66621d9410776743e677c0e481a580ef598ecc85/lib/formatError.js#L39-L48
train
lykmapipo/express-mquery
lib/parser.js
function (projection = '') { //prepare projections let fields = _.compact(projection.split(',')); fields = _.map(fields, _.trim); fields = _.uniq(fields); const accumulator = {}; _.forEach(fields, function (field) { //if exclude e.g -name if (field[0] === '-') { accumulator[field.substring(1)] = 0; } //if include i.e name else { accumulator[field] = 1; } }); return accumulator; }
javascript
function (projection = '') { //prepare projections let fields = _.compact(projection.split(',')); fields = _.map(fields, _.trim); fields = _.uniq(fields); const accumulator = {}; _.forEach(fields, function (field) { //if exclude e.g -name if (field[0] === '-') { accumulator[field.substring(1)] = 0; } //if include i.e name else { accumulator[field] = 1; } }); return accumulator; }
[ "function", "(", "projection", "=", "''", ")", "{", "let", "fields", "=", "_", ".", "compact", "(", "projection", ".", "split", "(", "','", ")", ")", ";", "fields", "=", "_", ".", "map", "(", "fields", ",", "_", ".", "trim", ")", ";", "fields", "=", "_", ".", "uniq", "(", "fields", ")", ";", "const", "accumulator", "=", "{", "}", ";", "_", ".", "forEach", "(", "fields", ",", "function", "(", "field", ")", "{", "if", "(", "field", "[", "0", "]", "===", "'-'", ")", "{", "accumulator", "[", "field", ".", "substring", "(", "1", ")", "]", "=", "0", ";", "}", "else", "{", "accumulator", "[", "field", "]", "=", "1", ";", "}", "}", ")", ";", "return", "accumulator", ";", "}" ]
parse comma separated fields into mongodb awase projections
[ "parse", "comma", "separated", "fields", "into", "mongodb", "awase", "projections" ]
15c685d6767e2894e15907b138f1ea56a3d3f69b
https://github.com/lykmapipo/express-mquery/blob/15c685d6767e2894e15907b138f1ea56a3d3f69b/lib/parser.js#L442-L465
train
fulup-bzh/GeoGate
AisWeb/app/Frontend/widgets/LeafletMap/AisToMap.js
DeviceOnMap
function DeviceOnMap (map, data) { this.trace=[]; // keep trace of device trace on xx positions this.count=0; // number of points created for this device this.devid = data.devid; this.src = data.src; this.name = data.name; this.cargo = data.cargo; this.vessel= ' cargo-' + data.cargo; this.map=map; this.lastshow = new Date().getTime(); }
javascript
function DeviceOnMap (map, data) { this.trace=[]; // keep trace of device trace on xx positions this.count=0; // number of points created for this device this.devid = data.devid; this.src = data.src; this.name = data.name; this.cargo = data.cargo; this.vessel= ' cargo-' + data.cargo; this.map=map; this.lastshow = new Date().getTime(); }
[ "function", "DeviceOnMap", "(", "map", ",", "data", ")", "{", "this", ".", "trace", "=", "[", "]", ";", "this", ".", "count", "=", "0", ";", "this", ".", "devid", "=", "data", ".", "devid", ";", "this", ".", "src", "=", "data", ".", "src", ";", "this", ".", "name", "=", "data", ".", "name", ";", "this", ".", "cargo", "=", "data", ".", "cargo", ";", "this", ".", "vessel", "=", "' cargo-'", "+", "data", ".", "cargo", ";", "this", ".", "map", "=", "map", ";", "this", ".", "lastshow", "=", "new", "Date", "(", ")", ".", "getTime", "(", ")", ";", "}" ]
Class to add vessel as POI on Leaflet
[ "Class", "to", "add", "vessel", "as", "POI", "on", "Leaflet" ]
34d9f256545b74d596747d1c2faf9bb450eb0777
https://github.com/fulup-bzh/GeoGate/blob/34d9f256545b74d596747d1c2faf9bb450eb0777/AisWeb/app/Frontend/widgets/LeafletMap/AisToMap.js#L27-L37
train
fulup-bzh/GeoGate
server/lib/GG-Controller.js
TcpClientData
function TcpClientData (buffer) { this.controller.Debug(7, "[%s] Data=[%s]", this.uid, buffer); // call adapter specific routine to process messages var status = this.adapter.ParseBuffer(this, buffer); }
javascript
function TcpClientData (buffer) { this.controller.Debug(7, "[%s] Data=[%s]", this.uid, buffer); // call adapter specific routine to process messages var status = this.adapter.ParseBuffer(this, buffer); }
[ "function", "TcpClientData", "(", "buffer", ")", "{", "this", ".", "controller", ".", "Debug", "(", "7", ",", "\"[%s] Data=[%s]\"", ",", "this", ".", "uid", ",", "buffer", ")", ";", "var", "status", "=", "this", ".", "adapter", ".", "ParseBuffer", "(", "this", ",", "buffer", ")", ";", "}" ]
Client receive data from server
[ "Client", "receive", "data", "from", "server" ]
34d9f256545b74d596747d1c2faf9bb450eb0777
https://github.com/fulup-bzh/GeoGate/blob/34d9f256545b74d596747d1c2faf9bb450eb0777/server/lib/GG-Controller.js#L103-L108
train
kunalnagar/jquery.peekABar
dist/js/jquery.peekabar.js
function() { that.bar = $('<div></div>').addClass('peek-a-bar').attr('id', '__peek_a_bar_' + rand); $('html').append(that.bar); that.bar.hide(); }
javascript
function() { that.bar = $('<div></div>').addClass('peek-a-bar').attr('id', '__peek_a_bar_' + rand); $('html').append(that.bar); that.bar.hide(); }
[ "function", "(", ")", "{", "that", ".", "bar", "=", "$", "(", "'<div></div>'", ")", ".", "addClass", "(", "'peek-a-bar'", ")", ".", "attr", "(", "'id'", ",", "'__peek_a_bar_'", "+", "rand", ")", ";", "$", "(", "'html'", ")", ".", "append", "(", "that", ".", "bar", ")", ";", "that", ".", "bar", ".", "hide", "(", ")", ";", "}" ]
Create the Bar
[ "Create", "the", "Bar" ]
1d7252e68606ebdc70704fd1e582f8e6854ffdac
https://github.com/kunalnagar/jquery.peekABar/blob/1d7252e68606ebdc70704fd1e582f8e6854ffdac/dist/js/jquery.peekabar.js#L88-L92
train
kunalnagar/jquery.peekABar
dist/js/jquery.peekabar.js
function() { if(that.settings.cssClass !== null) { that.bar.addClass(that.settings.cssClass); } }
javascript
function() { if(that.settings.cssClass !== null) { that.bar.addClass(that.settings.cssClass); } }
[ "function", "(", ")", "{", "if", "(", "that", ".", "settings", ".", "cssClass", "!==", "null", ")", "{", "that", ".", "bar", ".", "addClass", "(", "that", ".", "settings", ".", "cssClass", ")", ";", "}", "}" ]
Apply Custom CSS Class
[ "Apply", "Custom", "CSS", "Class" ]
1d7252e68606ebdc70704fd1e582f8e6854ffdac
https://github.com/kunalnagar/jquery.peekABar/blob/1d7252e68606ebdc70704fd1e582f8e6854ffdac/dist/js/jquery.peekabar.js#L131-L135
train
kunalnagar/jquery.peekABar
dist/js/jquery.peekabar.js
function() { switch(that.settings.position) { case 'top': that.bar.css('top', 0); break; case 'bottom': that.bar.css('bottom', 0); break; default: that.bar.css('top', 0); } }
javascript
function() { switch(that.settings.position) { case 'top': that.bar.css('top', 0); break; case 'bottom': that.bar.css('bottom', 0); break; default: that.bar.css('top', 0); } }
[ "function", "(", ")", "{", "switch", "(", "that", ".", "settings", ".", "position", ")", "{", "case", "'top'", ":", "that", ".", "bar", ".", "css", "(", "'top'", ",", "0", ")", ";", "break", ";", "case", "'bottom'", ":", "that", ".", "bar", ".", "css", "(", "'bottom'", ",", "0", ")", ";", "break", ";", "default", ":", "that", ".", "bar", ".", "css", "(", "'top'", ",", "0", ")", ";", "}", "}" ]
Apply Position where the Bar should be shown
[ "Apply", "Position", "where", "the", "Bar", "should", "be", "shown" ]
1d7252e68606ebdc70704fd1e582f8e6854ffdac
https://github.com/kunalnagar/jquery.peekABar/blob/1d7252e68606ebdc70704fd1e582f8e6854ffdac/dist/js/jquery.peekabar.js#L143-L154
train
fulup-bzh/GeoGate
server/lib/_HttpClient.js
GpsdHttpClient
function GpsdHttpClient (adapter, devid) { this.debug = adapter.debug; // inherit debug level this.uid = "httpclient//" + adapter.info + ":" + devid; this.adapter = adapter; this.gateway = adapter.gateway; this.controller = adapter.controller; this.socket = null; // we cannot rely on socket to talk to device this.devid = false; // we get uid directly from device this.name = false; this.logged = false; this.alarm = 0; // count alarm messages this.count = 0; // generic counter used by file backend this.errorcount = 0; // number of ignore messages this.uid = "httpclient://" + this.adapter.info + ":" + this.adapter.id; }
javascript
function GpsdHttpClient (adapter, devid) { this.debug = adapter.debug; // inherit debug level this.uid = "httpclient//" + adapter.info + ":" + devid; this.adapter = adapter; this.gateway = adapter.gateway; this.controller = adapter.controller; this.socket = null; // we cannot rely on socket to talk to device this.devid = false; // we get uid directly from device this.name = false; this.logged = false; this.alarm = 0; // count alarm messages this.count = 0; // generic counter used by file backend this.errorcount = 0; // number of ignore messages this.uid = "httpclient://" + this.adapter.info + ":" + this.adapter.id; }
[ "function", "GpsdHttpClient", "(", "adapter", ",", "devid", ")", "{", "this", ".", "debug", "=", "adapter", ".", "debug", ";", "this", ".", "uid", "=", "\"httpclient//\"", "+", "adapter", ".", "info", "+", "\":\"", "+", "devid", ";", "this", ".", "adapter", "=", "adapter", ";", "this", ".", "gateway", "=", "adapter", ".", "gateway", ";", "this", ".", "controller", "=", "adapter", ".", "controller", ";", "this", ".", "socket", "=", "null", ";", "this", ".", "devid", "=", "false", ";", "this", ".", "name", "=", "false", ";", "this", ".", "logged", "=", "false", ";", "this", ".", "alarm", "=", "0", ";", "this", ".", "count", "=", "0", ";", "this", ".", "errorcount", "=", "0", ";", "this", ".", "uid", "=", "\"httpclient://\"", "+", "this", ".", "adapter", ".", "info", "+", "\":\"", "+", "this", ".", "adapter", ".", "id", ";", "}" ]
called from http class of adapter
[ "called", "from", "http", "class", "of", "adapter" ]
34d9f256545b74d596747d1c2faf9bb450eb0777
https://github.com/fulup-bzh/GeoGate/blob/34d9f256545b74d596747d1c2faf9bb450eb0777/server/lib/_HttpClient.js#L42-L60
train
fulup-bzh/GeoGate
simulator/bin/HubSimulator.js
ScanGpxDir
function ScanGpxDir (gpxdir) { var availableRoutes=[]; var count=0; var routesDir = gpxdir; var directory = fs.readdirSync(routesDir); for (var i in directory) { var file = directory [i]; var route = path.basename (directory [i],".gpx"); var name = routesDir + route + '.gpx'; try { if (fs.statSync(name).isFile()) { count ++; availableRoutes [route] = name; console.log ("Found Gpx Route: " + route + " file: " + availableRoutes [route]); } } catch (err) {/* ignore errors */} } if (count < 3) { console.log ("Find only [%d] GPX file in [%s] please check your directory", count, parsing.opts.gpxdir); process.exit (-1); } return (availableRoutes); }
javascript
function ScanGpxDir (gpxdir) { var availableRoutes=[]; var count=0; var routesDir = gpxdir; var directory = fs.readdirSync(routesDir); for (var i in directory) { var file = directory [i]; var route = path.basename (directory [i],".gpx"); var name = routesDir + route + '.gpx'; try { if (fs.statSync(name).isFile()) { count ++; availableRoutes [route] = name; console.log ("Found Gpx Route: " + route + " file: " + availableRoutes [route]); } } catch (err) {/* ignore errors */} } if (count < 3) { console.log ("Find only [%d] GPX file in [%s] please check your directory", count, parsing.opts.gpxdir); process.exit (-1); } return (availableRoutes); }
[ "function", "ScanGpxDir", "(", "gpxdir", ")", "{", "var", "availableRoutes", "=", "[", "]", ";", "var", "count", "=", "0", ";", "var", "routesDir", "=", "gpxdir", ";", "var", "directory", "=", "fs", ".", "readdirSync", "(", "routesDir", ")", ";", "for", "(", "var", "i", "in", "directory", ")", "{", "var", "file", "=", "directory", "[", "i", "]", ";", "var", "route", "=", "path", ".", "basename", "(", "directory", "[", "i", "]", ",", "\".gpx\"", ")", ";", "var", "name", "=", "routesDir", "+", "route", "+", "'.gpx'", ";", "try", "{", "if", "(", "fs", ".", "statSync", "(", "name", ")", ".", "isFile", "(", ")", ")", "{", "count", "++", ";", "availableRoutes", "[", "route", "]", "=", "name", ";", "console", ".", "log", "(", "\"Found Gpx Route: \"", "+", "route", "+", "\" file: \"", "+", "availableRoutes", "[", "route", "]", ")", ";", "}", "}", "catch", "(", "err", ")", "{", "}", "}", "if", "(", "count", "<", "3", ")", "{", "console", ".", "log", "(", "\"Find only [%d] GPX file in [%s] please check your directory\"", ",", "count", ",", "parsing", ".", "opts", ".", "gpxdir", ")", ";", "process", ".", "exit", "(", "-", "1", ")", ";", "}", "return", "(", "availableRoutes", ")", ";", "}" ]
scan directory and extract all .gpx files
[ "scan", "directory", "and", "extract", "all", ".", "gpx", "files" ]
34d9f256545b74d596747d1c2faf9bb450eb0777
https://github.com/fulup-bzh/GeoGate/blob/34d9f256545b74d596747d1c2faf9bb450eb0777/simulator/bin/HubSimulator.js#L118-L140
train
fulup-bzh/GeoGate
server/adapters/AisProxyNmea-adapter.js
SetGarbage
function SetGarbage (proxy, timeout) { // let's call back ourself after timeout*1000/4 proxy.Debug (4, "SetGarbage timeout=%d", timeout); setTimeout (function(){SetGarbage (proxy, timeout);}, timeout*500); // let compute timeout timeout limit var lastshow = new Date().getTime() - (timeout *1000); for (var mmsi in proxy.vessels) { var vessel = proxy.vessels[mmsi]; if (vessel.lastshow < lastshow) { proxy.Debug (5, "Removed Vessel mmsi=%s", mmsi); delete proxy.vessels [mmsi]; } } }
javascript
function SetGarbage (proxy, timeout) { // let's call back ourself after timeout*1000/4 proxy.Debug (4, "SetGarbage timeout=%d", timeout); setTimeout (function(){SetGarbage (proxy, timeout);}, timeout*500); // let compute timeout timeout limit var lastshow = new Date().getTime() - (timeout *1000); for (var mmsi in proxy.vessels) { var vessel = proxy.vessels[mmsi]; if (vessel.lastshow < lastshow) { proxy.Debug (5, "Removed Vessel mmsi=%s", mmsi); delete proxy.vessels [mmsi]; } } }
[ "function", "SetGarbage", "(", "proxy", ",", "timeout", ")", "{", "proxy", ".", "Debug", "(", "4", ",", "\"SetGarbage timeout=%d\"", ",", "timeout", ")", ";", "setTimeout", "(", "function", "(", ")", "{", "SetGarbage", "(", "proxy", ",", "timeout", ")", ";", "}", ",", "timeout", "*", "500", ")", ";", "var", "lastshow", "=", "new", "Date", "(", ")", ".", "getTime", "(", ")", "-", "(", "timeout", "*", "1000", ")", ";", "for", "(", "var", "mmsi", "in", "proxy", ".", "vessels", ")", "{", "var", "vessel", "=", "proxy", ".", "vessels", "[", "mmsi", "]", ";", "if", "(", "vessel", ".", "lastshow", "<", "lastshow", ")", "{", "proxy", ".", "Debug", "(", "5", ",", "\"Removed Vessel mmsi=%s\"", ",", "mmsi", ")", ";", "delete", "proxy", ".", "vessels", "[", "mmsi", "]", ";", "}", "}", "}" ]
this function scan active device table and remove dead one based on inactivity timeout
[ "this", "function", "scan", "active", "device", "table", "and", "remove", "dead", "one", "based", "on", "inactivity", "timeout" ]
34d9f256545b74d596747d1c2faf9bb450eb0777
https://github.com/fulup-bzh/GeoGate/blob/34d9f256545b74d596747d1c2faf9bb450eb0777/server/adapters/AisProxyNmea-adapter.js#L35-L51
train
florianheinemann/passwordless-mongostore
lib/mongostore.js
MongoStore
function MongoStore(connection, options) { if(arguments.length === 0 || typeof arguments[0] !== 'string') { throw new Error('A valid connection string has to be provided'); } TokenStore.call(this); this._options = options || {}; this._collectionName = 'passwordless-token'; if(this._options.mongostore) { if(this._options.mongostore.collection) { this._collectionName = this._options.mongostore.collection; } delete this._options.mongostore; } this._uri = connection; this._db = null; this._collection = null; }
javascript
function MongoStore(connection, options) { if(arguments.length === 0 || typeof arguments[0] !== 'string') { throw new Error('A valid connection string has to be provided'); } TokenStore.call(this); this._options = options || {}; this._collectionName = 'passwordless-token'; if(this._options.mongostore) { if(this._options.mongostore.collection) { this._collectionName = this._options.mongostore.collection; } delete this._options.mongostore; } this._uri = connection; this._db = null; this._collection = null; }
[ "function", "MongoStore", "(", "connection", ",", "options", ")", "{", "if", "(", "arguments", ".", "length", "===", "0", "||", "typeof", "arguments", "[", "0", "]", "!==", "'string'", ")", "{", "throw", "new", "Error", "(", "'A valid connection string has to be provided'", ")", ";", "}", "TokenStore", ".", "call", "(", "this", ")", ";", "this", ".", "_options", "=", "options", "||", "{", "}", ";", "this", ".", "_collectionName", "=", "'passwordless-token'", ";", "if", "(", "this", ".", "_options", ".", "mongostore", ")", "{", "if", "(", "this", ".", "_options", ".", "mongostore", ".", "collection", ")", "{", "this", ".", "_collectionName", "=", "this", ".", "_options", ".", "mongostore", ".", "collection", ";", "}", "delete", "this", ".", "_options", ".", "mongostore", ";", "}", "this", ".", "_uri", "=", "connection", ";", "this", ".", "_db", "=", "null", ";", "this", ".", "_collection", "=", "null", ";", "}" ]
Constructor of MongoStore @param {String} connection URI as defined by the MongoDB specification. Please check the documentation for details: http://mongodb.github.io/node-mongodb-native/driver-articles/mongoclient.html @param {Object} [options] Combines both the options for the MongoClient as well as the options for MongoStore. For the MongoClient options please refer back to the documentation. MongoStore understands the following options: (1) { mongostore: { collection: string }} to change the name of the collection being used. Defaults to: 'passwordless-token' @constructor
[ "Constructor", "of", "MongoStore" ]
3352c12c916abaf1a5d2c6dd1af633d2a62ea34b
https://github.com/florianheinemann/passwordless-mongostore/blob/3352c12c916abaf1a5d2c6dd1af633d2a62ea34b/lib/mongostore.js#L20-L39
train
fulup-bzh/GeoGate
server/lib/GG-Gateway.js
SetCrontab
function SetCrontab (gateway, inactivity) { // let's call back ourself after inactivity*1000/4 gateway.Debug (5, "SetCrontab inactivity=%d", inactivity); setTimeout (function(){SetCrontab (gateway, inactivity);}, inactivity*250); // let compute inactivity timeout limit var timeout = new Date().getTime() - (inactivity *1000); for (var devid in gateway.activeClients) { var device = gateway.activeClients[devid]; if (device.lastshow < timeout) { gateway.Debug (1, "Removed ActiveDev Id=%s uid=%s", device.devid, device.uid); delete gateway.activeClients [devid]; } } }
javascript
function SetCrontab (gateway, inactivity) { // let's call back ourself after inactivity*1000/4 gateway.Debug (5, "SetCrontab inactivity=%d", inactivity); setTimeout (function(){SetCrontab (gateway, inactivity);}, inactivity*250); // let compute inactivity timeout limit var timeout = new Date().getTime() - (inactivity *1000); for (var devid in gateway.activeClients) { var device = gateway.activeClients[devid]; if (device.lastshow < timeout) { gateway.Debug (1, "Removed ActiveDev Id=%s uid=%s", device.devid, device.uid); delete gateway.activeClients [devid]; } } }
[ "function", "SetCrontab", "(", "gateway", ",", "inactivity", ")", "{", "gateway", ".", "Debug", "(", "5", ",", "\"SetCrontab inactivity=%d\"", ",", "inactivity", ")", ";", "setTimeout", "(", "function", "(", ")", "{", "SetCrontab", "(", "gateway", ",", "inactivity", ")", ";", "}", ",", "inactivity", "*", "250", ")", ";", "var", "timeout", "=", "new", "Date", "(", ")", ".", "getTime", "(", ")", "-", "(", "inactivity", "*", "1000", ")", ";", "for", "(", "var", "devid", "in", "gateway", ".", "activeClients", ")", "{", "var", "device", "=", "gateway", ".", "activeClients", "[", "devid", "]", ";", "if", "(", "device", ".", "lastshow", "<", "timeout", ")", "{", "gateway", ".", "Debug", "(", "1", ",", "\"Removed ActiveDev Id=%s uid=%s\"", ",", "device", ".", "devid", ",", "device", ".", "uid", ")", ";", "delete", "gateway", ".", "activeClients", "[", "devid", "]", ";", "}", "}", "}" ]
30s in between two retry this function scan active device table and remove dead one based on inactivity timeout
[ "30s", "in", "between", "two", "retry", "this", "function", "scan", "active", "device", "table", "and", "remove", "dead", "one", "based", "on", "inactivity", "timeout" ]
34d9f256545b74d596747d1c2faf9bb450eb0777
https://github.com/fulup-bzh/GeoGate/blob/34d9f256545b74d596747d1c2faf9bb450eb0777/server/lib/GG-Gateway.js#L35-L51
train
fulup-bzh/GeoGate
server/lib/GG-Gateway.js
JobCallback
function JobCallback (job) { if (job !== null) { job.gateway.Debug (6,"Queued Request:%s command=%s devid=%s [done]", job.request, job.command, job.devId); } }
javascript
function JobCallback (job) { if (job !== null) { job.gateway.Debug (6,"Queued Request:%s command=%s devid=%s [done]", job.request, job.command, job.devId); } }
[ "function", "JobCallback", "(", "job", ")", "{", "if", "(", "job", "!==", "null", ")", "{", "job", ".", "gateway", ".", "Debug", "(", "6", ",", "\"Queued Request:%s command=%s devid=%s [done]\"", ",", "job", ".", "request", ",", "job", ".", "command", ",", "job", ".", "devId", ")", ";", "}", "}" ]
Callback notify Async API that curent JobQueue processing is done
[ "Callback", "notify", "Async", "API", "that", "curent", "JobQueue", "processing", "is", "done" ]
34d9f256545b74d596747d1c2faf9bb450eb0777
https://github.com/fulup-bzh/GeoGate/blob/34d9f256545b74d596747d1c2faf9bb450eb0777/server/lib/GG-Gateway.js#L54-L58
train
fulup-bzh/GeoGate
simulator/lib/GG-Dispatcher.js
TcpStreamConnect
function TcpStreamConnect () { this.simulator.Debug (3, 'Dispatcher connected to %s:%s', simulator.opts.host, simulator.opts.port); ActiveClients[this] = this; // register on remote server in active socket list }
javascript
function TcpStreamConnect () { this.simulator.Debug (3, 'Dispatcher connected to %s:%s', simulator.opts.host, simulator.opts.port); ActiveClients[this] = this; // register on remote server in active socket list }
[ "function", "TcpStreamConnect", "(", ")", "{", "this", ".", "simulator", ".", "Debug", "(", "3", ",", "'Dispatcher connected to %s:%s'", ",", "simulator", ".", "opts", ".", "host", ",", "simulator", ".", "opts", ".", "port", ")", ";", "ActiveClients", "[", "this", "]", "=", "this", ";", "}" ]
this handler is called when TcpClient connect onto server
[ "this", "handler", "is", "called", "when", "TcpClient", "connect", "onto", "server" ]
34d9f256545b74d596747d1c2faf9bb450eb0777
https://github.com/fulup-bzh/GeoGate/blob/34d9f256545b74d596747d1c2faf9bb450eb0777/simulator/lib/GG-Dispatcher.js#L218-L221
train
fulup-bzh/GeoGate
simulator/lib/GG-Dispatcher.js
TcpStreamEnd
function TcpStreamEnd () { this.simulator.Debug (3,"TcpStream [%s:%s] connection ended", simulator.opts.host, simulator.opts.port); delete ActiveClients[this]; setTimeout (function(){ // wait for timeout and recreate a new Object from scratch simulator.TcpClient (); }, this.opts.timeout); }
javascript
function TcpStreamEnd () { this.simulator.Debug (3,"TcpStream [%s:%s] connection ended", simulator.opts.host, simulator.opts.port); delete ActiveClients[this]; setTimeout (function(){ // wait for timeout and recreate a new Object from scratch simulator.TcpClient (); }, this.opts.timeout); }
[ "function", "TcpStreamEnd", "(", ")", "{", "this", ".", "simulator", ".", "Debug", "(", "3", ",", "\"TcpStream [%s:%s] connection ended\"", ",", "simulator", ".", "opts", ".", "host", ",", "simulator", ".", "opts", ".", "port", ")", ";", "delete", "ActiveClients", "[", "this", "]", ";", "setTimeout", "(", "function", "(", ")", "{", "simulator", ".", "TcpClient", "(", ")", ";", "}", ",", "this", ".", "opts", ".", "timeout", ")", ";", "}" ]
Remote server close connection let's retry it
[ "Remote", "server", "close", "connection", "let", "s", "retry", "it" ]
34d9f256545b74d596747d1c2faf9bb450eb0777
https://github.com/fulup-bzh/GeoGate/blob/34d9f256545b74d596747d1c2faf9bb450eb0777/simulator/lib/GG-Dispatcher.js#L230-L236
train
fulup-bzh/GeoGate
server/adapters/TelnetConsole-adapter.js
function (dbresult) { if (dbresult === null || dbresult === undefined) { this.Debug (1,"Hoops: no DB info for %s", data.devid); return; } for (var idx = 0; (idx < dbresult.length); idx ++) { var posi= dbresult[idx]; posi.lon = posi.lon.toFixed (4); posi.lat = posi.lat.toFixed (4); posi.sog = posi.sog.toFixed (2); posi.cog = posi.cog.toFixed (2); var info=util.format ("> -%d- Lat:%s Lon:%s Sog:%s Cog:%s Alt:%s Acquired:%s\n" , idx, posi.lat, posi.lon, posi.sog, posi.cog, posi.alt, posi.acquired_at); socket.write (info); } }
javascript
function (dbresult) { if (dbresult === null || dbresult === undefined) { this.Debug (1,"Hoops: no DB info for %s", data.devid); return; } for (var idx = 0; (idx < dbresult.length); idx ++) { var posi= dbresult[idx]; posi.lon = posi.lon.toFixed (4); posi.lat = posi.lat.toFixed (4); posi.sog = posi.sog.toFixed (2); posi.cog = posi.cog.toFixed (2); var info=util.format ("> -%d- Lat:%s Lon:%s Sog:%s Cog:%s Alt:%s Acquired:%s\n" , idx, posi.lat, posi.lon, posi.sog, posi.cog, posi.alt, posi.acquired_at); socket.write (info); } }
[ "function", "(", "dbresult", ")", "{", "if", "(", "dbresult", "===", "null", "||", "dbresult", "===", "undefined", ")", "{", "this", ".", "Debug", "(", "1", ",", "\"Hoops: no DB info for %s\"", ",", "data", ".", "devid", ")", ";", "return", ";", "}", "for", "(", "var", "idx", "=", "0", ";", "(", "idx", "<", "dbresult", ".", "length", ")", ";", "idx", "++", ")", "{", "var", "posi", "=", "dbresult", "[", "idx", "]", ";", "posi", ".", "lon", "=", "posi", ".", "lon", ".", "toFixed", "(", "4", ")", ";", "posi", ".", "lat", "=", "posi", ".", "lat", ".", "toFixed", "(", "4", ")", ";", "posi", ".", "sog", "=", "posi", ".", "sog", ".", "toFixed", "(", "2", ")", ";", "posi", ".", "cog", "=", "posi", ".", "cog", ".", "toFixed", "(", "2", ")", ";", "var", "info", "=", "util", ".", "format", "(", "\"> -%d- Lat:%s Lon:%s Sog:%s Cog:%s Alt:%s Acquired:%s\\n\"", ",", "\\n", ",", "idx", ",", "posi", ".", "lat", ",", "posi", ".", "lon", ",", "posi", ".", "sog", ",", "posi", ".", "cog", ",", "posi", ".", "alt", ")", ";", "posi", ".", "acquired_at", "}", "}" ]
Ask DB backend to display on telnet socket last X position for devid=yyyy
[ "Ask", "DB", "backend", "to", "display", "on", "telnet", "socket", "last", "X", "position", "for", "devid", "=", "yyyy" ]
34d9f256545b74d596747d1c2faf9bb450eb0777
https://github.com/fulup-bzh/GeoGate/blob/34d9f256545b74d596747d1c2faf9bb450eb0777/server/adapters/TelnetConsole-adapter.js#L315-L331
train
fulup-bzh/GeoGate
server/adapters/NmeaTcpFeed-adapter.js
DevAdapter
function DevAdapter (controller) { this.id = controller.svc; this.uid = "//" + controller.svcopts.adapter + "/" + controller.svc + "@" + controller.svcopts.hostname + ":" +controller.svcopts.remport; this.info = 'nmeatcp'; this.control = 'tcpfeed'; // this adapter connect onto a remote server this.debug = controller.svcopts.debug; // inherit debug from controller this.controller= controller; // keep a link to device controller and TCP socket this.mmsi = controller.svcopts.mmsi; // use fake MMSI provided by user application in service options // Check mmsi is unique if (registermmsi [this.mmsi] !== undefined) { this.Debug (0,'Fatal adapter:%s this.mmsi:%s SHOULD be unique', this.info, this.mmsi); console.log ("Gpsd [duplicated NMEA MMSI] application aborted [please fix your configuration]"); process.exit (-1); } registermmsi [this.mmsi] = true; this.Debug (1,"uid=%s mmsi=%s", this.uid,this.mmsi); }
javascript
function DevAdapter (controller) { this.id = controller.svc; this.uid = "//" + controller.svcopts.adapter + "/" + controller.svc + "@" + controller.svcopts.hostname + ":" +controller.svcopts.remport; this.info = 'nmeatcp'; this.control = 'tcpfeed'; // this adapter connect onto a remote server this.debug = controller.svcopts.debug; // inherit debug from controller this.controller= controller; // keep a link to device controller and TCP socket this.mmsi = controller.svcopts.mmsi; // use fake MMSI provided by user application in service options // Check mmsi is unique if (registermmsi [this.mmsi] !== undefined) { this.Debug (0,'Fatal adapter:%s this.mmsi:%s SHOULD be unique', this.info, this.mmsi); console.log ("Gpsd [duplicated NMEA MMSI] application aborted [please fix your configuration]"); process.exit (-1); } registermmsi [this.mmsi] = true; this.Debug (1,"uid=%s mmsi=%s", this.uid,this.mmsi); }
[ "function", "DevAdapter", "(", "controller", ")", "{", "this", ".", "id", "=", "controller", ".", "svc", ";", "this", ".", "uid", "=", "\"//\"", "+", "controller", ".", "svcopts", ".", "adapter", "+", "\"/\"", "+", "controller", ".", "svc", "+", "\"@\"", "+", "controller", ".", "svcopts", ".", "hostname", "+", "\":\"", "+", "controller", ".", "svcopts", ".", "remport", ";", "this", ".", "info", "=", "'nmeatcp'", ";", "this", ".", "control", "=", "'tcpfeed'", ";", "this", ".", "debug", "=", "controller", ".", "svcopts", ".", "debug", ";", "this", ".", "controller", "=", "controller", ";", "this", ".", "mmsi", "=", "controller", ".", "svcopts", ".", "mmsi", ";", "if", "(", "registermmsi", "[", "this", ".", "mmsi", "]", "!==", "undefined", ")", "{", "this", ".", "Debug", "(", "0", ",", "'Fatal adapter:%s this.mmsi:%s SHOULD be unique'", ",", "this", ".", "info", ",", "this", ".", "mmsi", ")", ";", "console", ".", "log", "(", "\"Gpsd [duplicated NMEA MMSI] application aborted [please fix your configuration]\"", ")", ";", "process", ".", "exit", "(", "-", "1", ")", ";", "}", "registermmsi", "[", "this", ".", "mmsi", "]", "=", "true", ";", "this", ".", "Debug", "(", "1", ",", "\"uid=%s mmsi=%s\"", ",", "this", ".", "uid", ",", "this", ".", "mmsi", ")", ";", "}" ]
keep track of nmea MMSI for uniqueness Adapter is an object own by a given device controller that handle data connection
[ "keep", "track", "of", "nmea", "MMSI", "for", "uniqueness", "Adapter", "is", "an", "object", "own", "by", "a", "given", "device", "controller", "that", "handle", "data", "connection" ]
34d9f256545b74d596747d1c2faf9bb450eb0777
https://github.com/fulup-bzh/GeoGate/blob/34d9f256545b74d596747d1c2faf9bb450eb0777/server/adapters/NmeaTcpFeed-adapter.js#L45-L63
train
fulup-bzh/GeoGate
server/bin/Tracker2Json.js
EventHandlerQueue
function EventHandlerQueue (status, job){ console.log ("#%d- Queue Status=%s DevId=%s Command=%s JobReq=%d Retry=%d", count, status, job.devId, job.command, job.request, job.retry); }
javascript
function EventHandlerQueue (status, job){ console.log ("#%d- Queue Status=%s DevId=%s Command=%s JobReq=%d Retry=%d", count, status, job.devId, job.command, job.request, job.retry); }
[ "function", "EventHandlerQueue", "(", "status", ",", "job", ")", "{", "console", ".", "log", "(", "\"#%d- Queue Status=%s DevId=%s Command=%s JobReq=%d Retry=%d\"", ",", "count", ",", "status", ",", "job", ".", "devId", ",", "job", ".", "command", ",", "job", ".", "request", ",", "job", ".", "retry", ")", ";", "}" ]
Simple counter to make easier to follow message flow Events from queued jobs
[ "Simple", "counter", "to", "make", "easier", "to", "follow", "message", "flow", "Events", "from", "queued", "jobs" ]
34d9f256545b74d596747d1c2faf9bb450eb0777
https://github.com/fulup-bzh/GeoGate/blob/34d9f256545b74d596747d1c2faf9bb450eb0777/server/bin/Tracker2Json.js#L107-L109
train
Erdiko/ngx-user-admin
dist/bundles/ng-user-admin.umd.js
mergeResolvedReflectiveProviders
function mergeResolvedReflectiveProviders(providers, normalizedProvidersMap) { for (var /** @type {?} */ i = 0; i < providers.length; i++) { var /** @type {?} */ provider = providers[i]; var /** @type {?} */ existing = normalizedProvidersMap.get(provider.key.id); if (existing) { if (provider.multiProvider !== existing.multiProvider) { throw new MixingMultiProvidersWithRegularProvidersError(existing, provider); } if (provider.multiProvider) { for (var /** @type {?} */ j = 0; j < provider.resolvedFactories.length; j++) { existing.resolvedFactories.push(provider.resolvedFactories[j]); } } else { normalizedProvidersMap.set(provider.key.id, provider); } } else { var /** @type {?} */ resolvedProvider = void 0; if (provider.multiProvider) { resolvedProvider = new ResolvedReflectiveProvider_(provider.key, provider.resolvedFactories.slice(), provider.multiProvider); } else { resolvedProvider = provider; } normalizedProvidersMap.set(provider.key.id, resolvedProvider); } } return normalizedProvidersMap; }
javascript
function mergeResolvedReflectiveProviders(providers, normalizedProvidersMap) { for (var /** @type {?} */ i = 0; i < providers.length; i++) { var /** @type {?} */ provider = providers[i]; var /** @type {?} */ existing = normalizedProvidersMap.get(provider.key.id); if (existing) { if (provider.multiProvider !== existing.multiProvider) { throw new MixingMultiProvidersWithRegularProvidersError(existing, provider); } if (provider.multiProvider) { for (var /** @type {?} */ j = 0; j < provider.resolvedFactories.length; j++) { existing.resolvedFactories.push(provider.resolvedFactories[j]); } } else { normalizedProvidersMap.set(provider.key.id, provider); } } else { var /** @type {?} */ resolvedProvider = void 0; if (provider.multiProvider) { resolvedProvider = new ResolvedReflectiveProvider_(provider.key, provider.resolvedFactories.slice(), provider.multiProvider); } else { resolvedProvider = provider; } normalizedProvidersMap.set(provider.key.id, resolvedProvider); } } return normalizedProvidersMap; }
[ "function", "mergeResolvedReflectiveProviders", "(", "providers", ",", "normalizedProvidersMap", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "providers", ".", "length", ";", "i", "++", ")", "{", "var", "provider", "=", "providers", "[", "i", "]", ";", "var", "existing", "=", "normalizedProvidersMap", ".", "get", "(", "provider", ".", "key", ".", "id", ")", ";", "if", "(", "existing", ")", "{", "if", "(", "provider", ".", "multiProvider", "!==", "existing", ".", "multiProvider", ")", "{", "throw", "new", "MixingMultiProvidersWithRegularProvidersError", "(", "existing", ",", "provider", ")", ";", "}", "if", "(", "provider", ".", "multiProvider", ")", "{", "for", "(", "var", "j", "=", "0", ";", "j", "<", "provider", ".", "resolvedFactories", ".", "length", ";", "j", "++", ")", "{", "existing", ".", "resolvedFactories", ".", "push", "(", "provider", ".", "resolvedFactories", "[", "j", "]", ")", ";", "}", "}", "else", "{", "normalizedProvidersMap", ".", "set", "(", "provider", ".", "key", ".", "id", ",", "provider", ")", ";", "}", "}", "else", "{", "var", "resolvedProvider", "=", "void", "0", ";", "if", "(", "provider", ".", "multiProvider", ")", "{", "resolvedProvider", "=", "new", "ResolvedReflectiveProvider_", "(", "provider", ".", "key", ",", "provider", ".", "resolvedFactories", ".", "slice", "(", ")", ",", "provider", ".", "multiProvider", ")", ";", "}", "else", "{", "resolvedProvider", "=", "provider", ";", "}", "normalizedProvidersMap", ".", "set", "(", "provider", ".", "key", ".", "id", ",", "resolvedProvider", ")", ";", "}", "}", "return", "normalizedProvidersMap", ";", "}" ]
Merges a list of ResolvedProviders into a list where each key is contained exactly once and multi providers have been merged. @param {?} providers @param {?} normalizedProvidersMap @return {?}
[ "Merges", "a", "list", "of", "ResolvedProviders", "into", "a", "list", "where", "each", "key", "is", "contained", "exactly", "once", "and", "multi", "providers", "have", "been", "merged", "." ]
21901b69f6af39764b813c11502c482b0e451537
https://github.com/Erdiko/ngx-user-admin/blob/21901b69f6af39764b813c11502c482b0e451537/dist/bundles/ng-user-admin.umd.js#L2382-L2411
train
Erdiko/ngx-user-admin
dist/bundles/ng-user-admin.umd.js
assertPlatform
function assertPlatform(requiredToken) { var /** @type {?} */ platform = getPlatform(); if (!platform) { throw new Error('No platform exists!'); } if (!platform.injector.get(requiredToken, null)) { throw new Error('A platform with a different configuration has been created. Please destroy it first.'); } return platform; }
javascript
function assertPlatform(requiredToken) { var /** @type {?} */ platform = getPlatform(); if (!platform) { throw new Error('No platform exists!'); } if (!platform.injector.get(requiredToken, null)) { throw new Error('A platform with a different configuration has been created. Please destroy it first.'); } return platform; }
[ "function", "assertPlatform", "(", "requiredToken", ")", "{", "var", "platform", "=", "getPlatform", "(", ")", ";", "if", "(", "!", "platform", ")", "{", "throw", "new", "Error", "(", "'No platform exists!'", ")", ";", "}", "if", "(", "!", "platform", ".", "injector", ".", "get", "(", "requiredToken", ",", "null", ")", ")", "{", "throw", "new", "Error", "(", "'A platform with a different configuration has been created. Please destroy it first.'", ")", ";", "}", "return", "platform", ";", "}" ]
Checks that there currently is a platform which contains the given token as a provider. \@experimental APIs related to application bootstrap are currently under review. @param {?} requiredToken @return {?}
[ "Checks", "that", "there", "currently", "is", "a", "platform", "which", "contains", "the", "given", "token", "as", "a", "provider", "." ]
21901b69f6af39764b813c11502c482b0e451537
https://github.com/Erdiko/ngx-user-admin/blob/21901b69f6af39764b813c11502c482b0e451537/dist/bundles/ng-user-admin.umd.js#L8923-L8932
train
Erdiko/ngx-user-admin
dist/bundles/ng-user-admin.umd.js
getLocale
function getLocale (key) { var locale; if (key && key._locale && key._locale._abbr) { key = key._locale._abbr; } if (!key) { return globalLocale; } if (!isArray$2(key)) { //short-circuit everything else locale = loadLocale(key); if (locale) { return locale; } key = [key]; } return chooseLocale(key); }
javascript
function getLocale (key) { var locale; if (key && key._locale && key._locale._abbr) { key = key._locale._abbr; } if (!key) { return globalLocale; } if (!isArray$2(key)) { //short-circuit everything else locale = loadLocale(key); if (locale) { return locale; } key = [key]; } return chooseLocale(key); }
[ "function", "getLocale", "(", "key", ")", "{", "var", "locale", ";", "if", "(", "key", "&&", "key", ".", "_locale", "&&", "key", ".", "_locale", ".", "_abbr", ")", "{", "key", "=", "key", ".", "_locale", ".", "_abbr", ";", "}", "if", "(", "!", "key", ")", "{", "return", "globalLocale", ";", "}", "if", "(", "!", "isArray$2", "(", "key", ")", ")", "{", "locale", "=", "loadLocale", "(", "key", ")", ";", "if", "(", "locale", ")", "{", "return", "locale", ";", "}", "key", "=", "[", "key", "]", ";", "}", "return", "chooseLocale", "(", "key", ")", ";", "}" ]
returns locale data
[ "returns", "locale", "data" ]
21901b69f6af39764b813c11502c482b0e451537
https://github.com/Erdiko/ngx-user-admin/blob/21901b69f6af39764b813c11502c482b0e451537/dist/bundles/ng-user-admin.umd.js#L31707-L31728
train
Erdiko/ngx-user-admin
dist/bundles/ng-user-admin.umd.js
ComponentLoader
function ComponentLoader(_viewContainerRef, _renderer, _elementRef, _injector, _componentFactoryResolver, _ngZone, _posService) { this.onBeforeShow = new EventEmitter(); this.onShown = new EventEmitter(); this.onBeforeHide = new EventEmitter(); this.onHidden = new EventEmitter(); this._providers = []; this._ngZone = _ngZone; this._injector = _injector; this._renderer = _renderer; this._elementRef = _elementRef; this._posService = _posService; this._viewContainerRef = _viewContainerRef; this._componentFactoryResolver = _componentFactoryResolver; }
javascript
function ComponentLoader(_viewContainerRef, _renderer, _elementRef, _injector, _componentFactoryResolver, _ngZone, _posService) { this.onBeforeShow = new EventEmitter(); this.onShown = new EventEmitter(); this.onBeforeHide = new EventEmitter(); this.onHidden = new EventEmitter(); this._providers = []; this._ngZone = _ngZone; this._injector = _injector; this._renderer = _renderer; this._elementRef = _elementRef; this._posService = _posService; this._viewContainerRef = _viewContainerRef; this._componentFactoryResolver = _componentFactoryResolver; }
[ "function", "ComponentLoader", "(", "_viewContainerRef", ",", "_renderer", ",", "_elementRef", ",", "_injector", ",", "_componentFactoryResolver", ",", "_ngZone", ",", "_posService", ")", "{", "this", ".", "onBeforeShow", "=", "new", "EventEmitter", "(", ")", ";", "this", ".", "onShown", "=", "new", "EventEmitter", "(", ")", ";", "this", ".", "onBeforeHide", "=", "new", "EventEmitter", "(", ")", ";", "this", ".", "onHidden", "=", "new", "EventEmitter", "(", ")", ";", "this", ".", "_providers", "=", "[", "]", ";", "this", ".", "_ngZone", "=", "_ngZone", ";", "this", ".", "_injector", "=", "_injector", ";", "this", ".", "_renderer", "=", "_renderer", ";", "this", ".", "_elementRef", "=", "_elementRef", ";", "this", ".", "_posService", "=", "_posService", ";", "this", ".", "_viewContainerRef", "=", "_viewContainerRef", ";", "this", ".", "_componentFactoryResolver", "=", "_componentFactoryResolver", ";", "}" ]
Do not use this directly, it should be instanced via `ComponentLoadFactory.attach` @internal @param _viewContainerRef @param _elementRef @param _injector @param _renderer @param _componentFactoryResolver @param _ngZone @param _posService tslint:disable-next-line
[ "Do", "not", "use", "this", "directly", "it", "should", "be", "instanced", "via", "ComponentLoadFactory", ".", "attach" ]
21901b69f6af39764b813c11502c482b0e451537
https://github.com/Erdiko/ngx-user-admin/blob/21901b69f6af39764b813c11502c482b0e451537/dist/bundles/ng-user-admin.umd.js#L34953-L34966
train
Erdiko/ngx-user-admin
dist/bundles/ng-user-admin.umd.js
delayWhen$2
function delayWhen$2(delayDurationSelector, subscriptionDelay) { if (subscriptionDelay) { return new SubscriptionDelayObservable(this, subscriptionDelay) .lift(new DelayWhenOperator(delayDurationSelector)); } return this.lift(new DelayWhenOperator(delayDurationSelector)); }
javascript
function delayWhen$2(delayDurationSelector, subscriptionDelay) { if (subscriptionDelay) { return new SubscriptionDelayObservable(this, subscriptionDelay) .lift(new DelayWhenOperator(delayDurationSelector)); } return this.lift(new DelayWhenOperator(delayDurationSelector)); }
[ "function", "delayWhen$2", "(", "delayDurationSelector", ",", "subscriptionDelay", ")", "{", "if", "(", "subscriptionDelay", ")", "{", "return", "new", "SubscriptionDelayObservable", "(", "this", ",", "subscriptionDelay", ")", ".", "lift", "(", "new", "DelayWhenOperator", "(", "delayDurationSelector", ")", ")", ";", "}", "return", "this", ".", "lift", "(", "new", "DelayWhenOperator", "(", "delayDurationSelector", ")", ")", ";", "}" ]
Delays the emission of items from the source Observable by a given time span determined by the emissions of another Observable. <span class="informal">It's like {@link delay}, but the time span of the delay duration is determined by a second Observable.</span> <img src="./img/delayWhen.png" width="100%"> `delayWhen` time shifts each emitted value from the source Observable by a time span determined by another Observable. When the source emits a value, the `delayDurationSelector` function is called with the source value as argument, and should return an Observable, called the "duration" Observable. The source value is emitted on the output Observable only when the duration Observable emits a value or completes. Optionally, `delayWhen` takes a second argument, `subscriptionDelay`, which is an Observable. When `subscriptionDelay` emits its first value or completes, the source Observable is subscribed to and starts behaving like described in the previous paragraph. If `subscriptionDelay` is not provided, `delayWhen` will subscribe to the source Observable as soon as the output Observable is subscribed. @example <caption>Delay each click by a random amount of time, between 0 and 5 seconds</caption> var clicks = Rx.Observable.fromEvent(document, 'click'); var delayedClicks = clicks.delayWhen(event => Rx.Observable.interval(Math.random() * 5000) ); delayedClicks.subscribe(x => console.log(x)); @see {@link debounce} @see {@link delay} @param {function(value: T): Observable} delayDurationSelector A function that returns an Observable for each value emitted by the source Observable, which is then used to delay the emission of that item on the output Observable until the Observable returned from this function emits a value. @param {Observable} subscriptionDelay An Observable that triggers the subscription to the source Observable once it emits any value. @return {Observable} An Observable that delays the emissions of the source Observable by an amount of time specified by the Observable returned by `delayDurationSelector`. @method delayWhen @owner Observable
[ "Delays", "the", "emission", "of", "items", "from", "the", "source", "Observable", "by", "a", "given", "time", "span", "determined", "by", "the", "emissions", "of", "another", "Observable", "." ]
21901b69f6af39764b813c11502c482b0e451537
https://github.com/Erdiko/ngx-user-admin/blob/21901b69f6af39764b813c11502c482b0e451537/dist/bundles/ng-user-admin.umd.js#L47236-L47242
train
niieani/chunk-splitting-plugin
ChunkSplittingPlugin.js
leadingZeros
function leadingZeros(number, minLength = 0, padWith = '0') { const stringNumber = number.toString() const paddingLength = minLength - stringNumber.length return paddingLength > 0 ? `${padWith.repeat(paddingLength)}${stringNumber}` : stringNumber }
javascript
function leadingZeros(number, minLength = 0, padWith = '0') { const stringNumber = number.toString() const paddingLength = minLength - stringNumber.length return paddingLength > 0 ? `${padWith.repeat(paddingLength)}${stringNumber}` : stringNumber }
[ "function", "leadingZeros", "(", "number", ",", "minLength", "=", "0", ",", "padWith", "=", "'0'", ")", "{", "const", "stringNumber", "=", "number", ".", "toString", "(", ")", "const", "paddingLength", "=", "minLength", "-", "stringNumber", ".", "length", "return", "paddingLength", ">", "0", "?", "`", "${", "padWith", ".", "repeat", "(", "paddingLength", ")", "}", "${", "stringNumber", "}", "`", ":", "stringNumber", "}" ]
Ensures a number is padded with a certain amount of leading characters @param {number} number @param {number} minLength @param {string} padWith
[ "Ensures", "a", "number", "is", "padded", "with", "a", "certain", "amount", "of", "leading", "characters" ]
6af9e696751d882219d8fc0ead6865522034ba29
https://github.com/niieani/chunk-splitting-plugin/blob/6af9e696751d882219d8fc0ead6865522034ba29/ChunkSplittingPlugin.js#L62-L66
train
fulup-bzh/GeoGate
server/adapters/HttpAjax-adapter.js
function(dbresult) { // start with response header var jsonresponse= // validate syntaxe at http://geojsonlint.com/ {"type":"GeometryCollection" ,"device": {"type":"Device" ,"class":device.class ,"model": device.model ,"call": device.call },"properties": {"type":"Properties" ,'id' : query.devid ,"name": device.name ,'url': devurl ,'img': device.img } ,"geometries":[] }; for (var idx in dbresult) { var pos = dbresult [idx]; var ptsinfo=util.format ("%s<br>Position:[%s,%s] Speed:%s",pos.date,pos.lon.toFixed(4),pos.lat.toFixed(4),pos.sog.toFixed(1)); jsonresponse.geometries.push ( {'type':'Point' ,'coordinates' :[pos.lon, pos.lat] ,'sog' : pos.sog ,'cog' : pos.cog ,'date' : pos.date.getTime() ,'properties' : {'type':'Properties' ,"title": ptsinfo }}); }; if (query.jsoncallback === undefined) { response.writeHead(200,{"Content-Type": "application/json"}); response.write(JSON.stringify(jsonresponse)); } else { response.writeHead(200,{"Content-Type": "text/javascript",'Cache-Control':'no-cache'}); var fakescript=query.jsoncallback +'(' + JSON.stringify(jsonresponse) +');'; response.write (fakescript); } response.end(); }
javascript
function(dbresult) { // start with response header var jsonresponse= // validate syntaxe at http://geojsonlint.com/ {"type":"GeometryCollection" ,"device": {"type":"Device" ,"class":device.class ,"model": device.model ,"call": device.call },"properties": {"type":"Properties" ,'id' : query.devid ,"name": device.name ,'url': devurl ,'img': device.img } ,"geometries":[] }; for (var idx in dbresult) { var pos = dbresult [idx]; var ptsinfo=util.format ("%s<br>Position:[%s,%s] Speed:%s",pos.date,pos.lon.toFixed(4),pos.lat.toFixed(4),pos.sog.toFixed(1)); jsonresponse.geometries.push ( {'type':'Point' ,'coordinates' :[pos.lon, pos.lat] ,'sog' : pos.sog ,'cog' : pos.cog ,'date' : pos.date.getTime() ,'properties' : {'type':'Properties' ,"title": ptsinfo }}); }; if (query.jsoncallback === undefined) { response.writeHead(200,{"Content-Type": "application/json"}); response.write(JSON.stringify(jsonresponse)); } else { response.writeHead(200,{"Content-Type": "text/javascript",'Cache-Control':'no-cache'}); var fakescript=query.jsoncallback +'(' + JSON.stringify(jsonresponse) +');'; response.write (fakescript); } response.end(); }
[ "function", "(", "dbresult", ")", "{", "var", "jsonresponse", "=", "{", "\"type\"", ":", "\"GeometryCollection\"", ",", "\"device\"", ":", "{", "\"type\"", ":", "\"Device\"", ",", "\"class\"", ":", "device", ".", "class", ",", "\"model\"", ":", "device", ".", "model", ",", "\"call\"", ":", "device", ".", "call", "}", ",", "\"properties\"", ":", "{", "\"type\"", ":", "\"Properties\"", ",", "'id'", ":", "query", ".", "devid", ",", "\"name\"", ":", "device", ".", "name", ",", "'url'", ":", "devurl", ",", "'img'", ":", "device", ".", "img", "}", ",", "\"geometries\"", ":", "[", "]", "}", ";", "for", "(", "var", "idx", "in", "dbresult", ")", "{", "var", "pos", "=", "dbresult", "[", "idx", "]", ";", "var", "ptsinfo", "=", "util", ".", "format", "(", "\"%s<br>Position:[%s,%s] Speed:%s\"", ",", "pos", ".", "date", ",", "pos", ".", "lon", ".", "toFixed", "(", "4", ")", ",", "pos", ".", "lat", ".", "toFixed", "(", "4", ")", ",", "pos", ".", "sog", ".", "toFixed", "(", "1", ")", ")", ";", "jsonresponse", ".", "geometries", ".", "push", "(", "{", "'type'", ":", "'Point'", ",", "'coordinates'", ":", "[", "pos", ".", "lon", ",", "pos", ".", "lat", "]", ",", "'sog'", ":", "pos", ".", "sog", ",", "'cog'", ":", "pos", ".", "cog", ",", "'date'", ":", "pos", ".", "date", ".", "getTime", "(", ")", ",", "'properties'", ":", "{", "'type'", ":", "'Properties'", ",", "\"title\"", ":", "ptsinfo", "}", "}", ")", ";", "}", ";", "if", "(", "query", ".", "jsoncallback", "===", "undefined", ")", "{", "response", ".", "writeHead", "(", "200", ",", "{", "\"Content-Type\"", ":", "\"application/json\"", "}", ")", ";", "response", ".", "write", "(", "JSON", ".", "stringify", "(", "jsonresponse", ")", ")", ";", "}", "else", "{", "response", ".", "writeHead", "(", "200", ",", "{", "\"Content-Type\"", ":", "\"text/javascript\"", ",", "'Cache-Control'", ":", "'no-cache'", "}", ")", ";", "var", "fakescript", "=", "query", ".", "jsoncallback", "+", "'('", "+", "JSON", ".", "stringify", "(", "jsonresponse", ")", "+", "');'", ";", "response", ".", "write", "(", "fakescript", ")", ";", "}", "response", ".", "end", "(", ")", ";", "}" ]
DB callback return a json object with device name and possition
[ "DB", "callback", "return", "a", "json", "object", "with", "device", "name", "and", "possition" ]
34d9f256545b74d596747d1c2faf9bb450eb0777
https://github.com/fulup-bzh/GeoGate/blob/34d9f256545b74d596747d1c2faf9bb450eb0777/server/adapters/HttpAjax-adapter.js#L145-L187
train
fulup-bzh/GeoGate
server/adapters/HttpAjax-adapter.js
ReadFileCB
function ReadFileCB (err, byteread, buffer) { if (err) { response.write(err.toString()); } else { response.write(buffer); } response.end(); }
javascript
function ReadFileCB (err, byteread, buffer) { if (err) { response.write(err.toString()); } else { response.write(buffer); } response.end(); }
[ "function", "ReadFileCB", "(", "err", ",", "byteread", ",", "buffer", ")", "{", "if", "(", "err", ")", "{", "response", ".", "write", "(", "err", ".", "toString", "(", ")", ")", ";", "}", "else", "{", "response", ".", "write", "(", "buffer", ")", ";", "}", "response", ".", "end", "(", ")", ";", "}" ]
push file back onto response HTTP response handler
[ "push", "file", "back", "onto", "response", "HTTP", "response", "handler" ]
34d9f256545b74d596747d1c2faf9bb450eb0777
https://github.com/fulup-bzh/GeoGate/blob/34d9f256545b74d596747d1c2faf9bb450eb0777/server/adapters/HttpAjax-adapter.js#L232-L239
train
fulup-bzh/GeoGate
server/adapters/HttpAjax-adapter.js
OpenFileCB
function OpenFileCB (err, fd) { if (err) { response.setHeader('Content-Type','text/html'); response.writeHead(404, err.toString("utf8")); response.write("Hoops:" + err ); response.end(); return; } fs.fstat(fd, function(err,stats){ // get file size and allocate buffer to read it var buffer = new Buffer (stats.size); fs.read (fd, buffer,0,buffer.length,0,ReadFileCB); }); }
javascript
function OpenFileCB (err, fd) { if (err) { response.setHeader('Content-Type','text/html'); response.writeHead(404, err.toString("utf8")); response.write("Hoops:" + err ); response.end(); return; } fs.fstat(fd, function(err,stats){ // get file size and allocate buffer to read it var buffer = new Buffer (stats.size); fs.read (fd, buffer,0,buffer.length,0,ReadFileCB); }); }
[ "function", "OpenFileCB", "(", "err", ",", "fd", ")", "{", "if", "(", "err", ")", "{", "response", ".", "setHeader", "(", "'Content-Type'", ",", "'text/html'", ")", ";", "response", ".", "writeHead", "(", "404", ",", "err", ".", "toString", "(", "\"utf8\"", ")", ")", ";", "response", ".", "write", "(", "\"Hoops:\"", "+", "err", ")", ";", "response", ".", "end", "(", ")", ";", "return", ";", "}", "fs", ".", "fstat", "(", "fd", ",", "function", "(", "err", ",", "stats", ")", "{", "var", "buffer", "=", "new", "Buffer", "(", "stats", ".", "size", ")", ";", "fs", ".", "read", "(", "fd", ",", "buffer", ",", "0", ",", "buffer", ".", "length", ",", "0", ",", "ReadFileCB", ")", ";", "}", ")", ";", "}" ]
open file and check if its supported
[ "open", "file", "and", "check", "if", "its", "supported" ]
34d9f256545b74d596747d1c2faf9bb450eb0777
https://github.com/fulup-bzh/GeoGate/blob/34d9f256545b74d596747d1c2faf9bb450eb0777/server/adapters/HttpAjax-adapter.js#L242-L255
train
fulup-bzh/GeoGate
server/backends/MongoDB-backend.js
CreateConnection
function CreateConnection (backend) { backend.Debug (4, "MongoDB creating connection [%s]", backend.uid); MongoClient.connect(backend.uid, function (err, db) { if (err) { backend.Debug (0, "Fail to connect to MongoDB: %s err=[%s]", backend.uid, err) } else { backend.Debug (4, "Connected to MongoDB: %s", backend.uid) backend.base = db; } }); }
javascript
function CreateConnection (backend) { backend.Debug (4, "MongoDB creating connection [%s]", backend.uid); MongoClient.connect(backend.uid, function (err, db) { if (err) { backend.Debug (0, "Fail to connect to MongoDB: %s err=[%s]", backend.uid, err) } else { backend.Debug (4, "Connected to MongoDB: %s", backend.uid) backend.base = db; } }); }
[ "function", "CreateConnection", "(", "backend", ")", "{", "backend", ".", "Debug", "(", "4", ",", "\"MongoDB creating connection [%s]\"", ",", "backend", ".", "uid", ")", ";", "MongoClient", ".", "connect", "(", "backend", ".", "uid", ",", "function", "(", "err", ",", "db", ")", "{", "if", "(", "err", ")", "{", "backend", ".", "Debug", "(", "0", ",", "\"Fail to connect to MongoDB: %s err=[%s]\"", ",", "backend", ".", "uid", ",", "err", ")", "}", "else", "{", "backend", ".", "Debug", "(", "4", ",", "\"Connected to MongoDB: %s\"", ",", "backend", ".", "uid", ")", "backend", ".", "base", "=", "db", ";", "}", "}", ")", ";", "}" ]
10s timeout in between two MONGO reconnects ConnectDB is done on at creation time
[ "10s", "timeout", "in", "between", "two", "MONGO", "reconnects", "ConnectDB", "is", "done", "on", "at", "creation", "time" ]
34d9f256545b74d596747d1c2faf9bb450eb0777
https://github.com/fulup-bzh/GeoGate/blob/34d9f256545b74d596747d1c2faf9bb450eb0777/server/backends/MongoDB-backend.js#L25-L36
train
fulup-bzh/GeoGate
server/backends/MongoDB-backend.js
BackendStorage
function BackendStorage (gateway, opts){ // prepare ourself to make debug possible this.debug =opts.debug; this.gateway=gateway; this.opts= { hostname : opts.mongodb.hostname || "localhost" , username : opts.mongodb.username , password : opts.mongodb.password , basename : opts.mongodb.basename || opts.mongo.username , port : opts.mongodb.port || 27017 }; this.uid ="mongodb://" + this.opts.username + ':' + this.opts.password + "@" + this.opts.hostname +':'+ this.opts.port + "/" + this.opts.basename; // create initial connection handler to database CreateConnection (this); }
javascript
function BackendStorage (gateway, opts){ // prepare ourself to make debug possible this.debug =opts.debug; this.gateway=gateway; this.opts= { hostname : opts.mongodb.hostname || "localhost" , username : opts.mongodb.username , password : opts.mongodb.password , basename : opts.mongodb.basename || opts.mongo.username , port : opts.mongodb.port || 27017 }; this.uid ="mongodb://" + this.opts.username + ':' + this.opts.password + "@" + this.opts.hostname +':'+ this.opts.port + "/" + this.opts.basename; // create initial connection handler to database CreateConnection (this); }
[ "function", "BackendStorage", "(", "gateway", ",", "opts", ")", "{", "this", ".", "debug", "=", "opts", ".", "debug", ";", "this", ".", "gateway", "=", "gateway", ";", "this", ".", "opts", "=", "{", "hostname", ":", "opts", ".", "mongodb", ".", "hostname", "||", "\"localhost\"", ",", "username", ":", "opts", ".", "mongodb", ".", "username", ",", "password", ":", "opts", ".", "mongodb", ".", "password", ",", "basename", ":", "opts", ".", "mongodb", ".", "basename", "||", "opts", ".", "mongo", ".", "username", ",", "port", ":", "opts", ".", "mongodb", ".", "port", "||", "27017", "}", ";", "this", ".", "uid", "=", "\"mongodb://\"", "+", "this", ".", "opts", ".", "username", "+", "':'", "+", "this", ".", "opts", ".", "password", "+", "\"@\"", "+", "this", ".", "opts", ".", "hostname", "+", "':'", "+", "this", ".", "opts", ".", "port", "+", "\"/\"", "+", "this", ".", "opts", ".", "basename", ";", "CreateConnection", "(", "this", ")", ";", "}" ]
Create MongoDB Backend object
[ "Create", "MongoDB", "Backend", "object" ]
34d9f256545b74d596747d1c2faf9bb450eb0777
https://github.com/fulup-bzh/GeoGate/blob/34d9f256545b74d596747d1c2faf9bb450eb0777/server/backends/MongoDB-backend.js#L39-L56
train
fulup-bzh/GeoGate
utils/USR-TCP232-Config.js
WriteIpAddr
function WriteIpAddr (buffer, offset, ipstring) { var addr= ipstring.split('.'); buffer.writeUInt8(parseInt(addr[3]), offset); buffer.writeUInt8(parseInt(addr[2]), offset + 1); buffer.writeUInt8(parseInt(addr[1]), offset + 2); buffer.writeUInt8(parseInt(addr[0]), offset + 3); }
javascript
function WriteIpAddr (buffer, offset, ipstring) { var addr= ipstring.split('.'); buffer.writeUInt8(parseInt(addr[3]), offset); buffer.writeUInt8(parseInt(addr[2]), offset + 1); buffer.writeUInt8(parseInt(addr[1]), offset + 2); buffer.writeUInt8(parseInt(addr[0]), offset + 3); }
[ "function", "WriteIpAddr", "(", "buffer", ",", "offset", ",", "ipstring", ")", "{", "var", "addr", "=", "ipstring", ".", "split", "(", "'.'", ")", ";", "buffer", ".", "writeUInt8", "(", "parseInt", "(", "addr", "[", "3", "]", ")", ",", "offset", ")", ";", "buffer", ".", "writeUInt8", "(", "parseInt", "(", "addr", "[", "2", "]", ")", ",", "offset", "+", "1", ")", ";", "buffer", ".", "writeUInt8", "(", "parseInt", "(", "addr", "[", "1", "]", ")", ",", "offset", "+", "2", ")", ";", "buffer", ".", "writeUInt8", "(", "parseInt", "(", "addr", "[", "0", "]", ")", ",", "offset", "+", "3", ")", ";", "}" ]
adapter address at discovery parse IP Addr and add it to config buffer
[ "adapter", "address", "at", "discovery", "parse", "IP", "Addr", "and", "add", "it", "to", "config", "buffer" ]
34d9f256545b74d596747d1c2faf9bb450eb0777
https://github.com/fulup-bzh/GeoGate/blob/34d9f256545b74d596747d1c2faf9bb450eb0777/utils/USR-TCP232-Config.js#L92-L98
train
fulup-bzh/GeoGate
simulator/lib/GG-NmeaAisEncoder.js
NmeaAisEncoder
function NmeaAisEncoder (data) { var msg; // Use NMEA GRPMC or AIVDM depending on Vessel MMSI if (data.mmsi === 0) { // this ship has no MMSI let's use GPRMC format switch (data.cmd) { case 1: msg = { // built a Fake NMEA authentication message valid: true, nmea: "FAKID" + data.mmsi +',' + data.shipname }; break; case 2: msg = new GGencode.NmeaEncode(data); break; default: msg = null; } } else { // we are facing multiple boats use AIS ADVDM switch (data.cmd) { case 1: if (data.class === 'A') data.aistype = 5; else data.aistype = 24; msg = new GGencode.AisEncode(data); break; case 2: if (data.class === 'A') data.aistype = 3; else data.aistype = 18; msg = new GGencode.AisEncode(data); break; default: msg = null; } } if (msg.valid) return (msg.nmea); else return (null); }
javascript
function NmeaAisEncoder (data) { var msg; // Use NMEA GRPMC or AIVDM depending on Vessel MMSI if (data.mmsi === 0) { // this ship has no MMSI let's use GPRMC format switch (data.cmd) { case 1: msg = { // built a Fake NMEA authentication message valid: true, nmea: "FAKID" + data.mmsi +',' + data.shipname }; break; case 2: msg = new GGencode.NmeaEncode(data); break; default: msg = null; } } else { // we are facing multiple boats use AIS ADVDM switch (data.cmd) { case 1: if (data.class === 'A') data.aistype = 5; else data.aistype = 24; msg = new GGencode.AisEncode(data); break; case 2: if (data.class === 'A') data.aistype = 3; else data.aistype = 18; msg = new GGencode.AisEncode(data); break; default: msg = null; } } if (msg.valid) return (msg.nmea); else return (null); }
[ "function", "NmeaAisEncoder", "(", "data", ")", "{", "var", "msg", ";", "if", "(", "data", ".", "mmsi", "===", "0", ")", "{", "switch", "(", "data", ".", "cmd", ")", "{", "case", "1", ":", "msg", "=", "{", "valid", ":", "true", ",", "nmea", ":", "\"FAKID\"", "+", "data", ".", "mmsi", "+", "','", "+", "data", ".", "shipname", "}", ";", "break", ";", "case", "2", ":", "msg", "=", "new", "GGencode", ".", "NmeaEncode", "(", "data", ")", ";", "break", ";", "default", ":", "msg", "=", "null", ";", "}", "}", "else", "{", "switch", "(", "data", ".", "cmd", ")", "{", "case", "1", ":", "if", "(", "data", ".", "class", "===", "'A'", ")", "data", ".", "aistype", "=", "5", ";", "else", "data", ".", "aistype", "=", "24", ";", "msg", "=", "new", "GGencode", ".", "AisEncode", "(", "data", ")", ";", "break", ";", "case", "2", ":", "if", "(", "data", ".", "class", "===", "'A'", ")", "data", ".", "aistype", "=", "3", ";", "else", "data", ".", "aistype", "=", "18", ";", "msg", "=", "new", "GGencode", ".", "AisEncode", "(", "data", ")", ";", "break", ";", "default", ":", "msg", "=", "null", ";", "}", "}", "if", "(", "msg", ".", "valid", ")", "return", "(", "msg", ".", "nmea", ")", ";", "else", "return", "(", "null", ")", ";", "}" ]
Encode AIS AIVDM or GPRMC depending on position MMSI
[ "Encode", "AIS", "AIVDM", "or", "GPRMC", "depending", "on", "position", "MMSI" ]
34d9f256545b74d596747d1c2faf9bb450eb0777
https://github.com/fulup-bzh/GeoGate/blob/34d9f256545b74d596747d1c2faf9bb450eb0777/simulator/lib/GG-NmeaAisEncoder.js#L29-L65
train
fulup-bzh/GeoGate
simulator/lib/GG-Simulator.js
JobQueuePost
function JobQueuePost (job, callback) { // dummy job to activate jobqueue if (job === null) { callback (); return; } else { // force change to simulator context job.simulator.NewPosition.call (job.simulator, job); } // wait tic time before sending next message job.simulator.queue.pause (); // provide some randomization on tic with a 50% fluxtuation var nexttic = parseInt (job.simulator.ticms * (1+ Math.random()/2)); setTimeout(function () {job.simulator.queue.resume();}, nexttic); callback (); }
javascript
function JobQueuePost (job, callback) { // dummy job to activate jobqueue if (job === null) { callback (); return; } else { // force change to simulator context job.simulator.NewPosition.call (job.simulator, job); } // wait tic time before sending next message job.simulator.queue.pause (); // provide some randomization on tic with a 50% fluxtuation var nexttic = parseInt (job.simulator.ticms * (1+ Math.random()/2)); setTimeout(function () {job.simulator.queue.resume();}, nexttic); callback (); }
[ "function", "JobQueuePost", "(", "job", ",", "callback", ")", "{", "if", "(", "job", "===", "null", ")", "{", "callback", "(", ")", ";", "return", ";", "}", "else", "{", "job", ".", "simulator", ".", "NewPosition", ".", "call", "(", "job", ".", "simulator", ",", "job", ")", ";", "}", "job", ".", "simulator", ".", "queue", ".", "pause", "(", ")", ";", "var", "nexttic", "=", "parseInt", "(", "job", ".", "simulator", ".", "ticms", "*", "(", "1", "+", "Math", ".", "random", "(", ")", "/", "2", ")", ")", ";", "setTimeout", "(", "function", "(", ")", "{", "job", ".", "simulator", ".", "queue", ".", "resume", "(", ")", ";", "}", ",", "nexttic", ")", ";", "callback", "(", ")", ";", "}" ]
Notice method is called by async within async context !!!!
[ "Notice", "method", "is", "called", "by", "async", "within", "async", "context", "!!!!" ]
34d9f256545b74d596747d1c2faf9bb450eb0777
https://github.com/fulup-bzh/GeoGate/blob/34d9f256545b74d596747d1c2faf9bb450eb0777/simulator/lib/GG-Simulator.js#L76-L91
train
fulup-bzh/GeoGate
simulator/lib/GG-Simulator.js
JobQueueActivate
function JobQueueActivate(queue, callback, timeout) { setTimeout(function () {queue.push (null, callback);}, timeout); // wait 5S before start }
javascript
function JobQueueActivate(queue, callback, timeout) { setTimeout(function () {queue.push (null, callback);}, timeout); // wait 5S before start }
[ "function", "JobQueueActivate", "(", "queue", ",", "callback", ",", "timeout", ")", "{", "setTimeout", "(", "function", "(", ")", "{", "queue", ".", "push", "(", "null", ",", "callback", ")", ";", "}", ",", "timeout", ")", ";", "}" ]
push a dummy job in queue to force activation
[ "push", "a", "dummy", "job", "in", "queue", "to", "force", "activation" ]
34d9f256545b74d596747d1c2faf9bb450eb0777
https://github.com/fulup-bzh/GeoGate/blob/34d9f256545b74d596747d1c2faf9bb450eb0777/simulator/lib/GG-Simulator.js#L196-L198
train
fulup-bzh/GeoGate
server/adapters/AisTcpProxy-adapter.js
EventDevAuth
function EventDevAuth (device){ if (!device.mmsi) device.mmsi = parseInt (device.devid); if (isNaN (device.mmsi)) device.mmsi=String2Hash(device.devid); adapter.BroadcastStatic (device); if (device.stamp) adapter.BroadcastPos (device); }
javascript
function EventDevAuth (device){ if (!device.mmsi) device.mmsi = parseInt (device.devid); if (isNaN (device.mmsi)) device.mmsi=String2Hash(device.devid); adapter.BroadcastStatic (device); if (device.stamp) adapter.BroadcastPos (device); }
[ "function", "EventDevAuth", "(", "device", ")", "{", "if", "(", "!", "device", ".", "mmsi", ")", "device", ".", "mmsi", "=", "parseInt", "(", "device", ".", "devid", ")", ";", "if", "(", "isNaN", "(", "device", ".", "mmsi", ")", ")", "device", ".", "mmsi", "=", "String2Hash", "(", "device", ".", "devid", ")", ";", "adapter", ".", "BroadcastStatic", "(", "device", ")", ";", "if", "(", "device", ".", "stamp", ")", "adapter", ".", "BroadcastPos", "(", "device", ")", ";", "}" ]
if no MMSI avaliable let's try to build a fakeone
[ "if", "no", "MMSI", "avaliable", "let", "s", "try", "to", "build", "a", "fakeone" ]
34d9f256545b74d596747d1c2faf9bb450eb0777
https://github.com/fulup-bzh/GeoGate/blob/34d9f256545b74d596747d1c2faf9bb450eb0777/server/adapters/AisTcpProxy-adapter.js#L53-L58
train
fulup-bzh/GeoGate
smsc/lib/GG-SmsBatch.js
SmsBatch
function SmsBatch (smsc, callback, smsarray) { var idx=0; // when message is processed move to next one otherwise call user applicationCB function InternalCB (data) { // [good or bad] let's notify user application if (data.status != 0) callback (data); // it's time to move to next message if (data.status <= 0) { if (++idx < smsarray.length) { new SmsRequest (smsc, InternalCB, smsarray [idx]); } else { callback ({status: 0}); } } } // let's start by sending 1st SMS of the array new SmsRequest(smsc, InternalCB, smsarray [idx]); }
javascript
function SmsBatch (smsc, callback, smsarray) { var idx=0; // when message is processed move to next one otherwise call user applicationCB function InternalCB (data) { // [good or bad] let's notify user application if (data.status != 0) callback (data); // it's time to move to next message if (data.status <= 0) { if (++idx < smsarray.length) { new SmsRequest (smsc, InternalCB, smsarray [idx]); } else { callback ({status: 0}); } } } // let's start by sending 1st SMS of the array new SmsRequest(smsc, InternalCB, smsarray [idx]); }
[ "function", "SmsBatch", "(", "smsc", ",", "callback", ",", "smsarray", ")", "{", "var", "idx", "=", "0", ";", "function", "InternalCB", "(", "data", ")", "{", "if", "(", "data", ".", "status", "!=", "0", ")", "callback", "(", "data", ")", ";", "if", "(", "data", ".", "status", "<=", "0", ")", "{", "if", "(", "++", "idx", "<", "smsarray", ".", "length", ")", "{", "new", "SmsRequest", "(", "smsc", ",", "InternalCB", ",", "smsarray", "[", "idx", "]", ")", ";", "}", "else", "{", "callback", "(", "{", "status", ":", "0", "}", ")", ";", "}", "}", "}", "new", "SmsRequest", "(", "smsc", ",", "InternalCB", ",", "smsarray", "[", "idx", "]", ")", ";", "}" ]
this method send a batch of SMS and call user CB with status=0 when finish
[ "this", "method", "send", "a", "batch", "of", "SMS", "and", "call", "user", "CB", "with", "status", "=", "0", "when", "finish" ]
34d9f256545b74d596747d1c2faf9bb450eb0777
https://github.com/fulup-bzh/GeoGate/blob/34d9f256545b74d596747d1c2faf9bb450eb0777/smsc/lib/GG-SmsBatch.js#L24-L45
train
fulup-bzh/GeoGate
smsc/lib/GG-SmsBatch.js
InternalCB
function InternalCB (data) { // [good or bad] let's notify user application if (data.status != 0) callback (data); // it's time to move to next message if (data.status <= 0) { if (++idx < smsarray.length) { new SmsRequest (smsc, InternalCB, smsarray [idx]); } else { callback ({status: 0}); } } }
javascript
function InternalCB (data) { // [good or bad] let's notify user application if (data.status != 0) callback (data); // it's time to move to next message if (data.status <= 0) { if (++idx < smsarray.length) { new SmsRequest (smsc, InternalCB, smsarray [idx]); } else { callback ({status: 0}); } } }
[ "function", "InternalCB", "(", "data", ")", "{", "if", "(", "data", ".", "status", "!=", "0", ")", "callback", "(", "data", ")", ";", "if", "(", "data", ".", "status", "<=", "0", ")", "{", "if", "(", "++", "idx", "<", "smsarray", ".", "length", ")", "{", "new", "SmsRequest", "(", "smsc", ",", "InternalCB", ",", "smsarray", "[", "idx", "]", ")", ";", "}", "else", "{", "callback", "(", "{", "status", ":", "0", "}", ")", ";", "}", "}", "}" ]
when message is processed move to next one otherwise call user applicationCB
[ "when", "message", "is", "processed", "move", "to", "next", "one", "otherwise", "call", "user", "applicationCB" ]
34d9f256545b74d596747d1c2faf9bb450eb0777
https://github.com/fulup-bzh/GeoGate/blob/34d9f256545b74d596747d1c2faf9bb450eb0777/smsc/lib/GG-SmsBatch.js#L28-L41
train
fulup-bzh/GeoGate
server/backends/Dummy-backend.js
BackendStorage
function BackendStorage (gateway, opts){ // prepare ourself to make debug possible this.uid="Dummy@nothing"; this.gateway =gateway; this.debug=opts.debug; this.count=0; this.storesize= 20 +1; // number of position slot/devices this.event = new EventEmitter(); }
javascript
function BackendStorage (gateway, opts){ // prepare ourself to make debug possible this.uid="Dummy@nothing"; this.gateway =gateway; this.debug=opts.debug; this.count=0; this.storesize= 20 +1; // number of position slot/devices this.event = new EventEmitter(); }
[ "function", "BackendStorage", "(", "gateway", ",", "opts", ")", "{", "this", ".", "uid", "=", "\"Dummy@nothing\"", ";", "this", ".", "gateway", "=", "gateway", ";", "this", ".", "debug", "=", "opts", ".", "debug", ";", "this", ".", "count", "=", "0", ";", "this", ".", "storesize", "=", "20", "+", "1", ";", "this", ".", "event", "=", "new", "EventEmitter", "(", ")", ";", "}" ]
This is our fake device authentication DB table
[ "This", "is", "our", "fake", "device", "authentication", "DB", "table" ]
34d9f256545b74d596747d1c2faf9bb450eb0777
https://github.com/fulup-bzh/GeoGate/blob/34d9f256545b74d596747d1c2faf9bb450eb0777/server/backends/Dummy-backend.js#L43-L53
train
fulup-bzh/GeoGate
encoder/bin/Ais2JsonClient.js
function (job, callback) { // decode AIS message ignoring any not AIDVM paquet var nmea= job.toString ('ascii'); var ais = new AisDecode (nmea); // if message valid and mssi not excluded by --mmsi option if (ais.valid) { // Some cleanup to make JSON/AIS more human readable delete ais.bitarray; delete ais.valid; delete ais.length; delete ais.channel; delete ais.repeat; delete ais.navstatus; delete ais.utc; ais.lon = (parseInt(ais.lon * 10000))/10000; ais.lat = (parseInt(ais.lat * 10000))/10000; ais.sog = (parseInt(ais.sog * 10))/10; ais.cog = (parseInt(ais.cog * 10))/10; // we do not need class for each navigation report if (ais.msgtype === 18 || ais.msgtype === 3) { delete ais.class; } MsgCount ++; // push AIS usefull info to user if (DumpFd !== null) { fs.writeSync (DumpFd,MsgCount + " , " +JSON.stringify (ais)+'\n'); } if ((MmsiFilter===null || MmsiFilter===parseInt(ais.mmsi)) && (TypeFilter===null || TypeFilter===parseInt(ais.msgtype))){ console.log ("-%d- %s", MsgCount, JSON.stringify (ais)); } if (Verbose) console.log ("-%d- %s", MsgCount, nmea) } else { if (Verbose) console.log ("\n-***- %s", nmea) } // we're done let's move to next job in queue callback(); }
javascript
function (job, callback) { // decode AIS message ignoring any not AIDVM paquet var nmea= job.toString ('ascii'); var ais = new AisDecode (nmea); // if message valid and mssi not excluded by --mmsi option if (ais.valid) { // Some cleanup to make JSON/AIS more human readable delete ais.bitarray; delete ais.valid; delete ais.length; delete ais.channel; delete ais.repeat; delete ais.navstatus; delete ais.utc; ais.lon = (parseInt(ais.lon * 10000))/10000; ais.lat = (parseInt(ais.lat * 10000))/10000; ais.sog = (parseInt(ais.sog * 10))/10; ais.cog = (parseInt(ais.cog * 10))/10; // we do not need class for each navigation report if (ais.msgtype === 18 || ais.msgtype === 3) { delete ais.class; } MsgCount ++; // push AIS usefull info to user if (DumpFd !== null) { fs.writeSync (DumpFd,MsgCount + " , " +JSON.stringify (ais)+'\n'); } if ((MmsiFilter===null || MmsiFilter===parseInt(ais.mmsi)) && (TypeFilter===null || TypeFilter===parseInt(ais.msgtype))){ console.log ("-%d- %s", MsgCount, JSON.stringify (ais)); } if (Verbose) console.log ("-%d- %s", MsgCount, nmea) } else { if (Verbose) console.log ("\n-***- %s", nmea) } // we're done let's move to next job in queue callback(); }
[ "function", "(", "job", ",", "callback", ")", "{", "var", "nmea", "=", "job", ".", "toString", "(", "'ascii'", ")", ";", "var", "ais", "=", "new", "AisDecode", "(", "nmea", ")", ";", "if", "(", "ais", ".", "valid", ")", "{", "delete", "ais", ".", "bitarray", ";", "delete", "ais", ".", "valid", ";", "delete", "ais", ".", "length", ";", "delete", "ais", ".", "channel", ";", "delete", "ais", ".", "repeat", ";", "delete", "ais", ".", "navstatus", ";", "delete", "ais", ".", "utc", ";", "ais", ".", "lon", "=", "(", "parseInt", "(", "ais", ".", "lon", "*", "10000", ")", ")", "/", "10000", ";", "ais", ".", "lat", "=", "(", "parseInt", "(", "ais", ".", "lat", "*", "10000", ")", ")", "/", "10000", ";", "ais", ".", "sog", "=", "(", "parseInt", "(", "ais", ".", "sog", "*", "10", ")", ")", "/", "10", ";", "ais", ".", "cog", "=", "(", "parseInt", "(", "ais", ".", "cog", "*", "10", ")", ")", "/", "10", ";", "if", "(", "ais", ".", "msgtype", "===", "18", "||", "ais", ".", "msgtype", "===", "3", ")", "{", "delete", "ais", ".", "class", ";", "}", "MsgCount", "++", ";", "if", "(", "DumpFd", "!==", "null", ")", "{", "fs", ".", "writeSync", "(", "DumpFd", ",", "MsgCount", "+", "\" , \"", "+", "JSON", ".", "stringify", "(", "ais", ")", "+", "'\\n'", ")", ";", "}", "\\n", "if", "(", "(", "MmsiFilter", "===", "null", "||", "MmsiFilter", "===", "parseInt", "(", "ais", ".", "mmsi", ")", ")", "&&", "(", "TypeFilter", "===", "null", "||", "TypeFilter", "===", "parseInt", "(", "ais", ".", "msgtype", ")", ")", ")", "{", "console", ".", "log", "(", "\"-%d- %s\"", ",", "MsgCount", ",", "JSON", ".", "stringify", "(", "ais", ")", ")", ";", "}", "}", "else", "if", "(", "Verbose", ")", "console", ".", "log", "(", "\"-%d- %s\"", ",", "MsgCount", ",", "nmea", ")", "{", "if", "(", "Verbose", ")", "console", ".", "log", "(", "\"\\n-***- %s\"", ",", "\\n", ")", "}", "}" ]
Notice method is called by async within unknow context !!!!
[ "Notice", "method", "is", "called", "by", "async", "within", "unknow", "context", "!!!!" ]
34d9f256545b74d596747d1c2faf9bb450eb0777
https://github.com/fulup-bzh/GeoGate/blob/34d9f256545b74d596747d1c2faf9bb450eb0777/encoder/bin/Ais2JsonClient.js#L62-L105
train
fulup-bzh/GeoGate
smsc/lib/GG-SmsRequest.js
CheckDevAckCB
function CheckDevAckCB(err, results) { self.retry ++; // retry counter for ACK self.Debug (6, "CheckDevAckCB Phone=%s Retry=%d/%d Result=%j", smscmd.phone, self.retry, smsc.opts.retry, results); // ack no received if (results.length === 0) { if (self.retry <= smsc.opts.retry) { setTimeout (function() {CheckDevAck ();}, smsc.opts.delay); } else { self.Debug (7, "CheckDevAckCB Ack Abandoned MaxRetry=%s", smsc.opts.retry); appcb ({status: -2, smsid: smscmd.id}); } } else { // we may have more than one responses for a given command for (var slot in results) { var ack = { status: 2 , smsid: smscmd.id , phone: smscmd.phone , ack: results[slot].TextDecoded }; // ACK received, delete it from inbox and send it to application self.Debug (6, "CheckDevAckCB Ack Received %j", ack); smsc.DelById (DelByIdCB, results[slot].Id); appcb({status: 2, smsid: smscmd.id, msg: ack}); } appcb({status: 0}); } }
javascript
function CheckDevAckCB(err, results) { self.retry ++; // retry counter for ACK self.Debug (6, "CheckDevAckCB Phone=%s Retry=%d/%d Result=%j", smscmd.phone, self.retry, smsc.opts.retry, results); // ack no received if (results.length === 0) { if (self.retry <= smsc.opts.retry) { setTimeout (function() {CheckDevAck ();}, smsc.opts.delay); } else { self.Debug (7, "CheckDevAckCB Ack Abandoned MaxRetry=%s", smsc.opts.retry); appcb ({status: -2, smsid: smscmd.id}); } } else { // we may have more than one responses for a given command for (var slot in results) { var ack = { status: 2 , smsid: smscmd.id , phone: smscmd.phone , ack: results[slot].TextDecoded }; // ACK received, delete it from inbox and send it to application self.Debug (6, "CheckDevAckCB Ack Received %j", ack); smsc.DelById (DelByIdCB, results[slot].Id); appcb({status: 2, smsid: smscmd.id, msg: ack}); } appcb({status: 0}); } }
[ "function", "CheckDevAckCB", "(", "err", ",", "results", ")", "{", "self", ".", "retry", "++", ";", "self", ".", "Debug", "(", "6", ",", "\"CheckDevAckCB Phone=%s Retry=%d/%d Result=%j\"", ",", "smscmd", ".", "phone", ",", "self", ".", "retry", ",", "smsc", ".", "opts", ".", "retry", ",", "results", ")", ";", "if", "(", "results", ".", "length", "===", "0", ")", "{", "if", "(", "self", ".", "retry", "<=", "smsc", ".", "opts", ".", "retry", ")", "{", "setTimeout", "(", "function", "(", ")", "{", "CheckDevAck", "(", ")", ";", "}", ",", "smsc", ".", "opts", ".", "delay", ")", ";", "}", "else", "{", "self", ".", "Debug", "(", "7", ",", "\"CheckDevAckCB Ack Abandoned MaxRetry=%s\"", ",", "smsc", ".", "opts", ".", "retry", ")", ";", "appcb", "(", "{", "status", ":", "-", "2", ",", "smsid", ":", "smscmd", ".", "id", "}", ")", ";", "}", "}", "else", "{", "for", "(", "var", "slot", "in", "results", ")", "{", "var", "ack", "=", "{", "status", ":", "2", ",", "smsid", ":", "smscmd", ".", "id", ",", "phone", ":", "smscmd", ".", "phone", ",", "ack", ":", "results", "[", "slot", "]", ".", "TextDecoded", "}", ";", "self", ".", "Debug", "(", "6", ",", "\"CheckDevAckCB Ack Received %j\"", ",", "ack", ")", ";", "smsc", ".", "DelById", "(", "DelByIdCB", ",", "results", "[", "slot", "]", ".", "Id", ")", ";", "appcb", "(", "{", "status", ":", "2", ",", "smsid", ":", "smscmd", ".", "id", ",", "msg", ":", "ack", "}", ")", ";", "}", "appcb", "(", "{", "status", ":", "0", "}", ")", ";", "}", "}" ]
this method is called by MySql when sms.GetFrom return
[ "this", "method", "is", "called", "by", "MySql", "when", "sms", ".", "GetFrom", "return" ]
34d9f256545b74d596747d1c2faf9bb450eb0777
https://github.com/fulup-bzh/GeoGate/blob/34d9f256545b74d596747d1c2faf9bb450eb0777/smsc/lib/GG-SmsRequest.js#L36-L63
train
fulup-bzh/GeoGate
smsc/lib/GG-SmsRequest.js
CheckDevAck
function CheckDevAck() { self.Debug (3,"Waiting Acknowledgment Response %d/%d", self.retry, smsc.opts.retry); smsc.GetFrom (CheckDevAckCB, smscmd.phone) }
javascript
function CheckDevAck() { self.Debug (3,"Waiting Acknowledgment Response %d/%d", self.retry, smsc.opts.retry); smsc.GetFrom (CheckDevAckCB, smscmd.phone) }
[ "function", "CheckDevAck", "(", ")", "{", "self", ".", "Debug", "(", "3", ",", "\"Waiting Acknowledgment Response %d/%d\"", ",", "self", ".", "retry", ",", "smsc", ".", "opts", ".", "retry", ")", ";", "smsc", ".", "GetFrom", "(", "CheckDevAckCB", ",", "smscmd", ".", "phone", ")", "}" ]
this method check sms inbox table for OK ack from device
[ "this", "method", "check", "sms", "inbox", "table", "for", "OK", "ack", "from", "device" ]
34d9f256545b74d596747d1c2faf9bb450eb0777
https://github.com/fulup-bzh/GeoGate/blob/34d9f256545b74d596747d1c2faf9bb450eb0777/smsc/lib/GG-SmsRequest.js#L66-L69
train
fulup-bzh/GeoGate
smsc/lib/GG-SmsRequest.js
CheckOutboxCB
function CheckOutboxCB(err, results) { var result = results[0]; // Query result is alway an array of response even when unique self.retry ++; // update retry counter // if message is still in queue retry self.Debug (6,"CheckOutboxCB Phone=%s Result=%j Retry=%d/%d", smscmd.phone, result, self.retry, smsc.opts.retry); if (result !== undefined) { // message is still in queue loop one more time if (self.retry <= smsc.opts.retry) { setTimeout (function() {CheckOutbox (result.ID);}, smsc.opts.delay); } else { // notify appcb that SMS failed and was deleted self.Debug (6,"CheckOutboxCB Fail SqlId=%s SMS=%j", result.ID, smscmd); smsc.DelById (DelByIdCB, result.ID); appcb ({status: -1, smsid: smscmd.id}); } } else { // le message à été expédié self.Debug (6,"CheckOutboxCB OK SMS=%j", smscmd); appcb ({status: 1, smsid: smscmd.id}); // if an acknowledgement is asked loop until we get it. if (smscmd.ack) { self.retry = 0; // reset retry counter for ack setTimeout (function() {CheckDevAck (smscmd);}, smsc.opts.delay); } else { appcb ({status: 0}); } } }
javascript
function CheckOutboxCB(err, results) { var result = results[0]; // Query result is alway an array of response even when unique self.retry ++; // update retry counter // if message is still in queue retry self.Debug (6,"CheckOutboxCB Phone=%s Result=%j Retry=%d/%d", smscmd.phone, result, self.retry, smsc.opts.retry); if (result !== undefined) { // message is still in queue loop one more time if (self.retry <= smsc.opts.retry) { setTimeout (function() {CheckOutbox (result.ID);}, smsc.opts.delay); } else { // notify appcb that SMS failed and was deleted self.Debug (6,"CheckOutboxCB Fail SqlId=%s SMS=%j", result.ID, smscmd); smsc.DelById (DelByIdCB, result.ID); appcb ({status: -1, smsid: smscmd.id}); } } else { // le message à été expédié self.Debug (6,"CheckOutboxCB OK SMS=%j", smscmd); appcb ({status: 1, smsid: smscmd.id}); // if an acknowledgement is asked loop until we get it. if (smscmd.ack) { self.retry = 0; // reset retry counter for ack setTimeout (function() {CheckDevAck (smscmd);}, smsc.opts.delay); } else { appcb ({status: 0}); } } }
[ "function", "CheckOutboxCB", "(", "err", ",", "results", ")", "{", "var", "result", "=", "results", "[", "0", "]", ";", "self", ".", "retry", "++", ";", "self", ".", "Debug", "(", "6", ",", "\"CheckOutboxCB Phone=%s Result=%j Retry=%d/%d\"", ",", "smscmd", ".", "phone", ",", "result", ",", "self", ".", "retry", ",", "smsc", ".", "opts", ".", "retry", ")", ";", "if", "(", "result", "!==", "undefined", ")", "{", "if", "(", "self", ".", "retry", "<=", "smsc", ".", "opts", ".", "retry", ")", "{", "setTimeout", "(", "function", "(", ")", "{", "CheckOutbox", "(", "result", ".", "ID", ")", ";", "}", ",", "smsc", ".", "opts", ".", "delay", ")", ";", "}", "else", "{", "self", ".", "Debug", "(", "6", ",", "\"CheckOutboxCB Fail SqlId=%s SMS=%j\"", ",", "result", ".", "ID", ",", "smscmd", ")", ";", "smsc", ".", "DelById", "(", "DelByIdCB", ",", "result", ".", "ID", ")", ";", "appcb", "(", "{", "status", ":", "-", "1", ",", "smsid", ":", "smscmd", ".", "id", "}", ")", ";", "}", "}", "else", "{", "self", ".", "Debug", "(", "6", ",", "\"CheckOutboxCB OK SMS=%j\"", ",", "smscmd", ")", ";", "appcb", "(", "{", "status", ":", "1", ",", "smsid", ":", "smscmd", ".", "id", "}", ")", ";", "if", "(", "smscmd", ".", "ack", ")", "{", "self", ".", "retry", "=", "0", ";", "setTimeout", "(", "function", "(", ")", "{", "CheckDevAck", "(", "smscmd", ")", ";", "}", ",", "smsc", ".", "opts", ".", "delay", ")", ";", "}", "else", "{", "appcb", "(", "{", "status", ":", "0", "}", ")", ";", "}", "}", "}" ]
this function is call when MySql checked outbox
[ "this", "function", "is", "call", "when", "MySql", "checked", "outbox" ]
34d9f256545b74d596747d1c2faf9bb450eb0777
https://github.com/fulup-bzh/GeoGate/blob/34d9f256545b74d596747d1c2faf9bb450eb0777/smsc/lib/GG-SmsRequest.js#L72-L101
train
fulup-bzh/GeoGate
smsc/lib/GG-SmsRequest.js
CheckOutbox
function CheckOutbox (insertId) { self.Debug (3,"Waiting Sent Confirmation %d/%d", self.retry, smsc.opts.retry); smsc.CheckById (CheckOutboxCB, insertId) }
javascript
function CheckOutbox (insertId) { self.Debug (3,"Waiting Sent Confirmation %d/%d", self.retry, smsc.opts.retry); smsc.CheckById (CheckOutboxCB, insertId) }
[ "function", "CheckOutbox", "(", "insertId", ")", "{", "self", ".", "Debug", "(", "3", ",", "\"Waiting Sent Confirmation %d/%d\"", ",", "self", ".", "retry", ",", "smsc", ".", "opts", ".", "retry", ")", ";", "smsc", ".", "CheckById", "(", "CheckOutboxCB", ",", "insertId", ")", "}" ]
this function loop until SMS is effectively sent
[ "this", "function", "loop", "until", "SMS", "is", "effectively", "sent" ]
34d9f256545b74d596747d1c2faf9bb450eb0777
https://github.com/fulup-bzh/GeoGate/blob/34d9f256545b74d596747d1c2faf9bb450eb0777/smsc/lib/GG-SmsRequest.js#L104-L107
train
fulup-bzh/GeoGate
smsc/lib/GG-SmsRequest.js
SendToCB
function SendToCB (err, result) { // check if sms was sent from output table self.Debug (7,"SendToCB SMS=%j result=%j err=%j", smscmd, result, err); if (err) { self.Debug (1, "Insert in MySql outbox refused %s", err); appcb ({status: -1, id: smscmd.id, error: err}); } else { setTimeout (function() {CheckOutbox (result.insertId);}, smsc.opts.delay); } }
javascript
function SendToCB (err, result) { // check if sms was sent from output table self.Debug (7,"SendToCB SMS=%j result=%j err=%j", smscmd, result, err); if (err) { self.Debug (1, "Insert in MySql outbox refused %s", err); appcb ({status: -1, id: smscmd.id, error: err}); } else { setTimeout (function() {CheckOutbox (result.insertId);}, smsc.opts.delay); } }
[ "function", "SendToCB", "(", "err", ",", "result", ")", "{", "self", ".", "Debug", "(", "7", ",", "\"SendToCB SMS=%j result=%j err=%j\"", ",", "smscmd", ",", "result", ",", "err", ")", ";", "if", "(", "err", ")", "{", "self", ".", "Debug", "(", "1", ",", "\"Insert in MySql outbox refused %s\"", ",", "err", ")", ";", "appcb", "(", "{", "status", ":", "-", "1", ",", "id", ":", "smscmd", ".", "id", ",", "error", ":", "err", "}", ")", ";", "}", "else", "{", "setTimeout", "(", "function", "(", ")", "{", "CheckOutbox", "(", "result", ".", "insertId", ")", ";", "}", ",", "smsc", ".", "opts", ".", "delay", ")", ";", "}", "}" ]
this function is called when MySql inserted SMS in outbox
[ "this", "function", "is", "called", "when", "MySql", "inserted", "SMS", "in", "outbox" ]
34d9f256545b74d596747d1c2faf9bb450eb0777
https://github.com/fulup-bzh/GeoGate/blob/34d9f256545b74d596747d1c2faf9bb450eb0777/smsc/lib/GG-SmsRequest.js#L110-L119
train
fulup-bzh/GeoGate
server/lib/_TcpClient.js
TcpClient
function TcpClient (socket) { this.debug = socket.controller.debug; // inherit controller debug level this.gateway = socket.controller.gateway; this.controller= socket.controller; this.adapter = socket.adapter; this.socket = socket; this.devid = false; // devid/mmsi directly from device or adapter this.name = false; this.logged = false; this.alarmcount= 0; // count alarm messages this.errorcount= 0; // number of ignore messages this.jobcount = 0; // Job commands send to gateway this.count = 0; // generic counter used by file backend if (socket.remoteAddress !== undefined) { this.uid= "tcpclient//" + this.adapter.info + "/remote:" + socket.remoteAddress +":" + socket.remotePort; } else { this.uid= "tcpclient://" + this.adapter.info + ":" + socket.port; } }
javascript
function TcpClient (socket) { this.debug = socket.controller.debug; // inherit controller debug level this.gateway = socket.controller.gateway; this.controller= socket.controller; this.adapter = socket.adapter; this.socket = socket; this.devid = false; // devid/mmsi directly from device or adapter this.name = false; this.logged = false; this.alarmcount= 0; // count alarm messages this.errorcount= 0; // number of ignore messages this.jobcount = 0; // Job commands send to gateway this.count = 0; // generic counter used by file backend if (socket.remoteAddress !== undefined) { this.uid= "tcpclient//" + this.adapter.info + "/remote:" + socket.remoteAddress +":" + socket.remotePort; } else { this.uid= "tcpclient://" + this.adapter.info + ":" + socket.port; } }
[ "function", "TcpClient", "(", "socket", ")", "{", "this", ".", "debug", "=", "socket", ".", "controller", ".", "debug", ";", "this", ".", "gateway", "=", "socket", ".", "controller", ".", "gateway", ";", "this", ".", "controller", "=", "socket", ".", "controller", ";", "this", ".", "adapter", "=", "socket", ".", "adapter", ";", "this", ".", "socket", "=", "socket", ";", "this", ".", "devid", "=", "false", ";", "this", ".", "name", "=", "false", ";", "this", ".", "logged", "=", "false", ";", "this", ".", "alarmcount", "=", "0", ";", "this", ".", "errorcount", "=", "0", ";", "this", ".", "jobcount", "=", "0", ";", "this", ".", "count", "=", "0", ";", "if", "(", "socket", ".", "remoteAddress", "!==", "undefined", ")", "{", "this", ".", "uid", "=", "\"tcpclient//\"", "+", "this", ".", "adapter", ".", "info", "+", "\"/remote:\"", "+", "socket", ".", "remoteAddress", "+", "\":\"", "+", "socket", ".", "remotePort", ";", "}", "else", "{", "this", ".", "uid", "=", "\"tcpclient://\"", "+", "this", ".", "adapter", ".", "info", "+", "\":\"", "+", "socket", ".", "port", ";", "}", "}" ]
called from TcpFeed class of adapter
[ "called", "from", "TcpFeed", "class", "of", "adapter" ]
34d9f256545b74d596747d1c2faf9bb450eb0777
https://github.com/fulup-bzh/GeoGate/blob/34d9f256545b74d596747d1c2faf9bb450eb0777/server/lib/_TcpClient.js#L61-L80
train
fulup-bzh/GeoGate
encoder/lib/GG-NmeaDecode.js
function(lat){ // TK103 sample 4737.1024,N for 47°37'.1024 var deg= parseInt (lat[0]/100) || 0; var min= lat[0] - (deg*100); var dec= deg + (min/60); if (lat [1] === 'S' || lat [1] === 'W') dec= dec * -1; return (dec); }
javascript
function(lat){ // TK103 sample 4737.1024,N for 47°37'.1024 var deg= parseInt (lat[0]/100) || 0; var min= lat[0] - (deg*100); var dec= deg + (min/60); if (lat [1] === 'S' || lat [1] === 'W') dec= dec * -1; return (dec); }
[ "function", "(", "lat", ")", "{", "var", "deg", "=", "parseInt", "(", "lat", "[", "0", "]", "/", "100", ")", "||", "0", ";", "var", "min", "=", "lat", "[", "0", "]", "-", "(", "deg", "*", "100", ")", ";", "var", "dec", "=", "deg", "+", "(", "min", "/", "60", ")", ";", "if", "(", "lat", "[", "1", "]", "===", "'S'", "||", "lat", "[", "1", "]", "===", "'W'", ")", "dec", "=", "dec", "*", "-", "1", ";", "return", "(", "dec", ")", ";", "}" ]
Convert gps coordonnates in decimal
[ "Convert", "gps", "coordonnates", "in", "decimal" ]
34d9f256545b74d596747d1c2faf9bb450eb0777
https://github.com/fulup-bzh/GeoGate/blob/34d9f256545b74d596747d1c2faf9bb450eb0777/encoder/lib/GG-NmeaDecode.js#L96-L104
train
fulup-bzh/GeoGate
smsg/lib/GG-SmsControl.js
BatchCB
function BatchCB (response) { console.log ("### Batch SMS CallBack --> Status=%j", response); if (response.status === 0 || response.status === -4) { console.log ("SMS Batch Test done"); setTimeout (process.exit, 1000); } }
javascript
function BatchCB (response) { console.log ("### Batch SMS CallBack --> Status=%j", response); if (response.status === 0 || response.status === -4) { console.log ("SMS Batch Test done"); setTimeout (process.exit, 1000); } }
[ "function", "BatchCB", "(", "response", ")", "{", "console", ".", "log", "(", "\"### Batch SMS CallBack ", ",", "response", ")", ";", "if", "(", "response", ".", "status", "===", "0", "||", "response", ".", "status", "===", "-", "4", ")", "{", "console", ".", "log", "(", "\"SMS Batch Test done\"", ")", ";", "setTimeout", "(", "process", ".", "exit", ",", "1000", ")", ";", "}", "}" ]
Batch callback for acknowledgement
[ "Batch", "callback", "for", "acknowledgement" ]
34d9f256545b74d596747d1c2faf9bb450eb0777
https://github.com/fulup-bzh/GeoGate/blob/34d9f256545b74d596747d1c2faf9bb450eb0777/smsg/lib/GG-SmsControl.js#L136-L143
train
fulup-bzh/GeoGate
smsg/lib/GG-SmsControl.js
ResponseCB
function ResponseCB (response) { console.log ("### Single SMS CallBack --> Status=%j", response); if (response.status === 0) { var batch = require('../sample/SmsCommand-batch'); smscontrol.ProcessBatch (BatchCB, phonenumber, password, batch); } if (response.status < 0) { console.log ("Single SMS Test Fail"); setTimeout (process.exit, 1000); } }
javascript
function ResponseCB (response) { console.log ("### Single SMS CallBack --> Status=%j", response); if (response.status === 0) { var batch = require('../sample/SmsCommand-batch'); smscontrol.ProcessBatch (BatchCB, phonenumber, password, batch); } if (response.status < 0) { console.log ("Single SMS Test Fail"); setTimeout (process.exit, 1000); } }
[ "function", "ResponseCB", "(", "response", ")", "{", "console", ".", "log", "(", "\"### Single SMS CallBack ", ",", "response", ")", ";", "if", "(", "response", ".", "status", "===", "0", ")", "{", "var", "batch", "=", "require", "(", "'../sample/SmsCommand-batch'", ")", ";", "smscontrol", ".", "ProcessBatch", "(", "BatchCB", ",", "phonenumber", ",", "password", ",", "batch", ")", ";", "}", "if", "(", "response", ".", "status", "<", "0", ")", "{", "console", ".", "log", "(", "\"Single SMS Test Fail\"", ")", ";", "setTimeout", "(", "process", ".", "exit", ",", "1000", ")", ";", "}", "}" ]
application callback for acknowledgement
[ "application", "callback", "for", "acknowledgement" ]
34d9f256545b74d596747d1c2faf9bb450eb0777
https://github.com/fulup-bzh/GeoGate/blob/34d9f256545b74d596747d1c2faf9bb450eb0777/smsg/lib/GG-SmsControl.js#L147-L159
train
krunkosaurus/simg
src/simg.js
function(svg){ if (!svg){ throw new Error('.toString: No SVG found.'); } [ ['version', 1.1], ['xmlns', "http://www.w3.org/2000/svg"], ].forEach(function(item){ svg.setAttribute(item[0], item[1]); }); return svg.outerHTML; }
javascript
function(svg){ if (!svg){ throw new Error('.toString: No SVG found.'); } [ ['version', 1.1], ['xmlns', "http://www.w3.org/2000/svg"], ].forEach(function(item){ svg.setAttribute(item[0], item[1]); }); return svg.outerHTML; }
[ "function", "(", "svg", ")", "{", "if", "(", "!", "svg", ")", "{", "throw", "new", "Error", "(", "'.toString: No SVG found.'", ")", ";", "}", "[", "[", "'version'", ",", "1.1", "]", ",", "[", "'xmlns'", ",", "\"http://www.w3.org/2000/svg\"", "]", ",", "]", ".", "forEach", "(", "function", "(", "item", ")", "{", "svg", ".", "setAttribute", "(", "item", "[", "0", "]", ",", "item", "[", "1", "]", ")", ";", "}", ")", ";", "return", "svg", ".", "outerHTML", ";", "}" ]
Return SVG text.
[ "Return", "SVG", "text", "." ]
2b50dbdc06d80faad14dfae2312e594d7cdfcb02
https://github.com/krunkosaurus/simg/blob/2b50dbdc06d80faad14dfae2312e594d7cdfcb02/src/simg.js#L29-L41
train
krunkosaurus/simg
src/simg.js
function(cb){ this.toSvgImage(function(img){ var canvas = document.createElement('canvas'); var context = canvas.getContext("2d"); canvas.width = img.width; canvas.height = img.height; context.drawImage(img, 0, 0); cb(canvas); }); }
javascript
function(cb){ this.toSvgImage(function(img){ var canvas = document.createElement('canvas'); var context = canvas.getContext("2d"); canvas.width = img.width; canvas.height = img.height; context.drawImage(img, 0, 0); cb(canvas); }); }
[ "function", "(", "cb", ")", "{", "this", ".", "toSvgImage", "(", "function", "(", "img", ")", "{", "var", "canvas", "=", "document", ".", "createElement", "(", "'canvas'", ")", ";", "var", "context", "=", "canvas", ".", "getContext", "(", "\"2d\"", ")", ";", "canvas", ".", "width", "=", "img", ".", "width", ";", "canvas", ".", "height", "=", "img", ".", "height", ";", "context", ".", "drawImage", "(", "img", ",", "0", ",", "0", ")", ";", "cb", "(", "canvas", ")", ";", "}", ")", ";", "}" ]
Return canvas with this SVG drawn inside.
[ "Return", "canvas", "with", "this", "SVG", "drawn", "inside", "." ]
2b50dbdc06d80faad14dfae2312e594d7cdfcb02
https://github.com/krunkosaurus/simg/blob/2b50dbdc06d80faad14dfae2312e594d7cdfcb02/src/simg.js#L44-L55
train
krunkosaurus/simg
src/simg.js
function(cb){ this.toCanvas(function(canvas){ var canvasData = canvas.toDataURL("image/png"); var img = document.createElement('img'); img.onload = function(){ cb(img); }; // Make pngImg's source the canvas data. img.setAttribute('src', canvasData); }); }
javascript
function(cb){ this.toCanvas(function(canvas){ var canvasData = canvas.toDataURL("image/png"); var img = document.createElement('img'); img.onload = function(){ cb(img); }; // Make pngImg's source the canvas data. img.setAttribute('src', canvasData); }); }
[ "function", "(", "cb", ")", "{", "this", ".", "toCanvas", "(", "function", "(", "canvas", ")", "{", "var", "canvasData", "=", "canvas", ".", "toDataURL", "(", "\"image/png\"", ")", ";", "var", "img", "=", "document", ".", "createElement", "(", "'img'", ")", ";", "img", ".", "onload", "=", "function", "(", ")", "{", "cb", "(", "img", ")", ";", "}", ";", "img", ".", "setAttribute", "(", "'src'", ",", "canvasData", ")", ";", "}", ")", ";", "}" ]
Returns callback to new img from SVG. Call with no arguments to return svg image element. Call with callback to return png image element.
[ "Returns", "callback", "to", "new", "img", "from", "SVG", ".", "Call", "with", "no", "arguments", "to", "return", "svg", "image", "element", ".", "Call", "with", "callback", "to", "return", "png", "image", "element", "." ]
2b50dbdc06d80faad14dfae2312e594d7cdfcb02
https://github.com/krunkosaurus/simg/blob/2b50dbdc06d80faad14dfae2312e594d7cdfcb02/src/simg.js#L74-L86
train
krunkosaurus/simg
src/simg.js
function(cb){ this.toCanvas(function(canvas){ var dataUrl = canvas.toDataURL().replace(/^data:image\/(png|jpg);base64,/, ""); var byteString = atob(escape(dataUrl)); // write the bytes of the string to an ArrayBuffer var ab = new ArrayBuffer(byteString.length); var ia = new Uint8Array(ab); for (var i = 0; i < byteString.length; i++) { ia[i] = byteString.charCodeAt(i); } var dataView = new DataView(ab); var blob = new Blob([dataView], {type: "image/png"}); cb(blob); }); }
javascript
function(cb){ this.toCanvas(function(canvas){ var dataUrl = canvas.toDataURL().replace(/^data:image\/(png|jpg);base64,/, ""); var byteString = atob(escape(dataUrl)); // write the bytes of the string to an ArrayBuffer var ab = new ArrayBuffer(byteString.length); var ia = new Uint8Array(ab); for (var i = 0; i < byteString.length; i++) { ia[i] = byteString.charCodeAt(i); } var dataView = new DataView(ab); var blob = new Blob([dataView], {type: "image/png"}); cb(blob); }); }
[ "function", "(", "cb", ")", "{", "this", ".", "toCanvas", "(", "function", "(", "canvas", ")", "{", "var", "dataUrl", "=", "canvas", ".", "toDataURL", "(", ")", ".", "replace", "(", "/", "^data:image\\/(png|jpg);base64,", "/", ",", "\"\"", ")", ";", "var", "byteString", "=", "atob", "(", "escape", "(", "dataUrl", ")", ")", ";", "var", "ab", "=", "new", "ArrayBuffer", "(", "byteString", ".", "length", ")", ";", "var", "ia", "=", "new", "Uint8Array", "(", "ab", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "byteString", ".", "length", ";", "i", "++", ")", "{", "ia", "[", "i", "]", "=", "byteString", ".", "charCodeAt", "(", "i", ")", ";", "}", "var", "dataView", "=", "new", "DataView", "(", "ab", ")", ";", "var", "blob", "=", "new", "Blob", "(", "[", "dataView", "]", ",", "{", "type", ":", "\"image/png\"", "}", ")", ";", "cb", "(", "blob", ")", ";", "}", ")", ";", "}" ]
Converts canvas to binary blob.
[ "Converts", "canvas", "to", "binary", "blob", "." ]
2b50dbdc06d80faad14dfae2312e594d7cdfcb02
https://github.com/krunkosaurus/simg/blob/2b50dbdc06d80faad14dfae2312e594d7cdfcb02/src/simg.js#L101-L115
train
krunkosaurus/simg
src/simg.js
function(filename){ if (!filename){ filename = 'chart'; } this.toImg(function(img){ var a = document.createElement("a"); // Name of the file being downloaded. a.download = filename + ".png"; a.href = img.getAttribute('src'); // Support for Firefox which requires inserting in dom. a.style.display = 'none'; document.body.appendChild(a); a.click(); document.body.removeChild(a); }); }
javascript
function(filename){ if (!filename){ filename = 'chart'; } this.toImg(function(img){ var a = document.createElement("a"); // Name of the file being downloaded. a.download = filename + ".png"; a.href = img.getAttribute('src'); // Support for Firefox which requires inserting in dom. a.style.display = 'none'; document.body.appendChild(a); a.click(); document.body.removeChild(a); }); }
[ "function", "(", "filename", ")", "{", "if", "(", "!", "filename", ")", "{", "filename", "=", "'chart'", ";", "}", "this", ".", "toImg", "(", "function", "(", "img", ")", "{", "var", "a", "=", "document", ".", "createElement", "(", "\"a\"", ")", ";", "a", ".", "download", "=", "filename", "+", "\".png\"", ";", "a", ".", "href", "=", "img", ".", "getAttribute", "(", "'src'", ")", ";", "a", ".", "style", ".", "display", "=", "'none'", ";", "document", ".", "body", ".", "appendChild", "(", "a", ")", ";", "a", ".", "click", "(", ")", ";", "document", ".", "body", ".", "removeChild", "(", "a", ")", ";", "}", ")", ";", "}" ]
Trigger download of image.
[ "Trigger", "download", "of", "image", "." ]
2b50dbdc06d80faad14dfae2312e594d7cdfcb02
https://github.com/krunkosaurus/simg/blob/2b50dbdc06d80faad14dfae2312e594d7cdfcb02/src/simg.js#L118-L133
train
xch89820/wx-chart
src/util/helper.js
_assignGenerator
function _assignGenerator(own) { let _copy = function(target, ...source) { let deep = true; if (is.Boolean(target)) { deep = target; target = 0 in source ? source.shift() : null; } if (is.Array(target)) { source.forEach(sc => { target.push(...sc); }); } else if (is.Object(target)) { source.forEach(sc => { for (let key in sc) { if (own && !sc.hasOwnProperty(key)) continue; let so = sc[key], to = target[key]; if (is.PureObject(so)) { target[key] = deep ? extend(true, is.PureObject(to) ? to : {}, so) : so; } else if (is.Array(so)) { target[key] = deep ? extend(true, is.Array(to) ? to : [], so) : so; } else { target[key] = so; } } }); } // Do nothing return target; }; return _copy; }
javascript
function _assignGenerator(own) { let _copy = function(target, ...source) { let deep = true; if (is.Boolean(target)) { deep = target; target = 0 in source ? source.shift() : null; } if (is.Array(target)) { source.forEach(sc => { target.push(...sc); }); } else if (is.Object(target)) { source.forEach(sc => { for (let key in sc) { if (own && !sc.hasOwnProperty(key)) continue; let so = sc[key], to = target[key]; if (is.PureObject(so)) { target[key] = deep ? extend(true, is.PureObject(to) ? to : {}, so) : so; } else if (is.Array(so)) { target[key] = deep ? extend(true, is.Array(to) ? to : [], so) : so; } else { target[key] = so; } } }); } // Do nothing return target; }; return _copy; }
[ "function", "_assignGenerator", "(", "own", ")", "{", "let", "_copy", "=", "function", "(", "target", ",", "...", "source", ")", "{", "let", "deep", "=", "true", ";", "if", "(", "is", ".", "Boolean", "(", "target", ")", ")", "{", "deep", "=", "target", ";", "target", "=", "0", "in", "source", "?", "source", ".", "shift", "(", ")", ":", "null", ";", "}", "if", "(", "is", ".", "Array", "(", "target", ")", ")", "{", "source", ".", "forEach", "(", "sc", "=>", "{", "target", ".", "push", "(", "...", "sc", ")", ";", "}", ")", ";", "}", "else", "if", "(", "is", ".", "Object", "(", "target", ")", ")", "{", "source", ".", "forEach", "(", "sc", "=>", "{", "for", "(", "let", "key", "in", "sc", ")", "{", "if", "(", "own", "&&", "!", "sc", ".", "hasOwnProperty", "(", "key", ")", ")", "continue", ";", "let", "so", "=", "sc", "[", "key", "]", ",", "to", "=", "target", "[", "key", "]", ";", "if", "(", "is", ".", "PureObject", "(", "so", ")", ")", "{", "target", "[", "key", "]", "=", "deep", "?", "extend", "(", "true", ",", "is", ".", "PureObject", "(", "to", ")", "?", "to", ":", "{", "}", ",", "so", ")", ":", "so", ";", "}", "else", "if", "(", "is", ".", "Array", "(", "so", ")", ")", "{", "target", "[", "key", "]", "=", "deep", "?", "extend", "(", "true", ",", "is", ".", "Array", "(", "to", ")", "?", "to", ":", "[", "]", ",", "so", ")", ":", "so", ";", "}", "else", "{", "target", "[", "key", "]", "=", "so", ";", "}", "}", "}", ")", ";", "}", "return", "target", ";", "}", ";", "return", "_copy", ";", "}" ]
Assign function generator
[ "Assign", "function", "generator" ]
8cbbbcb17c43e650533a2c43e4fbb10cb9232f28
https://github.com/xch89820/wx-chart/blob/8cbbbcb17c43e650533a2c43e4fbb10cb9232f28/src/util/helper.js#L101-L144
train
amadeusmuc/node-ifttt
ifttt.js
function(req, res, next){ that.accessCheck(req, res, next, {forceHeaderCheck: true}); }
javascript
function(req, res, next){ that.accessCheck(req, res, next, {forceHeaderCheck: true}); }
[ "function", "(", "req", ",", "res", ",", "next", ")", "{", "that", ".", "accessCheck", "(", "req", ",", "res", ",", "next", ",", "{", "forceHeaderCheck", ":", "true", "}", ")", ";", "}" ]
Header check middleware wrapper.
[ "Header", "check", "middleware", "wrapper", "." ]
6004507e9ad4b9f247c7ecc7c4882019d42ba926
https://github.com/amadeusmuc/node-ifttt/blob/6004507e9ad4b9f247c7ecc7c4882019d42ba926/ifttt.js#L73-L75
train
mradionov/karma-jasmine-diff-reporter
src/format.js
strictReplace
function strictReplace(str, pairs, multiline) { var index; var fromIndex = 0; pairs.some(function (pair) { var toReplace = pair[0]; var replaceWith = pair[1]; index = str.indexOf(toReplace, fromIndex); if (index === -1) { return true; } var lhs = str.substr(0, index); var rhs = str.substr(index + toReplace.length); if (multiline) { lhs = trimSpaceAndPunctuation(lhs); rhs = trimSpaceAndPunctuation(rhs); } str = lhs + replaceWith + rhs; fromIndex = index + replaceWith.length; return false; }); return str; }
javascript
function strictReplace(str, pairs, multiline) { var index; var fromIndex = 0; pairs.some(function (pair) { var toReplace = pair[0]; var replaceWith = pair[1]; index = str.indexOf(toReplace, fromIndex); if (index === -1) { return true; } var lhs = str.substr(0, index); var rhs = str.substr(index + toReplace.length); if (multiline) { lhs = trimSpaceAndPunctuation(lhs); rhs = trimSpaceAndPunctuation(rhs); } str = lhs + replaceWith + rhs; fromIndex = index + replaceWith.length; return false; }); return str; }
[ "function", "strictReplace", "(", "str", ",", "pairs", ",", "multiline", ")", "{", "var", "index", ";", "var", "fromIndex", "=", "0", ";", "pairs", ".", "some", "(", "function", "(", "pair", ")", "{", "var", "toReplace", "=", "pair", "[", "0", "]", ";", "var", "replaceWith", "=", "pair", "[", "1", "]", ";", "index", "=", "str", ".", "indexOf", "(", "toReplace", ",", "fromIndex", ")", ";", "if", "(", "index", "===", "-", "1", ")", "{", "return", "true", ";", "}", "var", "lhs", "=", "str", ".", "substr", "(", "0", ",", "index", ")", ";", "var", "rhs", "=", "str", ".", "substr", "(", "index", "+", "toReplace", ".", "length", ")", ";", "if", "(", "multiline", ")", "{", "lhs", "=", "trimSpaceAndPunctuation", "(", "lhs", ")", ";", "rhs", "=", "trimSpaceAndPunctuation", "(", "rhs", ")", ";", "}", "str", "=", "lhs", "+", "replaceWith", "+", "rhs", ";", "fromIndex", "=", "index", "+", "replaceWith", ".", "length", ";", "return", "false", ";", "}", ")", ";", "return", "str", ";", "}" ]
Replace while increasing indexFrom If multiline is true - eat all spaces and punctuation around diffed objects - it will keep things look nice.
[ "Replace", "while", "increasing", "indexFrom", "If", "multiline", "is", "true", "-", "eat", "all", "spaces", "and", "punctuation", "around", "diffed", "objects", "-", "it", "will", "keep", "things", "look", "nice", "." ]
c53c38313f66afac73e4c594e1b1090d8cd12326
https://github.com/mradionov/karma-jasmine-diff-reporter/blob/c53c38313f66afac73e4c594e1b1090d8cd12326/src/format.js#L23-L52
train
mradionov/karma-jasmine-diff-reporter
src/parse.js
isMultipleArray
function isMultipleArray(valueStr) { var wrappedValueStr = '[ ' + valueStr + ' ]'; var wrappedArray = createArray(wrappedValueStr, {}, { checkMultipleArray: false }); return wrappedArray.children.length > 1; }
javascript
function isMultipleArray(valueStr) { var wrappedValueStr = '[ ' + valueStr + ' ]'; var wrappedArray = createArray(wrappedValueStr, {}, { checkMultipleArray: false }); return wrappedArray.children.length > 1; }
[ "function", "isMultipleArray", "(", "valueStr", ")", "{", "var", "wrappedValueStr", "=", "'[ '", "+", "valueStr", "+", "' ]'", ";", "var", "wrappedArray", "=", "createArray", "(", "wrappedValueStr", ",", "{", "}", ",", "{", "checkMultipleArray", ":", "false", "}", ")", ";", "return", "wrappedArray", ".", "children", ".", "length", ">", "1", ";", "}" ]
Wrap value in extra array, an it will have multiple children - then it's a multiple array. Make sure not to go recursive.
[ "Wrap", "value", "in", "extra", "array", "an", "it", "will", "have", "multiple", "children", "-", "then", "it", "s", "a", "multiple", "array", ".", "Make", "sure", "not", "to", "go", "recursive", "." ]
c53c38313f66afac73e4c594e1b1090d8cd12326
https://github.com/mradionov/karma-jasmine-diff-reporter/blob/c53c38313f66afac73e4c594e1b1090d8cd12326/src/parse.js#L263-L269
train
axemclion/grunt-saucelabs
grunt/saucelabs-custom.js
updateJob
function updateJob(jobId, attributes) { var user = process.env.SAUCE_USERNAME; var pass = process.env.SAUCE_ACCESS_KEY; return utils .makeRequest({ method: 'PUT', url: ['https://saucelabs.com/rest/v1', user, 'jobs', jobId].join('/'), auth: { user: user, pass: pass }, json: attributes }); }
javascript
function updateJob(jobId, attributes) { var user = process.env.SAUCE_USERNAME; var pass = process.env.SAUCE_ACCESS_KEY; return utils .makeRequest({ method: 'PUT', url: ['https://saucelabs.com/rest/v1', user, 'jobs', jobId].join('/'), auth: { user: user, pass: pass }, json: attributes }); }
[ "function", "updateJob", "(", "jobId", ",", "attributes", ")", "{", "var", "user", "=", "process", ".", "env", ".", "SAUCE_USERNAME", ";", "var", "pass", "=", "process", ".", "env", ".", "SAUCE_ACCESS_KEY", ";", "return", "utils", ".", "makeRequest", "(", "{", "method", ":", "'PUT'", ",", "url", ":", "[", "'https://saucelabs.com/rest/v1'", ",", "user", ",", "'jobs'", ",", "jobId", "]", ".", "join", "(", "'/'", ")", ",", "auth", ":", "{", "user", ":", "user", ",", "pass", ":", "pass", "}", ",", "json", ":", "attributes", "}", ")", ";", "}" ]
Updates a job's attributes. @param {String} jobId - Job ID. @param {Object} attributes - The attributes to update. @returns {Object} - A promise which will eventually be resolved after the job is updated.
[ "Updates", "a", "job", "s", "attributes", "." ]
127cac287947399be79b5d6c96493dff5fb45184
https://github.com/axemclion/grunt-saucelabs/blob/127cac287947399be79b5d6c96493dff5fb45184/grunt/saucelabs-custom.js#L16-L27
train
3logic/apollo-cassandra
libs/apollo.js
function(properties){ /** * Create a new instance for the model * @class Model * @augments BaseModel * @param {object} instance_values Key/value object containing values of the row * * @classdesc Generic model. Use it statically to find documents on Cassandra. Any instance represent a row retrieved or which can be saved on DB */ var Model = function(instance_values){ BaseModel.apply(this,Array.prototype.slice.call(arguments)); }; util.inherits(Model,BaseModel); for(var i in BaseModel){ if(BaseModel.hasOwnProperty(i)){ Model[i] = BaseModel[i]; } } Model._set_properties(properties); return Model; }
javascript
function(properties){ /** * Create a new instance for the model * @class Model * @augments BaseModel * @param {object} instance_values Key/value object containing values of the row * * @classdesc Generic model. Use it statically to find documents on Cassandra. Any instance represent a row retrieved or which can be saved on DB */ var Model = function(instance_values){ BaseModel.apply(this,Array.prototype.slice.call(arguments)); }; util.inherits(Model,BaseModel); for(var i in BaseModel){ if(BaseModel.hasOwnProperty(i)){ Model[i] = BaseModel[i]; } } Model._set_properties(properties); return Model; }
[ "function", "(", "properties", ")", "{", "var", "Model", "=", "function", "(", "instance_values", ")", "{", "BaseModel", ".", "apply", "(", "this", ",", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ")", ")", ";", "}", ";", "util", ".", "inherits", "(", "Model", ",", "BaseModel", ")", ";", "for", "(", "var", "i", "in", "BaseModel", ")", "{", "if", "(", "BaseModel", ".", "hasOwnProperty", "(", "i", ")", ")", "{", "Model", "[", "i", "]", "=", "BaseModel", "[", "i", "]", ";", "}", "}", "Model", ".", "_set_properties", "(", "properties", ")", ";", "return", "Model", ";", "}" ]
Generate a Model @param {object} properties Properties for the model @return {Model} Construcotr for the model @private
[ "Generate", "a", "Model" ]
d618b98e497f53d22c685d4e4690087ccf731f91
https://github.com/3logic/apollo-cassandra/blob/d618b98e497f53d22c685d4e4690087ccf731f91/libs/apollo.js#L44-L68
train
3logic/apollo-cassandra
libs/apollo.js
function(){ var copy_fields = ['contactPoints'], temp_connection = {}, connection = this._connection; for(var fk in copy_fields){ temp_connection[copy_fields[fk]] = connection[copy_fields[fk]]; } return new cql.Client(temp_connection); }
javascript
function(){ var copy_fields = ['contactPoints'], temp_connection = {}, connection = this._connection; for(var fk in copy_fields){ temp_connection[copy_fields[fk]] = connection[copy_fields[fk]]; } return new cql.Client(temp_connection); }
[ "function", "(", ")", "{", "var", "copy_fields", "=", "[", "'contactPoints'", "]", ",", "temp_connection", "=", "{", "}", ",", "connection", "=", "this", ".", "_connection", ";", "for", "(", "var", "fk", "in", "copy_fields", ")", "{", "temp_connection", "[", "copy_fields", "[", "fk", "]", "]", "=", "connection", "[", "copy_fields", "[", "fk", "]", "]", ";", "}", "return", "new", "cql", ".", "Client", "(", "temp_connection", ")", ";", "}" ]
Returns a client to be used only for keyspace assertion @return {Client} Node driver client @private
[ "Returns", "a", "client", "to", "be", "used", "only", "for", "keyspace", "assertion" ]
d618b98e497f53d22c685d4e4690087ccf731f91
https://github.com/3logic/apollo-cassandra/blob/d618b98e497f53d22c685d4e4690087ccf731f91/libs/apollo.js#L75-L84
train
3logic/apollo-cassandra
libs/apollo.js
function(replication_option){ if( typeof replication_option == 'string'){ return replication_option; }else{ var properties = []; for(var k in replication_option){ properties.push(util.format("'%s': '%s'", k, replication_option[k] )); } return util.format('{%s}', properties.join(',')); } }
javascript
function(replication_option){ if( typeof replication_option == 'string'){ return replication_option; }else{ var properties = []; for(var k in replication_option){ properties.push(util.format("'%s': '%s'", k, replication_option[k] )); } return util.format('{%s}', properties.join(',')); } }
[ "function", "(", "replication_option", ")", "{", "if", "(", "typeof", "replication_option", "==", "'string'", ")", "{", "return", "replication_option", ";", "}", "else", "{", "var", "properties", "=", "[", "]", ";", "for", "(", "var", "k", "in", "replication_option", ")", "{", "properties", ".", "push", "(", "util", ".", "format", "(", "\"'%s': '%s'\"", ",", "k", ",", "replication_option", "[", "k", "]", ")", ")", ";", "}", "return", "util", ".", "format", "(", "'{%s}'", ",", "properties", ".", "join", "(", "','", ")", ")", ";", "}", "}" ]
Generate replication strategy text for keyspace creation query @param {object|string} replication_option An object or a string representing replication strategy @return {string} Replication strategy text @private
[ "Generate", "replication", "strategy", "text", "for", "keyspace", "creation", "query" ]
d618b98e497f53d22c685d4e4690087ccf731f91
https://github.com/3logic/apollo-cassandra/blob/d618b98e497f53d22c685d4e4690087ccf731f91/libs/apollo.js#L92-L102
train
3logic/apollo-cassandra
libs/apollo.js
function(callback){ var client = this._get_system_client(); var keyspace_name = this._connection.keyspace, replication_text = '', options = this._options; replication_text = this._generate_replication_text(options.replication_strategy); var query = util.format( "CREATE KEYSPACE IF NOT EXISTS %s WITH REPLICATION = %s;", keyspace_name, replication_text ); client.execute(query, function(err,result){ client.shutdown(function(){ callback(err,result); }); }); }
javascript
function(callback){ var client = this._get_system_client(); var keyspace_name = this._connection.keyspace, replication_text = '', options = this._options; replication_text = this._generate_replication_text(options.replication_strategy); var query = util.format( "CREATE KEYSPACE IF NOT EXISTS %s WITH REPLICATION = %s;", keyspace_name, replication_text ); client.execute(query, function(err,result){ client.shutdown(function(){ callback(err,result); }); }); }
[ "function", "(", "callback", ")", "{", "var", "client", "=", "this", ".", "_get_system_client", "(", ")", ";", "var", "keyspace_name", "=", "this", ".", "_connection", ".", "keyspace", ",", "replication_text", "=", "''", ",", "options", "=", "this", ".", "_options", ";", "replication_text", "=", "this", ".", "_generate_replication_text", "(", "options", ".", "replication_strategy", ")", ";", "var", "query", "=", "util", ".", "format", "(", "\"CREATE KEYSPACE IF NOT EXISTS %s WITH REPLICATION = %s;\"", ",", "keyspace_name", ",", "replication_text", ")", ";", "client", ".", "execute", "(", "query", ",", "function", "(", "err", ",", "result", ")", "{", "client", ".", "shutdown", "(", "function", "(", ")", "{", "callback", "(", "err", ",", "result", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Ensure specified keyspace exists, try to create it otherwise @param {Apollo~GenericCallback} callback Called on keyspace assertion @private
[ "Ensure", "specified", "keyspace", "exists", "try", "to", "create", "it", "otherwise" ]
d618b98e497f53d22c685d4e4690087ccf731f91
https://github.com/3logic/apollo-cassandra/blob/d618b98e497f53d22c685d4e4690087ccf731f91/libs/apollo.js#L109-L128
train
3logic/apollo-cassandra
libs/apollo.js
function(client){ var define_connection_options = lodash.clone(this._connection); define_connection_options.policies = { loadBalancing: new SingleNodePolicy() }; //define_connection_options.hosts = define_connection_options.contactPoints; this._client = client; this._define_connection = new cql.Client(define_connection_options); /*this._client.on('log',function(level, message){ console.log(message); });*/ //Reset connections on all models for(var i in this._models){ this._models[i]._properties.cql = this._client; this._models[i]._properties.define_connection = this._define_connection; } }
javascript
function(client){ var define_connection_options = lodash.clone(this._connection); define_connection_options.policies = { loadBalancing: new SingleNodePolicy() }; //define_connection_options.hosts = define_connection_options.contactPoints; this._client = client; this._define_connection = new cql.Client(define_connection_options); /*this._client.on('log',function(level, message){ console.log(message); });*/ //Reset connections on all models for(var i in this._models){ this._models[i]._properties.cql = this._client; this._models[i]._properties.define_connection = this._define_connection; } }
[ "function", "(", "client", ")", "{", "var", "define_connection_options", "=", "lodash", ".", "clone", "(", "this", ".", "_connection", ")", ";", "define_connection_options", ".", "policies", "=", "{", "loadBalancing", ":", "new", "SingleNodePolicy", "(", ")", "}", ";", "this", ".", "_client", "=", "client", ";", "this", ".", "_define_connection", "=", "new", "cql", ".", "Client", "(", "define_connection_options", ")", ";", "for", "(", "var", "i", "in", "this", ".", "_models", ")", "{", "this", ".", "_models", "[", "i", "]", ".", "_properties", ".", "cql", "=", "this", ".", "_client", ";", "this", ".", "_models", "[", "i", "]", ".", "_properties", ".", "define_connection", "=", "this", ".", "_define_connection", ";", "}", "}" ]
Set internal clients @param {object} client Node driver client @private
[ "Set", "internal", "clients" ]
d618b98e497f53d22c685d4e4690087ccf731f91
https://github.com/3logic/apollo-cassandra/blob/d618b98e497f53d22c685d4e4690087ccf731f91/libs/apollo.js#L135-L155
train
3logic/apollo-cassandra
libs/apollo.js
function(callback){ var on_keyspace = function(err){ if(err){ return callback(err);} this._set_client(new cql.Client(this._connection)); callback(err, this); }; if(this._keyspace){ this._assert_keyspace( on_keyspace.bind(this) ); }else{ on_keyspace.call(this); } }
javascript
function(callback){ var on_keyspace = function(err){ if(err){ return callback(err);} this._set_client(new cql.Client(this._connection)); callback(err, this); }; if(this._keyspace){ this._assert_keyspace( on_keyspace.bind(this) ); }else{ on_keyspace.call(this); } }
[ "function", "(", "callback", ")", "{", "var", "on_keyspace", "=", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "return", "callback", "(", "err", ")", ";", "}", "this", ".", "_set_client", "(", "new", "cql", ".", "Client", "(", "this", ".", "_connection", ")", ")", ";", "callback", "(", "err", ",", "this", ")", ";", "}", ";", "if", "(", "this", ".", "_keyspace", ")", "{", "this", ".", "_assert_keyspace", "(", "on_keyspace", ".", "bind", "(", "this", ")", ")", ";", "}", "else", "{", "on_keyspace", ".", "call", "(", "this", ")", ";", "}", "}" ]
Connect your instance of Apollo to Cassandra @param {Apollo~onConnect} callback Callback on connection result
[ "Connect", "your", "instance", "of", "Apollo", "to", "Cassandra" ]
d618b98e497f53d22c685d4e4690087ccf731f91
https://github.com/3logic/apollo-cassandra/blob/d618b98e497f53d22c685d4e4690087ccf731f91/libs/apollo.js#L181-L193
train
3logic/apollo-cassandra
libs/apollo.js
function(model_name, model_schema, options) { if(!model_name || typeof(model_name) != "string") throw("Si deve specificare un nome per il modello"); options = options || {}; options.mismatch_behaviour = options.mismatch_behaviour || 'fail'; if(options.mismatch_behaviour !== 'fail' && options.mismatch_behaviour !== 'drop') throw 'Valid option values for "mismatch_behaviour": "fail" , "drop". Got: "'+options.mismatch_behaviour+'"'; //model_schema = schemer.normalize_model_schema(model_schema); schemer.validate_model_schema(model_schema); var base_properties = { name : model_name, schema : model_schema, keyspace : this._keyspace, mismatch_behaviour : options.mismatch_behaviour, define_connection : this._define_connection, cql : this._client, get_constructor : this.get_model.bind(this,model_name), connect: this.connect.bind(this) }; return (this._models[model_name] = this._generate_model(base_properties)); }
javascript
function(model_name, model_schema, options) { if(!model_name || typeof(model_name) != "string") throw("Si deve specificare un nome per il modello"); options = options || {}; options.mismatch_behaviour = options.mismatch_behaviour || 'fail'; if(options.mismatch_behaviour !== 'fail' && options.mismatch_behaviour !== 'drop') throw 'Valid option values for "mismatch_behaviour": "fail" , "drop". Got: "'+options.mismatch_behaviour+'"'; //model_schema = schemer.normalize_model_schema(model_schema); schemer.validate_model_schema(model_schema); var base_properties = { name : model_name, schema : model_schema, keyspace : this._keyspace, mismatch_behaviour : options.mismatch_behaviour, define_connection : this._define_connection, cql : this._client, get_constructor : this.get_model.bind(this,model_name), connect: this.connect.bind(this) }; return (this._models[model_name] = this._generate_model(base_properties)); }
[ "function", "(", "model_name", ",", "model_schema", ",", "options", ")", "{", "if", "(", "!", "model_name", "||", "typeof", "(", "model_name", ")", "!=", "\"string\"", ")", "throw", "(", "\"Si deve specificare un nome per il modello\"", ")", ";", "options", "=", "options", "||", "{", "}", ";", "options", ".", "mismatch_behaviour", "=", "options", ".", "mismatch_behaviour", "||", "'fail'", ";", "if", "(", "options", ".", "mismatch_behaviour", "!==", "'fail'", "&&", "options", ".", "mismatch_behaviour", "!==", "'drop'", ")", "throw", "'Valid option values for \"mismatch_behaviour\": \"fail\" , \"drop\". Got: \"'", "+", "options", ".", "mismatch_behaviour", "+", "'\"'", ";", "schemer", ".", "validate_model_schema", "(", "model_schema", ")", ";", "var", "base_properties", "=", "{", "name", ":", "model_name", ",", "schema", ":", "model_schema", ",", "keyspace", ":", "this", ".", "_keyspace", ",", "mismatch_behaviour", ":", "options", ".", "mismatch_behaviour", ",", "define_connection", ":", "this", ".", "_define_connection", ",", "cql", ":", "this", ".", "_client", ",", "get_constructor", ":", "this", ".", "get_model", ".", "bind", "(", "this", ",", "model_name", ")", ",", "connect", ":", "this", ".", "connect", ".", "bind", "(", "this", ")", "}", ";", "return", "(", "this", ".", "_models", "[", "model_name", "]", "=", "this", ".", "_generate_model", "(", "base_properties", ")", ")", ";", "}" ]
Create a model based on proposed schema @param {string} model_name - Name for the model @param {object} model_schema - Schema for the model @param {Apollo~ModelCreationOptions} options - Options for the creation @return {Model} Model constructor
[ "Create", "a", "model", "based", "on", "proposed", "schema" ]
d618b98e497f53d22c685d4e4690087ccf731f91
https://github.com/3logic/apollo-cassandra/blob/d618b98e497f53d22c685d4e4690087ccf731f91/libs/apollo.js#L203-L227
train
3logic/apollo-cassandra
libs/apollo.js
function(callback){ callback = callback || noop; if(!this._client){ return callback(); } this._client.shutdown(function(err){ if(!this._define_connection){ return callback(err); } this._define_connection.shutdown(function(derr){ callback(err || derr); }); }.bind(this)); }
javascript
function(callback){ callback = callback || noop; if(!this._client){ return callback(); } this._client.shutdown(function(err){ if(!this._define_connection){ return callback(err); } this._define_connection.shutdown(function(derr){ callback(err || derr); }); }.bind(this)); }
[ "function", "(", "callback", ")", "{", "callback", "=", "callback", "||", "noop", ";", "if", "(", "!", "this", ".", "_client", ")", "{", "return", "callback", "(", ")", ";", "}", "this", ".", "_client", ".", "shutdown", "(", "function", "(", "err", ")", "{", "if", "(", "!", "this", ".", "_define_connection", ")", "{", "return", "callback", "(", "err", ")", ";", "}", "this", ".", "_define_connection", ".", "shutdown", "(", "function", "(", "derr", ")", "{", "callback", "(", "err", "||", "derr", ")", ";", "}", ")", ";", "}", ".", "bind", "(", "this", ")", ")", ";", "}" ]
Chiusura della connessione @param {Function} callback callback
[ "Chiusura", "della", "connessione" ]
d618b98e497f53d22c685d4e4690087ccf731f91
https://github.com/3logic/apollo-cassandra/blob/d618b98e497f53d22c685d4e4690087ccf731f91/libs/apollo.js#L243-L257
train
hashchange/backbone.select
dist/backbone.select.js
triggerMultiSelectEvents
function triggerMultiSelectEvents ( collection, prevSelected, options, reselected ) { function mapCidsToModels ( cids, collection, previousSelection ) { function mapper ( cid ) { // Find the model in the collection. If not found, it has been removed, so get it from the array of // previously selected models. return collection.get( cid ) || previousSelection[cid]; } return _.map( cids, mapper ); } if ( options.silent || options["@bbs:silentLocally"] ) return; var diff, label = getLabel( options, collection ), selectionSize = getSelectionSize( collection, label ), length = collection.length, prevSelectedCids = _.keys( prevSelected ), selectedCids = _.keys( collection[label] ), addedCids = _.difference( selectedCids, prevSelectedCids ), removedCids = _.difference( prevSelectedCids, selectedCids ), unchanged = (selectionSize === prevSelectedCids.length && addedCids.length === 0 && removedCids.length === 0); if ( reselected && reselected.length && !options["@bbs:silentReselect"] ) { queueEventSet( "reselect:any", label, [ reselected, collection, toEventOptions( options, label, collection ) ], collection, options ); } if ( unchanged ) return; diff = { selected: mapCidsToModels( addedCids, collection, prevSelected ), deselected: mapCidsToModels( removedCids, collection, prevSelected ) }; if ( selectionSize === 0 ) { queueEventSet( "select:none", label, [ diff, collection, toEventOptions( options, label, collection ) ], collection, options ); return; } if ( selectionSize === length ) { queueEventSet( "select:all", label, [ diff, collection, toEventOptions( options, label, collection ) ], collection, options ); return; } if ( selectionSize > 0 && selectionSize < length ) { queueEventSet( "select:some", label, [ diff, collection, toEventOptions( options, label, collection ) ], collection, options ); return; } }
javascript
function triggerMultiSelectEvents ( collection, prevSelected, options, reselected ) { function mapCidsToModels ( cids, collection, previousSelection ) { function mapper ( cid ) { // Find the model in the collection. If not found, it has been removed, so get it from the array of // previously selected models. return collection.get( cid ) || previousSelection[cid]; } return _.map( cids, mapper ); } if ( options.silent || options["@bbs:silentLocally"] ) return; var diff, label = getLabel( options, collection ), selectionSize = getSelectionSize( collection, label ), length = collection.length, prevSelectedCids = _.keys( prevSelected ), selectedCids = _.keys( collection[label] ), addedCids = _.difference( selectedCids, prevSelectedCids ), removedCids = _.difference( prevSelectedCids, selectedCids ), unchanged = (selectionSize === prevSelectedCids.length && addedCids.length === 0 && removedCids.length === 0); if ( reselected && reselected.length && !options["@bbs:silentReselect"] ) { queueEventSet( "reselect:any", label, [ reselected, collection, toEventOptions( options, label, collection ) ], collection, options ); } if ( unchanged ) return; diff = { selected: mapCidsToModels( addedCids, collection, prevSelected ), deselected: mapCidsToModels( removedCids, collection, prevSelected ) }; if ( selectionSize === 0 ) { queueEventSet( "select:none", label, [ diff, collection, toEventOptions( options, label, collection ) ], collection, options ); return; } if ( selectionSize === length ) { queueEventSet( "select:all", label, [ diff, collection, toEventOptions( options, label, collection ) ], collection, options ); return; } if ( selectionSize > 0 && selectionSize < length ) { queueEventSet( "select:some", label, [ diff, collection, toEventOptions( options, label, collection ) ], collection, options ); return; } }
[ "function", "triggerMultiSelectEvents", "(", "collection", ",", "prevSelected", ",", "options", ",", "reselected", ")", "{", "function", "mapCidsToModels", "(", "cids", ",", "collection", ",", "previousSelection", ")", "{", "function", "mapper", "(", "cid", ")", "{", "return", "collection", ".", "get", "(", "cid", ")", "||", "previousSelection", "[", "cid", "]", ";", "}", "return", "_", ".", "map", "(", "cids", ",", "mapper", ")", ";", "}", "if", "(", "options", ".", "silent", "||", "options", "[", "\"@bbs:silentLocally\"", "]", ")", "return", ";", "var", "diff", ",", "label", "=", "getLabel", "(", "options", ",", "collection", ")", ",", "selectionSize", "=", "getSelectionSize", "(", "collection", ",", "label", ")", ",", "length", "=", "collection", ".", "length", ",", "prevSelectedCids", "=", "_", ".", "keys", "(", "prevSelected", ")", ",", "selectedCids", "=", "_", ".", "keys", "(", "collection", "[", "label", "]", ")", ",", "addedCids", "=", "_", ".", "difference", "(", "selectedCids", ",", "prevSelectedCids", ")", ",", "removedCids", "=", "_", ".", "difference", "(", "prevSelectedCids", ",", "selectedCids", ")", ",", "unchanged", "=", "(", "selectionSize", "===", "prevSelectedCids", ".", "length", "&&", "addedCids", ".", "length", "===", "0", "&&", "removedCids", ".", "length", "===", "0", ")", ";", "if", "(", "reselected", "&&", "reselected", ".", "length", "&&", "!", "options", "[", "\"@bbs:silentReselect\"", "]", ")", "{", "queueEventSet", "(", "\"reselect:any\"", ",", "label", ",", "[", "reselected", ",", "collection", ",", "toEventOptions", "(", "options", ",", "label", ",", "collection", ")", "]", ",", "collection", ",", "options", ")", ";", "}", "if", "(", "unchanged", ")", "return", ";", "diff", "=", "{", "selected", ":", "mapCidsToModels", "(", "addedCids", ",", "collection", ",", "prevSelected", ")", ",", "deselected", ":", "mapCidsToModels", "(", "removedCids", ",", "collection", ",", "prevSelected", ")", "}", ";", "if", "(", "selectionSize", "===", "0", ")", "{", "queueEventSet", "(", "\"select:none\"", ",", "label", ",", "[", "diff", ",", "collection", ",", "toEventOptions", "(", "options", ",", "label", ",", "collection", ")", "]", ",", "collection", ",", "options", ")", ";", "return", ";", "}", "if", "(", "selectionSize", "===", "length", ")", "{", "queueEventSet", "(", "\"select:all\"", ",", "label", ",", "[", "diff", ",", "collection", ",", "toEventOptions", "(", "options", ",", "label", ",", "collection", ")", "]", ",", "collection", ",", "options", ")", ";", "return", ";", "}", "if", "(", "selectionSize", ">", "0", "&&", "selectionSize", "<", "length", ")", "{", "queueEventSet", "(", "\"select:some\"", ",", "label", ",", "[", "diff", ",", "collection", ",", "toEventOptions", "(", "options", ",", "label", ",", "collection", ")", "]", ",", "collection", ",", "options", ")", ";", "return", ";", "}", "}" ]
Trigger events from a multi-select collection, based on the number of selected items.
[ "Trigger", "events", "from", "a", "multi", "-", "select", "collection", "based", "on", "the", "number", "of", "selected", "items", "." ]
237d75bf2fb3e0d955f07114d74622401f8942ae
https://github.com/hashchange/backbone.select/blob/237d75bf2fb3e0d955f07114d74622401f8942ae/dist/backbone.select.js#L651-L702
train
hashchange/backbone.select
dist/backbone.select.js
ensureModelMixin
function ensureModelMixin( model, collection, options ) { var applyModelMixin; if ( !model._pickyType ) { applyModelMixin = Backbone.Select.Me.custom.applyModelMixin; if ( applyModelMixin && _.isFunction( applyModelMixin ) ) { applyModelMixin( model, collection, options ); } else { Backbone.Select.Me.applyTo( model, options ); } } }
javascript
function ensureModelMixin( model, collection, options ) { var applyModelMixin; if ( !model._pickyType ) { applyModelMixin = Backbone.Select.Me.custom.applyModelMixin; if ( applyModelMixin && _.isFunction( applyModelMixin ) ) { applyModelMixin( model, collection, options ); } else { Backbone.Select.Me.applyTo( model, options ); } } }
[ "function", "ensureModelMixin", "(", "model", ",", "collection", ",", "options", ")", "{", "var", "applyModelMixin", ";", "if", "(", "!", "model", ".", "_pickyType", ")", "{", "applyModelMixin", "=", "Backbone", ".", "Select", ".", "Me", ".", "custom", ".", "applyModelMixin", ";", "if", "(", "applyModelMixin", "&&", "_", ".", "isFunction", "(", "applyModelMixin", ")", ")", "{", "applyModelMixin", "(", "model", ",", "collection", ",", "options", ")", ";", "}", "else", "{", "Backbone", ".", "Select", ".", "Me", ".", "applyTo", "(", "model", ",", "options", ")", ";", "}", "}", "}" ]
Auto-apply the Backbone.Select.Me mixin if not yet done for the model. Options are passed on to the mixin. Ie, if `defaultLabel` has been defined in the options, the model will be set up accordingly.
[ "Auto", "-", "apply", "the", "Backbone", ".", "Select", ".", "Me", "mixin", "if", "not", "yet", "done", "for", "the", "model", ".", "Options", "are", "passed", "on", "to", "the", "mixin", ".", "Ie", "if", "defaultLabel", "has", "been", "defined", "in", "the", "options", "the", "model", "will", "be", "set", "up", "accordingly", "." ]
237d75bf2fb3e0d955f07114d74622401f8942ae
https://github.com/hashchange/backbone.select/blob/237d75bf2fb3e0d955f07114d74622401f8942ae/dist/backbone.select.js#L882-L895
train
hashchange/backbone.select
demo/amd/trailing.js
function ( model ) { var trailing = this.collection.trailing && this.collection.trailing.id || this.collection.first().id, view = this, cbUpdateTrailing = function () { view.collection.get( Math.round( this.trailingId ) ).select( { label: "trailing" } ); }; // Animate the trailing element and make it catch up. Use the .select() method with the label // "trailing". $( { trailingId: trailing } ).animate( { trailingId: model.id }, { step: cbUpdateTrailing, done: cbUpdateTrailing, duration: trailingLag } ); }
javascript
function ( model ) { var trailing = this.collection.trailing && this.collection.trailing.id || this.collection.first().id, view = this, cbUpdateTrailing = function () { view.collection.get( Math.round( this.trailingId ) ).select( { label: "trailing" } ); }; // Animate the trailing element and make it catch up. Use the .select() method with the label // "trailing". $( { trailingId: trailing } ).animate( { trailingId: model.id }, { step: cbUpdateTrailing, done: cbUpdateTrailing, duration: trailingLag } ); }
[ "function", "(", "model", ")", "{", "var", "trailing", "=", "this", ".", "collection", ".", "trailing", "&&", "this", ".", "collection", ".", "trailing", ".", "id", "||", "this", ".", "collection", ".", "first", "(", ")", ".", "id", ",", "view", "=", "this", ",", "cbUpdateTrailing", "=", "function", "(", ")", "{", "view", ".", "collection", ".", "get", "(", "Math", ".", "round", "(", "this", ".", "trailingId", ")", ")", ".", "select", "(", "{", "label", ":", "\"trailing\"", "}", ")", ";", "}", ";", "$", "(", "{", "trailingId", ":", "trailing", "}", ")", ".", "animate", "(", "{", "trailingId", ":", "model", ".", "id", "}", ",", "{", "step", ":", "cbUpdateTrailing", ",", "done", ":", "cbUpdateTrailing", ",", "duration", ":", "trailingLag", "}", ")", ";", "}" ]
Only runs when a model is selected with the default label, not with the custom label "trailing"
[ "Only", "runs", "when", "a", "model", "is", "selected", "with", "the", "default", "label", "not", "with", "the", "custom", "label", "trailing" ]
237d75bf2fb3e0d955f07114d74622401f8942ae
https://github.com/hashchange/backbone.select/blob/237d75bf2fb3e0d955f07114d74622401f8942ae/demo/amd/trailing.js#L82-L96
train
doowb/npm-api
lib/models/maintainer.js
Maintainer
function Maintainer (name, store) { if (!(this instanceof Maintainer)) { return new Maintainer(name); } Base.call(this, store); this.is('maintainer'); this.name = name; }
javascript
function Maintainer (name, store) { if (!(this instanceof Maintainer)) { return new Maintainer(name); } Base.call(this, store); this.is('maintainer'); this.name = name; }
[ "function", "Maintainer", "(", "name", ",", "store", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Maintainer", ")", ")", "{", "return", "new", "Maintainer", "(", "name", ")", ";", "}", "Base", ".", "call", "(", "this", ",", "store", ")", ";", "this", ".", "is", "(", "'maintainer'", ")", ";", "this", ".", "name", "=", "name", ";", "}" ]
Maintainer constructor. Create an instance of an npm maintainer by maintainer name. ```js var maintainer = new Maintainer('doowb'); ``` @param {String} `name` Name of the npm maintainer to get information about. @param {Object} `store` Optional cache store instance for caching results. Defaults to a memory store. @api public
[ "Maintainer", "constructor", ".", "Create", "an", "instance", "of", "an", "npm", "maintainer", "by", "maintainer", "name", "." ]
2204395a7da8815465c12ba147cd7622b9d5bae2
https://github.com/doowb/npm-api/blob/2204395a7da8815465c12ba147cd7622b9d5bae2/lib/models/maintainer.js#L25-L32
train
ozum/sequelize-pg-generator
lib/index.js
template
function template(filePath, locals, fn) { filePath = path.join(getConfig('template.folder'), filePath + '.' + getConfig('template.extension')); // i.e. index -> index.ejs return cons[getConfig('template.engine')].call(null, filePath, locals, fn); // i.e. cons.swig('views/page.html', { user: 'tobi' }, function(err, html){} }
javascript
function template(filePath, locals, fn) { filePath = path.join(getConfig('template.folder'), filePath + '.' + getConfig('template.extension')); // i.e. index -> index.ejs return cons[getConfig('template.engine')].call(null, filePath, locals, fn); // i.e. cons.swig('views/page.html', { user: 'tobi' }, function(err, html){} }
[ "function", "template", "(", "filePath", ",", "locals", ",", "fn", ")", "{", "filePath", "=", "path", ".", "join", "(", "getConfig", "(", "'template.folder'", ")", ",", "filePath", "+", "'.'", "+", "getConfig", "(", "'template.extension'", ")", ")", ";", "return", "cons", "[", "getConfig", "(", "'template.engine'", ")", "]", ".", "call", "(", "null", ",", "filePath", ",", "locals", ",", "fn", ")", ";", "}" ]
Renders the template and executes callback function. @private @param {string} filePath - Path of the template file relative to template folder. @param {object} locals - Local variables to pass to template @param {function} fn - Callback function(err, output)
[ "Renders", "the", "template", "and", "executes", "callback", "function", "." ]
c38491b4d560981713a96a1923ad48d70e4aaff8
https://github.com/ozum/sequelize-pg-generator/blob/c38491b4d560981713a96a1923ad48d70e4aaff8/lib/index.js#L93-L96
train
ozum/sequelize-pg-generator
lib/index.js
parseDB
function parseDB(callback) { pgStructure(getConfig('database.host'), getConfig('database.database'), getConfig('database.user'), getConfig('database.password'), { port: getConfig('database.port'), schema: getConfig('database.schema') }, callback); }
javascript
function parseDB(callback) { pgStructure(getConfig('database.host'), getConfig('database.database'), getConfig('database.user'), getConfig('database.password'), { port: getConfig('database.port'), schema: getConfig('database.schema') }, callback); }
[ "function", "parseDB", "(", "callback", ")", "{", "pgStructure", "(", "getConfig", "(", "'database.host'", ")", ",", "getConfig", "(", "'database.database'", ")", ",", "getConfig", "(", "'database.user'", ")", ",", "getConfig", "(", "'database.password'", ")", ",", "{", "port", ":", "getConfig", "(", "'database.port'", ")", ",", "schema", ":", "getConfig", "(", "'database.schema'", ")", "}", ",", "callback", ")", ";", "}" ]
Parses by reverse engineering using pgStructure module and calls callback. @private @param {function} callback - Callback function(err, structure)
[ "Parses", "by", "reverse", "engineering", "using", "pgStructure", "module", "and", "calls", "callback", "." ]
c38491b4d560981713a96a1923ad48d70e4aaff8
https://github.com/ozum/sequelize-pg-generator/blob/c38491b4d560981713a96a1923ad48d70e4aaff8/lib/index.js#L104-L108
train
ozum/sequelize-pg-generator
lib/index.js
getBelongsToName
function getBelongsToName(fkc) { var as = fkc.foreignKey(0).name(), // company_id tableName = fkc.table().name(), camelCase = getSpecificConfig(tableName, 'generate.relationAccessorCamelCase'), prefix = getSpecificConfig(tableName, 'generate.prefixForBelongsTo'); // related if (as.match(/_id$/i)) { as = as.replace(/_id$/i, ''); // company_id -> company } else { as = prefix + '_' + as; // company -> related_company } if (camelCase) { as = inflection.camelize(inflection.underscore(as), true); } return inflection.singularize(as); }
javascript
function getBelongsToName(fkc) { var as = fkc.foreignKey(0).name(), // company_id tableName = fkc.table().name(), camelCase = getSpecificConfig(tableName, 'generate.relationAccessorCamelCase'), prefix = getSpecificConfig(tableName, 'generate.prefixForBelongsTo'); // related if (as.match(/_id$/i)) { as = as.replace(/_id$/i, ''); // company_id -> company } else { as = prefix + '_' + as; // company -> related_company } if (camelCase) { as = inflection.camelize(inflection.underscore(as), true); } return inflection.singularize(as); }
[ "function", "getBelongsToName", "(", "fkc", ")", "{", "var", "as", "=", "fkc", ".", "foreignKey", "(", "0", ")", ".", "name", "(", ")", ",", "tableName", "=", "fkc", ".", "table", "(", ")", ".", "name", "(", ")", ",", "camelCase", "=", "getSpecificConfig", "(", "tableName", ",", "'generate.relationAccessorCamelCase'", ")", ",", "prefix", "=", "getSpecificConfig", "(", "tableName", ",", "'generate.prefixForBelongsTo'", ")", ";", "if", "(", "as", ".", "match", "(", "/", "_id$", "/", "i", ")", ")", "{", "as", "=", "as", ".", "replace", "(", "/", "_id$", "/", "i", ",", "''", ")", ";", "}", "else", "{", "as", "=", "prefix", "+", "'_'", "+", "as", ";", "}", "if", "(", "camelCase", ")", "{", "as", "=", "inflection", ".", "camelize", "(", "inflection", ".", "underscore", "(", "as", ")", ",", "true", ")", ";", "}", "return", "inflection", ".", "singularize", "(", "as", ")", ";", "}" ]
Calculates belongsTo relation name based on table, column and config. @private @param {object} fkc - pg-structure foreign key constraint object. @returns {string} - Name for the belongsTo relationship.
[ "Calculates", "belongsTo", "relation", "name", "based", "on", "table", "column", "and", "config", "." ]
c38491b4d560981713a96a1923ad48d70e4aaff8
https://github.com/ozum/sequelize-pg-generator/blob/c38491b4d560981713a96a1923ad48d70e4aaff8/lib/index.js#L166-L181
train
ozum/sequelize-pg-generator
lib/index.js
getBelongsToManyName
function getBelongsToManyName(hasManyThrough) { var tfkc = hasManyThrough.throughForeignKeyConstraint(), as = tfkc.foreignKey(0).name(), // company_id throughTableName = hasManyThrough.through().name(), relationName = hasManyThrough.throughForeignKeyConstraintToSelf().name(), tableName = hasManyThrough.table().name(), camelCase = getSpecificConfig(tableName, 'generate.relationAccessorCamelCase'), prefix = getSpecificConfig(tableName, 'generate.prefixForBelongsTo'); // related if (getSpecificConfig(tableName, 'generate.addRelationNameToManyToMany')) { if (getSpecificConfig(tableName, 'generate.stripFirstTableNameFromManyToMany')) { relationName = relationName.replace(new RegExp('^' + tableName + '[_-]?', 'i'), ''); // cart_cart_line_items -> cart_line_item } as = inflection.singularize(relationName) + '_' + as; } else if (getSpecificConfig(tableName, 'generate.addTableNameToManyToMany')) { as = inflection.singularize(throughTableName) + '_' + as; } if (as.match(/_id$/i)) { as = as.replace(/_id$/i, ''); // company_id -> company } else { as = prefix + '_' + as; // company -> related_company } if (camelCase) { as = inflection.camelize(inflection.underscore(as), true); } return inflection.pluralize(as); }
javascript
function getBelongsToManyName(hasManyThrough) { var tfkc = hasManyThrough.throughForeignKeyConstraint(), as = tfkc.foreignKey(0).name(), // company_id throughTableName = hasManyThrough.through().name(), relationName = hasManyThrough.throughForeignKeyConstraintToSelf().name(), tableName = hasManyThrough.table().name(), camelCase = getSpecificConfig(tableName, 'generate.relationAccessorCamelCase'), prefix = getSpecificConfig(tableName, 'generate.prefixForBelongsTo'); // related if (getSpecificConfig(tableName, 'generate.addRelationNameToManyToMany')) { if (getSpecificConfig(tableName, 'generate.stripFirstTableNameFromManyToMany')) { relationName = relationName.replace(new RegExp('^' + tableName + '[_-]?', 'i'), ''); // cart_cart_line_items -> cart_line_item } as = inflection.singularize(relationName) + '_' + as; } else if (getSpecificConfig(tableName, 'generate.addTableNameToManyToMany')) { as = inflection.singularize(throughTableName) + '_' + as; } if (as.match(/_id$/i)) { as = as.replace(/_id$/i, ''); // company_id -> company } else { as = prefix + '_' + as; // company -> related_company } if (camelCase) { as = inflection.camelize(inflection.underscore(as), true); } return inflection.pluralize(as); }
[ "function", "getBelongsToManyName", "(", "hasManyThrough", ")", "{", "var", "tfkc", "=", "hasManyThrough", ".", "throughForeignKeyConstraint", "(", ")", ",", "as", "=", "tfkc", ".", "foreignKey", "(", "0", ")", ".", "name", "(", ")", ",", "throughTableName", "=", "hasManyThrough", ".", "through", "(", ")", ".", "name", "(", ")", ",", "relationName", "=", "hasManyThrough", ".", "throughForeignKeyConstraintToSelf", "(", ")", ".", "name", "(", ")", ",", "tableName", "=", "hasManyThrough", ".", "table", "(", ")", ".", "name", "(", ")", ",", "camelCase", "=", "getSpecificConfig", "(", "tableName", ",", "'generate.relationAccessorCamelCase'", ")", ",", "prefix", "=", "getSpecificConfig", "(", "tableName", ",", "'generate.prefixForBelongsTo'", ")", ";", "if", "(", "getSpecificConfig", "(", "tableName", ",", "'generate.addRelationNameToManyToMany'", ")", ")", "{", "if", "(", "getSpecificConfig", "(", "tableName", ",", "'generate.stripFirstTableNameFromManyToMany'", ")", ")", "{", "relationName", "=", "relationName", ".", "replace", "(", "new", "RegExp", "(", "'^'", "+", "tableName", "+", "'[_-]?'", ",", "'i'", ")", ",", "''", ")", ";", "}", "as", "=", "inflection", ".", "singularize", "(", "relationName", ")", "+", "'_'", "+", "as", ";", "}", "else", "if", "(", "getSpecificConfig", "(", "tableName", ",", "'generate.addTableNameToManyToMany'", ")", ")", "{", "as", "=", "inflection", ".", "singularize", "(", "throughTableName", ")", "+", "'_'", "+", "as", ";", "}", "if", "(", "as", ".", "match", "(", "/", "_id$", "/", "i", ")", ")", "{", "as", "=", "as", ".", "replace", "(", "/", "_id$", "/", "i", ",", "''", ")", ";", "}", "else", "{", "as", "=", "prefix", "+", "'_'", "+", "as", ";", "}", "if", "(", "camelCase", ")", "{", "as", "=", "inflection", ".", "camelize", "(", "inflection", ".", "underscore", "(", "as", ")", ",", "true", ")", ";", "}", "return", "inflection", ".", "pluralize", "(", "as", ")", ";", "}" ]
Calculates belongsToMany relation name based on table, column and config. @private @param {object} hasManyThrough - pg-structure foreign key constraint object. @returns {string} - Name for the belongsToMany relationship.
[ "Calculates", "belongsToMany", "relation", "name", "based", "on", "table", "column", "and", "config", "." ]
c38491b4d560981713a96a1923ad48d70e4aaff8
https://github.com/ozum/sequelize-pg-generator/blob/c38491b4d560981713a96a1923ad48d70e4aaff8/lib/index.js#L190-L217
train
ozum/sequelize-pg-generator
lib/index.js
getHasManyName
function getHasManyName(hasMany) { var as, tableName; if (hasMany.through() !== undefined) { as = getBelongsToManyName(hasMany); //inflection.pluralize(getBelongsToName(hasMany.throughForeignKeyConstraint())); } else { as = inflection.pluralize(hasMany.name()); // cart_cart_line_items tableName = hasMany.table().name(); if (getSpecificConfig(tableName, 'generate.stripFirstTableFromHasMany')) { as = as.replace(new RegExp('^' + tableName + '[_-]?', 'i'), ''); // cart_cart_line_items -> cart_line_items } if (getSpecificConfig(tableName, 'generate.relationAccessorCamelCase')) { as = inflection.camelize(inflection.underscore(as), true); // cart_line_items -> cartLineItems } } return as; }
javascript
function getHasManyName(hasMany) { var as, tableName; if (hasMany.through() !== undefined) { as = getBelongsToManyName(hasMany); //inflection.pluralize(getBelongsToName(hasMany.throughForeignKeyConstraint())); } else { as = inflection.pluralize(hasMany.name()); // cart_cart_line_items tableName = hasMany.table().name(); if (getSpecificConfig(tableName, 'generate.stripFirstTableFromHasMany')) { as = as.replace(new RegExp('^' + tableName + '[_-]?', 'i'), ''); // cart_cart_line_items -> cart_line_items } if (getSpecificConfig(tableName, 'generate.relationAccessorCamelCase')) { as = inflection.camelize(inflection.underscore(as), true); // cart_line_items -> cartLineItems } } return as; }
[ "function", "getHasManyName", "(", "hasMany", ")", "{", "var", "as", ",", "tableName", ";", "if", "(", "hasMany", ".", "through", "(", ")", "!==", "undefined", ")", "{", "as", "=", "getBelongsToManyName", "(", "hasMany", ")", ";", "}", "else", "{", "as", "=", "inflection", ".", "pluralize", "(", "hasMany", ".", "name", "(", ")", ")", ";", "tableName", "=", "hasMany", ".", "table", "(", ")", ".", "name", "(", ")", ";", "if", "(", "getSpecificConfig", "(", "tableName", ",", "'generate.stripFirstTableFromHasMany'", ")", ")", "{", "as", "=", "as", ".", "replace", "(", "new", "RegExp", "(", "'^'", "+", "tableName", "+", "'[_-]?'", ",", "'i'", ")", ",", "''", ")", ";", "}", "if", "(", "getSpecificConfig", "(", "tableName", ",", "'generate.relationAccessorCamelCase'", ")", ")", "{", "as", "=", "inflection", ".", "camelize", "(", "inflection", ".", "underscore", "(", "as", ")", ",", "true", ")", ";", "}", "}", "return", "as", ";", "}" ]
Calculates hasMany relation name based on table, column and config. @private @param {object} hasMany - pg-structure foreign key constraint object. @returns {string} - Name for the belongsTo relationship.
[ "Calculates", "hasMany", "relation", "name", "based", "on", "table", "column", "and", "config", "." ]
c38491b4d560981713a96a1923ad48d70e4aaff8
https://github.com/ozum/sequelize-pg-generator/blob/c38491b4d560981713a96a1923ad48d70e4aaff8/lib/index.js#L226-L243
train
ozum/sequelize-pg-generator
lib/index.js
getModelNameFor
function getModelNameFor(table) { var schemaName = getSpecificConfig(table.name(), 'generate.modelCamelCase') ? inflection.camelize(inflection.underscore(table.schema().name()), true) : table.schema().name(), tableName = getSpecificConfig(table.name(), 'generate.modelCamelCase') ? inflection.camelize(inflection.underscore(table.name()), true) : table.name(); return getSpecificConfig(table.name(), 'generate.useSchemaName') ? schemaName + '.' + tableName : tableName; }
javascript
function getModelNameFor(table) { var schemaName = getSpecificConfig(table.name(), 'generate.modelCamelCase') ? inflection.camelize(inflection.underscore(table.schema().name()), true) : table.schema().name(), tableName = getSpecificConfig(table.name(), 'generate.modelCamelCase') ? inflection.camelize(inflection.underscore(table.name()), true) : table.name(); return getSpecificConfig(table.name(), 'generate.useSchemaName') ? schemaName + '.' + tableName : tableName; }
[ "function", "getModelNameFor", "(", "table", ")", "{", "var", "schemaName", "=", "getSpecificConfig", "(", "table", ".", "name", "(", ")", ",", "'generate.modelCamelCase'", ")", "?", "inflection", ".", "camelize", "(", "inflection", ".", "underscore", "(", "table", ".", "schema", "(", ")", ".", "name", "(", ")", ")", ",", "true", ")", ":", "table", ".", "schema", "(", ")", ".", "name", "(", ")", ",", "tableName", "=", "getSpecificConfig", "(", "table", ".", "name", "(", ")", ",", "'generate.modelCamelCase'", ")", "?", "inflection", ".", "camelize", "(", "inflection", ".", "underscore", "(", "table", ".", "name", "(", ")", ")", ",", "true", ")", ":", "table", ".", "name", "(", ")", ";", "return", "getSpecificConfig", "(", "table", ".", "name", "(", ")", ",", "'generate.useSchemaName'", ")", "?", "schemaName", "+", "'.'", "+", "tableName", ":", "tableName", ";", "}" ]
Calculates model name for given table. @private @param {object} table - pg-structure table object. @returns {string} - Model name for table
[ "Calculates", "model", "name", "for", "given", "table", "." ]
c38491b4d560981713a96a1923ad48d70e4aaff8
https://github.com/ozum/sequelize-pg-generator/blob/c38491b4d560981713a96a1923ad48d70e4aaff8/lib/index.js#L252-L257
train
ozum/sequelize-pg-generator
lib/index.js
getTableOptions
function getTableOptions(table) { logger.debug('table details are calculated for: %s', table.name()); var specificName = 'tableOptionsOverride.' + table.name(), specificOptions = config.has(specificName) ? getConfig(specificName) : {}, generalOptions = getConfig('tableOptions'), otherOptions = { modelName : getModelNameFor(table), tableName : table.name(), schema : table.schema().name(), comment : getSpecificConfig(table.name(), 'generate.tableDescription') ? table.description() : undefined, columns : [], hasManies : [], belongsTos : [], belongsToManies : [] }, tableOptions = filterAttributes(lodash.defaults(specificOptions, generalOptions, otherOptions)); tableOptions.baseFileName = table.name(); return tableOptions; }
javascript
function getTableOptions(table) { logger.debug('table details are calculated for: %s', table.name()); var specificName = 'tableOptionsOverride.' + table.name(), specificOptions = config.has(specificName) ? getConfig(specificName) : {}, generalOptions = getConfig('tableOptions'), otherOptions = { modelName : getModelNameFor(table), tableName : table.name(), schema : table.schema().name(), comment : getSpecificConfig(table.name(), 'generate.tableDescription') ? table.description() : undefined, columns : [], hasManies : [], belongsTos : [], belongsToManies : [] }, tableOptions = filterAttributes(lodash.defaults(specificOptions, generalOptions, otherOptions)); tableOptions.baseFileName = table.name(); return tableOptions; }
[ "function", "getTableOptions", "(", "table", ")", "{", "logger", ".", "debug", "(", "'table details are calculated for: %s'", ",", "table", ".", "name", "(", ")", ")", ";", "var", "specificName", "=", "'tableOptionsOverride.'", "+", "table", ".", "name", "(", ")", ",", "specificOptions", "=", "config", ".", "has", "(", "specificName", ")", "?", "getConfig", "(", "specificName", ")", ":", "{", "}", ",", "generalOptions", "=", "getConfig", "(", "'tableOptions'", ")", ",", "otherOptions", "=", "{", "modelName", ":", "getModelNameFor", "(", "table", ")", ",", "tableName", ":", "table", ".", "name", "(", ")", ",", "schema", ":", "table", ".", "schema", "(", ")", ".", "name", "(", ")", ",", "comment", ":", "getSpecificConfig", "(", "table", ".", "name", "(", ")", ",", "'generate.tableDescription'", ")", "?", "table", ".", "description", "(", ")", ":", "undefined", ",", "columns", ":", "[", "]", ",", "hasManies", ":", "[", "]", ",", "belongsTos", ":", "[", "]", ",", "belongsToManies", ":", "[", "]", "}", ",", "tableOptions", "=", "filterAttributes", "(", "lodash", ".", "defaults", "(", "specificOptions", ",", "generalOptions", ",", "otherOptions", ")", ")", ";", "tableOptions", ".", "baseFileName", "=", "table", ".", "name", "(", ")", ";", "return", "tableOptions", ";", "}" ]
Returns table details as plain object to use in templates. @private @param table @returns {Object}
[ "Returns", "table", "details", "as", "plain", "object", "to", "use", "in", "templates", "." ]
c38491b4d560981713a96a1923ad48d70e4aaff8
https://github.com/ozum/sequelize-pg-generator/blob/c38491b4d560981713a96a1923ad48d70e4aaff8/lib/index.js#L266-L285
train
ozum/sequelize-pg-generator
lib/index.js
sequelizeType
function sequelizeType(column, varName) { varName = varName || 'DataTypes'; // DataTypes.INTEGER etc. prefix var enumValues = column.enumValues(); var type = enumValues ? '.ENUM' : sequelizeTypes[column.type()].type; var realType = column.arrayDimension() >= 1 ? column.arrayType() : column.type(); // type or type of array (if array). var hasLength = sequelizeTypes[realType].hasLength; var hasPrecision = sequelizeTypes[realType].hasPrecision; var isObject = type && type.indexOf('.') !== -1; // . ile başlıyorsa değişkene çevirmek için var details; var isArrayTypeObject; if (isObject) { type = varName + type; } details = function(num1, num2) { var detail = ''; if (num1 >= 0 && num1 !== null && num2 && num2 !== null) { detail = '(' + num1 + ',' + num2 + ')'; // (5,2) } else if (num1 >= 0 && num1 !== null) { detail = '(' + num1 + ')'; // (5) } return detail; }; if (column.arrayDimension() >= 1) { isArrayTypeObject = sequelizeTypes[column.arrayType()].type.indexOf('.') !== -1; type += '('; if (column.arrayDimension() > 1) { type += new Array(column.arrayDimension()).join(varName + '.ARRAY('); } // arrayDimension -1 tane 'ARRAY(' yaz type += isArrayTypeObject ? varName : "'"; type += sequelizeTypes[column.arrayType()].type; type += isArrayTypeObject ? '' : "'"; } if (enumValues) { enumValues = util.inspect(enumValues.substring(1, enumValues.length - 1).split(',')); // Strip { and } -> make array -> makeJSON; enumValues = enumValues.substring(2, enumValues.length - 2); // Strip '[ ' and ' ]' type += '(' + enumValues + ')'; } if (hasPrecision) { type += details(column.precision(), column.scale()); } if (hasLength) { type += details(column.length()); } if (column.arrayDimension() >= 1) { type += new Array(column.arrayDimension() + 1).join(')'); // arrayDimension -1 tane ) yaz } if (!isObject) { type = "'" + type + "'"; } return type; }
javascript
function sequelizeType(column, varName) { varName = varName || 'DataTypes'; // DataTypes.INTEGER etc. prefix var enumValues = column.enumValues(); var type = enumValues ? '.ENUM' : sequelizeTypes[column.type()].type; var realType = column.arrayDimension() >= 1 ? column.arrayType() : column.type(); // type or type of array (if array). var hasLength = sequelizeTypes[realType].hasLength; var hasPrecision = sequelizeTypes[realType].hasPrecision; var isObject = type && type.indexOf('.') !== -1; // . ile başlıyorsa değişkene çevirmek için var details; var isArrayTypeObject; if (isObject) { type = varName + type; } details = function(num1, num2) { var detail = ''; if (num1 >= 0 && num1 !== null && num2 && num2 !== null) { detail = '(' + num1 + ',' + num2 + ')'; // (5,2) } else if (num1 >= 0 && num1 !== null) { detail = '(' + num1 + ')'; // (5) } return detail; }; if (column.arrayDimension() >= 1) { isArrayTypeObject = sequelizeTypes[column.arrayType()].type.indexOf('.') !== -1; type += '('; if (column.arrayDimension() > 1) { type += new Array(column.arrayDimension()).join(varName + '.ARRAY('); } // arrayDimension -1 tane 'ARRAY(' yaz type += isArrayTypeObject ? varName : "'"; type += sequelizeTypes[column.arrayType()].type; type += isArrayTypeObject ? '' : "'"; } if (enumValues) { enumValues = util.inspect(enumValues.substring(1, enumValues.length - 1).split(',')); // Strip { and } -> make array -> makeJSON; enumValues = enumValues.substring(2, enumValues.length - 2); // Strip '[ ' and ' ]' type += '(' + enumValues + ')'; } if (hasPrecision) { type += details(column.precision(), column.scale()); } if (hasLength) { type += details(column.length()); } if (column.arrayDimension() >= 1) { type += new Array(column.arrayDimension() + 1).join(')'); // arrayDimension -1 tane ) yaz } if (!isObject) { type = "'" + type + "'"; } return type; }
[ "function", "sequelizeType", "(", "column", ",", "varName", ")", "{", "varName", "=", "varName", "||", "'DataTypes'", ";", "var", "enumValues", "=", "column", ".", "enumValues", "(", ")", ";", "var", "type", "=", "enumValues", "?", "'.ENUM'", ":", "sequelizeTypes", "[", "column", ".", "type", "(", ")", "]", ".", "type", ";", "var", "realType", "=", "column", ".", "arrayDimension", "(", ")", ">=", "1", "?", "column", ".", "arrayType", "(", ")", ":", "column", ".", "type", "(", ")", ";", "var", "hasLength", "=", "sequelizeTypes", "[", "realType", "]", ".", "hasLength", ";", "var", "hasPrecision", "=", "sequelizeTypes", "[", "realType", "]", ".", "hasPrecision", ";", "var", "isObject", "=", "type", "&&", "type", ".", "indexOf", "(", "'.'", ")", "!==", "-", "1", ";", "var", "details", ";", "var", "isArrayTypeObject", ";", "if", "(", "isObject", ")", "{", "type", "=", "varName", "+", "type", ";", "}", "details", "=", "function", "(", "num1", ",", "num2", ")", "{", "var", "detail", "=", "''", ";", "if", "(", "num1", ">=", "0", "&&", "num1", "!==", "null", "&&", "num2", "&&", "num2", "!==", "null", ")", "{", "detail", "=", "'('", "+", "num1", "+", "','", "+", "num2", "+", "')'", ";", "}", "else", "if", "(", "num1", ">=", "0", "&&", "num1", "!==", "null", ")", "{", "detail", "=", "'('", "+", "num1", "+", "')'", ";", "}", "return", "detail", ";", "}", ";", "if", "(", "column", ".", "arrayDimension", "(", ")", ">=", "1", ")", "{", "isArrayTypeObject", "=", "sequelizeTypes", "[", "column", ".", "arrayType", "(", ")", "]", ".", "type", ".", "indexOf", "(", "'.'", ")", "!==", "-", "1", ";", "type", "+=", "'('", ";", "if", "(", "column", ".", "arrayDimension", "(", ")", ">", "1", ")", "{", "type", "+=", "new", "Array", "(", "column", ".", "arrayDimension", "(", ")", ")", ".", "join", "(", "varName", "+", "'.ARRAY('", ")", ";", "}", "type", "+=", "isArrayTypeObject", "?", "varName", ":", "\"'\"", ";", "type", "+=", "sequelizeTypes", "[", "column", ".", "arrayType", "(", ")", "]", ".", "type", ";", "type", "+=", "isArrayTypeObject", "?", "''", ":", "\"'\"", ";", "}", "if", "(", "enumValues", ")", "{", "enumValues", "=", "util", ".", "inspect", "(", "enumValues", ".", "substring", "(", "1", ",", "enumValues", ".", "length", "-", "1", ")", ".", "split", "(", "','", ")", ")", ";", "enumValues", "=", "enumValues", ".", "substring", "(", "2", ",", "enumValues", ".", "length", "-", "2", ")", ";", "type", "+=", "'('", "+", "enumValues", "+", "')'", ";", "}", "if", "(", "hasPrecision", ")", "{", "type", "+=", "details", "(", "column", ".", "precision", "(", ")", ",", "column", ".", "scale", "(", ")", ")", ";", "}", "if", "(", "hasLength", ")", "{", "type", "+=", "details", "(", "column", ".", "length", "(", ")", ")", ";", "}", "if", "(", "column", ".", "arrayDimension", "(", ")", ">=", "1", ")", "{", "type", "+=", "new", "Array", "(", "column", ".", "arrayDimension", "(", ")", "+", "1", ")", ".", "join", "(", "')'", ")", ";", "}", "if", "(", "!", "isObject", ")", "{", "type", "=", "\"'\"", "+", "type", "+", "\"'\"", ";", "}", "return", "type", ";", "}" ]
Returns Sequelize ORM datatype for column. @param {Object} column - pg-structure column object. @param {string} [varName = DataTypes] - Variable name to use in sequelize data type. ie. 'DataTypes' for DataTypes.INTEGER @returns {string} @private @example var typeA = column.sequelizeType(); // DataTypes.INTEGER(3) var typeB = column.sequelizeType('Sequelize'); // Sequelize.INTEGER(3)
[ "Returns", "Sequelize", "ORM", "datatype", "for", "column", "." ]
c38491b4d560981713a96a1923ad48d70e4aaff8
https://github.com/ozum/sequelize-pg-generator/blob/c38491b4d560981713a96a1923ad48d70e4aaff8/lib/index.js#L299-L356
train
ozum/sequelize-pg-generator
lib/index.js
getColumnDetails
function getColumnDetails(column) { logger.debug('column details are calculated for: %s', column.name()); var result = filterAttributes({ source : 'generator', accessorName : getSpecificConfig(column.table().name(), 'generate.columnAccessorCamelCase') ? inflection.camelize(inflection.underscore(column.name()), true) : column.name(), name : column.name(), primaryKey : column.isPrimaryKey(), autoIncrement : column.isAutoIncrement() && getSpecificConfig(column.table().name(), 'generate.columnAutoIncrement') ? true : undefined, allowNull : column.allowNull(), defaultValue : getSpecificConfig(column.table().name(), 'generate.columnDefault') && column.default() !== null ? clearDefaultValue(column.default()) : undefined, unique : column.unique(), comment : getSpecificConfig(column.table().name(), 'generate.columnDescription') ? column.description() : undefined, references : column.foreignKeyConstraint() ? getModelNameFor(column.foreignKeyConstraint().referencesTable()) : undefined, referencesKey : column.foreignKeyConstraint() ? column.foreignKeyConstraint().foreignKey(0).name() : undefined, onUpdate : column.onUpdate(), onDelete : column.onDelete() }); result.type = sequelizeType(column, getSpecificConfig(column.table().name(), 'generate.dataTypeVariable')); // To prevent type having quotes. //result.type = column.sequelizeType(getSpecificConfig(column.table().name(), 'generate.dataTypeVariable')); // To prevent type having quotes. return result; }
javascript
function getColumnDetails(column) { logger.debug('column details are calculated for: %s', column.name()); var result = filterAttributes({ source : 'generator', accessorName : getSpecificConfig(column.table().name(), 'generate.columnAccessorCamelCase') ? inflection.camelize(inflection.underscore(column.name()), true) : column.name(), name : column.name(), primaryKey : column.isPrimaryKey(), autoIncrement : column.isAutoIncrement() && getSpecificConfig(column.table().name(), 'generate.columnAutoIncrement') ? true : undefined, allowNull : column.allowNull(), defaultValue : getSpecificConfig(column.table().name(), 'generate.columnDefault') && column.default() !== null ? clearDefaultValue(column.default()) : undefined, unique : column.unique(), comment : getSpecificConfig(column.table().name(), 'generate.columnDescription') ? column.description() : undefined, references : column.foreignKeyConstraint() ? getModelNameFor(column.foreignKeyConstraint().referencesTable()) : undefined, referencesKey : column.foreignKeyConstraint() ? column.foreignKeyConstraint().foreignKey(0).name() : undefined, onUpdate : column.onUpdate(), onDelete : column.onDelete() }); result.type = sequelizeType(column, getSpecificConfig(column.table().name(), 'generate.dataTypeVariable')); // To prevent type having quotes. //result.type = column.sequelizeType(getSpecificConfig(column.table().name(), 'generate.dataTypeVariable')); // To prevent type having quotes. return result; }
[ "function", "getColumnDetails", "(", "column", ")", "{", "logger", ".", "debug", "(", "'column details are calculated for: %s'", ",", "column", ".", "name", "(", ")", ")", ";", "var", "result", "=", "filterAttributes", "(", "{", "source", ":", "'generator'", ",", "accessorName", ":", "getSpecificConfig", "(", "column", ".", "table", "(", ")", ".", "name", "(", ")", ",", "'generate.columnAccessorCamelCase'", ")", "?", "inflection", ".", "camelize", "(", "inflection", ".", "underscore", "(", "column", ".", "name", "(", ")", ")", ",", "true", ")", ":", "column", ".", "name", "(", ")", ",", "name", ":", "column", ".", "name", "(", ")", ",", "primaryKey", ":", "column", ".", "isPrimaryKey", "(", ")", ",", "autoIncrement", ":", "column", ".", "isAutoIncrement", "(", ")", "&&", "getSpecificConfig", "(", "column", ".", "table", "(", ")", ".", "name", "(", ")", ",", "'generate.columnAutoIncrement'", ")", "?", "true", ":", "undefined", ",", "allowNull", ":", "column", ".", "allowNull", "(", ")", ",", "defaultValue", ":", "getSpecificConfig", "(", "column", ".", "table", "(", ")", ".", "name", "(", ")", ",", "'generate.columnDefault'", ")", "&&", "column", ".", "default", "(", ")", "!==", "null", "?", "clearDefaultValue", "(", "column", ".", "default", "(", ")", ")", ":", "undefined", ",", "unique", ":", "column", ".", "unique", "(", ")", ",", "comment", ":", "getSpecificConfig", "(", "column", ".", "table", "(", ")", ".", "name", "(", ")", ",", "'generate.columnDescription'", ")", "?", "column", ".", "description", "(", ")", ":", "undefined", ",", "references", ":", "column", ".", "foreignKeyConstraint", "(", ")", "?", "getModelNameFor", "(", "column", ".", "foreignKeyConstraint", "(", ")", ".", "referencesTable", "(", ")", ")", ":", "undefined", ",", "referencesKey", ":", "column", ".", "foreignKeyConstraint", "(", ")", "?", "column", ".", "foreignKeyConstraint", "(", ")", ".", "foreignKey", "(", "0", ")", ".", "name", "(", ")", ":", "undefined", ",", "onUpdate", ":", "column", ".", "onUpdate", "(", ")", ",", "onDelete", ":", "column", ".", "onDelete", "(", ")", "}", ")", ";", "result", ".", "type", "=", "sequelizeType", "(", "column", ",", "getSpecificConfig", "(", "column", ".", "table", "(", ")", ".", "name", "(", ")", ",", "'generate.dataTypeVariable'", ")", ")", ";", "return", "result", ";", "}" ]
Returns column details as plain object to use in templates. @private @param {object} column - pg-structure column object @returns {Object} - Simple object to use in template
[ "Returns", "column", "details", "as", "plain", "object", "to", "use", "in", "templates", "." ]
c38491b4d560981713a96a1923ad48d70e4aaff8
https://github.com/ozum/sequelize-pg-generator/blob/c38491b4d560981713a96a1923ad48d70e4aaff8/lib/index.js#L365-L386
train
ozum/sequelize-pg-generator
lib/index.js
getHasManyDetails
function getHasManyDetails(hasMany) { logger.debug('hasMany%s details are calculated for: %s', hasMany.through() ? 'through' : '', hasMany.name()); var model = getModelNameFor(hasMany.referencesTable()), as = getHasManyName(hasMany); return filterAttributes({ type : 'hasMany', source : 'generator', name : hasMany.name(), model : model, as : getAlias(hasMany.table(), as, 'hasMany'), targetSchema : hasMany.referencesTable().schema().name(), targetTable : hasMany.referencesTable().name(), foreignKey : hasMany.foreignKey(0).name(), // Sequelize support single key only onDelete : hasMany.onDelete(), onUpdate : hasMany.onUpdate(), through : hasMany.through() ? hasMany.through().name() : undefined }); }
javascript
function getHasManyDetails(hasMany) { logger.debug('hasMany%s details are calculated for: %s', hasMany.through() ? 'through' : '', hasMany.name()); var model = getModelNameFor(hasMany.referencesTable()), as = getHasManyName(hasMany); return filterAttributes({ type : 'hasMany', source : 'generator', name : hasMany.name(), model : model, as : getAlias(hasMany.table(), as, 'hasMany'), targetSchema : hasMany.referencesTable().schema().name(), targetTable : hasMany.referencesTable().name(), foreignKey : hasMany.foreignKey(0).name(), // Sequelize support single key only onDelete : hasMany.onDelete(), onUpdate : hasMany.onUpdate(), through : hasMany.through() ? hasMany.through().name() : undefined }); }
[ "function", "getHasManyDetails", "(", "hasMany", ")", "{", "logger", ".", "debug", "(", "'hasMany%s details are calculated for: %s'", ",", "hasMany", ".", "through", "(", ")", "?", "'through'", ":", "''", ",", "hasMany", ".", "name", "(", ")", ")", ";", "var", "model", "=", "getModelNameFor", "(", "hasMany", ".", "referencesTable", "(", ")", ")", ",", "as", "=", "getHasManyName", "(", "hasMany", ")", ";", "return", "filterAttributes", "(", "{", "type", ":", "'hasMany'", ",", "source", ":", "'generator'", ",", "name", ":", "hasMany", ".", "name", "(", ")", ",", "model", ":", "model", ",", "as", ":", "getAlias", "(", "hasMany", ".", "table", "(", ")", ",", "as", ",", "'hasMany'", ")", ",", "targetSchema", ":", "hasMany", ".", "referencesTable", "(", ")", ".", "schema", "(", ")", ".", "name", "(", ")", ",", "targetTable", ":", "hasMany", ".", "referencesTable", "(", ")", ".", "name", "(", ")", ",", "foreignKey", ":", "hasMany", ".", "foreignKey", "(", "0", ")", ".", "name", "(", ")", ",", "onDelete", ":", "hasMany", ".", "onDelete", "(", ")", ",", "onUpdate", ":", "hasMany", ".", "onUpdate", "(", ")", ",", "through", ":", "hasMany", ".", "through", "(", ")", "?", "hasMany", ".", "through", "(", ")", ".", "name", "(", ")", ":", "undefined", "}", ")", ";", "}" ]
Returns hasMany details as plain object to use in templates. @private @param {object} hasMany - pg-structure hasMany object @returns {Object} - Simple object to use in template
[ "Returns", "hasMany", "details", "as", "plain", "object", "to", "use", "in", "templates", "." ]
c38491b4d560981713a96a1923ad48d70e4aaff8
https://github.com/ozum/sequelize-pg-generator/blob/c38491b4d560981713a96a1923ad48d70e4aaff8/lib/index.js#L410-L428
train
ozum/sequelize-pg-generator
lib/index.js
getBelongsToDetails
function getBelongsToDetails(fkc) { logger.debug('belongsTo details are calculated for: %s', fkc.name()); var model = getModelNameFor(fkc.referencesTable()), as = getBelongsToName(fkc); return filterAttributes({ type : 'belongsTo', source : 'generator', name : fkc.name(), model : model, as : getAlias(fkc.table(), as, 'belongsTo'), targetSchema : fkc.referencesTable().schema().name(), targetTable : fkc.referencesTable().name(), foreignKey : fkc.foreignKey(0).name(), // Sequelize support single key only onDelete : fkc.onDelete(), onUpdate : fkc.onUpdate() }); }
javascript
function getBelongsToDetails(fkc) { logger.debug('belongsTo details are calculated for: %s', fkc.name()); var model = getModelNameFor(fkc.referencesTable()), as = getBelongsToName(fkc); return filterAttributes({ type : 'belongsTo', source : 'generator', name : fkc.name(), model : model, as : getAlias(fkc.table(), as, 'belongsTo'), targetSchema : fkc.referencesTable().schema().name(), targetTable : fkc.referencesTable().name(), foreignKey : fkc.foreignKey(0).name(), // Sequelize support single key only onDelete : fkc.onDelete(), onUpdate : fkc.onUpdate() }); }
[ "function", "getBelongsToDetails", "(", "fkc", ")", "{", "logger", ".", "debug", "(", "'belongsTo details are calculated for: %s'", ",", "fkc", ".", "name", "(", ")", ")", ";", "var", "model", "=", "getModelNameFor", "(", "fkc", ".", "referencesTable", "(", ")", ")", ",", "as", "=", "getBelongsToName", "(", "fkc", ")", ";", "return", "filterAttributes", "(", "{", "type", ":", "'belongsTo'", ",", "source", ":", "'generator'", ",", "name", ":", "fkc", ".", "name", "(", ")", ",", "model", ":", "model", ",", "as", ":", "getAlias", "(", "fkc", ".", "table", "(", ")", ",", "as", ",", "'belongsTo'", ")", ",", "targetSchema", ":", "fkc", ".", "referencesTable", "(", ")", ".", "schema", "(", ")", ".", "name", "(", ")", ",", "targetTable", ":", "fkc", ".", "referencesTable", "(", ")", ".", "name", "(", ")", ",", "foreignKey", ":", "fkc", ".", "foreignKey", "(", "0", ")", ".", "name", "(", ")", ",", "onDelete", ":", "fkc", ".", "onDelete", "(", ")", ",", "onUpdate", ":", "fkc", ".", "onUpdate", "(", ")", "}", ")", ";", "}" ]
Returns belongsTo details as plain object to use in templates. @private @param {object} fkc - pg-structure belongsTo object @returns {Object} - Simple object to use in template
[ "Returns", "belongsTo", "details", "as", "plain", "object", "to", "use", "in", "templates", "." ]
c38491b4d560981713a96a1923ad48d70e4aaff8
https://github.com/ozum/sequelize-pg-generator/blob/c38491b4d560981713a96a1923ad48d70e4aaff8/lib/index.js#L437-L454
train
ozum/sequelize-pg-generator
lib/index.js
getBelongsToManyDetails
function getBelongsToManyDetails(hasManyThrough) { logger.debug('belongsToMany details are calculated for: %s', hasManyThrough.name()); var model = getModelNameFor(hasManyThrough.referencesTable()), as = getBelongsToManyName(hasManyThrough); return filterAttributes({ type : 'belongsToMany', source : 'generator', name : hasManyThrough.name(), model : model, as : getAlias(hasManyThrough.table(), as, 'belongsToMany'), targetSchema : hasManyThrough.referencesTable().schema().name(), targetTable : hasManyThrough.referencesTable().name(), foreignKey : hasManyThrough.foreignKey(0).name(), // Sequelize support single key only otherKey : hasManyThrough.throughForeignKeyConstraint().foreignKey(0).name(), // Sequelize support single key only onDelete : hasManyThrough.onDelete(), onUpdate : hasManyThrough.onUpdate(), through : hasManyThrough.through().name() }); }
javascript
function getBelongsToManyDetails(hasManyThrough) { logger.debug('belongsToMany details are calculated for: %s', hasManyThrough.name()); var model = getModelNameFor(hasManyThrough.referencesTable()), as = getBelongsToManyName(hasManyThrough); return filterAttributes({ type : 'belongsToMany', source : 'generator', name : hasManyThrough.name(), model : model, as : getAlias(hasManyThrough.table(), as, 'belongsToMany'), targetSchema : hasManyThrough.referencesTable().schema().name(), targetTable : hasManyThrough.referencesTable().name(), foreignKey : hasManyThrough.foreignKey(0).name(), // Sequelize support single key only otherKey : hasManyThrough.throughForeignKeyConstraint().foreignKey(0).name(), // Sequelize support single key only onDelete : hasManyThrough.onDelete(), onUpdate : hasManyThrough.onUpdate(), through : hasManyThrough.through().name() }); }
[ "function", "getBelongsToManyDetails", "(", "hasManyThrough", ")", "{", "logger", ".", "debug", "(", "'belongsToMany details are calculated for: %s'", ",", "hasManyThrough", ".", "name", "(", ")", ")", ";", "var", "model", "=", "getModelNameFor", "(", "hasManyThrough", ".", "referencesTable", "(", ")", ")", ",", "as", "=", "getBelongsToManyName", "(", "hasManyThrough", ")", ";", "return", "filterAttributes", "(", "{", "type", ":", "'belongsToMany'", ",", "source", ":", "'generator'", ",", "name", ":", "hasManyThrough", ".", "name", "(", ")", ",", "model", ":", "model", ",", "as", ":", "getAlias", "(", "hasManyThrough", ".", "table", "(", ")", ",", "as", ",", "'belongsToMany'", ")", ",", "targetSchema", ":", "hasManyThrough", ".", "referencesTable", "(", ")", ".", "schema", "(", ")", ".", "name", "(", ")", ",", "targetTable", ":", "hasManyThrough", ".", "referencesTable", "(", ")", ".", "name", "(", ")", ",", "foreignKey", ":", "hasManyThrough", ".", "foreignKey", "(", "0", ")", ".", "name", "(", ")", ",", "otherKey", ":", "hasManyThrough", ".", "throughForeignKeyConstraint", "(", ")", ".", "foreignKey", "(", "0", ")", ".", "name", "(", ")", ",", "onDelete", ":", "hasManyThrough", ".", "onDelete", "(", ")", ",", "onUpdate", ":", "hasManyThrough", ".", "onUpdate", "(", ")", ",", "through", ":", "hasManyThrough", ".", "through", "(", ")", ".", "name", "(", ")", "}", ")", ";", "}" ]
Returns belongsToMany details as plain object to use in templates. @private @param {object} hasManyThrough - pg-structure hasManyThrough object @returns {Object} - Simple object to use in template
[ "Returns", "belongsToMany", "details", "as", "plain", "object", "to", "use", "in", "templates", "." ]
c38491b4d560981713a96a1923ad48d70e4aaff8
https://github.com/ozum/sequelize-pg-generator/blob/c38491b4d560981713a96a1923ad48d70e4aaff8/lib/index.js#L462-L481
train
ozum/sequelize-pg-generator
lib/index.js
getFileName
function getFileName(table) { var fileName = table.name() + '.js'; if (getSpecificConfig(table.name(), 'generate.useSchemaName')) { // Prefix with schema name if config requested it. fileName = table.schema().name() + '_' + fileName; } return fileName; }
javascript
function getFileName(table) { var fileName = table.name() + '.js'; if (getSpecificConfig(table.name(), 'generate.useSchemaName')) { // Prefix with schema name if config requested it. fileName = table.schema().name() + '_' + fileName; } return fileName; }
[ "function", "getFileName", "(", "table", ")", "{", "var", "fileName", "=", "table", ".", "name", "(", ")", "+", "'.js'", ";", "if", "(", "getSpecificConfig", "(", "table", ".", "name", "(", ")", ",", "'generate.useSchemaName'", ")", ")", "{", "fileName", "=", "table", ".", "schema", "(", ")", ".", "name", "(", ")", "+", "'_'", "+", "fileName", ";", "}", "return", "fileName", ";", "}" ]
Calculates and returns file name based on schema and table. @private @param {object} table - pg-structure table object @returns {string} - file name for the model
[ "Calculates", "and", "returns", "file", "name", "based", "on", "schema", "and", "table", "." ]
c38491b4d560981713a96a1923ad48d70e4aaff8
https://github.com/ozum/sequelize-pg-generator/blob/c38491b4d560981713a96a1923ad48d70e4aaff8/lib/index.js#L490-L496
train
ozum/sequelize-pg-generator
lib/index.js
shouldSkip
function shouldSkip(table, detail) { var skipTable = getConfig('generate.skipTable'); // Do not auto generate files for those tables. if (skipTable.indexOf(table.name()) !== -1 || skipTable.indexOf(table.schema().name() + '.' + table.name()) !== -1) { if (getConfig('output.log')) { if (detail === 'table') { logger.info('(Skipped ' + detail + ') File \'' + getFileName(table) + '\' is skipped for model \'' + getModelNameFor(table) + '\''); } else if (detail === 'relation') { logger.info('(Skipped ' + detail + ') Relation is skipped for model \'' + getModelNameFor(table) + '\''); } } return true; } return false; }
javascript
function shouldSkip(table, detail) { var skipTable = getConfig('generate.skipTable'); // Do not auto generate files for those tables. if (skipTable.indexOf(table.name()) !== -1 || skipTable.indexOf(table.schema().name() + '.' + table.name()) !== -1) { if (getConfig('output.log')) { if (detail === 'table') { logger.info('(Skipped ' + detail + ') File \'' + getFileName(table) + '\' is skipped for model \'' + getModelNameFor(table) + '\''); } else if (detail === 'relation') { logger.info('(Skipped ' + detail + ') Relation is skipped for model \'' + getModelNameFor(table) + '\''); } } return true; } return false; }
[ "function", "shouldSkip", "(", "table", ",", "detail", ")", "{", "var", "skipTable", "=", "getConfig", "(", "'generate.skipTable'", ")", ";", "if", "(", "skipTable", ".", "indexOf", "(", "table", ".", "name", "(", ")", ")", "!==", "-", "1", "||", "skipTable", ".", "indexOf", "(", "table", ".", "schema", "(", ")", ".", "name", "(", ")", "+", "'.'", "+", "table", ".", "name", "(", ")", ")", "!==", "-", "1", ")", "{", "if", "(", "getConfig", "(", "'output.log'", ")", ")", "{", "if", "(", "detail", "===", "'table'", ")", "{", "logger", ".", "info", "(", "'(Skipped '", "+", "detail", "+", "') File \\''", "+", "\\'", "+", "getFileName", "(", "table", ")", "+", "'\\' is skipped for model \\''", "+", "\\'", ")", ";", "}", "else", "\\'", "}", "getModelNameFor", "(", "table", ")", "}", "'\\''", "}" ]
Returns if table is in the list of tables to be skipped. Looks for schema.table and table name. @private @param {object} table - pg-structure object @param {string} detail - Type of object to include it in explanation @returns {boolean}
[ "Returns", "if", "table", "is", "in", "the", "list", "of", "tables", "to", "be", "skipped", ".", "Looks", "for", "schema", ".", "table", "and", "table", "name", "." ]
c38491b4d560981713a96a1923ad48d70e4aaff8
https://github.com/ozum/sequelize-pg-generator/blob/c38491b4d560981713a96a1923ad48d70e4aaff8/lib/index.js#L506-L520
train
ozum/sequelize-pg-generator
lib/index.js
generateModelFiles
function generateModelFiles(db, next) { var q, templateTable, allNamingErrors = []; q = async.queue(function (task, workerCallback) { var output = getConfig('output.beautify') ? beautify(task.content, { indent_size: getConfig('output.indent'), preserve_newlines: getConfig('output.preserveNewLines') }) : task.content; fs.writeFile(path.join(getConfig('output.folder'), 'definition-files', getFileName(task.table)), output, workerCallback); if (getConfig('output.log')) { logger.info('(Created) File \'' + getFileName(task.table) + '\' is created for model \'' + getModelNameFor(task.table) + '\''); } }, 4); db.schemas(function (schema) { schema.tables(function (table) { var namingError = ''; logger.debug('Now parsing table: %s', table.name()); if (getSpecificConfig(table.name(), 'generate.hasManyThrough') && getSpecificConfig(table.name(), 'generate.belongsToMany')) { next(new Error('Configuration error: Both "generate.hasManyThrough" and "generate.belongsToMany" configuration is set to be true for table "' + table.schema().name() + '.' + table.name() + '". They cannot be true at the same time.')); } if (shouldSkip(table, 'table')) { return; } templateTable = getTableOptions(table); table.columns(function (column) { templateTable.columns.push(getColumnDetails(column)); }); table.hasManies(function (hasMany) { if (shouldSkip(hasMany.referencesTable(), 'relation')) { return; } templateTable.hasManies.push(getHasManyDetails(hasMany)); }); table.hasManyThroughs(function (hasManyThrough) { if (getSpecificConfig(table.name(), 'generate.addRelationNameToManyToMany') && getSpecificConfig(table.name(), 'generate.addTableNameToManyToMany')) { next(new Error('Configuration error: Both "generate.addRelationNameToManyToMany" and "generate.addTableNameToManyToMany" configuration is set to be true for table "' + table.schema().name() + '.' + table.name() + '". They cannot be true at the same time.')); } if (shouldSkip(hasManyThrough.referencesTable(), 'relation') || shouldSkip(hasManyThrough.through(), 'relation')) { return; } if (getSpecificConfig(table.name(), 'generate.hasManyThrough')) { templateTable.hasManies.push(getHasManyDetails(hasManyThrough)); // has many throughs are deprecated after Sequelize 2.0 RC3 } if (getSpecificConfig(table.name(), 'generate.belongsToMany')) { templateTable.belongsToManies.push(getBelongsToManyDetails(hasManyThrough)); } }); table.foreignKeyConstraints(function (fkc) { if (shouldSkip(fkc.referencesTable(), 'relation')) { return; } templateTable.belongsTos.push(getBelongsToDetails(fkc)); }); templateTable.relations = templateTable.hasManies.concat(templateTable.belongsTos, templateTable.belongsToManies); namingError = validateNaming(templateTable); if (namingError) { allNamingErrors.push(namingError); } template('index', { table: templateTable, mainScript: path.join(getConfig('output.folder'), 'index.js'), warning: getConfig('output.warning'), dataTypeVariable: getSpecificConfig(table.name(), 'generate.dataTypeVariable') }, function (err, result) { if (err) { next(err); } q.push({content: result, table: table}, function (err) { if (err) { next(err); } }); }); }); }); q.drain = function () { if (allNamingErrors.length > 0) { next(new Error('There are naming errors. Either set "generate.addRelationNameToManyToMany" true in configuration or rename your relations.\n' + allNamingErrors.join('\n'))); } else { next(null); } }; }
javascript
function generateModelFiles(db, next) { var q, templateTable, allNamingErrors = []; q = async.queue(function (task, workerCallback) { var output = getConfig('output.beautify') ? beautify(task.content, { indent_size: getConfig('output.indent'), preserve_newlines: getConfig('output.preserveNewLines') }) : task.content; fs.writeFile(path.join(getConfig('output.folder'), 'definition-files', getFileName(task.table)), output, workerCallback); if (getConfig('output.log')) { logger.info('(Created) File \'' + getFileName(task.table) + '\' is created for model \'' + getModelNameFor(task.table) + '\''); } }, 4); db.schemas(function (schema) { schema.tables(function (table) { var namingError = ''; logger.debug('Now parsing table: %s', table.name()); if (getSpecificConfig(table.name(), 'generate.hasManyThrough') && getSpecificConfig(table.name(), 'generate.belongsToMany')) { next(new Error('Configuration error: Both "generate.hasManyThrough" and "generate.belongsToMany" configuration is set to be true for table "' + table.schema().name() + '.' + table.name() + '". They cannot be true at the same time.')); } if (shouldSkip(table, 'table')) { return; } templateTable = getTableOptions(table); table.columns(function (column) { templateTable.columns.push(getColumnDetails(column)); }); table.hasManies(function (hasMany) { if (shouldSkip(hasMany.referencesTable(), 'relation')) { return; } templateTable.hasManies.push(getHasManyDetails(hasMany)); }); table.hasManyThroughs(function (hasManyThrough) { if (getSpecificConfig(table.name(), 'generate.addRelationNameToManyToMany') && getSpecificConfig(table.name(), 'generate.addTableNameToManyToMany')) { next(new Error('Configuration error: Both "generate.addRelationNameToManyToMany" and "generate.addTableNameToManyToMany" configuration is set to be true for table "' + table.schema().name() + '.' + table.name() + '". They cannot be true at the same time.')); } if (shouldSkip(hasManyThrough.referencesTable(), 'relation') || shouldSkip(hasManyThrough.through(), 'relation')) { return; } if (getSpecificConfig(table.name(), 'generate.hasManyThrough')) { templateTable.hasManies.push(getHasManyDetails(hasManyThrough)); // has many throughs are deprecated after Sequelize 2.0 RC3 } if (getSpecificConfig(table.name(), 'generate.belongsToMany')) { templateTable.belongsToManies.push(getBelongsToManyDetails(hasManyThrough)); } }); table.foreignKeyConstraints(function (fkc) { if (shouldSkip(fkc.referencesTable(), 'relation')) { return; } templateTable.belongsTos.push(getBelongsToDetails(fkc)); }); templateTable.relations = templateTable.hasManies.concat(templateTable.belongsTos, templateTable.belongsToManies); namingError = validateNaming(templateTable); if (namingError) { allNamingErrors.push(namingError); } template('index', { table: templateTable, mainScript: path.join(getConfig('output.folder'), 'index.js'), warning: getConfig('output.warning'), dataTypeVariable: getSpecificConfig(table.name(), 'generate.dataTypeVariable') }, function (err, result) { if (err) { next(err); } q.push({content: result, table: table}, function (err) { if (err) { next(err); } }); }); }); }); q.drain = function () { if (allNamingErrors.length > 0) { next(new Error('There are naming errors. Either set "generate.addRelationNameToManyToMany" true in configuration or rename your relations.\n' + allNamingErrors.join('\n'))); } else { next(null); } }; }
[ "function", "generateModelFiles", "(", "db", ",", "next", ")", "{", "var", "q", ",", "templateTable", ",", "allNamingErrors", "=", "[", "]", ";", "q", "=", "async", ".", "queue", "(", "function", "(", "task", ",", "workerCallback", ")", "{", "var", "output", "=", "getConfig", "(", "'output.beautify'", ")", "?", "beautify", "(", "task", ".", "content", ",", "{", "indent_size", ":", "getConfig", "(", "'output.indent'", ")", ",", "preserve_newlines", ":", "getConfig", "(", "'output.preserveNewLines'", ")", "}", ")", ":", "task", ".", "content", ";", "fs", ".", "writeFile", "(", "path", ".", "join", "(", "getConfig", "(", "'output.folder'", ")", ",", "'definition-files'", ",", "getFileName", "(", "task", ".", "table", ")", ")", ",", "output", ",", "workerCallback", ")", ";", "if", "(", "getConfig", "(", "'output.log'", ")", ")", "{", "logger", ".", "info", "(", "'(Created) File \\''", "+", "\\'", "+", "getFileName", "(", "task", ".", "table", ")", "+", "'\\' is created for model \\''", "+", "\\'", ")", ";", "}", "}", ",", "\\'", ")", ";", "getModelNameFor", "(", "task", ".", "table", ")", "'\\''", "}" ]
Generates all model files. @private @param {object} db - pg-structure db object @param {function} next - Callback to execute.
[ "Generates", "all", "model", "files", "." ]
c38491b4d560981713a96a1923ad48d70e4aaff8
https://github.com/ozum/sequelize-pg-generator/blob/c38491b4d560981713a96a1923ad48d70e4aaff8/lib/index.js#L569-L639
train
ozum/sequelize-pg-generator
lib/index.js
createOutputFolder
function createOutputFolder(next) { var defPath = path.join(getConfig('output.folder'), 'definition-files'), defPathCustom = path.join(getConfig('output.folder'), 'definition-files-custom'); fs.remove(defPath, function (err) { if (err) { next(err); } fs.createFile(path.join(defPath, '_Dont_add_or_edit_any_files'), function (err) { if (err) { next(err); } fs.mkdirs(defPathCustom, function (err) { if (err) { next(err); } next(null); }); }); }); }
javascript
function createOutputFolder(next) { var defPath = path.join(getConfig('output.folder'), 'definition-files'), defPathCustom = path.join(getConfig('output.folder'), 'definition-files-custom'); fs.remove(defPath, function (err) { if (err) { next(err); } fs.createFile(path.join(defPath, '_Dont_add_or_edit_any_files'), function (err) { if (err) { next(err); } fs.mkdirs(defPathCustom, function (err) { if (err) { next(err); } next(null); }); }); }); }
[ "function", "createOutputFolder", "(", "next", ")", "{", "var", "defPath", "=", "path", ".", "join", "(", "getConfig", "(", "'output.folder'", ")", ",", "'definition-files'", ")", ",", "defPathCustom", "=", "path", ".", "join", "(", "getConfig", "(", "'output.folder'", ")", ",", "'definition-files-custom'", ")", ";", "fs", ".", "remove", "(", "defPath", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "next", "(", "err", ")", ";", "}", "fs", ".", "createFile", "(", "path", ".", "join", "(", "defPath", ",", "'_Dont_add_or_edit_any_files'", ")", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "next", "(", "err", ")", ";", "}", "fs", ".", "mkdirs", "(", "defPathCustom", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "next", "(", "err", ")", ";", "}", "next", "(", "null", ")", ";", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Creates 'definition-files' and 'definition-files-custom' directories if they do not exist. Before creating definition-files it deletes definition-files directory. @private @param {function} next - Callback to execute
[ "Creates", "definition", "-", "files", "and", "definition", "-", "files", "-", "custom", "directories", "if", "they", "do", "not", "exist", ".", "Before", "creating", "definition", "-", "files", "it", "deletes", "definition", "-", "files", "directory", "." ]
c38491b4d560981713a96a1923ad48d70e4aaff8
https://github.com/ozum/sequelize-pg-generator/blob/c38491b4d560981713a96a1923ad48d70e4aaff8/lib/index.js#L648-L662
train
ozum/sequelize-pg-generator
lib/index.js
generateUtilityFiles
function generateUtilityFiles(next) { fs.copy(path.join(getConfig('template.folder'), 'index.js'), path.join(getConfig('output.folder'), 'index.js'), function (err) { if (err) { next(err); return; } if (getConfig('output.log')) { logger.info('(Created) Index file: ' + path.resolve(path.join(getConfig('output.folder'), 'index.js'))); } fs.copy(path.join(getConfig('template.folder'), '..', 'utils.js'), path.join(getConfig('output.folder'), 'utils.js'), function (err) { if (err) { next(err); return; } next(null); }); }); try { overriddenAliases = require(path.join(process.cwd(), getConfig('output.folder'), 'alias.json')); } catch (ignore) {} }
javascript
function generateUtilityFiles(next) { fs.copy(path.join(getConfig('template.folder'), 'index.js'), path.join(getConfig('output.folder'), 'index.js'), function (err) { if (err) { next(err); return; } if (getConfig('output.log')) { logger.info('(Created) Index file: ' + path.resolve(path.join(getConfig('output.folder'), 'index.js'))); } fs.copy(path.join(getConfig('template.folder'), '..', 'utils.js'), path.join(getConfig('output.folder'), 'utils.js'), function (err) { if (err) { next(err); return; } next(null); }); }); try { overriddenAliases = require(path.join(process.cwd(), getConfig('output.folder'), 'alias.json')); } catch (ignore) {} }
[ "function", "generateUtilityFiles", "(", "next", ")", "{", "fs", ".", "copy", "(", "path", ".", "join", "(", "getConfig", "(", "'template.folder'", ")", ",", "'index.js'", ")", ",", "path", ".", "join", "(", "getConfig", "(", "'output.folder'", ")", ",", "'index.js'", ")", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "next", "(", "err", ")", ";", "return", ";", "}", "if", "(", "getConfig", "(", "'output.log'", ")", ")", "{", "logger", ".", "info", "(", "'(Created) Index file: '", "+", "path", ".", "resolve", "(", "path", ".", "join", "(", "getConfig", "(", "'output.folder'", ")", ",", "'index.js'", ")", ")", ")", ";", "}", "fs", ".", "copy", "(", "path", ".", "join", "(", "getConfig", "(", "'template.folder'", ")", ",", "'..'", ",", "'utils.js'", ")", ",", "path", ".", "join", "(", "getConfig", "(", "'output.folder'", ")", ",", "'utils.js'", ")", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "next", "(", "err", ")", ";", "return", ";", "}", "next", "(", "null", ")", ";", "}", ")", ";", "}", ")", ";", "try", "{", "overriddenAliases", "=", "require", "(", "path", ".", "join", "(", "process", ".", "cwd", "(", ")", ",", "getConfig", "(", "'output.folder'", ")", ",", "'alias.json'", ")", ")", ";", "}", "catch", "(", "ignore", ")", "{", "}", "}" ]
Generates index file by copying index.js from template directory to model directory. These locations come from config. @private @param next
[ "Generates", "index", "file", "by", "copying", "index", ".", "js", "from", "template", "directory", "to", "model", "directory", ".", "These", "locations", "come", "from", "config", "." ]
c38491b4d560981713a96a1923ad48d70e4aaff8
https://github.com/ozum/sequelize-pg-generator/blob/c38491b4d560981713a96a1923ad48d70e4aaff8/lib/index.js#L671-L683
train
ozum/sequelize-pg-generator
lib/index.js
setupConfig
function setupConfig(options) { if (options.resetConfig) { // Reset your environment variables for resetting node-config module. node-config is a singleton. // For testing it's necessary to reset and this is a workaround from node-config support. global.NODE_CONFIG = null; delete require.cache[require.resolve('config')]; config = require('config'); delete options.resetConfig; } var customConfigFile, customConfig, defaultConfig = require('../config/default.js'); options = options || {}; if (options.config) { customConfigFile = options.config.charAt(0) === '/' || options.config.charAt(0) === '\\' ? options.config : path.join(process.cwd(), options.config); // Absolute or relative customConfig = require(customConfigFile); } delete options.config; // Combine configs and override lower priority configs. config.util.extendDeep(config, defaultConfig, customConfig || {}, { "sequelize-pg-generator": options }); }
javascript
function setupConfig(options) { if (options.resetConfig) { // Reset your environment variables for resetting node-config module. node-config is a singleton. // For testing it's necessary to reset and this is a workaround from node-config support. global.NODE_CONFIG = null; delete require.cache[require.resolve('config')]; config = require('config'); delete options.resetConfig; } var customConfigFile, customConfig, defaultConfig = require('../config/default.js'); options = options || {}; if (options.config) { customConfigFile = options.config.charAt(0) === '/' || options.config.charAt(0) === '\\' ? options.config : path.join(process.cwd(), options.config); // Absolute or relative customConfig = require(customConfigFile); } delete options.config; // Combine configs and override lower priority configs. config.util.extendDeep(config, defaultConfig, customConfig || {}, { "sequelize-pg-generator": options }); }
[ "function", "setupConfig", "(", "options", ")", "{", "if", "(", "options", ".", "resetConfig", ")", "{", "global", ".", "NODE_CONFIG", "=", "null", ";", "delete", "require", ".", "cache", "[", "require", ".", "resolve", "(", "'config'", ")", "]", ";", "config", "=", "require", "(", "'config'", ")", ";", "delete", "options", ".", "resetConfig", ";", "}", "var", "customConfigFile", ",", "customConfig", ",", "defaultConfig", "=", "require", "(", "'../config/default.js'", ")", ";", "options", "=", "options", "||", "{", "}", ";", "if", "(", "options", ".", "config", ")", "{", "customConfigFile", "=", "options", ".", "config", ".", "charAt", "(", "0", ")", "===", "'/'", "||", "options", ".", "config", ".", "charAt", "(", "0", ")", "===", "'\\\\'", "?", "\\\\", ":", "options", ".", "config", ";", "path", ".", "join", "(", "process", ".", "cwd", "(", ")", ",", "options", ".", "config", ")", "}", "customConfig", "=", "require", "(", "customConfigFile", ")", ";", "delete", "options", ".", "config", ";", "}" ]
Combines default configuration, custom config file and command line options by overriding lower priority ones. @private @param {object} options - Options converted to config structure.
[ "Combines", "default", "configuration", "custom", "config", "file", "and", "command", "line", "options", "by", "overriding", "lower", "priority", "ones", "." ]
c38491b4d560981713a96a1923ad48d70e4aaff8
https://github.com/ozum/sequelize-pg-generator/blob/c38491b4d560981713a96a1923ad48d70e4aaff8/lib/index.js#L698-L722
train
doowb/npm-api
lib/view.js
View
function View (name) { if (!(this instanceof View)) { return new View(name); } this.name = name; this.config = utils.clone(config); this.config.pathname += '/_view/' + this.name; }
javascript
function View (name) { if (!(this instanceof View)) { return new View(name); } this.name = name; this.config = utils.clone(config); this.config.pathname += '/_view/' + this.name; }
[ "function", "View", "(", "name", ")", "{", "if", "(", "!", "(", "this", "instanceof", "View", ")", ")", "{", "return", "new", "View", "(", "name", ")", ";", "}", "this", ".", "name", "=", "name", ";", "this", ".", "config", "=", "utils", ".", "clone", "(", "config", ")", ";", "this", ".", "config", ".", "pathname", "+=", "'/_view/'", "+", "this", ".", "name", ";", "}" ]
View constructor. Create an instance of a view associated with a couchdb view in the npm registry. ```js var view = new View('dependedUpon'); ``` @param {String} `name` Name of couchdb view to use. @returns {Object} instance of `View` @api public
[ "View", "constructor", ".", "Create", "an", "instance", "of", "a", "view", "associated", "with", "a", "couchdb", "view", "in", "the", "npm", "registry", "." ]
2204395a7da8815465c12ba147cd7622b9d5bae2
https://github.com/doowb/npm-api/blob/2204395a7da8815465c12ba147cd7622b9d5bae2/lib/view.js#L26-L33
train
doowb/npm-api
lib/models/base.js
BaseModel
function BaseModel(store) { if (!(this instanceof BaseModel)) { return new BaseModel(store); } Base.call(this); this.options = this.options || {}; this.cache = this.cache || {}; this.use(utils.option()); this.use(utils.plugin()); this.define('List', List); this.define('View', View); this.define('Registry', Registry); this.define('store', store || new Memory()); }
javascript
function BaseModel(store) { if (!(this instanceof BaseModel)) { return new BaseModel(store); } Base.call(this); this.options = this.options || {}; this.cache = this.cache || {}; this.use(utils.option()); this.use(utils.plugin()); this.define('List', List); this.define('View', View); this.define('Registry', Registry); this.define('store', store || new Memory()); }
[ "function", "BaseModel", "(", "store", ")", "{", "if", "(", "!", "(", "this", "instanceof", "BaseModel", ")", ")", "{", "return", "new", "BaseModel", "(", "store", ")", ";", "}", "Base", ".", "call", "(", "this", ")", ";", "this", ".", "options", "=", "this", ".", "options", "||", "{", "}", ";", "this", ".", "cache", "=", "this", ".", "cache", "||", "{", "}", ";", "this", ".", "use", "(", "utils", ".", "option", "(", ")", ")", ";", "this", ".", "use", "(", "utils", ".", "plugin", "(", ")", ")", ";", "this", ".", "define", "(", "'List'", ",", "List", ")", ";", "this", ".", "define", "(", "'View'", ",", "View", ")", ";", "this", ".", "define", "(", "'Registry'", ",", "Registry", ")", ";", "this", ".", "define", "(", "'store'", ",", "store", "||", "new", "Memory", "(", ")", ")", ";", "}" ]
Base model to include common plugins. @param {Object} `store` Cache store instance to use. @api public
[ "Base", "model", "to", "include", "common", "plugins", "." ]
2204395a7da8815465c12ba147cd7622b9d5bae2
https://github.com/doowb/npm-api/blob/2204395a7da8815465c12ba147cd7622b9d5bae2/lib/models/base.js#L24-L38
train
hashchange/backbone.select
demo/amd/rjs/output/unified/trailing-build.js
function(obj, name, callback, context, listening) { obj._events = eventsApi(onApi, obj._events || {}, name, callback, { context: context, ctx: obj, listening: listening }); if (listening) { var listeners = obj._listeners || (obj._listeners = {}); listeners[listening.id] = listening; } return obj; }
javascript
function(obj, name, callback, context, listening) { obj._events = eventsApi(onApi, obj._events || {}, name, callback, { context: context, ctx: obj, listening: listening }); if (listening) { var listeners = obj._listeners || (obj._listeners = {}); listeners[listening.id] = listening; } return obj; }
[ "function", "(", "obj", ",", "name", ",", "callback", ",", "context", ",", "listening", ")", "{", "obj", ".", "_events", "=", "eventsApi", "(", "onApi", ",", "obj", ".", "_events", "||", "{", "}", ",", "name", ",", "callback", ",", "{", "context", ":", "context", ",", "ctx", ":", "obj", ",", "listening", ":", "listening", "}", ")", ";", "if", "(", "listening", ")", "{", "var", "listeners", "=", "obj", ".", "_listeners", "||", "(", "obj", ".", "_listeners", "=", "{", "}", ")", ";", "listeners", "[", "listening", ".", "id", "]", "=", "listening", ";", "}", "return", "obj", ";", "}" ]
Guard the `listening` argument from the public API.
[ "Guard", "the", "listening", "argument", "from", "the", "public", "API", "." ]
237d75bf2fb3e0d955f07114d74622401f8942ae
https://github.com/hashchange/backbone.select/blob/237d75bf2fb3e0d955f07114d74622401f8942ae/demo/amd/rjs/output/unified/trailing-build.js#L11937-L11950
train
hashchange/backbone.select
demo/amd/rjs/output/unified/trailing-build.js
function(obj) { if (obj == null) return void 0; return this._byId[obj] || this._byId[this.modelId(obj.attributes || obj)] || obj.cid && this._byId[obj.cid]; }
javascript
function(obj) { if (obj == null) return void 0; return this._byId[obj] || this._byId[this.modelId(obj.attributes || obj)] || obj.cid && this._byId[obj.cid]; }
[ "function", "(", "obj", ")", "{", "if", "(", "obj", "==", "null", ")", "return", "void", "0", ";", "return", "this", ".", "_byId", "[", "obj", "]", "||", "this", ".", "_byId", "[", "this", ".", "modelId", "(", "obj", ".", "attributes", "||", "obj", ")", "]", "||", "obj", ".", "cid", "&&", "this", ".", "_byId", "[", "obj", ".", "cid", "]", ";", "}" ]
Get a model from the set by id, cid, model object with id or cid properties, or an attributes object that is transformed through modelId.
[ "Get", "a", "model", "from", "the", "set", "by", "id", "cid", "model", "object", "with", "id", "or", "cid", "properties", "or", "an", "attributes", "object", "that", "is", "transformed", "through", "modelId", "." ]
237d75bf2fb3e0d955f07114d74622401f8942ae
https://github.com/hashchange/backbone.select/blob/237d75bf2fb3e0d955f07114d74622401f8942ae/demo/amd/rjs/output/unified/trailing-build.js#L12755-L12760
train
hashchange/backbone.select
demo/amd/rjs/output/unified/trailing-build.js
function() { var path = this.decodeFragment(this.location.pathname); var rootPath = path.slice(0, this.root.length - 1) + '/'; return rootPath === this.root; }
javascript
function() { var path = this.decodeFragment(this.location.pathname); var rootPath = path.slice(0, this.root.length - 1) + '/'; return rootPath === this.root; }
[ "function", "(", ")", "{", "var", "path", "=", "this", ".", "decodeFragment", "(", "this", ".", "location", ".", "pathname", ")", ";", "var", "rootPath", "=", "path", ".", "slice", "(", "0", ",", "this", ".", "root", ".", "length", "-", "1", ")", "+", "'/'", ";", "return", "rootPath", "===", "this", ".", "root", ";", "}" ]
Does the pathname match the root?
[ "Does", "the", "pathname", "match", "the", "root?" ]
237d75bf2fb3e0d955f07114d74622401f8942ae
https://github.com/hashchange/backbone.select/blob/237d75bf2fb3e0d955f07114d74622401f8942ae/demo/amd/rjs/output/unified/trailing-build.js#L13379-L13383
train
hashchange/backbone.select
demo/amd/rjs/output/unified/trailing-build.js
function() { var path = this.decodeFragment( this.location.pathname + this.getSearch() ).slice(this.root.length - 1); return path.charAt(0) === '/' ? path.slice(1) : path; }
javascript
function() { var path = this.decodeFragment( this.location.pathname + this.getSearch() ).slice(this.root.length - 1); return path.charAt(0) === '/' ? path.slice(1) : path; }
[ "function", "(", ")", "{", "var", "path", "=", "this", ".", "decodeFragment", "(", "this", ".", "location", ".", "pathname", "+", "this", ".", "getSearch", "(", ")", ")", ".", "slice", "(", "this", ".", "root", ".", "length", "-", "1", ")", ";", "return", "path", ".", "charAt", "(", "0", ")", "===", "'/'", "?", "path", ".", "slice", "(", "1", ")", ":", "path", ";", "}" ]
Get the pathname and search params, without the root.
[ "Get", "the", "pathname", "and", "search", "params", "without", "the", "root", "." ]
237d75bf2fb3e0d955f07114d74622401f8942ae
https://github.com/hashchange/backbone.select/blob/237d75bf2fb3e0d955f07114d74622401f8942ae/demo/amd/rjs/output/unified/trailing-build.js#L13407-L13412
train
hashchange/backbone.select
demo/amd/rjs/output/unified/trailing-build.js
function(fragment) { if (fragment == null) { if (this._usePushState || !this._wantsHashChange) { fragment = this.getPath(); } else { fragment = this.getHash(); } } return fragment.replace(routeStripper, ''); }
javascript
function(fragment) { if (fragment == null) { if (this._usePushState || !this._wantsHashChange) { fragment = this.getPath(); } else { fragment = this.getHash(); } } return fragment.replace(routeStripper, ''); }
[ "function", "(", "fragment", ")", "{", "if", "(", "fragment", "==", "null", ")", "{", "if", "(", "this", ".", "_usePushState", "||", "!", "this", ".", "_wantsHashChange", ")", "{", "fragment", "=", "this", ".", "getPath", "(", ")", ";", "}", "else", "{", "fragment", "=", "this", ".", "getHash", "(", ")", ";", "}", "}", "return", "fragment", ".", "replace", "(", "routeStripper", ",", "''", ")", ";", "}" ]
Get the cross-browser normalized URL fragment from the path or hash.
[ "Get", "the", "cross", "-", "browser", "normalized", "URL", "fragment", "from", "the", "path", "or", "hash", "." ]
237d75bf2fb3e0d955f07114d74622401f8942ae
https://github.com/hashchange/backbone.select/blob/237d75bf2fb3e0d955f07114d74622401f8942ae/demo/amd/rjs/output/unified/trailing-build.js#L13415-L13424
train
toajs/toa
lib/application.js
respond
function respond () { let res = this.res let body = this.body let code = this.status if (this.respond === false) return endContext(this) if (res.headersSent || this._finished != null) return this.set('server', 'Toa/' + Toa.VERSION) if (this.config.poweredBy) this.set('x-powered-by', this.config.poweredBy) // ignore body if (statuses.empty[code]) { // strip headers this.body = null res.end() } else if (this.method === 'HEAD') { if (isJSON(body)) this.length = Buffer.byteLength(JSON.stringify(body)) res.end() } else if (body == null) { // status body this.type = 'text' body = this.message || String(code) this.length = Buffer.byteLength(body) res.end(body) } else if (typeof body === 'string' || Buffer.isBuffer(body)) { res.end(body) } else if (body instanceof Stream) { body.pipe(res) // to ensure `res.headersSent === true` before `context.emit("end")` // if "error" occured before "data", it will goto `onResError(this, error)` body.once('data', () => endContext(this)) return } else { // body: json body = JSON.stringify(body) this.length = Buffer.byteLength(body) res.end(body) } endContext(this) }
javascript
function respond () { let res = this.res let body = this.body let code = this.status if (this.respond === false) return endContext(this) if (res.headersSent || this._finished != null) return this.set('server', 'Toa/' + Toa.VERSION) if (this.config.poweredBy) this.set('x-powered-by', this.config.poweredBy) // ignore body if (statuses.empty[code]) { // strip headers this.body = null res.end() } else if (this.method === 'HEAD') { if (isJSON(body)) this.length = Buffer.byteLength(JSON.stringify(body)) res.end() } else if (body == null) { // status body this.type = 'text' body = this.message || String(code) this.length = Buffer.byteLength(body) res.end(body) } else if (typeof body === 'string' || Buffer.isBuffer(body)) { res.end(body) } else if (body instanceof Stream) { body.pipe(res) // to ensure `res.headersSent === true` before `context.emit("end")` // if "error" occured before "data", it will goto `onResError(this, error)` body.once('data', () => endContext(this)) return } else { // body: json body = JSON.stringify(body) this.length = Buffer.byteLength(body) res.end(body) } endContext(this) }
[ "function", "respond", "(", ")", "{", "let", "res", "=", "this", ".", "res", "let", "body", "=", "this", ".", "body", "let", "code", "=", "this", ".", "status", "if", "(", "this", ".", "respond", "===", "false", ")", "return", "endContext", "(", "this", ")", "if", "(", "res", ".", "headersSent", "||", "this", ".", "_finished", "!=", "null", ")", "return", "this", ".", "set", "(", "'server'", ",", "'Toa/'", "+", "Toa", ".", "VERSION", ")", "if", "(", "this", ".", "config", ".", "poweredBy", ")", "this", ".", "set", "(", "'x-powered-by'", ",", "this", ".", "config", ".", "poweredBy", ")", "if", "(", "statuses", ".", "empty", "[", "code", "]", ")", "{", "this", ".", "body", "=", "null", "res", ".", "end", "(", ")", "}", "else", "if", "(", "this", ".", "method", "===", "'HEAD'", ")", "{", "if", "(", "isJSON", "(", "body", ")", ")", "this", ".", "length", "=", "Buffer", ".", "byteLength", "(", "JSON", ".", "stringify", "(", "body", ")", ")", "res", ".", "end", "(", ")", "}", "else", "if", "(", "body", "==", "null", ")", "{", "this", ".", "type", "=", "'text'", "body", "=", "this", ".", "message", "||", "String", "(", "code", ")", "this", ".", "length", "=", "Buffer", ".", "byteLength", "(", "body", ")", "res", ".", "end", "(", "body", ")", "}", "else", "if", "(", "typeof", "body", "===", "'string'", "||", "Buffer", ".", "isBuffer", "(", "body", ")", ")", "{", "res", ".", "end", "(", "body", ")", "}", "else", "if", "(", "body", "instanceof", "Stream", ")", "{", "body", ".", "pipe", "(", "res", ")", "body", ".", "once", "(", "'data'", ",", "(", ")", "=>", "endContext", "(", "this", ")", ")", "return", "}", "else", "{", "body", "=", "JSON", ".", "stringify", "(", "body", ")", "this", ".", "length", "=", "Buffer", ".", "byteLength", "(", "body", ")", "res", ".", "end", "(", "body", ")", "}", "endContext", "(", "this", ")", "}" ]
Response middleware.
[ "Response", "middleware", "." ]
21814e5cf29125dffc92ba84c7364e0d5335855b
https://github.com/toajs/toa/blob/21814e5cf29125dffc92ba84c7364e0d5335855b/lib/application.js#L253-L292
train